问:
Intermediate results from joblib
I'm trying to learn the joblib module as an alternative to the builtin multiprocessing module in python. I'm used to using multiprocessing.imap to run a function over an iterable and returning the results as they come in. In this minimal working example, I can't figure out how to do it with joblib:

```<code>import joblib, time

def hello(n):
    time.sleep(1)
    print "Inside function", n
    return n

with joblib.Parallel(n_jobs=1) as MP:

    func = joblib.delayed(hello)
    for x in MP(func(x) for x in range(3)):
        print "Outside function", x
</code>```

Which prints:

```<code>Inside function 0
Inside function 1
Inside function 2
Outside function 0
Outside function 1
Outside function 2
</code>```

I'd like to see the output:

```<code>Inside function 0
Outside function 0
Inside function 1
Outside function 1
Inside function 2
Outside function 2
</code>```

Or something similar, indicating that the iterable MP(...) is not waiting for all the results to complete. For longer demo change n_jobs=-1 and range(100).

答:
```<code>>>> import joblib, time
>>>
>>> def hello(n):
...     time.sleep(1)
...     print "Inside function", n
...     return n
...
>>> with joblib.Parallel(n_jobs=1) as MP:
...     func = joblib.delayed(hello)
...     res = MP(func(x) for x in range(3))  # This is not an iterator.
...
Inside function 0
Inside function 1
Inside function 2
>>> type(res)
<type 'list'>
</code>```

