问:
How can I use KNN /K-means to clustering time series in a dataframe
Suppose a dataframe which contains 1000 rows. Each row represents a time series.

Then I built a DTW algorithm to calculate the distance between 2 rows.

I don't know what to do next to complish an unsupervised classification task for the dataframe.

How to label all rows of the dataframe?

答:
Definitions

KNN algorithm = K-nearest-neighbour classification algorithm

K-means = centroid-based clustering algorithm

DTW =  Dynamic Time Warping a similarity-measurement algorithm for time-series

I show below step by step about how the two time-series can be built and how the Dynamic Time Warping (DTW) algorithm can be computed. You can build a unsupervised k-means clustering with scikit-learn without specifying the number of centroids, then the scikit-learn knows to use the algorithm called auto.

Building the time-series and computing the DTW

You have have two time-series and you compute the DTW such that

```<code>import pandas as pd
import numpy as np
import random
from dtw import dtw
from matplotlib.pyplot import plot
from matplotlib.pyplot import imshow
from matplotlib.pyplot import cm

from sklearn.cluster import KMeans
from sklearn.preprocessing import MultiLabelBinarizer
#About classification, read the tutorial
#http://scikit-learn.org/stable/tutorial/basic/tutorial.html

def createTs(myStart, myLength):
    index = pd.date_range(myStart, periods=myLength, freq='H');
    values= [random.random() for _ in range(myLength)];
    series = pd.Series(values, index=index);
    return(series)

#Time series of length 30, start from 1/1/2000 & 1/2/2000 so overlap
myStart='1/1/2000'
myLength=30
timeS1=createTs(myStart, myLength)
myStart='1/2/2000'
timeS2=createTs(myStart, myLength)

#This could be your dataframe but unnecessary here
#myDF = pd.DataFrame([x for x in timeS1.data], [x for x in timeS2.data])#, columns=['data1', 'data2'])

x=[xxx*100 for xxx in sorted(timeS1.data)]
y=[xx for xx in timeS2.data]

choice="dtw"

if (choice="timeseries"):
    print(timeS1)
    print(timeS2)
if (choice=="drawingPlots"):
    plot(x)
    plot(y)
if (choice=="dtw"):
    #DTW with the 1st order norm
    myDiff=[xx-yy for xx,yy in zip(x,y)]
    dist, cost, acc, path = dtw(x, y, dist=lambda x, y: np.linalg.norm(myDiff, ord=1))
    imshow(acc.T, origin='lower', cmap=cm.gray, interpolation='nearest')
    plot(path[0], path[1], 'w')
</code>```

Classification of the time-series with KNN

It is not evident in the question about what should be labelled and with which labels? So please provide the following details

What should we label in the data-frame? The path computed by DTW algorithm?

Which type of labeling? Binary? Multiclass?

after which we can decide our classification algorithm that may be the so-called KNN algorithm. It works such that you have two separate data sets: training set and test set. By training set, you teach the algorithm to label the time series while the test set is a tool by which we can measure about how well the model works with model selection tools such as AUC.

Small puzzle left open until details provided about the questions

```<code>#PUZZLE
#from tutorial (#http://scikit-learn.org/stable/tutorial/basic/tutorial.html)
newX = [[1, 2], [2, 4], [4, 5], [3, 2], [3, 1]]
newY = [[0, 1], [0, 2], [1, 3], [0, 2, 3], [2, 4]]
newY = MultiLabelBinarizer().fit_transform(newY)
#Continue to the article.
</code>```

Scikit-learn comparison article about classifiers is provided in the second enumerate item below.

Clustering with K-means (not the same as KNN)

K-means is the clustering algorithm and its unsupervised version you can use such that

```<code>#Unsupervised version "auto" of the KMeans as no assignment for the n_clusters
myClusters=KMeans(path)
#myClusters.fit(YourDataHere)
</code>```

which is very different algorithm than the KNN algorithm: here we do not need any labels. I provide you further material on the topic below in the first enumerate item.

Further reading

Does K-means incorporate the K-nearest-neighbour algorithm?

Comparison about classifiers in scikit learn here

Body:
Definitions

KNN algorithm = K-nearest-neighbour classification algorithm

K-means = centroid-based clustering algorithm

DTW =  Dynamic Time Warping a similarity-measurement algorithm for time-series

I show below step by step about how the two time-series can be built and how the Dynamic Time Warping (DTW) algorithm can be computed. You can build a unsupervised k-means clustering with scikit-learn without specifying the number of centroids, then the scikit-learn knows to use the algorithm called auto.

Building the time-series and computing the DTW

You have have two time-series and you compute the DTW such that

import pandas as pd
import numpy as np
import random
from dtw import dtw
from matplotlib.pyplot import plot
from matplotlib.pyplot import imshow
from matplotlib.pyplot import cm

from sklearn.cluster import KMeans
from sklearn.preprocessing import MultiLabelBinarizer
#About classification, read the tutorial
#http://scikit-learn.org/stable/tutorial/basic/tutorial.html

def createTs(myStart, myLength):
    index = pd.date_range(myStart, periods=myLength, freq='H');
    values= [random.random() for _ in range(myLength)];
    series = pd.Series(values, index=index);
    return(series)

#Time series of length 30, start from 1/1/2000 & 1/2/2000 so overlap
myStart='1/1/2000'
myLength=30
timeS1=createTs(myStart, myLength)
myStart='1/2/2000'
timeS2=createTs(myStart, myLength)

#This could be your dataframe but unnecessary here
#myDF = pd.DataFrame([x for x in timeS1.data], [x for x in timeS2.data])#, columns=['data1', 'data2'])

x=[xxx*100 for xxx in sorted(timeS1.data)]
y=[xx for xx in timeS2.data]

choice="dtw"

if (choice="timeseries"):
    print(timeS1)
    print(timeS2)
if (choice=="drawingPlots"):
    plot(x)
    plot(y)
if (choice=="dtw"):
    #DTW with the 1st order norm
    myDiff=[xx-yy for xx,yy in zip(x,y)]
    dist, cost, acc, path = dtw(x, y, dist=lambda x, y: np.linalg.norm(myDiff, ord=1))
    imshow(acc.T, origin='lower', cmap=cm.gray, interpolation='nearest')
    plot(path[0], path[1], 'w')

Classification of the time-series with KNN

It is not evident in the question about what should be labelled and with which labels? So please provide the following details

What should we label in the data-frame? The path computed by DTW algorithm?

Which type of labeling? Binary? Multiclass?

after which we can decide our classification algorithm that may be the so-called KNN algorithm. It works such that you have two separate data sets: training set and test set. By training set, you teach the algorithm to label the time series while the test set is a tool by which we can measure about how well the model works with model selection tools such as AUC.

Small puzzle left open until details provided about the questions

#PUZZLE
#from tutorial (#http://scikit-learn.org/stable/tutorial/basic/tutorial.html)
newX = [[1, 2], [2, 4], [4, 5], [3, 2], [3, 1]]
newY = [[0, 1], [0, 2], [1, 3], [0, 2, 3], [2, 4]]
newY = MultiLabelBinarizer().fit_transform(newY)
#Continue to the article.

Scikit-learn comparison article about classifiers is provided in the second enumerate item below.

Clustering with K-means (not the same as KNN)

K-means is the clustering algorithm and its unsupervised version you can use such that

#Unsupervised version "auto" of the KMeans as no assignment for the n_clusters
myClusters=KMeans(path)
#myClusters.fit(YourDataHere)

which is very different algorithm than the KNN algorithm: here we do not need any labels. I provide you further material on the topic below in the first enumerate item.

Further reading

Does K-means incorporate the K-nearest-neighbour algorithm?

Comparison about classifiers in scikit learn here


来源: stackexchange

问:
What is the time complexity of the following code snippet?
I have written the following code snippet to find the range summaries, i.e., when given a sorted integer array without any duplicates, it returns the summaries as:

```<code>/* IP: [0,1,2,4,5,7]
 * OP: ["0->2","4->5","7"]
 */

class Solution {
public:
    vector<string> summaryRanges(vector<int>& nums) {
        vector<string> res;

        if(nums.empty())
            return res;

        for(int i=0; i<nums.size(); i++) {
            int lowerRange=nums[i];

            while(((i+1)<nums.size()) && (nums[i+1]-nums[i]==1))
                i++;

            int higherRange=nums[i];

            if(lowerRange!=higherRange) {
                string str=to_string(lowerRange)+"->"+to_string(higherRange);
                res.push_back(str);
            } else
                res.push_back(to_string(lowerRange));
        }

        return res;
    }
};
</code>```

I am wondering about the time complexity of the above code snippet.  In my opinion, I am doing some "task" (execution of the inner while loop) for each element in the array (using the outer for loop).  Due to this, in the worst case, the complexity should be O(n^2) in my opinion.  On the other hand, I am doubtful because I do i++ in the inner while loop, due to which, I won't do the "task" on all the elements using the outer for loop.  Due to this increment, I am visiting all the elements only once in my entire code.  So, this should make the complexity O(n).  Could someone please confirm if the complexity is O(n^2) or O(n)?

答:
Since the inner loop advances the same iteration variable as the outer loop, any elements accessed by the inner loop are skipped by the outer loop. Together they just access each element once. So that makes it O(n).

In terms of time-complexity, it's like a loop with an if statement in it:

```<code>for (i = 0; i < nums.size(); i++) {
    if ((i+1)<nums.size()) && (nums[i+1]-nums[i]==1)) {
        //
    } else {
        //
    }
}
</code>```

Writing it this way would require different logic to determine when to update lowerRange and higherRange.

ContentLicense: CC BY-SA 3.0

Body:
I have written the following code snippet to find the range summaries, i.e., when given a sorted integer array without any duplicates, it returns the summaries as:

/* IP: [0,1,2,4,5,7]
 * OP: ["0->2","4->5","7"]
 */

class Solution {
public:
    vector<string> summaryRanges(vector<int>& nums) {
        vector<string> res;

        if(nums.empty())
            return res;

        for(int i=0; i<nums.size(); i++) {
            int lowerRange=nums[i];

            while(((i+1)<nums.size()) && (nums[i+1]-nums[i]==1))
                i++;

            int higherRange=nums[i];

            if(lowerRange!=higherRange) {
                string str=to_string(lowerRange)+"->"+to_string(higherRange);
                res.push_back(str);
            } else
                res.push_back(to_string(lowerRange));
        }

        return res;
    }
};

I am wondering about the time complexity of the above code snippet.  In my opinion, I am doing some "task" (execution of the inner while loop) for each element in the array (using the outer for loop).  Due to this, in the worst case, the complexity should be O(n^2) in my opinion.  On the other hand, I am doubtful because I do i++ in the inner while loop, due to which, I won't do the "task" on all the elements using the outer for loop.  Due to this increment, I am visiting all the elements only once in my entire code.  So, this should make the complexity O(n).  Could someone please confirm if the complexity is O(n^2) or O(n)?

Body:
Since the inner loop advances the same iteration variable as the outer loop, any elements accessed by the inner loop are skipped by the outer loop. Together they just access each element once. So that makes it O(n).

In terms of time-complexity, it's like a loop with an if statement in it:

for (i = 0; i < nums.size(); i++) {
    if ((i+1)<nums.size()) && (nums[i+1]-nums[i]==1)) {
        //
    } else {
        //
    }
}

Writing it this way would require different logic to determine when to update lowerRange and higherRange.


问:
JavaMail, IMAP, performance with large number of folders
We are developing a java based mail client for IMAP accounts and use latest java mail api (1.5.6). Our customers have mail accounts with more than 400 folders. Users perform check mails on folders and iterating on each folder and getting new messages for example,

```<code>folder.getMessagesByUid(lastStoredUID, UIDFolder.LastUID)
</code>```

or getting count of unread messages takes too much time beacuse huge number of folders. (We have to iterate on 400 folders)

To increase the performance we used paralel working connections in threads and we have a single SESSION instance but each thread(connection) has its own STORE instance. When we have to fetch new messages, we generate 10 threads with their STORE instances on the fly, connect/login them separately, get folder instance on that STORE, open folder, perform folder operations, close the folder and close the SESSION afterwards. But for me its not clear, whether I have to keep the folders intances and also I it is not clear  whether the folders should be kept opened or should we explicity close aftwerwards or we may leave all opened (leave the close operation to mailserver).

In my current implementation,

```<code>new Thread() {
    public void run() {
        //Get a new store instance
        Store tempStore = MySingleSession.getStore("imap");
        tempStore.connect(..);

        //Get a folder for example inbox
        Folder inbox = tempStore.get("INBOX");

        inbox.open(Folder.READ);

        // Perform get new messages
        inbox.getMessagesByUd(lastUID, UIDFolder.MaxUID);

        inbox.close();

        tempStore.close();
        ..
</code>```

When checked the performance, I see that opening/closing folders takes a long time especially on folders with more than 100.000 messages. And I see that even if I close the store of a folder, folder remains opened and we can operate on it if we do not explicitly close that folder. What are the disadvantages for a such mechanism if I change my implementation and do not close the folder explicitly and keep them open?

Keep the folder references in a hashtable keyed by their fullname, for example
"INBOX" -> IMAPFolder and perform isOpened check before any operation (getMessages), but when finished, do not close explicitly as in my current implementation. When doing like that we may have 400 folders opened, it may seem bad for mail server and mail server close them, but I will check for each folder opeation first, if it is opened or not. As a result folders will be kept opened as possible (until mailserver closes connection) and if the same folder is needed again we do not have to open it again.

I do not understand, why I can still operate on a folder which has its store closed?

Default value for mail.imap.connectionpoolsize is 1, does it help to increase this value in this case?

And I do not understand what happens with this scenario below?

```<code>Store tempStore = MySingleSession.getStore("imap");

tempStore.connect(..);

Folder f = tempStore.getFolder("INBOX");

f.open(Folder.READ_ONLY);

// close the store!!!
tempStore.close();

// now folder f becomes closed,
// but we may open it again even if its Store is disconnected!

f.open(Folder.READ_ONLY);

// we can continue operating on folder f
</code>```

Which is better approach, keep folder references in an hastable keyed by fullname or perform tempStore.getFolder(foldername) each time? For example we have to handle INBOX, first option use

IMAPFolder f = folderCache.get("INBOX"); // suppose already put in hashtable folderCache

or

IMAPFolder f = tempStore.getFolder("INBOX");

I generate the Store instances on demand and close them afterwards in order not to use huge resources on the mail server. But opening the folder again and not closing manually is not a good approach beacuse it uses still resource? or using that way is acceptable because mailserver may close it when needed and we have just to check whether

if the folder is already opened continue operating,

if the folder is closed perform open first, then operate, keep opened for further usage?

答:
Way too many questions for one post.  Let me try to answer a few of them...

After you close a Folder, you shouldn't use any Message objects from the Folder, so only close the Folder when you're done using its Messages.

If a single user has 400 folders, you can use a single Store connection since each open Folder will get its own connection.

If you open and close Folders frequently, increasing the connection pool size can help since the connection for a closed Folder will be added to the pool and reused when you open a new Folder, without needing to create a new connection.

Closing the Store should close all the Folders for that Store, but there's an inherent race condition if multiple threads are involved.  Closing the Store is a way to clean up all the connections when you're done using it, not a way to prevent other threads from re-opening Folders.

Caching Folder objects for closed Folders is not likely to be a big advantage over calling getFolder each time.

Body:
We are developing a java based mail client for IMAP accounts and use latest java mail api (1.5.6). Our customers have mail accounts with more than 400 folders. Users perform check mails on folders and iterating on each folder and getting new messages for example,

folder.getMessagesByUid(lastStoredUID, UIDFolder.LastUID)

or getting count of unread messages takes too much time beacuse huge number of folders. (We have to iterate on 400 folders)

To increase the performance we used paralel working connections in threads and we have a single SESSION instance but each thread(connection) has its own STORE instance. When we have to fetch new messages, we generate 10 threads with their STORE instances on the fly, connect/login them separately, get folder instance on that STORE, open folder, perform folder operations, close the folder and close the SESSION afterwards. But for me its not clear, whether I have to keep the folders intances and also I it is not clear  whether the folders should be kept opened or should we explicity close aftwerwards or we may leave all opened (leave the close operation to mailserver).

In my current implementation,