What you are dealing with is not a generator. Therefore you should not expect that it will provide you with intermediate results. Nothing that I read in the docs seem to mention otherwise (or I didn't read the relevant parts).

You are welcome to read the docs and search for "intermediate" results topic:
https://pythonhosted.org/joblib/search.html?q=intermediate&check_keywords=yes&area=default

My understanding is that each call to parallel is a barrier, and in order to have intermediate results, you need to chunk the processing:

```<code>>>> import joblib, time
>>>
>>> def hello(n):
...     time.sleep(1)
...     print "Inside function", n
...     return n
...
>>> with joblib.Parallel(n_jobs=1) as MP:
...     func = joblib.delayed(hello)
...     for chunk in range(3):
...         x = MP(func(y) for y in [chunk])
...         print "Outside function", x
...
Inside function 0
Outside function [0]
Inside function 1
Outside function [1]
Inside function 2
Outside function [2]
>>>
</code>```

If you want to get technical, there is a callback mechanism, but it is used exclusively for progress reporting (BatchCompletionCallBack), but you would need more involved code changes.

Title: Intermediate results from joblib

Body:
I'm trying to learn the joblib module as an alternative to the builtin multiprocessing module in python. I'm used to using multiprocessing.imap to run a function over an iterable and returning the results as they come in. In this minimal working example, I can't figure out how to do it with joblib:

import joblib, time

def hello(n):
    time.sleep(1)
    print "Inside function", n
    return n

with joblib.Parallel(n_jobs=1) as MP:

    func = joblib.delayed(hello)
    for x in MP(func(x) for x in range(3)):
        print "Outside function", x

Which prints:

Inside function 0
Inside function 1
Inside function 2
Outside function 0
Outside function 1
Outside function 2

I'd like to see the output:

Inside function 0
Outside function 0
Inside function 1
Outside function 1
Inside function 2
Outside function 2

Or something similar, indicating that the iterable MP(...) is not waiting for all the results to complete. For longer demo change n_jobs=-1 and range(100).

Body:
>>> import joblib, time
>>>
>>> def hello(n):
...     time.sleep(1)
...     print "Inside function", n
...     return n
...
>>> with joblib.Parallel(n_jobs=1) as MP:
...     func = joblib.delayed(hello)
...     res = MP(func(x) for x in range(3))  # This is not an iterator.
...
Inside function 0
Inside function 1
Inside function 2
>>> type(res)
<type 'list'>

What you are dealing with is not a generator. Therefore you should not expect that it will provide you with intermediate results. Nothing that I read in the docs seem to mention otherwise (or I didn't read the relevant parts).

You are welcome to read the docs and search for "intermediate" results topic:
https://pythonhosted.org/joblib/search.html?q=intermediate&check_keywords=yes&area=default

My understanding is that each call to parallel is a barrier, and in order to have intermediate results, you need to chunk the processing:

>>> import joblib, time
>>>
>>> def hello(n):
...     time.sleep(1)
...     print "Inside function", n
...     return n
...
>>> with joblib.Parallel(n_jobs=1) as MP:
...     func = joblib.delayed(hello)
...     for chunk in range(3):
...         x = MP(func(y) for y in [chunk])
...         print "Outside function", x
...
Inside function 0
Outside function [0]
Inside function 1
Outside function [1]
Inside function 2
Outside function [2]
>>>

If you want to get technical, there is a callback mechanism, but it is used exclusively for progress reporting (BatchCompletionCallBack), but you would need more involved code changes.


来源: stackexchange

问:
Location marker on map jquery
I used location marker on my address. but can't work properly for map and location marker

HTML code.

```<code><section class="contact-map2" id="contact-map2">
</section>
</code>```

Jquery code.

```<code><!-- Jquery -->
<script src="js/jquery-3.1.1-min.js" type="text/javascript"></script>
<script type="text/javascript" src="http://maps.googleapis.com/maps/api/js?key=AIzaSyAT4sxB6QJ6yqBA7bve0j6wLYSHeF2NKs0&sensor=false&libraries=places"></script>
<script type="text/javascript">
    google.maps.event.addDomListener(window, 'load', init);
    function init() {
        mapInit(11.01392086,76.96254899,"contact-map2","images/pin-house-green.png", true);
    }
</script>
</code>```

please help me for solve this problem.

答:
To add a location marker use this code:

```<code><script>
  function initMap() {
    var uluru = {lat: -25.363, lng: 131.044};
    var map = new google.maps.Map(document.getElementById('map'), {
      zoom: 4,
      center: uluru
      // You can set more attributes value here like map marker icon etc
    });
    var marker = new google.maps.Marker({
      position: uluru,
      map: map
    });
  }
</script>
<script async defer src="https://maps.googleapis.com/maps/api/js?key=YOUR_API_KEY&callback=initMap"></script>

<div id="map"></div>
</code>```

here callback=initMap will call the initMap() on page load and render the map with location marker.

Reference

ContentLicense: CC BY-SA 3.0

Title: Location marker on map jquery

Body:
I used location marker on my address. but can't work properly for map and location marker

HTML code.

Jquery code.

please help me for solve this problem.

Body:
To add a location marker use this code:

<script>
  function initMap() {
    var uluru = {lat: -25.363, lng: 131.044};
    var map = new google.maps.Map(document.getElementById('map'), {
      zoom: 4,
      center: uluru
      // You can set more attributes value here like map marker icon etc
    });
    var marker = new google.maps.Marker({
      position: uluru,
      map: map
    });
  }
</script>
<script async defer src="https://maps.googleapis.com/maps/api/js?key=YOUR_API_KEY&callback=initMap"></script>

<div id="map"></div>

here callback=initMap will call the initMap() on page load and render the map with location marker.

Reference


问:
How to correctly apply a 'multiply' tint to an image in HTML5 canvas?
I'm using the multiply value for the globalCompositeOperation property to apply a tint to a clipped region of an image. It works, but the bottom edge of the image sometimes gets a white border.

// Code goes here

document.addEventListener("DOMContentLoaded", function() {

  var canvas = document.getElementById('myCanvas');

  var img = new Image();
  img.onload = function() {

    render();

  }

  img.src = 'http://i.imgur.com/qiJkgK9.jpg';

  function render() {

    canvas.width = img.width * 2;
    canvas.height = img.height * 2;

    var ctx = canvas.getContext('2d');

    ctx.drawImage(img, 0, 0, canvas.width, canvas.height);

    ctx.save();
    ctx.beginPath();

    ctx.rect(200, 200, 200, 200);
    ctx.clip();

    ctx.globalCompositeOperation = 'multiply';
    ctx.fillStyle = 'red';
    ctx.fill();

    ctx.restore();

    ctx.save();
    ctx.beginPath();

    ctx.rect(300, 100, 200, 200);
    ctx.clip();

    ctx.globalCompositeOperation = 'multiply';
    ctx.fillStyle = 'red';
    ctx.fill();

    ctx.restore();

  }

});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><!DOCTYPE html>
<html>

<head>
  <link rel="stylesheet" href="style.css" />
  <script src="script.js"></script>
</head>

<body>
  <canvas id="myCanvas"></canvas>
</body>

</html></code>```

How to prevent the border from appearing OR is there a better way to apply multiply tint to an image?

答:
You can just use fillRect to the exact rectangle you're looking for instead of clip and fill, which is causing your clipping issue.

  var canvas = document.getElementById('myCanvas');
  function render() {
    canvas.width = img.width * 2;
    canvas.height = img.height * 2;
    var ctx = canvas.getContext('2d');
    ctx.drawImage(img, 0, 0, canvas.width, canvas.height);
    ctx.globalCompositeOperation = 'multiply';
    ctx.fillStyle = 'red';
    ctx.fillRect(200, 200, 200, 200);
    ctx.fillRect(300, 100, 200, 200);
  }

  var img = new Image();
  img.onload = render;
  img.src = 'http://i.imgur.com/qiJkgK9.jpg';```
<pre class="snippet-code-html lang-html prettyprint-override"><code><canvas id="myCanvas"></canvas></code>```

Body:
I'm using the multiply value for the globalCompositeOperation property to apply a tint to a clipped region of an image. It works, but the bottom edge of the image sometimes gets a white border.

// Code goes here

document.addEventListener("DOMContentLoaded", function() {

  var canvas = document.getElementById('myCanvas');

  var img = new Image();
  img.onload = function() {

    render();

  }

  img.src = 'http://i.imgur.com/qiJkgK9.jpg';

  function render() {

    canvas.width = img.width * 2;
    canvas.height = img.height * 2;

    var ctx = canvas.getContext('2d');

    ctx.drawImage(img, 0, 0, canvas.width, canvas.height);

    ctx.save();
    ctx.beginPath();

    ctx.rect(200, 200, 200, 200);
    ctx.clip();

    ctx.globalCompositeOperation = 'multiply';
    ctx.fillStyle = 'red';
    ctx.fill();

    ctx.restore();

    ctx.save();
    ctx.beginPath();

    ctx.rect(300, 100, 200, 200);
    ctx.clip();

    ctx.globalCompositeOperation = 'multiply';
    ctx.fillStyle = 'red';
    ctx.fill();

    ctx.restore();

  }

});

<!DOCTYPE html>

  <link rel="stylesheet" href="style.css" />

  <canvas id="myCanvas"></canvas>

How to prevent the border from appearing OR is there a better way to apply multiply tint to an image?

Body:
You can just use fillRect to the exact rectangle you're looking for instead of clip and fill, which is causing your clipping issue.

  var canvas = document.getElementById('myCanvas');
  function render() {
    canvas.width = img.width * 2;
    canvas.height = img.height * 2;
    var ctx = canvas.getContext('2d');
    ctx.drawImage(img, 0, 0, canvas.width, canvas.height);
    ctx.globalCompositeOperation = 'multiply';
    ctx.fillStyle = 'red';
    ctx.fillRect(200, 200, 200, 200);
    ctx.fillRect(300, 100, 200, 200);
  }

  var img = new Image();
  img.onload = render;
  img.src = 'http://i.imgur.com/qiJkgK9.jpg';

<canvas id="myCanvas"></canvas>


问:
Integrate an html template to wordpress
I have created a basic html template using HTML5 and CSS. I want to integrate it to wordpress. How do i do that? I am new to wordpress. And also can I integrate a template created with angular material?</p>

答:
Please refer below link.. </p>

<p>(https://www.elegantthemes.com/blog/tips-tricks/converting-html-sites-to-wordpress-sites)</p>

Title: Integrate an html template to wordpress

Body:
Please refer below link..

(https://www.elegantthemes.com/blog/tips-tricks/converting-html-sites-to-wordpress-sites)


问:
remove some elements if no children
i need to remove some elements if no children...

this will work...

```<code>$$('*').each(function() {
    ($$(this).text().trim() === '') && $$(this).remove()
});
</code>```

but it will look for all elements... i need to limit to some elements.. so i made this..

```<code>elements.forEach(element => {
    $$(element).each(function() {
        ($$(this).text().trim() === '') && $$(this).remove()
    });
})
</code>```

but it doesn't work..

答:
I like Mamun's approach. If you want to apply it on a certain collection of element types only you could modify/simplify it as such:

```<code>$("div,td,p,... and other elements").filter(":empty").remove();
</code>```

Sorry, just noticed, that Jay also provided a part of my solution. I did not want to repeat things unecessarily here, but maybe the combination of the two is still relevant.

Title: remove some elements if no children

Body:
i need to remove some elements if no children...

this will work...

$$('*').each(function() {
    ($$(this).text().trim() === '') && $$(this).remove()
});

but it will look for all elements... i need to limit to some elements.. so i made this..

elements.forEach(element => {
    $$(element).each(function() {
        ($$(this).text().trim() === '') && $$(this).remove()
    });
})

but it doesn't work..

Body:
I like Mamun's approach. If you want to apply it on a certain collection of element types only you could modify/simplify it as such:

$("div,td,p,... and other elements").filter(":empty").remove();

Sorry, just noticed, that Jay also provided a part of my solution. I did not want to repeat things unecessarily here, but maybe the combination of the two is still relevant.


问:
My jquery click isnt working
I am making a website and I included jQuery.

When I use click events, it isn't working.

HTML

```<code><body>
  <header>
    <h1 class="text-center">Pomodoro Clock</h1>
  </header>

  <section class="container">

    <div id="counter-main">
      <h1>Session Time</h1>
      <a href="#" class="btn btn-primary" id="plusCounterMain">-</a>
      <h2 id="timerMain">5</h2>
      <a href="#" class="btn btn-primary" id="minusCounterMain">+</a>
    </div>
    <div id="resetDiv">
      <a href="#" class="btn btn-primary" id="resetMain">Reset</a>
    </div>

    <div id="break-main">
      <h1>Session Time</h1>
      <a href="#" class="btn btn-primary" id="plusBreakMain">-</a>
      <h2 id="breakCount">5</h2>
      <a href="#" class="btn btn-primary" id="minusBreakMain">+</a>
    </div>
    <div id="startDiv">
      <button class="btn btn-primary" id="start">Start</button>
    </div>
  </section>
  <!-- jQuery library -->
  <script type="text/javascript" src="jquery-3.2.0"></script>
</body>
</code>```

Here is my JavaScript(jQuery) code:

```<code>$(document).ready(function(){
  var timer_main = $("#timerMain");
  var break_count = $("#breakCount");

  var count = parseInt(timer_main.html());
  var break = parseInt(break_count.html());

  $("plusCounterMain").click(function(){
    count +=5;
    console.log(count.toString());
    timer_main.text(count.toString());
  });

  $("#start").click(function{
    var counter = setInterval(timer,1000);

    function timer() {
      count -=1;
      if (count === 0) {
        clearInterval(counter);
      }
      $("#timerMain").text(count.toString());
    }
  });
});
</code>```

I have no idea where I went wrong.

I was trying to make a pomodoro clock, so I used the setInterval function to execute code every second.

Where have I went wrong?

答:
Id should be prefix with #. The main issue is you have given variable name as break. This is keyword in JS. I have changed it. Please check below code.</p>

```<code>   $(document).ready(function(){
var timer_main = $("#timerMain");
var break_count = $("#breakCount");

var count = parseInt(timer_main.html());
var breakCount = parseInt(break_count.html());

$("#plusCounterMain").click(function(){
    count +=5;
    console.log(count.toString());
    timer_main.text(count.toString());
});

$("#start").click(function(){
    var counter = setInterval(timer,1000);

    function timer() {
        count -=1;
        if (count === 0) {
            clearInterval(counter);
        }
        $("#timerMain").text(count.toString());
    }

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

Title: My jquery click isnt working

Body:
I am making a website and I included jQuery.

When I use click events, it isn't working.

HTML

Pomodoro Clock

Session Time

      -

5

      +

      Reset

Session Time

      -

5

      +

      <button class="btn btn-primary" id="start">Start</button>

Here is my JavaScript(jQuery) code:

$(document).ready(function(){
  var timer_main = $("#timerMain");
  var break_count = $("#breakCount");

  var count = parseInt(timer_main.html());
  var break = parseInt(break_count.html());

  $("plusCounterMain").click(function(){
    count +=5;
    console.log(count.toString());
    timer_main.text(count.toString());
  });

  $("#start").click(function{
    var counter = setInterval(timer,1000);

    function timer() {
      count -=1;
      if (count === 0) {
        clearInterval(counter);
      }
      $("#timerMain").text(count.toString());
    }
  });
});

I have no idea where I went wrong.

I was trying to make a pomodoro clock, so I used the setInterval function to execute code every second.

Where have I went wrong?

Body:
Id should be prefix with #. The main issue is you have given variable name as break. This is keyword in JS. I have changed it. Please check below code.

   $(document).ready(function(){
var timer_main = $("#timerMain");
var break_count = $("#breakCount");

var count = parseInt(timer_main.html());
var breakCount = parseInt(break_count.html());

$("#plusCounterMain").click(function(){
    count +=5;
    console.log(count.toString());
    timer_main.text(count.toString());
});

$("#start").click(function(){
    var counter = setInterval(timer,1000);

    function timer() {
        count -=1;
        if (count === 0) {
            clearInterval(counter);
        }
        $("#timerMain").text(count.toString());
    }

}); });


问:
Do I need a wildcard ssl certificate for subdomains in Azure?
In our Azure subscription, we have 3 apps: dev.myapp.com, test.myapp.com, prod.myapp.com (www.myapp.com, myapp.com).

Previously I just purchased a wildcard cert, and then converted it to PFX format and uploaded it.

But I see now that I can get an SSL cert directly from Azure, and save a bit of hassle. But I am wondering if I buy an S1 certificate, if I can use it with my subdomains, or if I need to buy the wildcard (which is quite expensive compared to getting it from another source).

I assume I need the wildcard, would just like to confirm.

答:
You can either get the Single domain certificates or else you can go with the Wildcard SSL Certificates.

The Individual Single Domain SSL certificate will cost you low if you are going to buy from Comodo, but as it is for one domain you have to create the new CSR and Private Key for each domain. If you are wishing to secure one more app, you need to purchase a new SSL, New CSR & Private Key... This is really

But in the case of Wildcard SSL, the one CSR and Private Key will work for all your sub-domains. additionally, it will allow you to secure any number of sub-domains.


问:
What is the difference between String.slice and String.substring?
Does anyone know what the difference is between these two methods?</p>

```<code>String.prototype.slice
String.prototype.substring
</code>```

答:
For slice(start, stop), if stop is negative, stop will be set to:

```<code>string.length – Math.abs(stop)
</code>```

rather than:

```<code>string.length – 1 – Math.abs(stop)
</code>```

ContentLicense: CC BY-SA 4.0

Body:
Does anyone know what the difference is between these two methods?

String.prototype.slice
String.prototype.substring

Body:
For slice(start, stop), if stop is negative, stop will be set to:

string.length – Math.abs(stop)

rather than:

string.length – 1 – Math.abs(stop)


问:
Cocoa Touch: What to release, when to release it?
I'm trying hard to understand when and what I must relase in Cocoa Touch as it doesn't have garbage collection.

This code block is from apples iphone sample PeriodicElements and they release anElement and rawElementArray but not thePath, firstLetter, existingArray and tempArray?

I would have thought that at least tempArray and existingArray should be released.

Could some brainy person please explain to me why?

Thanks :)

```<code>- (void)setupElementsArray {
NSDictionary *eachElement;

// create dictionaries that contain the arrays of element data indexed by
// name
self.elementsDictionary = [NSMutableDictionary dictionary];
// physical state
self.statesDictionary = [NSMutableDictionary dictionary];
// unique first characters (for the Name index table)
self.nameIndexesDictionary = [NSMutableDictionary dictionary];

// create empty array entries in the states Dictionary or each physical state
[statesDictionary setObject:[NSMutableArray array] forKey:@"Solid"];
[statesDictionary setObject:[NSMutableArray array] forKey:@"Liquid"];
[statesDictionary setObject:[NSMutableArray array] forKey:@"Gas"];
[statesDictionary setObject:[NSMutableArray array] forKey:@"Artificial"];

// read the element data from the plist
NSString *thePath = [[NSBundle mainBundle]  pathForResource:@"Elements" ofType:@"plist"];
NSArray *rawElementsArray = [[NSArray alloc] initWithContentsOfFile:thePath];

// iterate over the values in the raw elements dictionary
for (eachElement in rawElementsArray)
{
    // create an atomic element instance for each
    AtomicElement *anElement = [[AtomicElement alloc] initWithDictionary:eachElement];

    // store that item in the elements dictionary with the name as the key
    [elementsDictionary setObject:anElement forKey:anElement.name];

    // add that element to the appropriate array in the physical state dictionary
    [[statesDictionary objectForKey:anElement.state] addObject:anElement];

    // get the element's initial letter
    NSString *firstLetter = [anElement.name substringToIndex:1];
    NSMutableArray *existingArray;

    // if an array already exists in the name index dictionary
    // simply add the element to it, otherwise create an array
    // and add it to the name index dictionary with the letter as the key
    if (existingArray = [nameIndexesDictionary valueForKey:firstLetter])
    {
    [existingArray addObject:anElement];
    } else {
        NSMutableArray *tempArray = [NSMutableArray array];
        [nameIndexesDictionary setObject:tempArray forKey:firstLetter];
        [tempArray addObject:anElement];
    }

    // release the element, it is held by the various collections
    [anElement release];

}
// release the raw element data
[rawElementsArray release];

// create the dictionary containing the possible element states
// and presort the states data
self.elementPhysicalStatesArray = [NSArray arrayWithObjects:@"Solid",@"Liquid",@"Gas",@"Artificial",nil];
[self presortElementsByPhysicalState];

// presort the dictionaries now
// this could be done the first time they are requested instead

[self presortElementInitialLetterIndexes];

self.elementsSortedByNumber = [self presortElementsByNumber];
self.elementsSortedBySymbol = [self presortElementsBySymbol];
</code>```

}

答:
The reason you don't have to release tempArray is because it's been allocated and then autoreleased right away.  Autorelease is a method of scheduling a release call sometime in the future, so that the caller of an API doesn't have to do any explicit releasing of the result.

Matt Dillard has provided a detailed explanation of Objective C's memory management strategy and has explained it much better than I can.

OwnerDisplayName: BJ McKay

ContentLicense: CC BY-SA 2.5

Body:
I'm trying hard to understand when and what I must relase in Cocoa Touch as it doesn't have garbage collection.

This code block is from apples iphone sample PeriodicElements and they release anElement and rawElementArray but not thePath, firstLetter, existingArray and tempArray?

I would have thought that at least tempArray and existingArray should be released.

Could some brainy person please explain to me why?

Thanks :)

- (void)setupElementsArray {
NSDictionary *eachElement;

// create dictionaries that contain the arrays of element data indexed by
// name
self.elementsDictionary = [NSMutableDictionary dictionary];
// physical state
self.statesDictionary = [NSMutableDictionary dictionary];
// unique first characters (for the Name index table)
self.nameIndexesDictionary = [NSMutableDictionary dictionary];

// create empty array entries in the states Dictionary or each physical state
[statesDictionary setObject:[NSMutableArray array] forKey:@"Solid"];
[statesDictionary setObject:[NSMutableArray array] forKey:@"Liquid"];
[statesDictionary setObject:[NSMutableArray array] forKey:@"Gas"];
[statesDictionary setObject:[NSMutableArray array] forKey:@"Artificial"];

// read the element data from the plist
NSString *thePath = [[NSBundle mainBundle]  pathForResource:@"Elements" ofType:@"plist"];
NSArray *rawElementsArray = [[NSArray alloc] initWithContentsOfFile:thePath];

// iterate over the values in the raw elements dictionary
for (eachElement in rawElementsArray)
{
    // create an atomic element instance for each
    AtomicElement *anElement = [[AtomicElement alloc] initWithDictionary:eachElement];

    // store that item in the elements dictionary with the name as the key
    [elementsDictionary setObject:anElement forKey:anElement.name];

    // add that element to the appropriate array in the physical state dictionary
    [[statesDictionary objectForKey:anElement.state] addObject:anElement];

    // get the element's initial letter
    NSString *firstLetter = [anElement.name substringToIndex:1];
    NSMutableArray *existingArray;

    // if an array already exists in the name index dictionary
    // simply add the element to it, otherwise create an array
    // and add it to the name index dictionary with the letter as the key
    if (existingArray = [nameIndexesDictionary valueForKey:firstLetter])
    {
    [existingArray addObject:anElement];
    } else {
        NSMutableArray *tempArray = [NSMutableArray array];
        [nameIndexesDictionary setObject:tempArray forKey:firstLetter];
        [tempArray addObject:anElement];
    }

    // release the element, it is held by the various collections
    [anElement release];

}
// release the raw element data
[rawElementsArray release];

// create the dictionary containing the possible element states
// and presort the states data
self.elementPhysicalStatesArray = [NSArray arrayWithObjects:@"Solid",@"Liquid",@"Gas",@"Artificial",nil];
[self presortElementsByPhysicalState];

// presort the dictionaries now
// this could be done the first time they are requested instead

[self presortElementInitialLetterIndexes];

self.elementsSortedByNumber = [self presortElementsByNumber];
self.elementsSortedBySymbol = [self presortElementsBySymbol];

}

OwnerDisplayName: rpetrich


问:
Is there a way to retrieve a document properties without dsolfile?
I want to retrieve document properties such as author, last edited by, etc using vbscript.

Is there a way to get the above info without using dsolefile extension ?

答: Well you could parse the file yourself, but Word documents are assentially structured storage files. You don't need to read them with dsOleFile, because you can treat them as any structured storage file. It is however convenient to use dsOleFile. Why don't you want to use it?


问:
AutoMoq an abstract class with specific constructor
Is there a way to setup AutoFixture.AutoMoq such that when mocking an abstract class it uses a specific constructor?

I need to test the implementation done in my abstract class. However, I do need to use one specific constructor.

```<code>public abstract class A
{
    public A(IQueryable q) // I need to use this
    { /*...*/ }
}
</code>```

Regards,

EDIT:

I am trying to use something like below but still does not work.
The class is abstract so I need to mock it, but I need a very specific constructor.

How to tell AutoMoq that when mocking A please do not use either MockConstructorQuery or GreedyMockConstructorQuery. Just use QueryableParamConstructorQuery.

fixture.Customize(
        new ConstructorCustomization(typeof(A),
          new QueryableParamConstructorQuery()));

答:
If you need a particular constructor, you can pass the argument list when you create the test double:

```<code>var q = fixture.Create<IQueryable>();
var a = new Mock<A>(q).Object;
</code>```

If you need to change AutoFixture's behaviour to always use this particular constructor, you can do something like this:

```<code>fixture.Register(q => new Mock<A>(q));
</code>```

Body:
Is there a way to setup AutoFixture.AutoMoq such that when mocking an abstract class it uses a specific constructor?

I need to test the implementation done in my abstract class. However, I do need to use one specific constructor.

public abstract class A
{
    public A(IQueryable q) // I need to use this
    { /*...*/ }
}

Regards,

EDIT:

I am trying to use something like below but still does not work.
The class is abstract so I need to mock it, but I need a very specific constructor.

How to tell AutoMoq that when mocking A please do not use either MockConstructorQuery or GreedyMockConstructorQuery. Just use QueryableParamConstructorQuery.

fixture.Customize(
        new ConstructorCustomization(typeof(A),
          new QueryableParamConstructorQuery()));

Body:
If you need a particular constructor, you can pass the argument list when you create the test double:

var q = fixture.Create<IQueryable>();
var a = new Mock<A>(q).Object;

If you need to change AutoFixture's behaviour to always use this particular constructor, you can do something like this:

fixture.Register(q => new Mock<A>(q));


问:
Insert into same table avoiding duplicate
```<code>Table enrollments
-----------------

id      classId     userId
--      -------     ------
1         1           1
--      -------     ------
</code>```

after this stats: want to reject inserting whenever again inserting { classId=1, userId=1 }

If user inserts same classId and userId then it should rejects inserting.
I've already tried:

```<code>INSERT INTO enrollments(classId, userId)
    VALUES('{$classId}', '{$userId}')
    WHERE
    NOT EXISTS(SELECT NULL FROM
                enrollments WHERE
                    classId='{$classId}' AND userId='{$userId}')
</code>```

答:
instead of below Code

```<code>INSERT INTO enrollments(classId, userId)
    VALUES('{$classId}', '{$userId}')
    WHERE
    NOT EXISTS(SELECT NULL FROM
                enrollments WHERE
                    classId='{$classId}' AND userId='{$userId}')
</code>```

replace with

```<code>INSERT INTO enrollments(classId, userId)
    SELECT '{$classId}', '{$userId}'
    WHERE
    NOT EXISTS(SELECT * FROM
                enrollments WHERE
                    classId='{$classId}' AND userId='{$userId}')
</code>```

Example : you can try with demo data

```<code>INSERT INTO enrollments(classId, userId)
    SELECT 2, 2
    WHERE
    NOT EXISTS(SELECT * FROM
                enrollments WHERE
                    classId=2 AND userId=2)
</code>```

Body:
Table enrollments
-----------------

id      classId     userId
--      -------     ------
1         1           1
--      -------     ------

after this stats: want to reject inserting whenever again inserting { classId=1, userId=1 }

If user inserts same classId and userId then it should rejects inserting.
I've already tried:

INSERT INTO enrollments(classId, userId)
    VALUES('{$classId}', '{$userId}')
    WHERE
    NOT EXISTS(SELECT NULL FROM
                enrollments WHERE
                    classId='{$classId}' AND userId='{$userId}')

Body:
instead of below Code

INSERT INTO enrollments(classId, userId)
    VALUES('{$classId}', '{$userId}')
    WHERE
    NOT EXISTS(SELECT NULL FROM
                enrollments WHERE
                    classId='{$classId}' AND userId='{$userId}')

replace with

INSERT INTO enrollments(classId, userId)
    SELECT '{$classId}', '{$userId}'
    WHERE
    NOT EXISTS(SELECT * FROM
                enrollments WHERE
                    classId='{$classId}' AND userId='{$userId}')

Example : you can try with demo data

INSERT INTO enrollments(classId, userId)
    SELECT 2, 2
    WHERE
    NOT EXISTS(SELECT * FROM
                enrollments WHERE
                    classId=2 AND userId=2)


问:
Can I use Xamarin.Forms for creating windows phone application which will support Win 7, 8, 8.1, 10?
I want to create windows phone application which will support Win phone 7, 8, 8.1, 10, all these 4 OS. Can I use Xamarin.Forms for this application?
If not then please suggest good option.</p>

答:
Xamarin.Forms Supports below platforms:

Android

iOS

WinPhone

Windows(WinRT)

UWP

By checking on Windows Side:

WinPhone: Supports WP8 or above

WinRT : Support Windows 8.1 or above

UWP : Support Windows 10

Unfortunately Xamarin.Forms does not support Windows 7 and windows 8.


问:
Check in controller which input element has been modified
I need to check which input element has modified in update form.

```<code>    <form name="utilizationForm" role="form" novalidate>
    <div class="row" data-ng-repeat="i in [1,2,3,4]">
            <div class="col-md-3">
                <div asterick class="form-group" ng-class="{'form-group has-success': !error['resource_type'] && (submitted), 'form-group has-error': (error['resource_type']) && (submitted)}">
                    <label for="resourceType">Resource Type</label>
                    <input type="hidden" name="id" id="id" class="form-control" ng-model="data['id' + i]" value="">
                                        <select name="resourceType" id="resourceType" ng-model="data['resource_type' + i]" class="form-control" ng-required="true"  >
                                            <option ng-repeat="option in resourceTypeJson" value="{{option}}">{{option}}</option>
                                        </select>
                    <span class="er-block" ng-show="utilizationForm.resourceType.$touched && utilizationForm.resourceType.$error.required">Please provide Resource type.</span>
                    <span ng-show="error.resource_type1" class="er-block">{{error.resource_type1}}</span>
                </div>
            </div>
            <div class="col-md-3">
                <label for="efforts">Efforts (in hours)</label>
                <input type="hidden" name="id" id="id" class="form-control" ng-model="data['id' + i]" value="">
                <input type="text"  test-change name="efforts" id="efforts" class="form-control" ng-model="data['efforts' + i]"  value="">
            </div>
        </div>
        <div class="text-right" ng-class="{'col-md-6 mt25': showCompletion}">
            <button class="btn btn-primary" ng-disabled="utilizationForm.$invalid" ng-click="addUtilizationReport()">{{buttonText}}</button>
        </div>

    </form>
</code>```

Now when I click on update button I need to check which input element has modified in update form in controller. Please help.

答:
Here is simplest example of using $watch in controller:

var app = angular.module('myApp', []);
app.controller('appCtrl', function($scope, $location) {
    $scope.$watch('abc', function(newVal,oldVal) {
      if(oldVal != newVal){
        alert("value changed!");
      }
    });
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div ng-app="myApp" ng-controller="appCtrl">
 <input type="text" name="first" ng-model="abc">
</div></code>```

Body:
I need to check which input element has modified in update form.

    <form name="utilizationForm" role="form" novalidate>

                    Resource Type
                    <input type="hidden" name="id" id="id" class="form-control" ng-model="data['id' + i]" value="">
                                        <select name="resourceType" id="resourceType" ng-model="data['resource_type' + i]" class="form-control" ng-required="true"  >
                                            <option ng-repeat="option in resourceTypeJson" value="{{option}}">{{option}}</option>
                                        </select>
                    Please provide Resource type.
                    {{error.resource_type1}}

                Efforts (in hours)
                <input type="hidden" name="id" id="id" class="form-control" ng-model="data['id' + i]" value="">
                <input type="text"  test-change name="efforts" id="efforts" class="form-control" ng-model="data['efforts' + i]"  value="">

            <button class="btn btn-primary" ng-disabled="utilizationForm.$invalid" ng-click="addUtilizationReport()">{{buttonText}}</button>

    </form>

Now when I click on update button I need to check which input element has modified in update form in controller. Please help.

Body:
Here is simplest example of using $watch in controller:

var app = angular.module('myApp', []);
app.controller('appCtrl', function($scope, $location) {
    $scope.$watch('abc', function(newVal,oldVal) {
      if(oldVal != newVal){
        alert("value changed!");
      }
    });
});

<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div ng-app="myApp" ng-controller="appCtrl">
 <input type="text" name="first" ng-model="abc">
</div>


问:
What is difference between put code after await v.s. chain code using ContinueWith
In my understanding, if I await an async function, then the following code will be wrapped in a delegate and executed after the async function returns:

```<code>async bool Test()
{
    await byte[] arr = ReadAsync(....)

    // all following code will be wrapped into a delegate
    if (arr != null)
    {
        // Do something

        return true;
    }

    return false;
}
</code>```

It sounds like equal to if I explicitly wrap following code in a ContinueWith:

```<code>async bool Test()
{
    bool res = await ReadAsync(...)
                    .ContinueWith(t =>
                    {
                        byte[] arr = t.Result;
                        if (arr != null)
                        {
                            // Do something
                            return true;
                        }
                        return false;
                    });
}
</code>```

Are there any differences between these two implementations?

答:
One mayor difference is that if the thread you call await from has a SynchronizationContext, await will schedule the continuation inside that SynchronizationContext by default. So after the await you will be back on the same thread as before. You can change that by using .ConfigureAwait(false).

With .ContinueWith() it is eaxactly the other way around, by default it will be scheduled on an aribitary (threadpool) thread unless you pass TaskScheduler.FromCurrentSynchronizationContext() to it.

Body:
In my understanding, if I await an async function, then the following code will be wrapped in a delegate and executed after the async function returns:

async bool Test()
{
    await byte[] arr = ReadAsync(....)

    // all following code will be wrapped into a delegate
    if (arr != null)
    {
        // Do something

        return true;
    }

    return false;
}

It sounds like equal to if I explicitly wrap following code in a ContinueWith:

async bool Test()
{
    bool res = await ReadAsync(...)
                    .ContinueWith(t =>
                    {
                        byte[] arr = t.Result;
                        if (arr != null)
                        {
                            // Do something
                            return true;
                        }
                        return false;
                    });
}

Are there any differences between these two implementations?


问:
How to get the value of an ASP.net variable into a javascript textbox
I'm writing some Javascript code for an ASP.net page.

I have the string "foo" assigned to a string variable myString.

I would like to assign the value of myString to a JavaScript variable, so I write in my ASP.net code:

```<code><script type='txt/javascript' language='javascript'>
    var stringFromDotNet = '<%=myString%>';
</script>
</code>```

This works fine as long as myString does not contain quotation marks or line-breaks, but as as soon as I try to assign something with quotation marks or line-breaks, all hell breaks loose and my code doesn't work.  As a matter of fact, I can see that this code is vulnerable to all sort of injection attacks.

So... What can I do get the value of myString assigned to a variable in JavaScript?

Update:  I've tried creating a page with just an ASP:Hidden field.  It looks like the values inside are html encoded.

答:
I think this may be the answer are looking for: http://www.velocityreviews.com/forums/t70655-escape-function-in-asp-net.html#edit352659. Basically, encode the value on the server side and unencode it with JavaScript:

```<code>var stringFromDotNet = decodeURI(<%=Server.URLEncode(myString)%>);
</code>```

This will ensure that quotes and other dangerous characters won't break your script, or open up attack vectors.

Body:
I'm writing some Javascript code for an ASP.net page.

I have the string "foo" assigned to a string variable myString.

I would like to assign the value of myString to a JavaScript variable, so I write in my ASP.net code:

This works fine as long as myString does not contain quotation marks or line-breaks, but as as soon as I try to assign something with quotation marks or line-breaks, all hell breaks loose and my code doesn't work.  As a matter of fact, I can see that this code is vulnerable to all sort of injection attacks.

So... What can I do get the value of myString assigned to a variable in JavaScript?

Update:  I've tried creating a page with just an ASP:Hidden field.  It looks like the values inside are html encoded.

Body:
I think this may be the answer are looking for: http://www.velocityreviews.com/forums/t70655-escape-function-in-asp-net.html#edit352659. Basically, encode the value on the server side and unencode it with JavaScript:

var stringFromDotNet = decodeURI(<%=Server.URLEncode(myString)%>);

This will ensure that quotes and other dangerous characters won't break your script, or open up attack vectors.


问:
Dynamic Where Clause T-SQL varibable operator
I am trying to set my where condition in my sql based on an input variable to a stored procedure.

```<code>Where RF.InternalCompany = @Company
And RF.Installdate between @Datefrom  and @DateTo
AND CASE WHEN @ContractType = 'Single Asset Contract' THEN numA.NumOfAssets = 1
    WHEN @ContractType = 'Multi-Asset Contract' THEN numA.NumOfAssets > 1
    END
</code>```

How do I set this?

答:
Change it like below..</p>

```<code>Where RF.InternalCompany = @Company
And RF.Installdate between @Datefrom  and @DateTo
AND ((@ContractType = 'Single Asset Contract' AND     numA.NumOfAssets = 1 ) Or
(@ContractType = 'Multi-Asset Contract' AND numA.NumOfAssets > 1))
</code>```

Body:
I am trying to set my where condition in my sql based on an input variable to a stored procedure.

Where RF.InternalCompany = @Company
And RF.Installdate between @Datefrom  and @DateTo
AND CASE WHEN @ContractType = 'Single Asset Contract' THEN numA.NumOfAssets = 1
    WHEN @ContractType = 'Multi-Asset Contract' THEN numA.NumOfAssets > 1
    END

How do I set this?

Body:
Change it like below..

Where RF.InternalCompany = @Company
And RF.Installdate between @Datefrom  and @DateTo
AND ((@ContractType = 'Single Asset Contract' AND     numA.NumOfAssets = 1 ) Or
(@ContractType = 'Multi-Asset Contract' AND numA.NumOfAssets > 1))


问:
Retrieve data from json using Python
I am trying to retrieve the urls from the sub elements given comp1 and comp2 as input to the python script

```<code>{
  "main1": {
    "comp1": {
      "url": [
        "http://kcdclcm.com",
        "http://dacklsd.com"
       ]
    },
    "comp2": {
      "url": [
           "http://dccmsdlkm.com",
           "http://clsdmcsm.com"
        ]
    }
  },
  "main2": {
    "comp3": {
      "url": [
        "http://csdc.com",
        "http://uihjkn.com"
       ]
    },
    "comp4": {
      "url": [
           "http://jkll.com",
           "http://ackjn.com"
        ]
    }
  }
}
</code>```

Following is the snippet of the python function, I am trying to use to grab the urls

```<code>import json
data = json.load(open('test.json'))
def geturl(comp):
    if comp in data[comp]:
        for url in data[comp]['url']:
            print url
geturl('comp1')
geturl('comp2')
</code>```

I totally understand the error is in the 4th and 5th line of the script, since i am trying to grab the url information from the second element of the json data without passing the first element 'main1' or 'main2'. Same script works fine if I replace the 4th and 5th line as below:

```<code>if comp in data['main1']:
    for url in data['main1'][comp]['url']:
</code>```

In my case, i would not know main1 and main2 as the user would just pass comp1, comp2, comp3 and comp4 part as input to the script. Is there a way to find the url information given that only the second element is known

Any inputs would be highly appreciated.

答:
You need to iterate through the keys/values in the dict to check if the second level key you are searching for is present:</p>

```<code>import json

data = json.load(open('test.json'))

def geturl(comp):
    for k, v in data.items():
        if comp in v and 'url' in v[comp]:
            print "%s" % "\n".join(v[comp]['url'])

geturl('comp1')
geturl('comp2')
</code>```

Title: Retrieve data from json using Python

Body:
I am trying to retrieve the urls from the sub elements given comp1 and comp2 as input to the python script

{
  "main1": {
    "comp1": {
      "url": [
        "http://kcdclcm.com",
        "http://dacklsd.com"
       ]
    },
    "comp2": {
      "url": [
           "http://dccmsdlkm.com",
           "http://clsdmcsm.com"
        ]
    }
  },
  "main2": {
    "comp3": {
      "url": [
        "http://csdc.com",
        "http://uihjkn.com"
       ]
    },
    "comp4": {
      "url": [
           "http://jkll.com",
           "http://ackjn.com"
        ]
    }
  }
}

Following is the snippet of the python function, I am trying to use to grab the urls

import json
data = json.load(open('test.json'))
def geturl(comp):
    if comp in data[comp]:
        for url in data[comp]['url']:
            print url
geturl('comp1')
geturl('comp2')

I totally understand the error is in the 4th and 5th line of the script, since i am trying to grab the url information from the second element of the json data without passing the first element 'main1' or 'main2'. Same script works fine if I replace the 4th and 5th line as below:

if comp in data['main1']:
    for url in data['main1'][comp]['url']:

In my case, i would not know main1 and main2 as the user would just pass comp1, comp2, comp3 and comp4 part as input to the script. Is there a way to find the url information given that only the second element is known

Any inputs would be highly appreciated.

Body:
You need to iterate through the keys/values in the dict to check if the second level key you are searching for is present:

import json

data = json.load(open('test.json'))

def geturl(comp):
    for k, v in data.items():
        if comp in v and 'url' in v[comp]:
            print "%s" % "\n".join(v[comp]['url'])

geturl('comp1')
geturl('comp2')


答:
```<code>AND
(
    ( @ContractType = 'Single Asset Contract' AND numA.NumOfAssets = 1 )
    OR
    ( @ContractType = 'Multi-Asset Contract'  AND numA.NumOfAssets > 1 )
)
</code>```

Title: Dynamic Where Clause T-SQL varibable operator


问:
How to get individual values from JSON object
I'm using PubNub API in android to fetch real time data but I need some particular value instead of whole. How can I get value for example c7 & c9. I want them to plot a real time graph.

```<code> @Override
        public void message(PubNub pubnub, PNMessageResult message) {
            System.out.println(message);
        }
</code>```

The result I'm getting :-

PNMessageResult (message={"c1":27,"c2":3,"c3":2017,"c4":15,"c5":56,"c6":52,"c7":15.07,"c8":"P&Q","c9":24.86,"c10":82,"c11":32.74}`

答:
if you parse any value from json api you should make json object for that

for Example:

```<code>{
"c1":27,
"c2":3,
"c3":2017,
"c4":15,
"c5":56,
"c6":52,
"c7":15.07,
"c8":"P&Q",
"c9":24.86,
"c10":82,
"c11":32.74
}

try{
  JSONObject jsonObject = new JSONObject("string");
  String c8 = jsonObject.getString("c8");
}
catch(Exception e){
}
</code>```

Body:
I'm using PubNub API in android to fetch real time data but I need some particular value instead of whole. How can I get value for example c7 & c9. I want them to plot a real time graph.

 @Override
        public void message(PubNub pubnub, PNMessageResult message) {
            System.out.println(message);
        }

The result I'm getting :-

PNMessageResult (message={"c1":27,"c2":3,"c3":2017,"c4":15,"c5":56,"c6":52,"c7":15.07,"c8":"P&Q","c9":24.86,"c10":82,"c11":32.74}`

Body:
if you parse any value from json api you should make json object for that

for Example:

{
"c1":27,
"c2":3,
"c3":2017,
"c4":15,
"c5":56,
"c6":52,
"c7":15.07,
"c8":"P&Q",
"c9":24.86,
"c10":82,
"c11":32.74
}

try{
  JSONObject jsonObject = new JSONObject("string");
  String c8 = jsonObject.getString("c8");
}
catch(Exception e){
}


答:
You could either assign the js variable using double quotes like so

```<code>var stringFromDotNet = "<%=myString%>";
</code>```

Or you could escape the single quotes and replace line breaks with literal "\r\n" in your string in the server side.

Title: How to get the value of an ASP.net variable into a javascript textbox

Body:
You could either assign the js variable using double quotes like so

var stringFromDotNet = "<%=myString%>";

Or you could escape the single quotes and replace line breaks with literal "\r\n" in your string in the server side.


答:
You have some syntax errors 1. break is a reserved word,2. you forgot the () in the #start click event function,3. the # in the plusCounterMain id

  var timer_main = $("#timerMain");
  var break_count = $("#breakCount");

  var count = parseInt(timer_main.html());
  var breaked = parseInt(break_count.html());

  $("#plusCounterMain").click(function() {
    count += 5;
    console.log(count.toString());
    timer_main.text(count.toString());
  });

  $("#start").click(function (){
    var counter = setInterval(timer, 1000);

    function timer() {
      count -= 1;
      if (count === 0) {
        clearInterval(counter);
      }
      $("#timerMain").text(count.toString());
    }

  });```
<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>
<header>
  <h1 class="text-center">Pomodoro Clock</h1>
</header>

<section class="container">

  <div id="counter-main">
    <h1>Session Time</h1>
    -
    <h2 id="timerMain">5</h2>
    +
  </div>
  <div id="resetDiv">Reset</div>

  <div id="break-main">
    <h1>Session Time</h1>
    -
    <h2 id="breakCount">5</h2>
    +
  </div>
  <div id="startDiv"><button class="btn btn-primary" id="start">Start</button>
  </div>
</section>
<!-- jQuery library --></code>```

Note: you should use classes if your implementation has multiple instances

Title: My jquery click isnt working

Body:
I am making a website and I included jQuery.

When I use click events, it isn't working.

HTML

Pomodoro Clock

Session Time

      -

5

      +

      Reset

Session Time

      -

5

      +

      <button class="btn btn-primary" id="start">Start</button>

Here is my JavaScript(jQuery) code:

$(document).ready(function(){
  var timer_main = $("#timerMain");
  var break_count = $("#breakCount");

  var count = parseInt(timer_main.html());
  var break = parseInt(break_count.html());

  $("plusCounterMain").click(function(){
    count +=5;
    console.log(count.toString());
    timer_main.text(count.toString());
  });

  $("#start").click(function{
    var counter = setInterval(timer,1000);

    function timer() {
      count -=1;
      if (count === 0) {
        clearInterval(counter);
      }
      $("#timerMain").text(count.toString());
    }
  });
});

I have no idea where I went wrong.

I was trying to make a pomodoro clock, so I used the setInterval function to execute code every second.

Where have I went wrong?

Body:
You have some syntax errors 1. break is a reserved word,2. you forgot the () in the #start click event function,3. the # in the plusCounterMain id

  var timer_main = $("#timerMain");
  var break_count = $("#breakCount");

  var count = parseInt(timer_main.html());
  var breaked = parseInt(break_count.html());

  $("#plusCounterMain").click(function() {
    count += 5;
    console.log(count.toString());
    timer_main.text(count.toString());
  });

  $("#start").click(function (){
    var counter = setInterval(timer, 1000);

    function timer() {
      count -= 1;
      if (count === 0) {
        clearInterval(counter);
      }
      $("#timerMain").text(count.toString());
    }

  });

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<header>
  <h1 class="text-center">Pomodoro Clock</h1>
</header>

<section class="container">

  <div id="counter-main">
    <h1>Session Time</h1>
    <a href="#" class="btn btn-primary" id="plusCounterMain">-</a>
    <h2 id="timerMain">5</h2>
    <a href="#" class="btn btn-primary" id="minusCounterMain">+</a>
  </div>
  <div id="resetDiv"><a href="#" class="btn btn-primary" id="resetMain">Reset</a></div>

  <div id="break-main">
    <h1>Session Time</h1>
    <a href="#" class="btn btn-primary" id="plusBreakMain">-</a>
    <h2 id="breakCount">5</h2>
    <a href="#" class="btn btn-primary" id="minusBreakMain">+</a>
  </div>
  <div id="startDiv"><button class="btn btn-primary" id="start">Start</button>
  </div>
</section>
<!-- jQuery library -->

Note: you should use classes if your implementation has multiple instances


问:
Simple excel macro
I have just started to work on Excel macros.
Please let me know what is wrong in the following code:

```<code>Sub color_red()

Dim range As range

For R = 1 To 20
    If Cells(R, 1).Value = 1 Then range(R, R).Interior.ColorIndex = 3
Next R

End Sub
</code>```

Error message displayed:

Object variable or with block variable not set

Thanks in advance for your guidance.

答:
Instead of range you can use the Cells function. You have to refer the WorkSheet for using range. Since nothing is mentioned ,its throwing Object variable or with block variable not set.

```<code>Sub color_red()
Dim r As Integer

For r = 1 To 20
If Cells(r, 1).Value = 1 Then Cells(r, r).Interior.ColorIndex = 3
Next r
</code>```

End Sub

Title: Simple excel macro

Body:
I have just started to work on Excel macros.
Please let me know what is wrong in the following code:

Sub color_red()

Dim range As range

For R = 1 To 20
    If Cells(R, 1).Value = 1 Then range(R, R).Interior.ColorIndex = 3
Next R

End Sub

Error message displayed:

Object variable or with block variable not set

Thanks in advance for your guidance.

Body:
Instead of range you can use the Cells function. You have to refer the WorkSheet for using range. Since nothing is mentioned ,its throwing Object variable or with block variable not set.

Sub color_red()
Dim r As Integer

For r = 1 To 20
If Cells(r, 1).Value = 1 Then Cells(r, r).Interior.ColorIndex = 3
Next r

End Sub


问:
Improve code readability on webpack entry point
So basically i want to improve my code readability on webpack.

I try to split the entry point so it looks like this.

```<code>entry : {
    dashboard : ["./scripts/monuments.js", "./scripts/dashboard.js"]
}
</code>```

And it will be resulting in dashboard-bundled.js

The question is, how i can get the variable from the monuments.js to use in dashboard.js? Do i need to export it? Or can you guys perhaps suggest a better way to split the entry point?

答:
how i can get the variable from the monuments.js to use in dashboard.js? Do i need to export it?

Yes, you must export them in order to use them in different modules by using import statements.

can you guys perhaps suggest a better way to split the entry point?

You want to bundle your third party code into one separate bundle as these don't change often, and your application code in a different module, that way you can take advantage of browser long term caching of the vendor code which you don't want the clients to download everytime they make a request because if something doesn't change, the browsers will just fetch from its cache (better for you and the users)

Body:
So basically i want to improve my code readability on webpack.

I try to split the entry point so it looks like this.

entry : {
    dashboard : ["./scripts/monuments.js", "./scripts/dashboard.js"]
}

And it will be resulting in dashboard-bundled.js

The question is, how i can get the variable from the monuments.js to use in dashboard.js? Do i need to export it? Or can you guys perhaps suggest a better way to split the entry point?


问:
ToolStripButton text gets cut off in ContextMenuStrip
I am instantiating my own ToolStripButton and adding it to a ContextMenuStrip. It pops up but the text gets cut off:

```<code>string[] layouts = new string[]{"Test 1", "Test 2", "Test 3"};
List<ToolStripButton> items = new List<ToolStripButton>();
foreach (string layout in layouts)
{
    ToolStripButton item = new ToolStripButton(layout, image, LayoutClicked);
    item.AutoSize = true;
    items.Add(item);
}
layoutMenus.Items.Clear();
layoutMenus.Items.AddRange(items.ToArray());
layoutMenus.Show(Cursor.Position.X, Cursor.Position.Y);
</code>```

Any idea why the text is getting cut off as the AutoSize property is true?

答: I have the same problem. Tried all these things, and it turned out there the MaxSize is set by mistake, like (200, 0). Reset it to (0,0) fix the problem.

Body:
I am instantiating my own ToolStripButton and adding it to a ContextMenuStrip. It pops up but the text gets cut off:

string[] layouts = new string[]{"Test 1", "Test 2", "Test 3"};
List<ToolStripButton> items = new List<ToolStripButton>();
foreach (string layout in layouts)
{
    ToolStripButton item = new ToolStripButton(layout, image, LayoutClicked);
    item.AutoSize = true;
    items.Add(item);
}
layoutMenus.Items.Clear();
layoutMenus.Items.AddRange(items.ToArray());
layoutMenus.Show(Cursor.Position.X, Cursor.Position.Y);

Any idea why the text is getting cut off as the AutoSize property is true?


问:
What is the Regex for decimal numbers in Java?
I am not quite sure of what is the correct regex for the period in Java. Here are some of my attempts. Sadly, they all meant any character.

```<code>String regex = "[0-9]*[.]?[0-9]*";
String regex = "[0-9]*['.']?[0-9]*";
String regex = "[0-9]*["."]?[0-9]*";
String regex = "[0-9]*[\.]?[0-9]*";
String regex = "[0-9]*[\\.]?[0-9]*";
String regex = "[0-9]*.?[0-9]*";
String regex = "[0-9]*\.?[0-9]*";
String regex = "[0-9]*\\.?[0-9]*";
</code>```

But what I want is the actual "." character itself. Anyone have an idea?

What I'm trying to do actually is to write out the regex for a non-negative real number (decimals allowed). So the possibilities are: 12.2, 3.7, 2., 0.3, .89, 19

```<code>String regex = "[0-9]*['.']?[0-9]*";
Pattern pattern = Pattern.compile(regex);

String x = "5p4";
Matcher matcher = pattern.matcher(x);
System.out.println(matcher.find());
</code>```

The last line is supposed to print false but prints true anyway. I think my regex is wrong though.

答:
Your initial understanding was probably right, but you were being thrown because when using matcher.find(), your regex will find the first valid match within the string, and all of your examples would match a zero-length string.

I would suggest "^([0-9]+\\.?[0-9]*|\\.[0-9]+)$"

Body:
I am not quite sure of what is the correct regex for the period in Java. Here are some of my attempts. Sadly, they all meant any character.

String regex = "[0-9]*[.]?[0-9]*";
String regex = "[0-9]*['.']?[0-9]*";
String regex = "[0-9]*["."]?[0-9]*";
String regex = "[0-9]*[\.]?[0-9]*";
String regex = "[0-9]*[\\.]?[0-9]*";
String regex = "[0-9]*.?[0-9]*";
String regex = "[0-9]*\.?[0-9]*";
String regex = "[0-9]*\\.?[0-9]*";

But what I want is the actual "." character itself. Anyone have an idea?

What I'm trying to do actually is to write out the regex for a non-negative real number (decimals allowed). So the possibilities are: 12.2, 3.7, 2., 0.3, .89, 19

String regex = "[0-9]*['.']?[0-9]*";
Pattern pattern = Pattern.compile(regex);

String x = "5p4";
Matcher matcher = pattern.matcher(x);
System.out.println(matcher.find());

The last line is supposed to print false but prints true anyway. I think my regex is wrong though.


问:
Compare every last two records inside ng repeat
Below are the records :

```<code>$scope.myArray =
  [
    {
      "id": 100,
      "child": [
        {
          "id": 77,
          "part": 33,
          "name" : 16
          "subName": 16.1,
        },
        {
          "id": 76,
          "part": 30,
          "name" : 14,
          "subName": 14.3,
        },
       {
        "id": 75,
        "part": 29,
        "name" : 12,
        "subName": 12.1,
       }
      ]
    }
  ]
</code>```

Now in above records,16.1 belongs to part = 33 and 14.3 belongs to part = 30 so as both the Subname belongs to different parts so I would like to display name 16 and 14.

So expected output for above records are like below which I am getting:

```<code>16
14
12
</code>```

Problem comes when i have below records :

```<code>$scope.myArray =
  [
    {
      "id": 100,
      "child": [
        {
          "id": 76,
          "part": 30,
          "name" : 14,
          "subName": 14.3,
        },
        {
          "id": 71,
          "part": 30,
          "name" : 14,
          "subName": 14.2,
        },
        {
          "id": 70,
          "part": 30,
          "name" : 14,
          "subName": 14.1,
        }
      ]
    }
  ]
</code>```

Here child contains all subname for same part ie 30 so now I want to display Subname.So expected output in this case will be Subname like below :

```<code>14.3
14.2
14.1
</code>```

Records will be compare from 0 - 1,1 - 2, 2 - 3 but here I am not getting how to compare records if child array contains more than two records.

Note: I will not have duplicate part in child array if any of the two records contains different part. For example, I will not have Subname like 16.1,14.3,14.2 as because here I have 16.1 which belongs to different part. But if 16.1 is not there then I can have 14.3,14.2 which are of same part.

var app = angular.module('myApp', []);
        app.controller('myCtrl', function ($scope) {
          $scope.myArray =
  [
    {
      "id": 100,
      "child": [
        {
          "id": 77,
          "part": 33,
          "name" : 16,
          "subName": 16.1,
        },
        {
          "id": 76,
          "part": 30,
          "name" : 14,
          "subName": 14.3,
        },
        {
          "id": 75,
          "part": 29,
          "name" : 12,
          "subName": 12.1,
        }
      ]
    }
  ]
        });```
<pre class="snippet-code-html lang-html prettyprint-override"><code><!DOCTYPE html>
<html ng-app="myApp" ng-controller="myCtrl">
<head>
    <title></title>
    <meta charset="utf-8" />
    <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.min.js"></script>
</head>
<body>
    <div ng-repeat="item in myArray[0].child">
       {{ item.name }}
    </div>
</body>
</html></code>```

答:
Please see below controller code. I tried to implement what you want.

```<code>$scope.myArray = [ {
        "id" : 100,
        "child" : [ {
            "id" : 76,
            "part" : 30,
            "name" : 14,
            "subName" : 14.3,
        }, {
            "id" : 71,
            "part" : 30,
            "name" : 14,
            "subName" : 14.2,
        }, {
            "id" : 70,
            "part" : 30,
            "name" : 14,
            "subName" : 14.1,
        } ]
    }, {
        "id" : 101,
        "child" : [ {
            "id" : 77,
            "part" : 33,
            "name" : 16,
            "subName" : 16.1,
        }, {
            "id" : 76,
            "part" : 30,
            "name" : 14,
            "subName" : 14.3,
        }, {
            "id" : 75,
            "part" : 29,
            "name" : 12,
            "subName" : 12.1,
        } ]
    } ]
</code>```

HTML code:

```<code><div ng-repeat="item in myArray">
            ============<br />
            <div ng-repeat="item1 in item.child">
                <span>{{(item1.part==item.child[$index+1].part ||
                    ($index==item.child.length-1 &&
                    item1.part==item.child[$index-1].part))?item1.subName:item1.name}}</span>
            </div>
        </div>
</code>```

Here I am checking that, if current item and next item's part are same or not and if it is last item then current item and previous item's part are same or not and based on that I am displaying subName or name. I hope this solution will work for you.

Updated:

    var app = angular.module('myApp', []);
    app.controller('myCtrl', function($scope) {
        $scope.myArray = [{
            "id": 100,
            "child": [{
                "id": 76,
                "part": 30,
                "name": 14,
                "subName": 14.3,
            }, {
                "id": 71,
                "part": 30,
                "name": 14,
                "subName": 14.2,
            }, {
                "id": 70,
                "part": 30,
                "name": 14,
                "subName": 14.1,
            }]
        }, {
            "id": 101,
            "child": [{
                "id": 77,
                "part": 33,
                "name": 16,
                "subName": 16.1,
            }, {
                "id": 76,
                "part": 30,
                "name": 14,
                "subName": 14.3,
            }, {
                "id": 75,
                "part": 29,
                "name": 12,
                "subName": 12.1,
            }]
        }]
    });```
<pre class="snippet-code-html lang-html prettyprint-override"><code><html ng-app="myApp" ng-controller="myCtrl">
   <head>
      <title></title>
      <meta charset="utf-8" />
      <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.min.js"></script>
   </head>
   <body>
      <div ng-repeat="item in myArray">
         ============<br />
         <div ng-repeat="item1 in item.child">
            <span>{{(item1.part==item.child[$index+1].part ||
            ($index==item.child.length-1 &&
            item1.part==item.child[$index-1].part))?item1.subName:item1.name}}</span>
         </div>
      </div>
   </body>
</html></code>```

Body:
Below are the records :

$scope.myArray =
  [
    {
      "id": 100,
      "child": [
        {
          "id": 77,
          "part": 33,
          "name" : 16
          "subName": 16.1,
        },
        {
          "id": 76,
          "part": 30,
          "name" : 14,
          "subName": 14.3,
        },
       {
        "id": 75,
        "part": 29,
        "name" : 12,
        "subName": 12.1,
       }
      ]
    }
  ]

Now in above records,16.1 belongs to part = 33 and 14.3 belongs to part = 30 so as both the Subname belongs to different parts so I would like to display name 16 and 14.

So expected output for above records are like below which I am getting:

16
14
12

Problem comes when i have below records :

$scope.myArray =
  [
    {
      "id": 100,
      "child": [
        {
          "id": 76,
          "part": 30,
          "name" : 14,
          "subName": 14.3,
        },
        {
          "id": 71,
          "part": 30,
          "name" : 14,
          "subName": 14.2,
        },
        {
          "id": 70,
          "part": 30,
          "name" : 14,
          "subName": 14.1,
        }
      ]
    }
  ]

Here child contains all subname for same part ie 30 so now I want to display Subname.So expected output in this case will be Subname like below :

14.3
14.2
14.1

Records will be compare from 0 - 1,1 - 2, 2 - 3 but here I am not getting how to compare records if child array contains more than two records.

Note: I will not have duplicate part in child array if any of the two records contains different part. For example, I will not have Subname like 16.1,14.3,14.2 as because here I have 16.1 which belongs to different part. But if 16.1 is not there then I can have 14.3,14.2 which are of same part.

var app = angular.module('myApp', []);
        app.controller('myCtrl', function ($scope) {
          $scope.myArray =
  [
    {
      "id": 100,
      "child": [
        {
          "id": 77,
          "part": 33,
          "name" : 16,
          "subName": 16.1,
        },
        {
          "id": 76,
          "part": 30,
          "name" : 14,
          "subName": 14.3,
        },
        {
          "id": 75,
          "part": 29,
          "name" : 12,
          "subName": 12.1,
        }
      ]
    }
  ]
        });

<!DOCTYPE html>

    <title></title>
    <meta charset="utf-8" />

       {{ item.name }}

Body:
Please see below controller code. I tried to implement what you want.

$scope.myArray = [ {
        "id" : 100,
        "child" : [ {
            "id" : 76,
            "part" : 30,
            "name" : 14,
            "subName" : 14.3,
        }, {
            "id" : 71,
            "part" : 30,
            "name" : 14,
            "subName" : 14.2,
        }, {
            "id" : 70,
            "part" : 30,
            "name" : 14,
            "subName" : 14.1,
        } ]
    }, {
        "id" : 101,
        "child" : [ {
            "id" : 77,
            "part" : 33,
            "name" : 16,
            "subName" : 16.1,
        }, {
            "id" : 76,
            "part" : 30,
            "name" : 14,
            "subName" : 14.3,
        }, {
            "id" : 75,
            "part" : 29,
            "name" : 12,
            "subName" : 12.1,
        } ]
    } ]

HTML code:

<div ng-repeat="item in myArray">
            ============<br />
            <div ng-repeat="item1 in item.child">
                <span>{{(item1.part==item.child[$index+1].part ||
                    ($index==item.child.length-1 &&
                    item1.part==item.child[$index-1].part))?item1.subName:item1.name}}</span>
            </div>
        </div>

Here I am checking that, if current item and next item's part are same or not and if it is last item then current item and previous item's part are same or not and based on that I am displaying subName or name. I hope this solution will work for you.

Updated:

    var app = angular.module('myApp', []);
    app.controller('myCtrl', function($scope) {
        $scope.myArray = [{
            "id": 100,
            "child": [{
                "id": 76,
                "part": 30,
                "name": 14,
                "subName": 14.3,
            }, {
                "id": 71,
                "part": 30,
                "name": 14,
                "subName": 14.2,
            }, {
                "id": 70,
                "part": 30,
                "name": 14,
                "subName": 14.1,
            }]
        }, {
            "id": 101,
            "child": [{
                "id": 77,
                "part": 33,
                "name": 16,
                "subName": 16.1,
            }, {
                "id": 76,
                "part": 30,
                "name": 14,
                "subName": 14.3,
            }, {
                "id": 75,
                "part": 29,
                "name": 12,
                "subName": 12.1,
            }]
        }]
    });

<html ng-app="myApp" ng-controller="myCtrl">
   <head>
      <title></title>
      <meta charset="utf-8" />
      <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.min.js"></script>
   </head>
   <body>
      <div ng-repeat="item in myArray">
         ============<br />
         <div ng-repeat="item1 in item.child">
            <span>{{(item1.part==item.child[$index+1].part ||
            ($index==item.child.length-1 &&
            item1.part==item.child[$index-1].part))?item1.subName:item1.name}}</span>
         </div>
      </div>
   </body>
</html>


问:
angularjs ng-change function not fire poperly in html input
```<code><input name="maxSalary" id="MaxSalary" type="number" min="0" class="form-control" ng-model="dp.maximumSalary" ng-change="minMaxSalaryComparision()" />
</code>```

this is my html input. when I add a integer value, its work properly. but if I add 0000 ng-change only fire with first entered 0. this is my java script.

```<code> $scope.minMaxSalaryComparision = function () {
        alert($scope.dp.maximumSalary);
    };
</code>```

any idea?

答:
ng change fires when you change the value of the ng model. since 0000 is equal to 0 ng change does not getting fired.

alternatively can use ngKeyup to fire this event when key released

angular.module("app",[])
.controller("ctrl",function($scope){

 $scope.minMaxSalaryComparision = function () {
        alert($scope.dp.maximumSalary);
    };
})```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="app" ng-controller="ctrl">
 <input name="maxSalary" id="MaxSalary" type="number" min="0" class="form-control" ng-model="dp.maximumSalary" ng-keyup="minMaxSalaryComparision()" />

</div></code>```

Body:
<input name="maxSalary" id="MaxSalary" type="number" min="0" class="form-control" ng-model="dp.maximumSalary" ng-change="minMaxSalaryComparision()" />

this is my html input. when I add a integer value, its work properly. but if I add 0000 ng-change only fire with first entered 0. this is my java script.

 $scope.minMaxSalaryComparision = function () {
        alert($scope.dp.maximumSalary);
    };

any idea?

Body:
ng change fires when you change the value of the ng model. since 0000 is equal to 0 ng change does not getting fired.

alternatively can use ngKeyup to fire this event when key released

angular.module("app",[])
.controller("ctrl",function($scope){

 $scope.minMaxSalaryComparision = function () {
        alert($scope.dp.maximumSalary);
    };
})

<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="app" ng-controller="ctrl">
 <input name="maxSalary" id="MaxSalary" type="number" min="0" class="form-control" ng-model="dp.maximumSalary" ng-keyup="minMaxSalaryComparision()" />

</div>


答:
```<code>{"c1":27,
"c2":3,
"c3":2017,
"c4":15,
"c5":56,
"c6":52,
"c7":15.07,
"c8":"P&Q",
"c9":24.86,
"c10":82,
"c11":32.74
}

//In place of your string place a response string which /////you get after successful API call
try{
  JSONObject jsonObject = new JSONObject("your string");
  double c7 = jsonObject.getDouble("c7");
  double c9 = jsonObject.getDouble("c9");
}
catch(JSONException e){
 e.printStackTrace();//shouldn't be empty
}
</code>```

you need to download the org.json library and include it in your program.

Title: How to get individual values from JSON object

Body:
{"c1":27,
"c2":3,
"c3":2017,
"c4":15,
"c5":56,
"c6":52,
"c7":15.07,
"c8":"P&Q",
"c9":24.86,
"c10":82,
"c11":32.74
}

//In place of your string place a response string which /////you get after successful API call
try{
  JSONObject jsonObject = new JSONObject("your string");
  double c7 = jsonObject.getDouble("c7");
  double c9 = jsonObject.getDouble("c9");
}
catch(JSONException e){
 e.printStackTrace();//shouldn't be empty
}

you need to download the org.json library and include it in your program.


问:
max date changes with mindate in datepicker
Here,I have selected max date as 3 week from current date. but actually I don't want to shift max date until current week gets over. I want something like, when current week gets over again max date change to next week end.</p>

```<code>jQuery(document).ready(function ($) {
    $("#datepicker").datepicker({
        dateFormat: 'yy-mm-dd',
        showAnim: "slideDown",
        minDate: 0,
        maxDate: "+3w",
        beforeShowDay: $.datepicker.noWeekends
    });
});
</code>```

答:
Remove extra days in the last week by getting the left no of days in the current week.

var now=new Date();
var startDay = 1; //0=sunday, 1=monday etc.
var d = now.getDay(); //get the current day
var weekStart = new Date(now.valueOf() - (d<=0 ? 7-startDay:d-startDay)*86400000); //rewind to start day
var weekEnd = new Date(weekStart.valueOf() + 6*86400000);

var maxdate=((weekEnd-now)/86400000-1);
if(d!=0 && d<6)
maxdate = 6-maxdate;
else
maxdate = 0;

 $("#datepicker").datepicker({
        dateFormat: 'yy-mm-dd',
        showAnim: "slideDown",
        minDate: 0,
        //maxDate: "+3w",
        maxDate: "+3w -"+maxdate+"d",//"+3w -2d",
        beforeShowDay: $.datepicker.noWeekends
    });```
<pre class="snippet-code-html lang-html prettyprint-override"><code><link rel="stylesheet" type="text/css" href="https://cdnjs.cloudflare.com/ajax/libs/jqueryui/1.12.1/jquery-ui.css" media="screen" />
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<script src="https://cdnjs.cloudflare.com/ajax/libs/jqueryui/1.12.1/jquery-ui.js"></script>

<input type="text" id="datepicker"/></code>```

Body:
Here,I have selected max date as 3 week from current date. but actually I don't want to shift max date until current week gets over. I want something like, when current week gets over again max date change to next week end.

jQuery(document).ready(function ($) {
    $("#datepicker").datepicker({
        dateFormat: 'yy-mm-dd',
        showAnim: "slideDown",
        minDate: 0,
        maxDate: "+3w",
        beforeShowDay: $.datepicker.noWeekends
    });
});

Body:
Remove extra days in the last week by getting the left no of days in the current week.

var now=new Date();
var startDay = 1; //0=sunday, 1=monday etc.
var d = now.getDay(); //get the current day
var weekStart = new Date(now.valueOf() - (d<=0 ? 7-startDay:d-startDay)*86400000); //rewind to start day
var weekEnd = new Date(weekStart.valueOf() + 6*86400000);

var maxdate=((weekEnd-now)/86400000-1);
if(d!=0 && d<6)
maxdate = 6-maxdate;
else
maxdate = 0;

 $("#datepicker").datepicker({
        dateFormat: 'yy-mm-dd',
        showAnim: "slideDown",
        minDate: 0,
        //maxDate: "+3w",
        maxDate: "+3w -"+maxdate+"d",//"+3w -2d",
        beforeShowDay: $.datepicker.noWeekends
    });

<link rel="stylesheet" type="text/css" href="https://cdnjs.cloudflare.com/ajax/libs/jqueryui/1.12.1/jquery-ui.css" media="screen" />
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<script src="https://cdnjs.cloudflare.com/ajax/libs/jqueryui/1.12.1/jquery-ui.js"></script>

<input type="text" id="datepicker"/>


问:
get the data passed in url through get method using rest api
I have integrated rest controller with codeigniter. following is the function for get method

```<code>public function cource_topics_get($res=1) {
    $this->response(array('status' => 1, 'succ_message' =>  $res));
}
</code>```

I want to get the data from following link in the above function
http://localhost/login/index.php/admin/cource_topics?key=value

Help me how to do this

答:
You can normally get it using $this->input->get('key');

```<code>http://localhost/login/index.php/admin/cource_topics?key=value
</code>```

You controller admin and function cource_topics
in your function write

```<code>$value = $this->input->get('key');
</code>```

Body:
I have integrated rest controller with codeigniter. following is the function for get method

public function cource_topics_get($res=1) {
    $this->response(array('status' => 1, 'succ_message' =>  $res));
}

I want to get the data from following link in the above function
http://localhost/login/index.php/admin/cource_topics?key=value

Help me how to do this

Body:
You can normally get it using $this->input->get('key');

http://localhost/login/index.php/admin/cource_topics?key=value

You controller admin and function cource_topics
in your function write

$value = $this->input->get('key');


问:
Notifications in Xcode not coming up
I'm trying to add a notification to my code so that when a button is pressed, a user is saved to a database and a notification pops up saying that the user has been successfully saved to the database. I have checked my code, but it's still not working. No errors are coming up, but neither are any notifications. I'm trying to create a small banner at the top of the screen saying "Customer saved to database".

Here's my code; if you could spot any errors or suggest how to fix it, I would be really grateful!

Using Xcode 8.2.1. and Objective C

in AppDelegate.m:

```<code>-(void)application:(UIApplication *)application     didRegisterUserNotificationSettings:(nonnull UIUserNotificationSettings *)notificationSettings{}
</code>```

in NewCustomerViewController.m:

```<code>@interface NewCustomerViewController(){NSUserDefaults *defaults;}
</code>```

in the viewdidload:

```<code>defaults = [NSUserDefaults standardUserDefaults];
UIUserNotificationType types = UIUserNotificationTypeBadge| UIUserNotificationTypeSound| UIUserNotificationTypeAlert;
UIUserNotificationSettings *mySettings = [UIUserNotificationSettings settingsForTypes:types categories:nil];[[UIApplication sharedApplication] registerUserNotificationSettings:mySettings];
</code>```

and finally, in my IBaction for the button that saves customers:

```<code>[defaults setBool:YES forKey:@"notificationIsActive"];
    [defaults synchronize];
    UILocalNotification* localNotification = [[UILocalNotification alloc] init];
    localNotification.fireDate = 0;
    //Enter the time here in seconds.
    localNotification.alertBody= @"Customer Saved to Database";
    localNotification.timeZone = [NSTimeZone defaultTimeZone];
    //localNotification.repeatInterval= NSCalendarUnitDay;//NSCalendarUnitMinute; //Repeating instructions here.
    localNotification.soundName= UILocalNotificationDefaultSoundName;
    [[UIApplication sharedApplication] scheduleLocalNotification:localNotification];
</code>```

Thanks again!

答:
The way you use to work with Local Notification in iOS 9 and below is completely different in iOS 10.
Below is code for local notification :

Objective-C :

```<code>1. In App-delegate.h file use @import UserNotifications;
2. App-delegate should conform to UNUserNotificationCenterDelegate protocol
3. In didFinishLaunchingOptions use below code :

UNUserNotificationCenter *center = [UNUserNotificationCenter currentNotificationCenter];
[center requestAuthorizationWithOptions:(UNAuthorizationOptionBadge | UNAuthorizationOptionSound | UNAuthorizationOptionAlert)
                          completionHandler:^(BOOL granted, NSError * _Nullable error) {
            if (!error) {
                     NSLog(@"request authorization succeeded!");
                     [self showAlert];
                              }
                          }];

-(void)showAlert {
    UIAlertController *objAlertController = [UIAlertControlleralertControllerWithTitle:@"Alert" message:@"show an alert!"preferredStyle:UIAlertControllerStyleAlert];

    UIAlertAction *cancelAction = [UIAlertAction
                                   actionWithTitle:@"OK"
                                   style:UIAlertActionStyleCancel
                                   handler:^(UIAlertAction *action) {
                                       NSLog(@"Ok clicked!");
                                   }];
    [objAlertController addAction:cancelAction];

    [[[[[UIApplication sharedApplication] windows] objectAtIndex:0] rootViewController] presentViewController:objAlertController animated:YEScompletion:^{

    }];

}
4. Now create a button in any view controller and in IBAction use below code :
UNMutableNotificationContent *objNotificationContent = [[UNMutableNotificationContent alloc] init];
    objNotificationContent.title = [NSStringlocalizedUserNotificationStringForKey:@“Notification!”arguments:nil];
    objNotificationContent.body = [NSStringlocalizedUserNotificationStringForKey:@“This is local notification message!“
                                                         arguments:nil];
    objNotificationContent.sound = [UNNotificationSounddefaultSound];

    /// 4. update application icon badge number
    objNotificationContent.badge = @([[UIApplicationsharedApplication] applicationIconBadgeNumber] + 1);

    // Deliver the notification in five seconds.
    UNTimeIntervalNotificationTrigger *trigger = [UNTimeIntervalNotificationTrigger
                                                  triggerWithTimeInterval:10.f repeats:NO];

    UNNotificationRequest *request = [UNNotificationRequestrequestWithIdentifier:@“ten”
                                                                          content:objNotificationContent trigger:trigger];
    /// 3. schedule localNotification
    UNUserNotificationCenter *center = [UNUserNotificationCentercurrentNotificationCenter];
    [center addNotificationRequest:request withCompletionHandler:^(NSError * _Nullable error) {
        if (!error) {
            NSLog(@“Local Notification succeeded“);
        }
  else {
      NSLog(@“Local Notification failed“);
  }
    }];
</code>```

You can refer apple reference document https://developer.apple.com/reference/usernotifications for UserNotification.

Title: Notifications in Xcode not coming up

Body:
I'm trying to add a notification to my code so that when a button is pressed, a user is saved to a database and a notification pops up saying that the user has been successfully saved to the database. I have checked my code, but it's still not working. No errors are coming up, but neither are any notifications. I'm trying to create a small banner at the top of the screen saying "Customer saved to database".

Here's my code; if you could spot any errors or suggest how to fix it, I would be really grateful!

Using Xcode 8.2.1. and Objective C

in AppDelegate.m:

-(void)application:(UIApplication *)application     didRegisterUserNotificationSettings:(nonnull UIUserNotificationSettings *)notificationSettings{}

in NewCustomerViewController.m:

@interface NewCustomerViewController(){NSUserDefaults *defaults;}

in the viewdidload:

defaults = [NSUserDefaults standardUserDefaults];
UIUserNotificationType types = UIUserNotificationTypeBadge| UIUserNotificationTypeSound| UIUserNotificationTypeAlert;
UIUserNotificationSettings *mySettings = [UIUserNotificationSettings settingsForTypes:types categories:nil];[[UIApplication sharedApplication] registerUserNotificationSettings:mySettings];

and finally, in my IBaction for the button that saves customers:

[defaults setBool:YES forKey:@"notificationIsActive"];
    [defaults synchronize];
    UILocalNotification* localNotification = [[UILocalNotification alloc] init];
    localNotification.fireDate = 0;
    //Enter the time here in seconds.
    localNotification.alertBody= @"Customer Saved to Database";
    localNotification.timeZone = [NSTimeZone defaultTimeZone];
    //localNotification.repeatInterval= NSCalendarUnitDay;//NSCalendarUnitMinute; //Repeating instructions here.
    localNotification.soundName= UILocalNotificationDefaultSoundName;
    [[UIApplication sharedApplication] scheduleLocalNotification:localNotification];

Thanks again!

Body:
The way you use to work with Local Notification in iOS 9 and below is completely different in iOS 10.
Below is code for local notification :

Objective-C :

1. In App-delegate.h file use @import UserNotifications;
2. App-delegate should conform to UNUserNotificationCenterDelegate protocol
3. In didFinishLaunchingOptions use below code :

UNUserNotificationCenter *center = [UNUserNotificationCenter currentNotificationCenter];
[center requestAuthorizationWithOptions:(UNAuthorizationOptionBadge | UNAuthorizationOptionSound | UNAuthorizationOptionAlert)
                          completionHandler:^(BOOL granted, NSError * _Nullable error) {
            if (!error) {
                     NSLog(@"request authorization succeeded!");
                     [self showAlert];
                              }
                          }];

-(void)showAlert {
    UIAlertController *objAlertController = [UIAlertControlleralertControllerWithTitle:@"Alert" message:@"show an alert!"preferredStyle:UIAlertControllerStyleAlert];

    UIAlertAction *cancelAction = [UIAlertAction
                                   actionWithTitle:@"OK"
                                   style:UIAlertActionStyleCancel
                                   handler:^(UIAlertAction *action) {
                                       NSLog(@"Ok clicked!");
                                   }];
    [objAlertController addAction:cancelAction];

    [[[[[UIApplication sharedApplication] windows] objectAtIndex:0] rootViewController] presentViewController:objAlertController animated:YEScompletion:^{

    }];

}
4. Now create a button in any view controller and in IBAction use below code :
UNMutableNotificationContent *objNotificationContent = [[UNMutableNotificationContent alloc] init];
    objNotificationContent.title = [NSStringlocalizedUserNotificationStringForKey:@“Notification!”arguments:nil];
    objNotificationContent.body = [NSStringlocalizedUserNotificationStringForKey:@“This is local notification message!“
                                                         arguments:nil];
    objNotificationContent.sound = [UNNotificationSounddefaultSound];

    /// 4. update application icon badge number
    objNotificationContent.badge = @([[UIApplicationsharedApplication] applicationIconBadgeNumber] + 1);

    // Deliver the notification in five seconds.
    UNTimeIntervalNotificationTrigger *trigger = [UNTimeIntervalNotificationTrigger
                                                  triggerWithTimeInterval:10.f repeats:NO];

    UNNotificationRequest *request = [UNNotificationRequestrequestWithIdentifier:@“ten”
                                                                          content:objNotificationContent trigger:trigger];
    /// 3. schedule localNotification
    UNUserNotificationCenter *center = [UNUserNotificationCentercurrentNotificationCenter];
    [center addNotificationRequest:request withCompletionHandler:^(NSError * _Nullable error) {
        if (!error) {
            NSLog(@“Local Notification succeeded“);
        }
  else {
      NSLog(@“Local Notification failed“);
  }
    }];

You can refer apple reference document https://developer.apple.com/reference/usernotifications for UserNotification.


问:
Sending SMS, MMS messages from mobile device and getting that message to a Java application server
I've been tasked with a project where the customer would like to send SMS, MMS messages from a mobile device.  They would like to have a dedicated phone number to send these messages to.  We would like these messages get routed through a gateway so it can be processed in a Java Application Server and have the server generate a response that will make its way back to the users mobile device.  The server side of this will be done in Java.

I'm new to this and trying to understand the best approach.  Please let me know what services and APIs are available that will allow me to do this.  It seems like there are plenty of services available to get the message from the server to the phone, but I'm not clear on the mechanism for getting the message from the device routed to the Java application server.

Any suggestions are greatly appreciated.

Thanks in advance.

Seth

答: You could get yourself an old Nokia 3210 or something with a data cable and connect it to a server.</p>


问:
Second CSS class not applying to div
I'm attempting to break my html into separate php files and have an error I can't seem to crack. Here is the first file, index.php

.topheader {
  background-color: #404040;
  color: white;
  padding: 16px;
}

.footer {
  background-color: #404040;
  color: white;
  padding: 16px;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><head>
  <link rel="stylesheet" href="./css/main.css">
</head>

<div class="topheader">
  <h1>KivaGIS</h1>
</div>

<div class="footer">
  <h1>Footer</h1>
</div></code>```

As of right now, only .topheader is applying to the html. I understand that both classes are identical, I plan to expand on each once I confirm they are applying individually. Can someone please take a look and advise why .footer wouldn't be applying to the sheet?

Here is a sample of the output on my machine

答:
Seems working for me, .topheader and .footer having different styles

.topheader {
  background-color: #404040;
  color: blue;
  padding: 16px;
}

.footer {
  background-color: #404040;
  color: red;
  padding: 16px;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><head>
  <link rel="stylesheet" href="./css/main.css">
</head>

<div class="topheader">
  <h1>I AM BLUE</h1>
</div>
<br>
<div class="footer">
  <h1>I AM RED</h1>
</div></code>```

Title: Second CSS class not applying to div

Body:
I'm attempting to break my html into separate php files and have an error I can't seem to crack. Here is the first file, index.php

.topheader {
  background-color: #404040;
  color: white;
  padding: 16px;
}

.footer {
  background-color: #404040;
  color: white;
  padding: 16px;
}

  <link rel="stylesheet" href="./css/main.css">

KivaGIS

Footer

As of right now, only .topheader is applying to the html. I understand that both classes are identical, I plan to expand on each once I confirm they are applying individually. Can someone please take a look and advise why .footer wouldn't be applying to the sheet?

Here is a sample of the output on my machine

Body:
Seems working for me, .topheader and .footer having different styles

.topheader {
  background-color: #404040;
  color: blue;
  padding: 16px;
}

.footer {
  background-color: #404040;
  color: red;
  padding: 16px;
}

<head>
  <link rel="stylesheet" href="./css/main.css">
</head>

<div class="topheader">
  <h1>I AM BLUE</h1>
</div>
<br>
<div class="footer">
  <h1>I AM RED</h1>
</div>


问:
How can i set double height to Imageview programmatically?
Image view takes int value programmatically but in some time height calculate in double so any one have suggestion which one procedure. I searched but did not get exact solution

Here is my code:

```<code>//--------calculate width and height
        int final_width;
        double final_height;
        final_width  = width - 40;
        final_height = ((final_width) * (0.75));
        Log.e("final height",""+final_height);
        imageView.getLayoutParams().width  = Utility.pxToDp(final_width,mContext);
        imageView.getLayoutParams().height = Utility.pxToDp(final_height,mContext);
</code>```

答:
Perhaps

```<code>final_height=final_height+final_height
</code>```

Thats what I would do to get a 2x effect on height.

Body:
Image view takes int value programmatically but in some time height calculate in double so any one have suggestion which one procedure. I searched but did not get exact solution

Here is my code:

//--------calculate width and height
        int final_width;
        double final_height;
        final_width  = width - 40;
        final_height = ((final_width) * (0.75));
        Log.e("final height",""+final_height);
        imageView.getLayoutParams().width  = Utility.pxToDp(final_width,mContext);
        imageView.getLayoutParams().height = Utility.pxToDp(final_height,mContext);

Body:
Perhaps

final_height=final_height+final_height

Thats what I would do to get a 2x effect on height.


问:
Android: Are there any benefits to using @id over @+id performance wise?
I know that the + in @+id tells the compiler to add the id to the (R.id.???) resources. However i was wondering if there were performance benefits to be gained by not putting the + ?

Perhaps for example when dealing with complex list view layouts?

答:
That's not the difference. If you use android:id it should always be @+id (I think). That means you're assigning it an ID. Otherwise, as raybritton said, you're referencing an ID.

But also, R is generated even before compile time. Not only would the benefits be minuscule, but they would come at compile time and not at run time so it doesn't matter.


答:
This is Applying to your file, both .topheader and .footer class contain same style. just change the style values, you can see the difference

```<code>.topheader {
  background-color: #404040;
  color: white;
  padding:16px;
 }
.footer {
  background-color: #FFEE00;
  color: Red;
  padding:16px;
 }
</code>```

Title: Second CSS class not applying to div

Body:
This is Applying to your file, both .topheader and .footer class contain same style. just change the style values, you can see the difference

.topheader {
  background-color: #404040;
  color: white;
  padding:16px;
 }
.footer {
  background-color: #FFEE00;
  color: Red;
  padding:16px;
 }


问:
How do you debug a Windows Universal App built with command line?
This is easy for a Win32 app, you just build it with cl.exe and include debugging information, then you can open the .exe in Visual Studio and step through the code. What is the equivalent for a Univeral Windows Platform (UWP) app that is distributed using an .appx?  When I try to open the .exe for it in Visual Studio 2015 (before packaging, or after unpacking the generated .appx) I just get error 0x8007006E, "The system cannot open the device or file specified".</p>

答:
Once your APPX is installed, you can debug it from VS using the following steps:

Debug --> Other Debug Target --> Debug Installed App Package

Select the app you want to debug

Select the type of code you want to debug (managed/native)

Check any of the optional checkboxes (as needed)

Click "Start"

Thanks,

Stefan Wick - Windows Developer Platform