new Thread() {
    public void run() {
        //Get a new store instance
        Store tempStore = MySingleSession.getStore("imap");
        tempStore.connect(..);

        //Get a folder for example inbox
        Folder inbox = tempStore.get("INBOX");

        inbox.open(Folder.READ);

        // Perform get new messages
        inbox.getMessagesByUd(lastUID, UIDFolder.MaxUID);

        inbox.close();

        tempStore.close();
        ..

When checked the performance, I see that opening/closing folders takes a long time especially on folders with more than 100.000 messages. And I see that even if I close the store of a folder, folder remains opened and we can operate on it if we do not explicitly close that folder. What are the disadvantages for a such mechanism if I change my implementation and do not close the folder explicitly and keep them open?

Keep the folder references in a hashtable keyed by their fullname, for example
"INBOX" -> IMAPFolder and perform isOpened check before any operation (getMessages), but when finished, do not close explicitly as in my current implementation. When doing like that we may have 400 folders opened, it may seem bad for mail server and mail server close them, but I will check for each folder opeation first, if it is opened or not. As a result folders will be kept opened as possible (until mailserver closes connection) and if the same folder is needed again we do not have to open it again.

I do not understand, why I can still operate on a folder which has its store closed?

Default value for mail.imap.connectionpoolsize is 1, does it help to increase this value in this case?

And I do not understand what happens with this scenario below?

Store tempStore = MySingleSession.getStore("imap");

tempStore.connect(..);

Folder f = tempStore.getFolder("INBOX");

f.open(Folder.READ_ONLY);

// close the store!!!
tempStore.close();

// now folder f becomes closed,
// but we may open it again even if its Store is disconnected!

f.open(Folder.READ_ONLY);

// we can continue operating on folder f

Which is better approach, keep folder references in an hastable keyed by fullname or perform tempStore.getFolder(foldername) each time? For example we have to handle INBOX, first option use

IMAPFolder f = folderCache.get("INBOX"); // suppose already put in hashtable folderCache

or

IMAPFolder f = tempStore.getFolder("INBOX");

I generate the Store instances on demand and close them afterwards in order not to use huge resources on the mail server. But opening the folder again and not closing manually is not a good approach beacuse it uses still resource? or using that way is acceptable because mailserver may close it when needed and we have just to check whether

if the folder is already opened continue operating,

if the folder is closed perform open first, then operate, keep opened for further usage?


问:
Can't retrieve Id from the database
I can't retrieve the ID from my database when I try to access it :

This is my database:

This is my event controller class:

```<code><?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\Event3;
class EventsController extends Controller
{
    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function index()
    {
        $data = Event3::get(['title','start','end','color']);

       return Response()->json($data);
    }

    /**
     * Show the form for creating a new resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function create()
    {
        //
    }

    /**
     * Store a newly created resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return \Illuminate\Http\Response
     */
    public function store(Request $request)
    {
       $event = new Event3();
        $event->id = $request->id;
       $event->title = $request->title;
       $event->start = $request->date_start .' '. $request->time_start;
        $event->end = $request->date_end;
       $event->color = $request->color;
        $event->save();

        return redirect('/');
    }

    /**
     * Display the specified resource.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function show($id)
    {
        //
    }

    /**
     * Show the form for editing the specified resource.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function edit($id)
    {
        //
    }

    /**
     * Update the specified resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function update(Request $request, $id)
    {
        //
    }

    /**
     * Remove the specified resource from storage.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function destroy($id)
    {
        //
    }
}
</code>```

I have tried adding the following:

$event->id= $request->id; into the above class but that didn't help .

Event3

```<code>namespace App;

use Illuminate\Database\Eloquent\Model;

class Event3 extends Model
{
    /**
     * @var string
     * [$table description]
     * @var string
     */

    protected $table = 'event3s';

    public $timestamps = false;

    /**
     * @var string
     * [$table description]
     * @var string
     */
    protected $filltable =[
        'title','start','end','color'

    ];
}
</code>```

答:
Found the mistake ,really simple one :
In the controller class forgot to add id :

```<code> public function index()
    {
        $data = Event::get(['id', 'title', 'start', 'end', 'color']);
        return Response()->json($data);
    }
</code>```

Title: Can't retrieve Id from the database

Body:
I can't retrieve the ID from my database when I try to access it :

This is my database:

This is my event controller class:

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\Event3;
class EventsController extends Controller
{
    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function index()
    {
        $data = Event3::get(['title','start','end','color']);

       return Response()->json($data);
    }

    /**
     * Show the form for creating a new resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function create()
    {
        //
    }

    /**
     * Store a newly created resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return \Illuminate\Http\Response
     */
    public function store(Request $request)
    {
       $event = new Event3();
        $event->id = $request->id;
       $event->title = $request->title;
       $event->start = $request->date_start .' '. $request->time_start;
        $event->end = $request->date_end;
       $event->color = $request->color;
        $event->save();

        return redirect('/');
    }

    /**
     * Display the specified resource.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function show($id)
    {
        //
    }

    /**
     * Show the form for editing the specified resource.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function edit($id)
    {
        //
    }

    /**
     * Update the specified resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function update(Request $request, $id)
    {
        //
    }

    /**
     * Remove the specified resource from storage.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function destroy($id)
    {
        //
    }
}

I have tried adding the following:

$event->id= $request->id; into the above class but that didn't help .

Event3

namespace App;

use Illuminate\Database\Eloquent\Model;

class Event3 extends Model
{
    /**
     * @var string
     * [$table description]
     * @var string
     */

    protected $table = 'event3s';

    public $timestamps = false;

    /**
     * @var string
     * [$table description]
     * @var string
     */
    protected $filltable =[
        'title','start','end','color'

    ];
}

Body:
Found the mistake ,really simple one :
In the controller class forgot to add id :

 public function index()
    {
        $data = Event::get(['id', 'title', 'start', 'end', 'color']);
        return Response()->json($data);
    }


问:
Lua - calculating if a time is between two time stamps
Given the following examples:

```<code>--Test current     start     end     between
--1    10:00       09:00     12:00   true
--2    01:00       07:34     09:54   false
--3    17:00       16:00     03:00   true
--4    10:00       10:00     15:00   true
--5    10:30       10:00     10:30   true
</code>```

In Lua, how is it best to create a function that I can call:

```<code>BetweenTimes ("10:00", "09:00","12:00")
</code>```

and in this case (Test 1) return true.  The issue I have is will Test case 3.

I can assume that the first time is always before the second time.

I think this might be it:

```<code>local function parse_time(str)
   local hour, min = str:match("(%d+):(%d+)")
   return os.time{hour = hour, min = min, day = 1, month = 1, year = 1970}
end

local function BetweenTimes(between, start, stop)
   between = parse_time(between)
   start   = parse_time(start)
   stop    = parse_time(stop)

   if stop < start then
      return (start <= between) or (between <= stop)
   else
      return (start <= between) and (between <= stop)
   end
end

print(BetweenTimes("10:00", "09:00", "12:00")) -- true
print(BetweenTimes("15:00", "09:00", "12:00")) -- false
print(BetweenTimes("15:00", "09:00", "01:00")) -- true
print(BetweenTimes("10:00", "10:00", "11:00")) -- true
print(BetweenTimes("11:00", "10:00", "11:00")) -- true
print(BetweenTimes("19:00", "17:00", "03:30")) -- true
print(BetweenTimes("03:00", "04:00", "05:30")) -- false
print(BetweenTimes("03:00", "02:00", "05:30")) -- true
print(BetweenTimes("01:00", "09:00", "02:30")) -- true
</code>```

or even just the following should work to remove os.time():

```<code>local function BetweenTimes(between, start, stop)
   local start   = string.gsub(start,":", "")
   local between = string.gsub(between,":", "")
   local stop    = string.gsub(stop,":", "")

   if stop < start then
      return (start <= between) or (between <= stop)
   else
      return (start <= between) and (between <= stop)
   end
end
</code>```

答:
Your approach sounds overly complicated.  Just parse the hours and minutes out of the string and convert it to a UNIX timestamp.  These are regular integers and you can easily compare them using < and >.

```<code>local function parse_time(str)
   local hour, min = str:match("(%d+):(%d+)")
   return os.time{hour = hour, min = min, day = 1, month = 1, year = 1970}
end

local function BetweenTimes(between, start, stop)
   between = parse_time(between)
   start   = parse_time(start)
   stop    = parse_time(stop)
   if stop < start then
      stop = stop + 24*60*60 -- add 24 h
   end
   return (start <= between) and (between <= stop)
end

print(BetweenTimes("10:00", "09:00", "12:00")) -- true
print(BetweenTimes("15:00", "09:00", "12:00")) -- false
print(BetweenTimes("15:00", "09:00", "01:00")) -- true
</code>```

Body:
Given the following examples:

--Test current     start     end     between
--1    10:00       09:00     12:00   true
--2    01:00       07:34     09:54   false
--3    17:00       16:00     03:00   true
--4    10:00       10:00     15:00   true
--5    10:30       10:00     10:30   true

In Lua, how is it best to create a function that I can call:

BetweenTimes ("10:00", "09:00","12:00")

and in this case (Test 1) return true.  The issue I have is will Test case 3.

I can assume that the first time is always before the second time.

I think this might be it:

local function parse_time(str)
   local hour, min = str:match("(%d+):(%d+)")
   return os.time{hour = hour, min = min, day = 1, month = 1, year = 1970}
end

local function BetweenTimes(between, start, stop)
   between = parse_time(between)
   start   = parse_time(start)
   stop    = parse_time(stop)

   if stop < start then
      return (start <= between) or (between <= stop)
   else
      return (start <= between) and (between <= stop)
   end
end

print(BetweenTimes("10:00", "09:00", "12:00")) -- true
print(BetweenTimes("15:00", "09:00", "12:00")) -- false
print(BetweenTimes("15:00", "09:00", "01:00")) -- true
print(BetweenTimes("10:00", "10:00", "11:00")) -- true
print(BetweenTimes("11:00", "10:00", "11:00")) -- true
print(BetweenTimes("19:00", "17:00", "03:30")) -- true
print(BetweenTimes("03:00", "04:00", "05:30")) -- false
print(BetweenTimes("03:00", "02:00", "05:30")) -- true
print(BetweenTimes("01:00", "09:00", "02:30")) -- true

or even just the following should work to remove os.time():

local function BetweenTimes(between, start, stop)
   local start   = string.gsub(start,":", "")
   local between = string.gsub(between,":", "")
   local stop    = string.gsub(stop,":", "")

   if stop < start then
      return (start <= between) or (between <= stop)
   else
      return (start <= between) and (between <= stop)
   end
end

Body:
Your approach sounds overly complicated.  Just parse the hours and minutes out of the string and convert it to a UNIX timestamp.  These are regular integers and you can easily compare them using < and >.

local function parse_time(str)
   local hour, min = str:match("(%d+):(%d+)")
   return os.time{hour = hour, min = min, day = 1, month = 1, year = 1970}
end

local function BetweenTimes(between, start, stop)
   between = parse_time(between)
   start   = parse_time(start)
   stop    = parse_time(stop)
   if stop < start then
      stop = stop + 24*60*60 -- add 24 h
   end
   return (start <= between) and (between <= stop)
end

print(BetweenTimes("10:00", "09:00", "12:00")) -- true
print(BetweenTimes("15:00", "09:00", "12:00")) -- false
print(BetweenTimes("15:00", "09:00", "01:00")) -- true


问:
How to draw a multi stack, many to many relationship diagram, something like in the attached picture, using JavaScript?

I want to draw a relationship diagram (something like in the above picture) using JavaScript. I have tried many js libraries like D3, GoJs, JsPlumb, etc, but nothing has worked out for my requirement. Please find below the additional requirements.

The boxes (e.g Business Architecture > Process > Resolve Complaint) may have up to four inner levels.

Any box can be connected (internal - with-in the group and external - with the nodes in the other groups) with any box(s)

Relationship can be uni and bi directional (one side arrow and double side arrow) and should have relationship type (e.g process).

Every box (in all levels) should have four clickable hot-spots

Can be saved as template for future modification

Data feed is JSON

答:
This solution is created in GoJS.

Here's the result.  Sorry, I didn't feel up to entering all of the data from your screenshot, so I only did the top two groups.  And I didn't bother styling stuff nicely, either.

And here's the complete page, including the diagram's model data in JSON format:

```<code><!DOCTYPE html>
<html>
<head>
<title>Simple Nested Relationships in GoJS</title>
<!-- Copyright 1998-2017 by Northwoods Software Corporation. -->
<meta charset="UTF-8">
<script src="go.js"></script>
<script id="code">
  function init() {
    var $ = go.GraphObject.make;

    myDiagram =
      $(go.Diagram, "myDiagramDiv",
        {
          initialContentAlignment: go.Spot.Center,
          "undoManager.isEnabled": true
        });

    function makePort(id, spot) {
      return $(go.Shape,
        {
          fill: "transparent", strokeWidth: 0,
          width: 10, height: 10,
          alignment: spot, alignmentFocus: spot,
          portId: id,
          fromLinkable: true, toLinkable: true, cursor: "pointer"
        });
    }

    myDiagram.nodeTemplate =
      $(go.Node, "Spot",
        new go.Binding("location", "loc", go.Point.parse).makeTwoWay(go.Point.stringify),
        $(go.Panel, "Auto",
          $(go.Shape, "RoundedRectangle",
            { fill: "white" },
            new go.Binding("fill", "color"),
            new go.Binding("figure"),
            new go.Binding("angle", "figure", function(f) { return f === "Hexagon" ? 90 : 0; })),
          $(go.TextBlock,
            { margin: 4, editable: true, maxSize: new go.Size(150, NaN), textAlign: "center" },
            new go.Binding("text").makeTwoWay())
        ),
        makePort("T", go.Spot.Top),
        makePort("R", go.Spot.Right),
        makePort("B", go.Spot.Bottom),
        makePort("L", go.Spot.Left)
      );

    myDiagram.groupTemplate =
      $(go.Group, "Spot",
        new go.Binding("location", "loc", go.Point.parse).makeTwoWay(go.Point.stringify),
        $(go.Panel, "Auto",
          $(go.Shape,
            { fill: "whitesmoke" },
            new go.Binding("fill", "color"),
            new go.Binding("stroke", "color", go.Brush.darken)),
          $(go.Panel, "Vertical",
            $(go.TextBlock,
              { margin: 4, editable: true },
              new go.Binding("text").makeTwoWay()),
            $(go.Placeholder, { padding: 10 })
          )
        ),
        makePort("T", go.Spot.Top),
        makePort("R", go.Spot.Right),
        makePort("B", go.Spot.Bottom),
        makePort("L", go.Spot.Left)
      );

    myDiagram.linkTemplate =
      $(go.Link,
        $(go.Shape, { strokeWidth: 2 }),
        $(go.Shape, { fromArrow: "Standard", visible: false },
          new go.Binding("visible", "from")),
        $(go.Shape, { toArrow: "Standard" }),
        $(go.TextBlock,
          { font: "11px sans-serif", editable: true },
          new go.Binding("text").makeTwoWay())
      );

    myDiagram.model = go.Model.fromJson(
      '{ "class": "go.GraphLinksModel",\
        "linkFromPortIdProperty": "fp",\
        "linkToPortIdProperty": "tp",\
        "nodeDataArray": [\
          { "key": 1, "text": "Strategic Planning", "color": "lightgreen", "isGroup": true, "loc": "10.5 22" },\
          { "key": 11, "text": "Business Policy", "color": "rgba(182, 255, 180, 1)", "isGroup": true, "group": 1, "loc": "21 116" },\
          { "key": 111, "text": "Adhere to FSA Guidelines", "color": "lightgreen", "figure": "Hexagon", "group": 11, "loc": "31 126" },\
          { "key": 12, "text": "Strategy", "color": "rgba(182, 255, 180, 1)", "isGroup": true, "group": 1, "loc": "162 55" },\
          { "key": 121, "text": "Adopt Customer\\nComplaints Process", "color": "lightskyblue", "group": 12, "loc": "172 65" },\
          { "key": 122, "text": "Mission and\\nVision", "color": "plum", "group": 12, "loc": "274 136" },\
          { "key": 123, "text": "Improve Customer Satisfaction", "color": "lightskyblue", "group": 12, "loc": "177 206" },\
          { "key": 124, "text": "Decisions made wlil Maximize Benefit to the Enterprise", "color": "lightskyblue", "group": 12, "loc": "304 203" },\
          { "key": 2, "text": "Business Architecture", "color": "silver", "isGroup": true, "loc": "503 21" },\
          { "key": 21, "text": "Process", "color": "lightgray", "isGroup": true, "group": 2, "loc": "514 54" },\
          { "key": 211, "text": "Complaints\\n Handling", "color": "lightgreen", "figure":"Hexagon", "group": 21, "loc": "546 35" },\
          { "key": 212, "text": "Resolve \\nComplaint", "color": "lightskyblue", "group": 21, "loc": "679 64" },\
          { "key": 213, "text": "Complaints\\n Handling", "color": "lightskyblue", "group": 21, "loc": "550 145" },\
          { "key": 22, "text": "Organization", "color": "lightgray", "isGroup": true, "group": 2, "loc": "842 55" },\
          { "key": 221, "text": "Complaints \\nCall Handler", "color": "lightskyblue", "group": 22, "loc": "852 65.6" },\
          { "key": -18, "text": "Complaints \\nClient", "color": "lightskyblue", "group": 22, "loc": "854 142" },\
          { "key": -19, "text": "Complaints \\nManager", "color": "lightskyblue", "group": 22, "loc": "852 225" },\
          { "key": 23, "text": "Business Service", "color": "lightgray", "isGroup": true, "group": 2, "loc": "514 217" },\
          { "key": 231, "text": "Manage \\nComplaints", "color": "lightskyblue", "group": 23, "loc": "550 247" }\
        ],\
          "linkDataArray": [\
            { "from": 111, "to": 123, "fp": "R", "tp": "L" },\
            { "from": 121, "to": 123, "fp": "B", "tp": "T", "text": "Process" },\
            { "from": 121, "to": 122, "fp": "B", "tp": "T", "text": "Process" },\
            { "from": 121, "to": 211, "fp": "R", "tp": "L", "text": "Process" },\
            { "from": 121, "to": 231, "fp": "R", "tp": "L", "text": "Process" },\
            { "from": 211, "to": 213, "fp": "B", "tp": "T", "text": "Process type:\\nProcess" },\
            { "from": 231, "to": 213, "fp": "T", "tp": "B", "text": "Process" },\
            { "from": 231, "to": 212, "fp": "T", "tp": "B" },\
            { "from": 212, "to": -19, "fp": "B", "tp": "L", "text": "Process" },\
            { "from": 212, "to": -18, "fp": "B", "tp": "L", "text": "Process" },\
            { "from": 212, "to": 221, "fp": "R", "tp": "L", "text": "Process" }\
          ]\
      }'
    );
  }
</script>
</head>
<body onload="init()">
  <div id="myDiagramDiv" style="border: solid 1px black; width:100%; height:600px"></div>
</body>
</html>
</code>```

Body:
This solution is created in GoJS.

Here's the result.  Sorry, I didn't feel up to entering all of the data from your screenshot, so I only did the top two groups.  And I didn't bother styling stuff nicely, either.

And here's the complete page, including the diagram's model data in JSON format:

<!DOCTYPE html>
<html>
<head>
<title>Simple Nested Relationships in GoJS</title>
<!-- Copyright 1998-2017 by Northwoods Software Corporation. -->
<meta charset="UTF-8">
<script src="go.js"></script>
<script id="code">
  function init() {
    var $ = go.GraphObject.make;

    myDiagram =
      $(go.Diagram, "myDiagramDiv",
        {
          initialContentAlignment: go.Spot.Center,
          "undoManager.isEnabled": true
        });

    function makePort(id, spot) {
      return $(go.Shape,
        {
          fill: "transparent", strokeWidth: 0,
          width: 10, height: 10,
          alignment: spot, alignmentFocus: spot,
          portId: id,
          fromLinkable: true, toLinkable: true, cursor: "pointer"
        });
    }

    myDiagram.nodeTemplate =
      $(go.Node, "Spot",
        new go.Binding("location", "loc", go.Point.parse).makeTwoWay(go.Point.stringify),
        $(go.Panel, "Auto",
          $(go.Shape, "RoundedRectangle",
            { fill: "white" },
            new go.Binding("fill", "color"),
            new go.Binding("figure"),
            new go.Binding("angle", "figure", function(f) { return f === "Hexagon" ? 90 : 0; })),
          $(go.TextBlock,
            { margin: 4, editable: true, maxSize: new go.Size(150, NaN), textAlign: "center" },
            new go.Binding("text").makeTwoWay())
        ),
        makePort("T", go.Spot.Top),
        makePort("R", go.Spot.Right),
        makePort("B", go.Spot.Bottom),
        makePort("L", go.Spot.Left)
      );

    myDiagram.groupTemplate =
      $(go.Group, "Spot",
        new go.Binding("location", "loc", go.Point.parse).makeTwoWay(go.Point.stringify),
        $(go.Panel, "Auto",
          $(go.Shape,
            { fill: "whitesmoke" },
            new go.Binding("fill", "color"),
            new go.Binding("stroke", "color", go.Brush.darken)),
          $(go.Panel, "Vertical",
            $(go.TextBlock,
              { margin: 4, editable: true },
              new go.Binding("text").makeTwoWay()),
            $(go.Placeholder, { padding: 10 })
          )
        ),
        makePort("T", go.Spot.Top),
        makePort("R", go.Spot.Right),
        makePort("B", go.Spot.Bottom),
        makePort("L", go.Spot.Left)
      );

    myDiagram.linkTemplate =
      $(go.Link,
        $(go.Shape, { strokeWidth: 2 }),
        $(go.Shape, { fromArrow: "Standard", visible: false },
          new go.Binding("visible", "from")),
        $(go.Shape, { toArrow: "Standard" }),
        $(go.TextBlock,
          { font: "11px sans-serif", editable: true },
          new go.Binding("text").makeTwoWay())
      );

    myDiagram.model = go.Model.fromJson(
      '{ "class": "go.GraphLinksModel",\
        "linkFromPortIdProperty": "fp",\
        "linkToPortIdProperty": "tp",\
        "nodeDataArray": [\
          { "key": 1, "text": "Strategic Planning", "color": "lightgreen", "isGroup": true, "loc": "10.5 22" },\
          { "key": 11, "text": "Business Policy", "color": "rgba(182, 255, 180, 1)", "isGroup": true, "group": 1, "loc": "21 116" },\
          { "key": 111, "text": "Adhere to FSA Guidelines", "color": "lightgreen", "figure": "Hexagon", "group": 11, "loc": "31 126" },\
          { "key": 12, "text": "Strategy", "color": "rgba(182, 255, 180, 1)", "isGroup": true, "group": 1, "loc": "162 55" },\
          { "key": 121, "text": "Adopt Customer\\nComplaints Process", "color": "lightskyblue", "group": 12, "loc": "172 65" },\
          { "key": 122, "text": "Mission and\\nVision", "color": "plum", "group": 12, "loc": "274 136" },\
          { "key": 123, "text": "Improve Customer Satisfaction", "color": "lightskyblue", "group": 12, "loc": "177 206" },\
          { "key": 124, "text": "Decisions made wlil Maximize Benefit to the Enterprise", "color": "lightskyblue", "group": 12, "loc": "304 203" },\
          { "key": 2, "text": "Business Architecture", "color": "silver", "isGroup": true, "loc": "503 21" },\
          { "key": 21, "text": "Process", "color": "lightgray", "isGroup": true, "group": 2, "loc": "514 54" },\
          { "key": 211, "text": "Complaints\\n Handling", "color": "lightgreen", "figure":"Hexagon", "group": 21, "loc": "546 35" },\
          { "key": 212, "text": "Resolve \\nComplaint", "color": "lightskyblue", "group": 21, "loc": "679 64" },\
          { "key": 213, "text": "Complaints\\n Handling", "color": "lightskyblue", "group": 21, "loc": "550 145" },\
          { "key": 22, "text": "Organization", "color": "lightgray", "isGroup": true, "group": 2, "loc": "842 55" },\
          { "key": 221, "text": "Complaints \\nCall Handler", "color": "lightskyblue", "group": 22, "loc": "852 65.6" },\
          { "key": -18, "text": "Complaints \\nClient", "color": "lightskyblue", "group": 22, "loc": "854 142" },\
          { "key": -19, "text": "Complaints \\nManager", "color": "lightskyblue", "group": 22, "loc": "852 225" },\
          { "key": 23, "text": "Business Service", "color": "lightgray", "isGroup": true, "group": 2, "loc": "514 217" },\
          { "key": 231, "text": "Manage \\nComplaints", "color": "lightskyblue", "group": 23, "loc": "550 247" }\
        ],\
          "linkDataArray": [\
            { "from": 111, "to": 123, "fp": "R", "tp": "L" },\
            { "from": 121, "to": 123, "fp": "B", "tp": "T", "text": "Process" },\
            { "from": 121, "to": 122, "fp": "B", "tp": "T", "text": "Process" },\
            { "from": 121, "to": 211, "fp": "R", "tp": "L", "text": "Process" },\
            { "from": 121, "to": 231, "fp": "R", "tp": "L", "text": "Process" },\
            { "from": 211, "to": 213, "fp": "B", "tp": "T", "text": "Process type:\\nProcess" },\
            { "from": 231, "to": 213, "fp": "T", "tp": "B", "text": "Process" },\
            { "from": 231, "to": 212, "fp": "T", "tp": "B" },\
            { "from": 212, "to": -19, "fp": "B", "tp": "L", "text": "Process" },\
            { "from": 212, "to": -18, "fp": "B", "tp": "L", "text": "Process" },\
            { "from": 212, "to": 221, "fp": "R", "tp": "L", "text": "Process" }\
          ]\
      }'
    );
  }
</script>
</head>
<body onload="init()">
  <div id="myDiagramDiv" style="border: solid 1px black; width:100%; height:600px"></div>
</body>
</html>


问:
How can I disable typing in a ttk.Combobox tkinter?
I have a Combobox that I can currently type into. I want it to be so that the user can only choose a valid option from the drop down.

I can't seem to find a similar question online, and I don't see anything in the documentation that could help me out.

答:
You can set the state to "readonly"

```<code>cb = ttk.Combobox(root, state="readonly",
                  values=("one", "two", "three"))
</code>```

From the python 3.6 documentation:

state: One of “normal”, “readonly”, or “disabled”. In the “readonly” state, the value may not be edited directly, and the user can only selection of the values from the dropdown list. In the “normal” state, the text field is directly editable. In the “disabled” state, no interaction is possible.

Body:
You can set the state to "readonly"

cb = ttk.Combobox(root, state="readonly",
                  values=("one", "two", "three"))

From the python 3.6 documentation:

state: One of “normal”, “readonly”, or “disabled”. In the “readonly” state, the value may not be edited directly, and the user can only selection of the values from the dropdown list. In the “normal” state, the text field is directly editable. In the “disabled” state, no interaction is possible.


问:
Translating Windows absolute path to Java
I have a file named dog.jpg that resides in c:\Temp. So its full Windows path is C:\Temp\dog.jpg

Every answer on this site suggests to replace the \ with a /, but none of these statements I tried seems to work:

```<code>Image image = new Image("C:\\Temp\\dog.jpg");
Image image = new Image("C://Temp//dog.jpg");
Image image = new Image("C:/Temp/dog.jpg");
</code>```

(btw, it does work if I put dog.jpg in the current working directory and use:

```<code>Image image = new Image("dog.jpg");
</code>```

)

I am getting the following exception report:

```<code>Exception in Application start method
Exception in thread "main" java.lang.reflect.InvocationTargetException
        at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
        at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
        at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
        at java.lang.reflect.Method.invoke(Unknown Source)
        at sun.launcher.LauncherHelper$FXHelper.main(Unknown Source)
Caused by: java.lang.RuntimeException: Exception in Application start method
        at com.sun.javafx.application.LauncherImpl.launchApplication1(LauncherImpl.java:917)
        at com.sun.javafx.application.LauncherImpl.lambda$launchApplication$155(LauncherImpl.java:182)
        at java.lang.Thread.run(Unknown Source)
Caused by: java.lang.IllegalArgumentException: Invalid URL: unknown protocol: c
        at javafx.scene.image.Image.validateUrl(Image.java:1121)
        at javafx.scene.image.Image.<init>(Image.java:620)
        at Inclass_week7_session_1_4.start(Inclass_week7_session_1_4.java:21)
        at com.sun.javafx.application.LauncherImpl.lambda$launchApplication1$162(LauncherImpl.java:863)
        at com.sun.javafx.application.PlatformImpl.lambda$runAndWait$175(PlatformImpl.java:326)
        at com.sun.javafx.application.PlatformImpl.lambda$null$173(PlatformImpl.java:295)
        at java.security.AccessController.doPrivileged(Native Method)
        at com.sun.javafx.application.PlatformImpl.lambda$runLater$174(PlatformImpl.java:294)
        at com.sun.glass.ui.InvokeLaterDispatcher$Future.run(InvokeLaterDispatcher.java:95)
        at com.sun.glass.ui.win.WinApplication._runLoop(Native Method)
        at com.sun.glass.ui.win.WinApplication.lambda$null$148(WinApplication.java:191)
        ... 1 more
Caused by: java.net.MalformedURLException: unknown protocol: c
        at java.net.URL.<init>(Unknown Source)
        at java.net.URL.<init>(Unknown Source)
        at java.net.URL.<init>(Unknown Source)
        at javafx.scene.image.Image.validateUrl(Image.java:1115)

C:\Java\Tutorial\JavaFX 2>javac -version
javac 1.8.0_102
</code>```

What am I doing wrong? And how can I get this Windows absolute path to work?

Thanks for your help.

答:
Image class constructor requires a url rather than an absolute path, so add the protocol in your url</p>

```<code> Image img = new Image("file:///C:/Temp/dog.jpg");
</code>```

Body:
I have a file named dog.jpg that resides in c:\Temp. So its full Windows path is C:\Temp\dog.jpg

Every answer on this site suggests to replace the \ with a /, but none of these statements I tried seems to work:

Image image = new Image("C:\\Temp\\dog.jpg");
Image image = new Image("C://Temp//dog.jpg");
Image image = new Image("C:/Temp/dog.jpg");

(btw, it does work if I put dog.jpg in the current working directory and use:

Image image = new Image("dog.jpg");

)

I am getting the following exception report:

Exception in Application start method
Exception in thread "main" java.lang.reflect.InvocationTargetException
        at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
        at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
        at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
        at java.lang.reflect.Method.invoke(Unknown Source)
        at sun.launcher.LauncherHelper$FXHelper.main(Unknown Source)
Caused by: java.lang.RuntimeException: Exception in Application start method
        at com.sun.javafx.application.LauncherImpl.launchApplication1(LauncherImpl.java:917)
        at com.sun.javafx.application.LauncherImpl.lambda$launchApplication$155(LauncherImpl.java:182)
        at java.lang.Thread.run(Unknown Source)
Caused by: java.lang.IllegalArgumentException: Invalid URL: unknown protocol: c
        at javafx.scene.image.Image.validateUrl(Image.java:1121)
        at javafx.scene.image.Image.<init>(Image.java:620)
        at Inclass_week7_session_1_4.start(Inclass_week7_session_1_4.java:21)
        at com.sun.javafx.application.LauncherImpl.lambda$launchApplication1$162(LauncherImpl.java:863)
        at com.sun.javafx.application.PlatformImpl.lambda$runAndWait$175(PlatformImpl.java:326)
        at com.sun.javafx.application.PlatformImpl.lambda$null$173(PlatformImpl.java:295)
        at java.security.AccessController.doPrivileged(Native Method)
        at com.sun.javafx.application.PlatformImpl.lambda$runLater$174(PlatformImpl.java:294)
        at com.sun.glass.ui.InvokeLaterDispatcher$Future.run(InvokeLaterDispatcher.java:95)
        at com.sun.glass.ui.win.WinApplication._runLoop(Native Method)
        at com.sun.glass.ui.win.WinApplication.lambda$null$148(WinApplication.java:191)
        ... 1 more
Caused by: java.net.MalformedURLException: unknown protocol: c
        at java.net.URL.<init>(Unknown Source)
        at java.net.URL.<init>(Unknown Source)
        at java.net.URL.<init>(Unknown Source)
        at javafx.scene.image.Image.validateUrl(Image.java:1115)

C:\Java\Tutorial\JavaFX 2>javac -version
javac 1.8.0_102

What am I doing wrong? And how can I get this Windows absolute path to work?

Thanks for your help.

Body:
Image class constructor requires a url rather than an absolute path, so add the protocol in your url

 Image img = new Image("file:///C:/Temp/dog.jpg");


问:
Angular update object in object array
Say i have the following object array, lets name it itemArray;

```<code>{
  "totalItems": 2,
  "items": [
    {
      "id": 1,
      "name": "foo"

    },
    {
      "id": 2,
      "name": "bar"
    },
    ]
}
</code>```

And i have a subscription that returns the updated result of only id 2. How would i update the object array without looping through the entire array?

What i would like is something like the example below;

```<code>updateUser(user){
    this.myservice.getUpdate(user.id)
    .subscribe(newitem => {
      this.updateArray(newitem);
    });
}

  updateArray(newitem){
    this.itemArray.items[newitem.id].name = newitem.name
  }
</code>```

or even better, replacing the entire object;

```<code>  updateArray(newitem){
    this.itemArray.items[newitem.id] = newitem
  }
</code>```

This example however updates the array based on the index of the array. So how do i instead update based on newitem.id?

Template requested in comment:

```<code><tr *ngFor="let u of itemsArray.items; let i = index">
  <td>{{ u.id }}</td>
  <td>{{ u.name }}</td>
  <td>
    <input type="checkbox" checked="u.accepted" [(ngModel)]="itemsArray.items[i].accepted" (ngModelChange)="updateUser(u)">
    <label for="singleCheckbox-{{i}}"></label>
  </td>
</tr>
</code>```

答:
I would rather create a map

```<code>export class item{
    name: string;
    id: string
}

let caches = new Map<string, item>();
</code>```

and then you can simply

```<code>this.caches[newitem.id] = newitem;
</code>```

even

```<code>this.caches.set(newitem.id, newitem);
</code>```

array is so 1999. :)

Title: Angular update object in object array

Body:
Say i have the following object array, lets name it itemArray;

{
  "totalItems": 2,
  "items": [
    {
      "id": 1,
      "name": "foo"

    },
    {
      "id": 2,
      "name": "bar"
    },
    ]
}

And i have a subscription that returns the updated result of only id 2. How would i update the object array without looping through the entire array?

What i would like is something like the example below;

updateUser(user){
    this.myservice.getUpdate(user.id)
    .subscribe(newitem => {
      this.updateArray(newitem);
    });
}

  updateArray(newitem){
    this.itemArray.items[newitem.id].name = newitem.name
  }

or even better, replacing the entire object;

  updateArray(newitem){
    this.itemArray.items[newitem.id] = newitem
  }

This example however updates the array based on the index of the array. So how do i instead update based on newitem.id?

Template requested in comment:

  {{ u.id }}
  {{ u.name }}

    <input type="checkbox" checked="u.accepted" [(ngModel)]="itemsArray.items[i].accepted" (ngModelChange)="updateUser(u)">

Body:
I would rather create a map

export class item{
    name: string;
    id: string
}

let caches = new Map<string, item>();

and then you can simply

this.caches[newitem.id] = newitem;

even

this.caches.set(newitem.id, newitem);

array is so 1999. :)


问:
Using threads with Observer Pattern
I have this code:

```<code>public class classExample implements Observer Runnable {

    public classExample() {
    //...
    }

    @Override
    public void run() {
        while (true) {
           //wait for EVENT;
           //do something;
        }
    }

    @Override
    public void update(Observable arg0, Object arg1) {
    //signal EVENT;
    }

}
</code>```

Basically, i want my thread to do something every time the update() method is called. I can't do in the update() method itself cause it would be executed in the same thread of the Observable calling notifyObservers().
Are there any ways to "signal" an event to the run() method?

答:
At the very basic elements: Why not just use some membervariable/flag that you set in your update-Method?

```<code>eventWasFired = true;
</code>```

In your while-loop inside of run() do something like:

```<code>try {
    Thread.sleep(updateTimer);
    if(eventWasFired) {
         doSomeAction();
         eventWasFired = false;
    }
} catch (InterruptedException ie) {
    // handle if you like
}
</code>```

you need to synchronize access and use some atomic-variable if you have multiple threads that may access your observable. Otherwise your program is exposed to data races.

Title: Using threads with Observer Pattern

Body:
I have this code:

public class classExample implements Observer Runnable {

    public classExample() {
    //...
    }

    @Override
    public void run() {
        while (true) {
           //wait for EVENT;
           //do something;
        }
    }

    @Override
    public void update(Observable arg0, Object arg1) {
    //signal EVENT;
    }

}

Basically, i want my thread to do something every time the update() method is called. I can't do in the update() method itself cause it would be executed in the same thread of the Observable calling notifyObservers().
Are there any ways to "signal" an event to the run() method?

Body:
At the very basic elements: Why not just use some membervariable/flag that you set in your update-Method?

eventWasFired = true;

In your while-loop inside of run() do something like:

try {
    Thread.sleep(updateTimer);
    if(eventWasFired) {
         doSomeAction();
         eventWasFired = false;
    }
} catch (InterruptedException ie) {
    // handle if you like
}

you need to synchronize access and use some atomic-variable if you have multiple threads that may access your observable. Otherwise your program is exposed to data races.


问:
Throw keyword in function's signature
What is the technical reason why it is considered bad practice to use the C++ throw keyword in a function signature?

```<code>bool some_func() throw(myExc)
{
  ...
  if (problem_occurred)
  {
    throw myExc("problem occurred");
  }
  ...
}
</code>```

答:
A no throw specification on an inlined function that only returns a member variable and could not possibly throw exceptions may be used by some compilers to do pessimizations (a made-up word for the opposite of optimizations) that can have a detrimental effect on performance. This is described in the Boost literature: Exception-specification

With some compilers a no-throw specification on non-inline functions may be beneficial if the correct optimizations are made and the use of that function impacts performance in a way that it justifies it.

To me it sounds like whether to use it or not is a call made by a very critical eye as part of a performance optimization effort, perhaps using profiling tools.

A quote from the above link for those in a hurry (contains an example of bad unintended effects of specifying throw on an inline function from a naive compiler):

Exception-specification rationale

Exception specifications [ISO 15.4] are sometimes coded to indicate what exceptions may be thrown, or because the programmer hopes they will improve performance. But consider the following member from a smart pointer:

T& operator*() const throw()  { return *ptr; }

This function calls no other functions; it only manipulates fundamental data types like pointers Therefore, no runtime behavior of the exception-specification can ever be invoked. The function is completely exposed to the compiler; indeed it is declared inline Therefore, a smart compiler can easily deduce that the functions are incapable of throwing exceptions, and make the same optimizations it would have made based on the empty exception-specification. A "dumb" compiler, however, may make all kinds of pessimizations.

For example, some compilers turn off inlining if there is an exception-specification. Some compilers add try/catch blocks. Such pessimizations can be a performance disaster which makes the code unusable in practical applications.

Although initially appealing, an exception-specification tends to have consequences that require very careful thought to understand. The biggest problem with exception-specifications is that programmers use them as though they have the effect the programmer would like, instead of the effect they actually have.

A non-inline function is the one place a "throws nothing" exception-specification may have some benefit with some compilers.

Title: Throw keyword in function's signature

Body:
What is the technical reason why it is considered bad practice to use the C++ throw keyword in a function signature?

bool some_func() throw(myExc)
{
  ...
  if (problem_occurred)
  {
    throw myExc("problem occurred");
  }
  ...
}

ContentLicense: CC BY-SA 4.0


问:
Cannot upgrade npm to the latest version on Mac
No matter what I've tried, I can't update npm to the latest version (currently 3.10.7) on my Mac. The install seems to work, in terms of pulling down the latest version, but the latest version is stuck at 3.8.0. Here are all the details I can pull up.

system: Mac OS X El Capitan, Version 10.11.6

command: node -v

results: v6.6.0

command: npm -v

results: 3.8.0

command: npm cache clean

results: nothing

command: which npm

results: Users/wrburgess/.npm-packages/bin/npm

command: npm install -g npm@latest

results:

/usr/local/bin/npm -> /usr/local/lib/node_modules/npm/bin/npm-cli.js
/usr/local/lib
├── abbrev@1.0.9
├── aproba@1.0.4
├── fstream@1.0.10
├─┬ fstream-npm@1.1.1
│ └─┬ fstream-ignore@1.0.5
│   └── minimatch@3.0.3
├─┬ glob@7.0.5
│ └── minimatch@3.0.3
├── graceful-fs@4.1.5
├── has-unicode@2.0.1
├── lodash.clonedeep@4.4.1
├── lodash.union@4.5.0
├── lodash.uniq@4.4.0
├── lodash.without@4.3.0
├── minimatch@3.0.3
├─┬ node-gyp@3.4.0
│ └── minimatch@3.0.3
├─┬ npm@3.10.7
│ └─┬ init-package-json@1.9.4
│   └─┬ glob@6.0.4
│     └── minimatch@3.0.3
├── npm-package-arg@4.2.0
├── npm-user-validate@0.1.5
├── read-package-tree@5.1.5
├── readable-stream@2.1.4
├── request@2.74.0
├── rimraf@2.5.4
├── which@1.2.10
└── wrappy@1.0.2

command: npm cache clean

results: nothing

command: npm -v

results: 3.8.0

Any ideas?

答:
Probably you need to add /Users/wrburgess/.npm-packages/bin after /Users/wrburgess/.npm-packages in your PATH.

So, you can put in your ~/.bash_profile:

export PATH=/Users/wrburgess/.npm-packages:/Users/wrburgess/.npm-packages/bin:~/.npm:$PATH


Title: JavaScript - dispatch 10 promises in every minute?

Body:
How can I dispatch 10 promises in every minute?

I have these dynamic dates in a list:

var dates = ["2016-08-31T23:00:00.000Z","2016-09-01T23:00:00.000Z","2016-09-02T23:00:00.000Z","2016-09-03T23:00:00.000Z","2016-09-04T23:00:00.000Z","2016-09-05T23:00:00.000Z","2016-09-06T23:00:00.000Z","2016-09-07T23:00:00.000Z","2016-09-08T23:00:00.000Z","2016-09-09T23:00:00.000Z","2016-09-10T23:00:00.000Z","2016-09-11T23:00:00.000Z","2016-09-12T23:00:00.000Z","2016-09-13T23:00:00.000Z","2016-09-14T23:00:00.000Z","2016-09-15T23:00:00.000Z","2016-09-16T23:00:00.000Z","2016-09-17T23:00:00.000Z","2016-09-18T23:00:00.000Z","2016-09-19T23:00:00.000Z","2016-09-20T23:00:00.000Z","2016-09-21T23:00:00.000Z","2016-09-22T23:00:00.000Z","2016-09-23T23:00:00.000Z","2016-09-24T23:00:00.000Z","2016-09-25T23:00:00.000Z","2016-09-26T23:00:00.000Z","2016-09-27T23:00:00.000Z","2016-09-28T23:00:00.000Z","2016-09-29T23:00:00.000Z","2016-09-30T23:00:00.000Z","2016-10-01T23:00:00.000Z"];

I want to get the content or result that associated with these dates. But I don't want to get them in one go, but every 10 items in every minute, until the date is no more.

This is my working code:

     var promises = dates.map(function (date, i) {
        return getContent(date);
    });

    Promise.all(promises).then((data) => {
        console.log(data);
    }).catch((err) => {
        console.log(err.message);
    });

It gets the content in a row, not exactly what I want.

But is it possible to achieve what I need? Any ideas?

Notes:

getContent(date) contains a massive of async await promises, so in that promse.all that calls it has to be a promise too i guess, otherwise I can get all return data in one place (which is console.log(data);) when the promises end.

EDIT:

const delayValue = (val, ms) => {
    new Promise(resolve => {
        setTimeout(resolve.bind(null, val), ms)
    });
}

Body:
A Promise only resolves once, so if you need to have results every minute, and want to do this with promises, you'll need to have a separate promise per chunk of data.

Here is how you could do that by repeatedly creating a promise with a custom delayValue function:

const delayValue = (val, ms) =>
    new Promise(resolve => setTimeout(resolve.bind(null, val), ms));

async function loopDates(dates, chunk, delay) {
    for (let i = 0; i < dates.length; i += chunk) {
        console.log(await delayValue(dates.slice(i, i+chunk), i ? delay : 0));
    }
}

var dates = ["2016-08-31T23:00:00.000Z", "2016-09-01T23:00:00.000Z", "2016-09-02T23:00:00.000Z", "2016-09-03T23:00:00.000Z", "2016-09-04T23:00:00.000Z", "2016-09-05T23:00:00.000Z", "2016-09-06T23:00:00.000Z", "2016-09-07T23:00:00.000Z", "2016-09-08T23:00:00.000Z", "2016-09-09T23:00:00.000Z", "2016-09-10T23:00:00.000Z", "2016-09-11T23:00:00.000Z", "2016-09-12T23:00:00.000Z", "2016-09-13T23:00:00.000Z", "2016-09-14T23:00:00.000Z", "2016-09-15T23:00:00.000Z", "2016-09-16T23:00:00.000Z", "2016-09-17T23:00:00.000Z", "2016-09-18T23:00:00.000Z", "2016-09-19T23:00:00.000Z", "2016-09-20T23:00:00.000Z", "2016-09-21T23:00:00.000Z", "2016-09-22T23:00:00.000Z", "2016-09-23T23:00:00.000Z", "2016-09-24T23:00:00.000Z", "2016-09-25T23:00:00.000Z", "2016-09-26T23:00:00.000Z", "2016-09-27T23:00:00.000Z", "2016-09-28T23:00:00.000Z", "2016-09-29T23:00:00.000Z", "2016-09-30T23:00:00.000Z", "2016-10-01T23:00:00.000Z"];

loopDates(dates, 10, 2000);

.as-console-wrapper { max-height: 100% !important; top: 0; }

Now to add the getContent factor into it, you would do the map like you did (although the syntax can be shortened), and then apply Promise.all on each chunk:

const delayValue = (val, ms) =>
    new Promise(resolve => setTimeout(resolve.bind(null, val), ms));

// Mock for getContent:
const getContent = date => Promise.resolve(date);

async function loopDates(dates, chunk, delay) {
    const promises = dates.map(getContent);

    for (let i = 0; i < dates.length; i += chunk) {
        console.log(await delayValue(Promise.all(promises.slice(i, i+chunk)),
                                     i ? delay : 0));
    }
}

var dates = ["2016-08-31T23:00:00.000Z", "2016-09-01T23:00:00.000Z", "2016-09-02T23:00:00.000Z", "2016-09-03T23:00:00.000Z", "2016-09-04T23:00:00.000Z", "2016-09-05T23:00:00.000Z", "2016-09-06T23:00:00.000Z", "2016-09-07T23:00:00.000Z", "2016-09-08T23:00:00.000Z", "2016-09-09T23:00:00.000Z", "2016-09-10T23:00:00.000Z", "2016-09-11T23:00:00.000Z", "2016-09-12T23:00:00.000Z", "2016-09-13T23:00:00.000Z", "2016-09-14T23:00:00.000Z", "2016-09-15T23:00:00.000Z", "2016-09-16T23:00:00.000Z", "2016-09-17T23:00:00.000Z", "2016-09-18T23:00:00.000Z", "2016-09-19T23:00:00.000Z", "2016-09-20T23:00:00.000Z", "2016-09-21T23:00:00.000Z", "2016-09-22T23:00:00.000Z", "2016-09-23T23:00:00.000Z", "2016-09-24T23:00:00.000Z", "2016-09-25T23:00:00.000Z", "2016-09-26T23:00:00.000Z", "2016-09-27T23:00:00.000Z", "2016-09-28T23:00:00.000Z", "2016-09-29T23:00:00.000Z", "2016-09-30T23:00:00.000Z", "2016-10-01T23:00:00.000Z"];

loopDates(dates, 10, 2000);

.as-console-wrapper { max-height: 100% !important; top: 0; }


问:
Java String quote delimiter
Is there any way in Java to use a special delimiter at the start and the end of a String to avoid having to backslash all of the quotes within that String?

i.e. not have to do this:

```<code>String s = "Quote marks like this \" are just the best, here are a few more \" \" \""
</code>```

答:
Its not possible as of now, May be NOT in future also.

if you can give us what and why you are loookng for this kind of feature we can defnitely Suggest some more alternatives

ContentLicense: CC BY-SA 2.5

Title: Java String quote delimiter

Body:
Is there any way in Java to use a special delimiter at the start and the end of a String to avoid having to backslash all of the quotes within that String?

i.e. not have to do this:

String s = "Quote marks like this \" are just the best, here are a few more \" \" \""


问:
Add Fields and Methods to classes that inherit from same base without modifying base class
In my application i need to add some extra functionality to 3rd party controls.

An example would be TcxLabel and TcxDBLabel (from DevExpress).
Both inherit from the the same base class.

For those controls i would like to add some fields and methods.

The way i do it today:

```<code>TMycxLabel = class(TcxLabel)
private
  FMyField1: string;
  FMyField2: Integer;
public
  procedure DoSomething;
end;
</code>```

```<code>TMycxDBLabel = class(TcxDBLabel)
private
  FMyField1: string;
  FMyField2: Integer;
public
  procedure DoSomething;
end;
</code>```

So basically i have to write everything twice.

One way to achieve it would be modifying the base class those 2 controls inherit from.
But that is not an option - the DevExpress classses / packages should not be modified.

Is there a way to add achieve this?

答:
There is a way, although it will serve only if you only need what is available in the base class.
For instance, if TcxDBLabel inherits from TcxLabel, you can add a method (loosely speaking) to both as long as you only use the TcxLabel part (fields, methods and properties) of the TcxDBLabel.

I'm referring to typecasting.

I should warn that the use of this practice is not consensual. Many developers regard typecasting as a bad practice, and I myself tend to use it only as last resort. However, I'll leave to you the philosophical discussion of weather you should or shouldn't use this.

So if you create a subclass like this:

```<code>THcxLabel = Class(TcxLabel)
private
  FMyField1: string;
  FMyField2: Integer;
public
  procedure DoSomething;
End;
</code>```

You can then add this to any TcxLabel based class instance, like so:

```<code>THcxLabel(cxLabel1).DoSomething;
THcxLabel(cxDBLabel1).DoSomething;
</code>```

Like I said, no specifics from TcxDBLabel will be available to you inside the DoSomething method, but you will be able to use the base class resources.

Body:
In my application i need to add some extra functionality to 3rd party controls.

An example would be TcxLabel and TcxDBLabel (from DevExpress).
Both inherit from the the same base class.

For those controls i would like to add some fields and methods.

The way i do it today:

TMycxLabel = class(TcxLabel)
private
  FMyField1: string;
  FMyField2: Integer;
public
  procedure DoSomething;
end;

TMycxDBLabel = class(TcxDBLabel)
private
  FMyField1: string;
  FMyField2: Integer;
public
  procedure DoSomething;
end;

So basically i have to write everything twice.

One way to achieve it would be modifying the base class those 2 controls inherit from.
But that is not an option - the DevExpress classses / packages should not be modified.

Is there a way to add achieve this?

Body:
There is a way, although it will serve only if you only need what is available in the base class.
For instance, if TcxDBLabel inherits from TcxLabel, you can add a method (loosely speaking) to both as long as you only use the TcxLabel part (fields, methods and properties) of the TcxDBLabel.

I'm referring to typecasting.

I should warn that the use of this practice is not consensual. Many developers regard typecasting as a bad practice, and I myself tend to use it only as last resort. However, I'll leave to you the philosophical discussion of weather you should or shouldn't use this.

So if you create a subclass like this:

THcxLabel = Class(TcxLabel)
private
  FMyField1: string;
  FMyField2: Integer;
public
  procedure DoSomething;
End;

You can then add this to any TcxLabel based class instance, like so:

THcxLabel(cxLabel1).DoSomething;
THcxLabel(cxDBLabel1).DoSomething;

Like I said, no specifics from TcxDBLabel will be available to you inside the DoSomething method, but you will be able to use the base class resources.


问:
How to create a dynamic id for a dynamic button?
I am able to create an onlick dynamic button with an incrementer and a decrementer option, but I am unable to create a dynamic id for other buttons due to which these buttons are not getting incremented or decremented. Currently only the first button gets decremented/incremented even when clicked on other buttons.

Here is the plunker

When you click on + icon content and a incrementer/decrementer button is added in Manage Portfolio section. I have tried different solutions which have been defined on Stack Overflow but they don't seem to work here.

```<code>             <table>
                <thead>
                    <tr>
                        <th>STOCK</th>
                        <th>PRICE</th>
                        <th>SHARES</th>
                        <th>WEIGHT</th>
                    </tr>
                </thead>
                <tbody>
                    <tr ng-repeat="stock in stocksArray" class="portfoliokey">
                        <td>{{stock.key}}</td>
                        <td class="portfoliovalue">{{"₹" + stock.value}}</td>
                        <td>
                            <input type="button" onclick="decrementValue()" value="-">
                            <input type="button" id="number" value="0" />
                            <input type="button" onclick="incrementValue()" value="+" />
                        </td>
                        <td></td>
                    </tr>
                </tbody>
            </table>
</code>```

Script

```<code>   function incrementValue() {
    var value = parseInt(document.getElementById('number').value, 10);
    value = isNaN(value) ? 0 : value;
    value++;
    document.getElementById('number').value = value;
}

function decrementValue() {
    value = parseInt(document.getElementById('number').value, 10);
    value = isNaN(value) ? 0 : value;
    value--;
    document.getElementById('number').value = value;
}
</code>```

答:
Speaking purely of Web standards HTML/CSS/JS-ECMA, I believe using data attributes is purpose built for your use case. In other words, use data-whatever="myIdentifierForWhateverProperty" and then use vanilla JS logic if(document.getElementsByTagName("button")[iterateOverEachOne]){do this} else {do that};.

Using data attributes

HTML5 is designed with extensibility in mind for data that should be
  associated with a particular element but need not have any defined
  meaning. data-* attributes allow us to store extra information on
  standard, semantic HTML elements without other hacks such as
  non-standard attributes, extra properties on DOM, or
  Node.setUserData().

```<code><article
  id="electriccars"
  data-columns="3"
  data-index-number="12314"
  data-parent="cars">
...
</article>
</code>```

Body:
I am able to create an onlick dynamic button with an incrementer and a decrementer option, but I am unable to create a dynamic id for other buttons due to which these buttons are not getting incremented or decremented. Currently only the first button gets decremented/incremented even when clicked on other buttons.

Here is the plunker

When you click on + icon content and a incrementer/decrementer button is added in Manage Portfolio section. I have tried different solutions which have been defined on Stack Overflow but they don't seem to work here.

                        STOCK
                        PRICE
                        SHARES
                        WEIGHT

                        {{stock.key}}
                        {{"₹" + stock.value}}

                            <input type="button" onclick="decrementValue()" value="-">
                            <input type="button" id="number" value="0" />
                            <input type="button" onclick="incrementValue()" value="+" />

Script

   function incrementValue() {
    var value = parseInt(document.getElementById('number').value, 10);
    value = isNaN(value) ? 0 : value;
    value++;
    document.getElementById('number').value = value;
}

function decrementValue() {
    value = parseInt(document.getElementById('number').value, 10);
    value = isNaN(value) ? 0 : value;
    value--;
    document.getElementById('number').value = value;
}

Body:
Speaking purely of Web standards HTML/CSS/JS-ECMA, I believe using data attributes is purpose built for your use case. In other words, use data-whatever="myIdentifierForWhateverProperty" and then use vanilla JS logic if(document.getElementsByTagName("button")[iterateOverEachOne]){do this} else {do that};.

Using data attributes

HTML5 is designed with extensibility in mind for data that should be
  associated with a particular element but need not have any defined
  meaning. data-* attributes allow us to store extra information on
  standard, semantic HTML elements without other hacks such as
  non-standard attributes, extra properties on DOM, or
  Node.setUserData().

<article
  id="electriccars"
  data-columns="3"
  data-index-number="12314"
  data-parent="cars">
...
</article>


问:
C#: Throw an exception without overwriting the currently-active one
Take the following minimal example:

```<code>try { foo }
finally { bar() }
</code>```

foo may or may not throw, and bar() may or may not throw.
If both functions throw, then the exception thrown by bar() will overwrite the exception thrown by foo. However, I need to instead see the exception that was thrown by foo. The only code I can control is that inside bar().
In C++, this can be achieved by checking std::uncaught_exceptions inside bar().
What about C#?

There is a check using Marshal.GetExceptionPointers(), but as the answer states, this is a horrible hack, and in my case it does not suffice because my code needs to run on Mono, which does not implement that function.

Context:

In my real-life case, foo is a large block of code which is provided by the library user and may throw all sorts of exceptions, and bar() is a Dispose function which is provided by me and called automatically.

答:
You will need to code this manually:

```<code>// Whether an exception has been thrown from the main block.
bool hasMainException = false;

try
{
    foo();
}
catch
{
    // Record that exception has been thrown from main block, and rethrow.
    hasMainException = true;
    throw;
}
finally
{
    // Execute secondary block within its own try-catch block.
    try
    {
        bar();
    }
    catch
    {
        // Only rethrow exception from secondary block if there isn't
        // already an exception from the main block.
        if (!hasMainException)
            throw;
    }
}
</code>```

Incidentally, I needed to achieve something very similar to your use-case involving Dispose methods that could throw, so I wrote some extension methods to achieve this, plus a variety of strategies to support all use-cases. See DisposableExtensions and DisposeExceptionStrategy. The strategy you're interested in is Subjugate.

Body:
Take the following minimal example:

try { foo }
finally { bar() }

foo may or may not throw, and bar() may or may not throw.
If both functions throw, then the exception thrown by bar() will overwrite the exception thrown by foo. However, I need to instead see the exception that was thrown by foo. The only code I can control is that inside bar().
In C++, this can be achieved by checking std::uncaught_exceptions inside bar().
What about C#?

There is a check using Marshal.GetExceptionPointers(), but as the answer states, this is a horrible hack, and in my case it does not suffice because my code needs to run on Mono, which does not implement that function.

Context:

In my real-life case, foo is a large block of code which is provided by the library user and may throw all sorts of exceptions, and bar() is a Dispose function which is provided by me and called automatically.

Body:
You will need to code this manually:

// Whether an exception has been thrown from the main block.
bool hasMainException = false;

try
{
    foo();
}
catch
{
    // Record that exception has been thrown from main block, and rethrow.
    hasMainException = true;
    throw;
}
finally
{
    // Execute secondary block within its own try-catch block.
    try
    {
        bar();
    }
    catch
    {
        // Only rethrow exception from secondary block if there isn't
        // already an exception from the main block.
        if (!hasMainException)
            throw;
    }
}

Incidentally, I needed to achieve something very similar to your use-case involving Dispose methods that could throw, so I wrote some extension methods to achieve this, plus a variety of strategies to support all use-cases. See DisposableExtensions and DisposeExceptionStrategy. The strategy you're interested in is Subjugate.


问:
accessing a method from a property and not an instance? Xcode
I'm confused how the following code uses the view property to access the subView method in the viewDidLoad() function. The viewDidLoad function provides access to the view property, but why is the addSubView method accessed from a property and not an instance?

```<code>override func viewDidLoad() {
    super.viewDidLoad()
    let label = UILabel(frame: CGRect(x: 16, y: 16, width: 200,
height: 44))
    view.addSubview(label) // Adds label as a child view to `view`
}
</code>```

答:
A UIViewController has a property view. In swift, you can usually skip the "self" prefix when referring to properties of the current object.

The line view.addSubview(label) is equivalent to:

```<code>self.view.addSubview(label)
</code>```

Or, to make it even clearer what it's doing by using a local variable:

```<code>let aView = self.view
aView.addSubview(label)
</code>```

Body:
I'm confused how the following code uses the view property to access the subView method in the viewDidLoad() function. The viewDidLoad function provides access to the view property, but why is the addSubView method accessed from a property and not an instance?

override func viewDidLoad() {
    super.viewDidLoad()
    let label = UILabel(frame: CGRect(x: 16, y: 16, width: 200,
height: 44))
    view.addSubview(label) // Adds label as a child view to `view`
}

Body:
A UIViewController has a property view. In swift, you can usually skip the "self" prefix when referring to properties of the current object.

The line view.addSubview(label) is equivalent to:

self.view.addSubview(label)

Or, to make it even clearer what it's doing by using a local variable:

let aView = self.view
aView.addSubview(label)


问:
Performing a count on an item that never has focus
Using either JavaScript or jQuery, is it possible to capture a count on an item on a page that never get focus from the user and is only used to store values into it from another item that has the user focus?

I basically require a means of counting the total number of entries that are going into a item as that item gets populated.

答:
hidden field within a form should work

```<code><html>
<head>
<title>My Page</title>
<script type="text/javascript">
function getvar1()
{
var x=document.getElementById("var1")
return x;
}
</script>
</head>
<body>
<form name="myform" action="http://www.address.com/" method="POST">
<input type="hidden" id="var1" value="myvariable">
</form>
</body>
</html>
</code>```

i dont really know what you mean but are you trying to do this.. where you count the text in the box?

```<code><html>
<head>
<title>My Page</title>
</head>

<body>

<input type='text' id='var1' onkeypress='javascript:magic();' onkeyup='javascript:magic();' value="hi">

<div id='displaydiv'>Waiting..</div>

<script type="text/javascript">
function magic(){
    document.getElementById('displaydiv').innerHTML = ""+(document.getElementById('var1').value.length);
}
</script>
</body>
</html>
</code>```

Body:
hidden field within a form should work

<html>
<head>
<title>My Page</title>
<script type="text/javascript">
function getvar1()
{
var x=document.getElementById("var1")
return x;
}
</script>
</head>
<body>
<form name="myform" action="http://www.address.com/" method="POST">
<input type="hidden" id="var1" value="myvariable">
</form>
</body>
</html>

i dont really know what you mean but are you trying to do this.. where you count the text in the box?

<html>
<head>
<title>My Page</title>
</head>

<body>

<input type='text' id='var1' onkeypress='javascript:magic();' onkeyup='javascript:magic();' value="hi">

<div id='displaydiv'>Waiting..</div>

<script type="text/javascript">
function magic(){
    document.getElementById('displaydiv').innerHTML = ""+(document.getElementById('var1').value.length);
}
</script>
</body>
</html>


问:
Do HttpClient and HttpClientHandler have to be disposed between requests?
System.Net.Http.HttpClient and System.Net.Http.HttpClientHandler in .NET Framework 4.5 implement IDisposable (via System.Net.Http.HttpMessageInvoker).

The using statement documentation says:

As a rule, when you use an IDisposable object, you should declare and
  instantiate it in a using statement.

This answer uses this pattern:

```<code>var baseAddress = new Uri("http://example.com");
var cookieContainer = new CookieContainer();
using (var handler = new HttpClientHandler() { CookieContainer = cookieContainer })
using (var client = new HttpClient(handler) { BaseAddress = baseAddress })
{
    var content = new FormUrlEncodedContent(new[]
    {
        new KeyValuePair<string, string>("foo", "bar"),
        new KeyValuePair<string, string>("baz", "bazinga"),
    });
    cookieContainer.Add(baseAddress, new Cookie("CookieName", "cookie_value"));
    var result = client.PostAsync("/test", content).Result;
    result.EnsureSuccessStatusCode();
}
</code>```

But the most visible examples from Microsoft don't call Dispose() either explicitly or implicitly. For instance:

The original blog article announcing the relase of HttpClient.

The actual MSDN documentation for HttpClient.

BingTranslateSample

GoogleMapsSample

WorldBankSample

In the announcement's comments, someone asked the Microsoft employee:

After checking your samples, I saw that you didn't perform the dispose
  action on HttpClient instance. I have used all instances of HttpClient
  with using statement on my app and I thought that it is the right way
  since HttpClient  implements the IDisposable interface. Am I on the
  right path?

His answer was:

In general that is correct although you have to be careful with
  "using" and async as they dont' really mix in .Net 4, In .Net 4.5 you
  can use "await" inside a "using" statement.

Btw, you can reuse the same HttpClient as many times are [as] you like so
  typically you won't create/dispose them all the time.

The second paragraph is superfluous to this question, which is not concerned about how many times you can use an HttpClient instance, but about if it is necessary to dispose it after you no longer need it.

(Update: in fact that second paragraph is the key to the answer, as provided below by @DPeden.)

So my questions are:

Is it necessary, given the current implementation (.NET Framework 4.5), to call Dispose() on HttpClient and HttpClientHandler instances? Clarification: by "necessary" I mean if there are any negative consequences for not disposing, such as resource leakage or data corruption risks.

If it's not necessary, would it be a "good practice" anyway, since they implement IDisposable?

If it's necessary (or recommended), is this code mentioned above implementing it safely (for .NET Framework 4.5)?

If these classes don't require calling Dispose(), why were they implemented as IDisposable?

If they require, or if it's a recommended practice, are the Microsoft examples misleading or unsafe?

答:
The current answers are a bit confusing and misleading, and they are missing some important DNS implications. I'll try to summarize where things stand clearly.

Generally speaking most IDisposable objects should ideally be disposed when you are done with them, especially those that own Named/shared OS resources. HttpClient is no exception, since as Darrel Miller points out it allocates cancellation tokens, and request/response bodies can be unmanaged streams.

However, the best practice for HttpClient says you should create one instance and reuse it as much as possible (using its thread-safe members in multi-threaded scenarios). Therefore, in most scenarios you'll never dispose of it simply because you will be needing it all the time.

The problem with re-using the same HttpClient "forever" is that the underlying HTTP connection might remain open against the originally DNS-resolved IP, regardless of DNS changes. This can be an issue in scenarios like blue/green deployment and DNS-based failover. There are various approaches for dealing with this issue, the most reliable one involving the server sending out a Connection:close header after DNS changes take place. Another possibility involves recycling the HttpClient on the client side, either periodically or via some mechanism that learns about the DNS change. See https://github.com/dotnet/corefx/issues/11224 for more information (I suggest reading it carefully before blindly using the code suggested in the linked blog post).

Body:
System.Net.Http.HttpClient and System.Net.Http.HttpClientHandler in .NET Framework 4.5 implement IDisposable (via System.Net.Http.HttpMessageInvoker).

The using statement documentation says:

As a rule, when you use an IDisposable object, you should declare and
  instantiate it in a using statement.

This answer uses this pattern:

var baseAddress = new Uri("http://example.com");
var cookieContainer = new CookieContainer();
using (var handler = new HttpClientHandler() { CookieContainer = cookieContainer })
using (var client = new HttpClient(handler) { BaseAddress = baseAddress })
{
    var content = new FormUrlEncodedContent(new[]
    {
        new KeyValuePair<string, string>("foo", "bar"),
        new KeyValuePair<string, string>("baz", "bazinga"),
    });
    cookieContainer.Add(baseAddress, new Cookie("CookieName", "cookie_value"));
    var result = client.PostAsync("/test", content).Result;
    result.EnsureSuccessStatusCode();
}

But the most visible examples from Microsoft don't call Dispose() either explicitly or implicitly. For instance:

The original blog article announcing the relase of HttpClient.

The actual MSDN documentation for HttpClient.

BingTranslateSample

GoogleMapsSample

WorldBankSample

In the announcement's comments, someone asked the Microsoft employee:

After checking your samples, I saw that you didn't perform the dispose
  action on HttpClient instance. I have used all instances of HttpClient
  with using statement on my app and I thought that it is the right way
  since HttpClient  implements the IDisposable interface. Am I on the
  right path?

His answer was:

In general that is correct although you have to be careful with
  "using" and async as they dont' really mix in .Net 4, In .Net 4.5 you
  can use "await" inside a "using" statement.

Btw, you can reuse the same HttpClient as many times are [as] you like so
  typically you won't create/dispose them all the time.

The second paragraph is superfluous to this question, which is not concerned about how many times you can use an HttpClient instance, but about if it is necessary to dispose it after you no longer need it.

(Update: in fact that second paragraph is the key to the answer, as provided below by @DPeden.)

So my questions are:

Is it necessary, given the current implementation (.NET Framework 4.5), to call Dispose() on HttpClient and HttpClientHandler instances? Clarification: by "necessary" I mean if there are any negative consequences for not disposing, such as resource leakage or data corruption risks.

If it's not necessary, would it be a "good practice" anyway, since they implement IDisposable?

If it's necessary (or recommended), is this code mentioned above implementing it safely (for .NET Framework 4.5)?

If these classes don't require calling Dispose(), why were they implemented as IDisposable?

If they require, or if it's a recommended practice, are the Microsoft examples misleading or unsafe?


问:
Ionic 3/Angular 2 - Renderer2.setValue() doesn't update the value of my input field
I'm trying to update the value of an input that isn't bound to a <form> in my component, and my research has lead me to use the Renderer2 service that Angular provides.

So I have my input that looks like this:

```<code><input type="text" #zipEl placeholder="Enter zip">
<button type="button" (click)="getLocation()">
   <span>Use current location</span>
</button>
</code>```

And in my component, I'm trying to just set the value simply like this:

```<code>@ViewChild('zipEl') zipEl:ElementRef;

constructor(private renderer: Renderer2) {

}

getLocation() {
    this.renderer.setValue(this.zipEl, '94085');
}
</code>```

Though nothing is happening. When I click the button to run the function, the input box never gets its value updated with 94085. Does anyone know what I'm doing wrong here?

Thanks in advance!

答:
What is your angular version ?

I do not yet find in which version is Renderer2

But it work with Renderer :

```<code>  @ViewChild('zipEl') zipEl:ElementRef;
  constructor(public renderer: Renderer) {
  }

  getLocation() {
    this.renderer.setElementAttribute(this.zipEl.nativeElement, 'value', '94085');
  }
</code>```

Body:
I'm trying to update the value of an input that isn't bound to a <form> in my component, and my research has lead me to use the Renderer2 service that Angular provides.

So I have my input that looks like this:

<input type="text" #zipEl placeholder="Enter zip">
<button type="button" (click)="getLocation()">
   Use current location
</button>

And in my component, I'm trying to just set the value simply like this:

@ViewChild('zipEl') zipEl:ElementRef;

constructor(private renderer: Renderer2) {

}

getLocation() {
    this.renderer.setValue(this.zipEl, '94085');
}

Though nothing is happening. When I click the button to run the function, the input box never gets its value updated with 94085. Does anyone know what I'm doing wrong here?

Thanks in advance!

Body:
What is your angular version ?

I do not yet find in which version is Renderer2

But it work with Renderer :

  @ViewChild('zipEl') zipEl:ElementRef;
  constructor(public renderer: Renderer) {
  }

  getLocation() {
    this.renderer.setElementAttribute(this.zipEl.nativeElement, 'value', '94085');
  }


问:
How to add Jboss server in IntelliJ
Does anyone know how to setup JBoss server in IntelliJ and debug J2EE application from within the IDE?

When I click on + sign in Settings > Plugins there is no option for JBoss.

答:
You can type cmd+shift+a ( or ctrl+shift+a on windows ) to access the action pop-up, then type something like add server and choose the 'server' option. This will bring you to the application servers panel of the preferences where you can add (+) the JBoss server.

Note: you only have JEE support in the ultimate version. The open-source version doesn't have this capability.

Title: How to add Jboss server in IntelliJ