问:
Check if array of objects key is empty and splice it
I have an array of objects, in that there is an empty key with Boolean value, if the Boolean value is false then the array of objects should be spliced.

The below is the array structure:

this.dataTobeDeleted= [{
    NotificationID: "2180",
    Quantity: 1,
    NotificationName: "453",
    AlertNumber: "02/19/2020",
    "": true
  },
  {
    NotificationID: "2182",
    Quantity: 1,
    NotificationName: "453",
    AlertNumber: "02/19/2020",
    "": false
  },
  {
    NotificationID: "2181",
    Quantity: 1,
    NotificationName: "453",
    AlertNumber: "02/19/2020",
    "": false
  }
]```
</div>
</div>
</p>

<p>In the above array there is an empty string "key" if the key value is <code>false</code> then need to splice the array of objects using index.</p>

<p>Below is the code which I have tried:</p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>for (var i = 0; i < this.dataTobeDeleted.length; i++) {
    for (var val in this.dataTobeDeleted[i]) {
      if (val === "") {

        this.dataTobeDeleted[i]['isCheckedValue'] = this.dataTobeDeleted[i][""]; // insetring new key for empty key string
        delete this.dataTobeDeleted[i][""]; // Delete old key
        if (this.dataTobeDeleted[i].isCheckedValue === false) {
          this.dataTobeDeleted.splice(i, 1)
        }
      }
    }
}</code>```

The above code is correct, but I need it in shorter way as the code I tried is in lengthier and when there is too much data it will create a problem.

I tried using filter also, but I am not getting the empty key to check the boolean value.

答:
This is experimental, but you could also dabble with native ES6 iterator (using a generator) instead of looping through the data backwards.

class ClassicIterator {
  constructor(list) {
    this.list = list;
    this.index = 0;
  }
  *[Symbol.iterator]() {
    while (this.index < this.list.length) {
      yield this.list[this.index];
      this.index++; // Move forward
    }
  }
  remove() {
    this.list.splice(this.index, 1);
    this.index--; // Rollback
  }
}

class InPlaceFilter {
  constructor(opts) {
    this.list = opts.list;
    this.filterFn = opts.filterFn;
  }
  execute() {
    let it = new ClassicIterator(this.list);
    for (let item of it) {
      if (!this.filterFn(item)) {
        it.remove();
      }
    }
    return this;
  }
  get() {
    return this.list;
  }
}

const data = [
  { NotificationID:"2180", Quantity:1, NotificationName:"453", AlertNumber:"02/19/2020", "":true  },
  { NotificationID:"2181", Quantity:1, NotificationName:"453", AlertNumber:"02/19/2020", "":false },
  { NotificationID:"2182", Quantity:1, NotificationName:"453", AlertNumber:"02/19/2020", "":false },
  { NotificationID:"2183", Quantity:1, NotificationName:"453", AlertNumber:"02/19/2020", "":true  }
];

let sameRef = new InPlaceFilter({
  list : data,
  filterFn : (e) => e[''] === false
}).execute().get();

console.log('Are the same?:', sameRef === data); // Same list!```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.as-console-wrapper { top: 0; max-height: 100% !important; }</code>```

Simplified version:

const InPlaceFilter = (opts) => {
  for (let i = opts.list.length - 1; i >= 0; i--) {
    if (!opts.filterFn(opts.list[i])) {
      opts.list.splice(i, 1);
    }
  }
  return opts.list;
}

const data = [
  { NotificationID:"2180", Quantity:1, NotificationName:"453", AlertNumber:"02/19/2020", "":true  },
  { NotificationID:"2181", Quantity:1, NotificationName:"453", AlertNumber:"02/19/2020", "":false },
  { NotificationID:"2182", Quantity:1, NotificationName:"453", AlertNumber:"02/19/2020", "":false },
  { NotificationID:"2183", Quantity:1, NotificationName:"453", AlertNumber:"02/19/2020", "":true  }
];

let otherRef = data.filter(e => e[''] === false);
let sameRef = InPlaceFilter({
  list : data,
  filterFn : (e) => e[''] === false
});

console.log('Are the same?:', sameRef === data);     // Same list!
console.log('Are the same?:', sameRef === otherRef); // Not the same list!```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.as-console-wrapper { top: 0; max-height: 100% !important; }</code>```

Body:
I have an array of objects, in that there is an empty key with Boolean value, if the Boolean value is false then the array of objects should be spliced.

The below is the array structure:

this.dataTobeDeleted= [{
    NotificationID: "2180",
    Quantity: 1,
    NotificationName: "453",
    AlertNumber: "02/19/2020",
    "": true
  },
  {
    NotificationID: "2182",
    Quantity: 1,
    NotificationName: "453",
    AlertNumber: "02/19/2020",
    "": false
  },
  {
    NotificationID: "2181",
    Quantity: 1,
    NotificationName: "453",
    AlertNumber: "02/19/2020",
    "": false
  }
]

In the above array there is an empty string "key" if the key value is false then need to splice the array of objects using index.

Below is the code which I have tried:

for (var i = 0; i < this.dataTobeDeleted.length; i++) {
    for (var val in this.dataTobeDeleted[i]) {
      if (val === "") {

        this.dataTobeDeleted[i]['isCheckedValue'] = this.dataTobeDeleted[i][""]; // insetring new key for empty key string
        delete this.dataTobeDeleted[i][""]; // Delete old key
        if (this.dataTobeDeleted[i].isCheckedValue === false) {
          this.dataTobeDeleted.splice(i, 1)
        }
      }
    }
}

The above code is correct, but I need it in shorter way as the code I tried is in lengthier and when there is too much data it will create a problem.

I tried using filter also, but I am not getting the empty key to check the boolean value.

Body:
This is experimental, but you could also dabble with native ES6 iterator (using a generator) instead of looping through the data backwards.

class ClassicIterator {
  constructor(list) {
    this.list = list;
    this.index = 0;
  }
  *[Symbol.iterator]() {
    while (this.index < this.list.length) {
      yield this.list[this.index];
      this.index++; // Move forward
    }
  }
  remove() {
    this.list.splice(this.index, 1);
    this.index--; // Rollback
  }
}

class InPlaceFilter {
  constructor(opts) {
    this.list = opts.list;
    this.filterFn = opts.filterFn;
  }
  execute() {
    let it = new ClassicIterator(this.list);
    for (let item of it) {
      if (!this.filterFn(item)) {
        it.remove();
      }
    }
    return this;
  }
  get() {
    return this.list;
  }
}

const data = [
  { NotificationID:"2180", Quantity:1, NotificationName:"453", AlertNumber:"02/19/2020", "":true  },
  { NotificationID:"2181", Quantity:1, NotificationName:"453", AlertNumber:"02/19/2020", "":false },
  { NotificationID:"2182", Quantity:1, NotificationName:"453", AlertNumber:"02/19/2020", "":false },
  { NotificationID:"2183", Quantity:1, NotificationName:"453", AlertNumber:"02/19/2020", "":true  }
];

let sameRef = new InPlaceFilter({
  list : data,
  filterFn : (e) => e[''] === false
}).execute().get();

console.log('Are the same?:', sameRef === data); // Same list!

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

Simplified version:

const InPlaceFilter = (opts) => {
  for (let i = opts.list.length - 1; i >= 0; i--) {
    if (!opts.filterFn(opts.list[i])) {
      opts.list.splice(i, 1);
    }
  }
  return opts.list;
}

const data = [
  { NotificationID:"2180", Quantity:1, NotificationName:"453", AlertNumber:"02/19/2020", "":true  },
  { NotificationID:"2181", Quantity:1, NotificationName:"453", AlertNumber:"02/19/2020", "":false },
  { NotificationID:"2182", Quantity:1, NotificationName:"453", AlertNumber:"02/19/2020", "":false },
  { NotificationID:"2183", Quantity:1, NotificationName:"453", AlertNumber:"02/19/2020", "":true  }
];

let otherRef = data.filter(e => e[''] === false);
let sameRef = InPlaceFilter({
  list : data,
  filterFn : (e) => e[''] === false
});

console.log('Are the same?:', sameRef === data);     // Same list!
console.log('Are the same?:', sameRef === otherRef); // Not the same list!

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


来源: stackexchange

问:
Template friendly string to numeric in C++
In C++ standard library there are functions to convert from string to numeric types:

```<code>stoi
stol
stoll
stoul
stoull
stof
stod
stold
</code>```

but I find it tedious to use them in template code. Why there are no template functions something like:

```<code>template<typename T>
T sto(...)
</code>```

to convert strings to numeric types?

I don't see any technical reason to not have them, but maybe I'm missing something. They can be specialised to call the underlying named functions and use enable_if/concepts to disable non numeric types.

Are there any template friendly alternatives in the standard library to convert string to numeric types and the other way around in an efficient way?

答:
It's not a template, and it doesn't work with locales but if that isn't a show stopper then C++17 already has what you want: std::from_chars

There are overloads for all of the integer and floating-point types and the interface is the same except for the last parameters which are different for the integer and floating-point types respectively (but if the default is fine then you don't need to change anything).  Because this is not a locale-aware function it is also quite fast.  It will beat any of the other string to value conversion function and generally it is by orders of magnitude.

There is a very good CPPCON video about <charconv> (the header from_chars lives in) by Stephan T. Lavavej that you can watch about its usage and performance here: https://www.youtube.com/watch?v=4P_kbF0EbZM

ContentLicense: CC BY-SA 4.0

Body:
In C++ standard library there are functions to convert from string to numeric types:

stoi
stol
stoll
stoul
stoull
stof
stod
stold

but I find it tedious to use them in template code. Why there are no template functions something like:

template<typename T>
T sto(...)

to convert strings to numeric types?

I don't see any technical reason to not have them, but maybe I'm missing something. They can be specialised to call the underlying named functions and use enable_if/concepts to disable non numeric types.

Are there any template friendly alternatives in the standard library to convert string to numeric types and the other way around in an efficient way?


问:
Require two identically named classes in ruby
In my rails application I connect to another ruby application foo that has a class Database in its folder /classes/database.rb and to another application bar that has another class Databse in its folder /classes/database.rb

In that application I have to put the requires in the application controller. That is done by the following code

```<code>$: << "C:\foo\
require "plug_in_foo.rb"
</code>```

in the plug_in_foo.rb there are the requires of the foo project, i.e.

```<code>require "/classes/database.rb"
</code>```

as in the foo project so for the bar project

```<code>$: << "C:\bar\
require "plug_in_bar.rb"
</code>```

and in the plug_in_bar.rb there are the requires of the bar project, i.e.

```<code>require "/classes/database.rb"
</code>```

The Database class in the bar project has its own module wrapped around it but when I try to access the class by BaRModule::Datbase.new it is recognized as an unitialized constant so I think that the require does not work.

Can someone help me with this? Is there a workaround for this?

答:
You can require the absolute paths to the different database files.

(You might also check, if you really need to add all this stuff to your load path)

ContentLicense: CC BY-SA 3.0

Body:
In my rails application I connect to another ruby application foo that has a class Database in its folder /classes/database.rb and to another application bar that has another class Databse in its folder /classes/database.rb

In that application I have to put the requires in the application controller. That is done by the following code

$: << "C:\foo\
require "plug_in_foo.rb"

in the plug_in_foo.rb there are the requires of the foo project, i.e.

require "/classes/database.rb"

as in the foo project so for the bar project

$: << "C:\bar\
require "plug_in_bar.rb"

and in the plug_in_bar.rb there are the requires of the bar project, i.e.

require "/classes/database.rb"

The Database class in the bar project has its own module wrapped around it but when I try to access the class by BaRModule::Datbase.new it is recognized as an unitialized constant so I think that the require does not work.

Can someone help me with this? Is there a workaround for this?


问:
Ocaml: Sorting a list into equivalence classes
I recently started learning ocaml and am having trouble figuring out a problem.

Goal:

Given a list of integers and a function, sort the integers into equivalence classes based on the given function as lists inside another list. The order of the equivalence lists must be the same as the order given in the original list.

Update: I have decided to try and get it working without library function.

This is my code so far. It compiles but does not run. Any help with syntax would be appreciated.

```<code>let buckets f lst =
  let rec helpfunction f lst newlist =
     match lst with
      | [] ->newlist
      | h::t -> match newlist with
             | [] -> helpfunction f lst [h]@newlist
             | [a]::_ -> if f h a
                  then helpfunction f t [a::h]@newlist
                  else helpfunction f t ([a]::[h]@mylist
</code>```

IMPORTANT: this is a homework question, so I am not looking for the code pasted for me. Im trying to logic through it on my home with a bit of help with the overall thought-process and syntax. Once I get it working I would to work on making it more efficient

答:
What you are trying is to take each element in the input and then insert it somewhere in the result list of lists. Let me propose a different approach.

You start with an 'a list of input and an empty 'a list list of the result you construct.

If the input is empty your result is complete and you return it.

Otherwise split the input into head and tail (the pattern matching does that already). Next partition the input list into items that are equivalent to the head and those that are not. Recurse with the second list as new input and (first list :: result) as new result.

Body:
I recently started learning ocaml and am having trouble figuring out a problem.

Goal:

Given a list of integers and a function, sort the integers into equivalence classes based on the given function as lists inside another list. The order of the equivalence lists must be the same as the order given in the original list.

Update: I have decided to try and get it working without library function.

This is my code so far. It compiles but does not run. Any help with syntax would be appreciated.

let buckets f lst =
  let rec helpfunction f lst newlist =
     match lst with
      | [] ->newlist
      | h::t -> match newlist with
             | [] -> helpfunction f lst [h]@newlist
             | [a]::_ -> if f h a
                  then helpfunction f t [a::h]@newlist
                  else helpfunction f t ([a]::[h]@mylist

IMPORTANT: this is a homework question, so I am not looking for the code pasted for me. Im trying to logic through it on my home with a bit of help with the overall thought-process and syntax. Once I get it working I would to work on making it more efficient


问:
When asyncio task gets stored after creation, exceptions from task get muted
I was using asyncio for a project, and encountered this strange behavior.

```<code>import asyncio

def schedule_something():
    global f
    tsk = asyncio.async(do_something())
    f = tsk #If this line is commented out, exceptions can be heard.

@asyncio.coroutine
def do_something():
    raise Exception()

loop = asyncio.get_event_loop()
loop.call_soon(schedule_something)
loop.run_forever()
loop.close()
</code>```

For some reason, storing the resulting task when you call asyncio.async() stops exceptions from doing anything.

Could someone shed some light on this situation? I need to have a way to catch exceptions in my current project.

答:
Thanks, @dano. Here's a drop-in replacement for asyncio.create_task that does this automatically -

def create_task(coro):
    task = asyncio.create_task(coro)
    return TaskWrapper(task)

class TaskWrapper:
    def __init__(self, task):
        self.task = task
        task.add_done_callback(self.on_task_done)

    def __getattr__(self, name):
        return getattr(self.task, name)

    def __await__(self):
        self.task.remove_done_callback(self.on_task_done)
        return self.task.__await__()

    def on_task_done(self, fut: asyncio.Future):
        if fut.cancelled() or not fut.done():
            return
        fut.result()

    def __str__(self):
        return f"TaskWrapper<task={self.task}>"
```

<hr>

<p>Updated version of the given example -</p>

<pre class="lang-py prettyprint-override"><code>async def do_something():
    raise Exception()

async def schedule_something():
    global f
    tsk = create_task(do_something())
    f = tsk  # If this line is commented out, exceptions can be heard.

asyncio.run(schedule_something())
</code>```

```<code>$ python test.py
Exception in callback TaskWrapper.on_task_done(<Task finishe...n=Exception()>)
handle: <Handle TaskWrapper.on_task_done(<Task finishe...n=Exception()>)>
Traceback (most recent call last):
  File "/Users/dev/.pyenv/versions/3.8.1/lib/python3.8/asyncio/events.py", line 81, in _run
    self._context.run(self._callback, *self._args)
  File "/Users/dev/Projects/dara/server/bot/async_util.py", line 21, in on_task_done
    fut.result()
  File "/Users/dev/Projects/dara/server/test.py", line 7, in do_something
    raise Exception()
Exception
</code>```

Body:
I was using asyncio for a project, and encountered this strange behavior.

import asyncio

def schedule_something():
    global f
    tsk = asyncio.async(do_something())
    f = tsk #If this line is commented out, exceptions can be heard.

@asyncio.coroutine
def do_something():
    raise Exception()

loop = asyncio.get_event_loop()
loop.call_soon(schedule_something)
loop.run_forever()
loop.close()

For some reason, storing the resulting task when you call asyncio.async() stops exceptions from doing anything.

Could someone shed some light on this situation? I need to have a way to catch exceptions in my current project.

Body:
Thanks, @dano. Here's a drop-in replacement for asyncio.create_task that does this automatically -

def create_task(coro):
    task = asyncio.create_task(coro)
    return TaskWrapper(task)

class TaskWrapper:
    def __init__(self, task):
        self.task = task
        task.add_done_callback(self.on_task_done)

    def __getattr__(self, name):
        return getattr(self.task, name)

    def __await__(self):
        self.task.remove_done_callback(self.on_task_done)
        return self.task.__await__()

    def on_task_done(self, fut: asyncio.Future):
        if fut.cancelled() or not fut.done():
            return
        fut.result()

    def __str__(self):
        return f"TaskWrapper<task={self.task}>"

Updated version of the given example -

async def do_something():
    raise Exception()

async def schedule_something():
    global f
    tsk = create_task(do_something())
    f = tsk  # If this line is commented out, exceptions can be heard.

asyncio.run(schedule_something())

$ python test.py
Exception in callback TaskWrapper.on_task_done(<Task finishe...n=Exception()>)
handle: <Handle TaskWrapper.on_task_done(<Task finishe...n=Exception()>)>
Traceback (most recent call last):
  File "/Users/dev/.pyenv/versions/3.8.1/lib/python3.8/asyncio/events.py", line 81, in _run
    self._context.run(self._callback, *self._args)
  File "/Users/dev/Projects/dara/server/bot/async_util.py", line 21, in on_task_done
    fut.result()
  File "/Users/dev/Projects/dara/server/test.py", line 7, in do_something
    raise Exception()
Exception


问:
Still having problems with jQuery background animate - works in safari and IE, nothing else!
I made a thread a few days ago about animating a background image. I was advised to use a certain plugin which worked ok. I was using jQuery 1.4.2 - however, I have since been having real issues with the coda slider on my website. I then decided to change to the newest jQuery (1.6.1) and the issue was resolved. On the other hand my background animations broke in some browsers.

The weird thing is it works in safari on a mac, and ie9, 8, 7 and even 6 with a transparent png fix. It doesn't work for me in firefox on mac or pc and opera on mac.

Has anyone else had any problems like this? I spent some time making this images and would love to get it sorted! There must be some way round this, or maybe the code I have written it just plain wrong!?

I have made a fiddle with the actual images and script. It's the first one I have made so i'm not 100% sure I have done it right, feel free to say if it needs tweaking...

You can find the jsfiddle here

Many Thanks : )

答:
This is working in FF4 using "background-position : x, y" instead of 2 separate properties :

```<code>$('.trans_bg').css({
    backgroundPosition: "0 0"
});

$('.trans_bg').hover(

function() {
    $(this).stop().animate({
        backgroundPosition: "0 -250"
    }, 500);
}, function() {
    $(this).stop().animate({
        backgroundPosition: "0 0"
    }, 400);
});
</code>```

http://jsfiddle.net/69hZY/4/

Body:
This is working in FF4 using "background-position : x, y" instead of 2 separate properties :

$('.trans_bg').css({
    backgroundPosition: "0 0"
});

$('.trans_bg').hover(

function() {
    $(this).stop().animate({
        backgroundPosition: "0 -250"
    }, 500);
}, function() {
    $(this).stop().animate({
        backgroundPosition: "0 0"
    }, 400);
});

http://jsfiddle.net/69hZY/4/


问:
Simplify Boolean Expression: X + X'Y'Z
I know that the following is equal:
X + X'Y'Z = X + Y'Z
How can simplify the left side to arrive the right side using basic Boolean identities?
Thanks in advance.</p>

Title: Simplify Boolean Expression: X + X'Y'Z

Body:
Expression                            Justification
---------------------------------     -------------------------
X + X'Y'Z                             initial expression
(XY'Z + X(Y'Z)') + X'Y'Z              r  = rs + rs'
(XY'Z + XY'Z + X(Y'Z)') + X'Y'Z       r = r + r
(XY'Z + X(Y'Z)' + XY'Z) + X'Y'Z       r + s = s + r
(XY'Z + X(Y'Z)') + (XY'Z + X'Y'Z)     (r + s) + t = r + (s + t)
X(Y'Z + (Y'Z)') + (Y'Z)(X + X')       rs + rt = r(s + t)
X(1) + (Y'Z)(1)                       r + r' = 1
X + Y'Z                               r(1) = r


问:
Days/Months/Years between two dates
I have two dates. One retrieved from the table from other application in format YYYYMMDD and the second date is local time and I need Days/Months/Years between these two dates.

I tried this

```<code>  my $t = Time::Piece->strptime($expi, "%Y %m %d"); #First date
  my $today = Time::Piece->new; #Localtime

  my $diff = $t - $today;
  print $diff;
</code>```

but this gives me some gibberish numbers.

variable $t = Fri Dec 31 00:00:00 9999

variable $today = Wed Feb 19 14:40:55 2020

OUTPUT: 251820094888

Any ideas?
Thanks in advance.

答:
Time::Piece can at-most get you the difference in seconds, and there's no way to convert that into months, days, etc.

```<code>use DateTime                   qw( );
use DateTime::Format::Strptime qw( );

my $format = DateTime::Format::Strptime->new(
   pattern   => '%Y%m%d',
   time_zone => 'floating',
   on_error  => 'croak',
);

my $today =
   DateTime
   ->now( time_zone => 'local' )
   ->set_time_zone('floating')
   ->truncate( to => 'day' );

my $dt = $format->parse_datetime('20200101');

my $diff = $today - $dt;

printf("%d years, %d months and %d days\n", $diff->in_units(qw( years months days )));
</code>```

Output:

```<code>0 years, 1 months and 18 days
</code>```

Title: Days/Months/Years between two dates

Body:
I have two dates. One retrieved from the table from other application in format YYYYMMDD and the second date is local time and I need Days/Months/Years between these two dates.

I tried this

  my $t = Time::Piece->strptime($expi, "%Y %m %d"); #First date
  my $today = Time::Piece->new; #Localtime

  my $diff = $t - $today;
  print $diff;

but this gives me some gibberish numbers.

variable $t = Fri Dec 31 00:00:00 9999

variable $today = Wed Feb 19 14:40:55 2020

OUTPUT: 251820094888

Any ideas?
Thanks in advance.

Body:
Time::Piece can at-most get you the difference in seconds, and there's no way to convert that into months, days, etc.

use DateTime                   qw( );
use DateTime::Format::Strptime qw( );

my $format = DateTime::Format::Strptime->new(
   pattern   => '%Y%m%d',
   time_zone => 'floating',
   on_error  => 'croak',
);

my $today =
   DateTime
   ->now( time_zone => 'local' )
   ->set_time_zone('floating')
   ->truncate( to => 'day' );

my $dt = $format->parse_datetime('20200101');

my $diff = $today - $dt;

printf("%d years, %d months and %d days\n", $diff->in_units(qw( years months days )));

Output:

0 years, 1 months and 18 days


问:
ResourceHandler stop hosting files with jetty 9 - 404 not found error (works fine with jetty 8)
Apparently, ResourceHandler stop hosting files with jetty 9 - 404 not found error (works fine with jetty 8). Here is the code:

```<code>    ResourceHandler resourceHandler = new ResourceHandler();
    resourceHandler.setDirectoriesListed(true);
    resourceHandler.setResourceBase("some_resource_base");

    HandlerList handlerList = new HandlerList();
    handlerList.setHandlers(new Handler[]{servletHandler, resourceHandler});
    server.setHandler(handlerList);
    server.start();
</code>```

This quistion with the accepted answer does not seem to work against jetty 9 -  Serving static files w/ embedded Jetty

答:
In case somebody is looking for a working example, this is how I combined a ResourceHandler with a ContextHandler (partially based on current Jetty docs: Jetty documentation)</p>

```<code>        srv = new Server();
        ServerConnector srvConn = new ServerConnector(srv);
        srvConn.setHost("localhost");
        srvConn.setPort(8080);
        srvConn.setIdleTimeout(30000);
        srv.addConnector(srvConn);
        //used for webSocket comm later:
        ServletContextHandler context = new ServletContextHandler(ServletContextHandler.SESSIONS);
        context.setContextPath("/");

        //for static  content:
        ResourceHandler resH = new ResourceHandler();
        resH.setDirectoriesListed(true);
        resH.setWelcomeFiles(new String[]{ "index.html" });
        resH.setResourceBase("./my/web/root");
        ContextHandler resCtx = new ContextHandler();
        resCtx.setHandler(resH);

        //Add both ContextHandlers to server:
        ContextHandlerCollection handlers = new ContextHandlerCollection(resCtx, context);
        srv.setHandler(handlers);
</code>```

Body:
Apparently, ResourceHandler stop hosting files with jetty 9 - 404 not found error (works fine with jetty 8). Here is the code:

    ResourceHandler resourceHandler = new ResourceHandler();
    resourceHandler.setDirectoriesListed(true);
    resourceHandler.setResourceBase("some_resource_base");

    HandlerList handlerList = new HandlerList();
    handlerList.setHandlers(new Handler[]{servletHandler, resourceHandler});
    server.setHandler(handlerList);
    server.start();

This quistion with the accepted answer does not seem to work against jetty 9 -  Serving static files w/ embedded Jetty

Body:
In case somebody is looking for a working example, this is how I combined a ResourceHandler with a ContextHandler (partially based on current Jetty docs: Jetty documentation)

        srv = new Server();
        ServerConnector srvConn = new ServerConnector(srv);
        srvConn.setHost("localhost");
        srvConn.setPort(8080);
        srvConn.setIdleTimeout(30000);
        srv.addConnector(srvConn);
        //used for webSocket comm later:
        ServletContextHandler context = new ServletContextHandler(ServletContextHandler.SESSIONS);
        context.setContextPath("/");

        //for static  content:
        ResourceHandler resH = new ResourceHandler();
        resH.setDirectoriesListed(true);
        resH.setWelcomeFiles(new String[]{ "index.html" });
        resH.setResourceBase("./my/web/root");
        ContextHandler resCtx = new ContextHandler();
        resCtx.setHandler(resH);

        //Add both ContextHandlers to server:
        ContextHandlerCollection handlers = new ContextHandlerCollection(resCtx, context);
        srv.setHandler(handlers);


问:
MessageBox in material design wpf c#
I’m using Material Design In XAML Toolkit C# ,MessageBox in material design  WPF C# ,

I need like this or better Design for MessageBox

I’ve tried  use DialogHost but this Error happens

No loaded DialogHost instances.

```<code>private async void MenuPopupButton_OnClick(object sender, RoutedEventArgs e) {
    var sampleMessageDialog = new SampleMessageDialog {
        Message = {Text = "Goodbye"}
    };

    await DialogHost.Show(sampleMessageDialog, "RootDialog");
}
</code>```

No loaded DialogHost instances.

答:
I have developed one custom message box(using material design controls) in my application.
i'll show you the code below of WPF XAML and C#.
it contains three types of message boxes as below.

Yes,No

Ok

Ok,Cancel

Download code from below link.
https://github.com/sandeepjadhav75502/CustomMessageBoxWPF

WPF XAML Code

Heading

```<code><Window x:Class="EVotingDashBoard.MessageBoxCustom"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
        xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
        mc:Ignorable="d"
        Title="MessageBoxWindow" Height="220" Width="500"
        WindowStartupLocation="CenterScreen" WindowStyle="None" Background="White"
        ResizeMode="CanResize" Topmost="True" ShowInTaskbar="False"
        xmlns:materialDesign="http://materialdesigninxaml.net/winfx/xaml/themes"
        TextElement.Foreground="{DynamicResource MaterialDesignBody}"
        TextElement.FontWeight="Regular"
        TextElement.FontSize="10"
        TextOptions.TextFormattingMode="Ideal"
        TextOptions.TextRenderingMode="Auto"
        FontFamily="{DynamicResource MaterialDesignFont}">
    <Grid>
        <Grid.ColumnDefinitions>
            <ColumnDefinition Width="197*"/>
            <ColumnDefinition Width="295*"/>
        </Grid.ColumnDefinitions>
        <Grid.RowDefinitions>
            <RowDefinition Height="auto"/>
            <RowDefinition Height="*"/>
        </Grid.RowDefinitions>
        <materialDesign:Card x:Name="cardHeader" Grid.Row="0" Padding="10" Margin="0" materialDesign:ShadowAssist.ShadowDepth="Depth5"   Background="{DynamicResource PrimaryHueDarkBrush}" Foreground="{DynamicResource PrimaryHueDarkForegroundBrush}" Visibility="Visible" Grid.ColumnSpan="2">
            <StackPanel>
                <TextBlock x:Name="txtTitle" HorizontalAlignment="Center" VerticalAlignment="Stretch" Style="{DynamicResource MaterialDesignTitleTextBlock}" FontSize="20" >Message Title</TextBlock>
            </StackPanel>
        </materialDesign:Card>
        <StackPanel  HorizontalAlignment="Right" Margin="0,5,5,0"  VerticalAlignment="Top" Grid.Column="1">
            <Button x:Name="btnClose" Click="btnClose_Click" Width="35" Height="35"  Background="White" Foreground="{DynamicResource PrimaryHueDarkBrush}" Style="{StaticResource MaterialDesignFloatingActionDarkButton}">
                <materialDesign:PackIcon Kind="Close" />
            </Button>
        </StackPanel>
        <Grid Grid.Row="1" Grid.ColumnSpan="2">
            <Grid Margin="20">
                <Grid.RowDefinitions>
                    <RowDefinition Height="auto"/>
                    <RowDefinition Height="auto"/>
                    <RowDefinition Height="*"/>
                </Grid.RowDefinitions>

                <Grid Grid.Row="0">
                    <Grid.RowDefinitions>
                        <RowDefinition Height="auto"/>
                        <RowDefinition Height="*"/>
                    </Grid.RowDefinitions>

                    <materialDesign:TransitioningContent>
                        <materialDesign:TransitioningContent.OpeningEffects >
                            <materialDesign:TransitionEffect Kind="FadeIn" />
                            <materialDesign:TransitionEffect Kind="SlideInFromBottom" />
                        </materialDesign:TransitioningContent.OpeningEffects>
                        <TextBox x:Name="txtMessage" HorizontalAlignment="Center" IsReadOnly="True" Grid.Row="0" Margin="5" materialDesign:HintAssist.Hint="" FontSize="18" Style="{StaticResource MaterialDesignFloatingHintTextBox}" />
                    </materialDesign:TransitioningContent>

                </Grid>
                <Grid Grid.Row="1" Margin="0,20,0,5">
                    <Grid.ColumnDefinitions>
                        <ColumnDefinition Width="*"/>
                        <ColumnDefinition Width="auto"/>
                        <ColumnDefinition Width="auto"/>
                        <ColumnDefinition Width="*"/>
                    </Grid.ColumnDefinitions>

                    <Button x:Name="btnOk" Click="btnOk_Click" Grid.Column="1" Style="{StaticResource MaterialDesignRaisedButton}" Margin="5" Width="100" Content="OK" ToolTip="Ok"/>
                    <Button x:Name="btnCancel" Click="btnCancel_Click" Grid.Column="2" Style="{StaticResource MaterialDesignRaisedButton}" Margin="5" Width="100" Content="Cancel" ToolTip="Cancel"/>
                    <Button x:Name="btnYes" Click="btnYes_Click" Grid.Column="1" Style="{StaticResource MaterialDesignRaisedButton}" Margin="5" Width="100" Content="Yes" ToolTip="Yes"/>
                    <Button x:Name="btnNo" Click="btnNo_Click" Grid.Column="2" Style="{StaticResource MaterialDesignRaisedButton}" Margin="5" Width="100" Content="No" ToolTip="No"/>
                </Grid>

            </Grid>
        </Grid>
    </Grid>
</Window>
</code>```

C# Code Behind

```<code> /// <summary>
    /// Interaction logic for MessageBoxCustom.xaml
    /// </summary>
    public partial class MessageBoxCustom : Window
    {
        public MessageBoxCustom(string Message, MessageType Type, MessageButtons Buttons)
        {
            InitializeComponent();
            txtMessage.Text = Message;
            switch (Type)
            {

                case MessageType.Info:
                    txtTitle.Text = "Info";
                    break;
                case MessageType.Confirmation:
                    txtTitle.Text = "Confirmation";
                    break;
                case MessageType.Success:
                    {
                        txtTitle.Text = "Success";
                    }
                    break;
                case MessageType.Warning:
                    txtTitle.Text = "Warning";
                    break;
                case MessageType.Error:
                    {
                        txtTitle.Text = "Error";
                    }
                    break;
            }
            switch (Buttons)
            {
                case MessageButtons.OkCancel:
                    btnYes.Visibility = Visibility.Collapsed; btnNo.Visibility = Visibility.Collapsed;
                    break;
                case MessageButtons.YesNo:
                    btnOk.Visibility = Visibility.Collapsed; btnCancel.Visibility = Visibility.Collapsed;
                    break;
                case MessageButtons.Ok:
                    btnOk.Visibility = Visibility.Visible;
                    btnCancel.Visibility = Visibility.Collapsed;
                    btnYes.Visibility = Visibility.Collapsed; btnNo.Visibility = Visibility.Collapsed;
                    break;
            }
        }

        private void btnYes_Click(object sender, RoutedEventArgs e)
        {
            this.DialogResult = true;
            this.Close();
        }

        private void btnCancel_Click(object sender, RoutedEventArgs e)
        {
            this.DialogResult = false;
            this.Close();
        }

        private void btnOk_Click(object sender, RoutedEventArgs e)
        {
            this.DialogResult = true;
            this.Close();
        }

        private void btnNo_Click(object sender, RoutedEventArgs e)
        {
            this.DialogResult = false;
            this.Close();
        }

        private void btnClose_Click(object sender, RoutedEventArgs e)
        {
            this.DialogResult = false;
            this.Close();
        }
    }
    public enum MessageType
    {
        Info,
        Confirmation,
        Success,
        Warning,
        Error,
    }
    public enum MessageButtons
    {
        OkCancel,
        YesNo,
        Ok,
    }
</code>```

we can call it like

```<code> private void Button_Close(object sender, RoutedEventArgs e)
 {
        bool? Result = new MessageBoxCustom("Are you sure, You want to close
        application ?", MessageType.Confirmation, MessageButtons.YesNo).ShowDialog();

        if (Result.Value)
        {
            Application.Current.Shutdown();
        }
    }
</code>```

Title: MessageBox in material design wpf c#

Body:
I’m using Material Design In XAML Toolkit C# ,MessageBox in material design  WPF C# ,

I need like this or better Design for MessageBox

I’ve tried  use DialogHost but this Error happens

No loaded DialogHost instances.

private async void MenuPopupButton_OnClick(object sender, RoutedEventArgs e) {
    var sampleMessageDialog = new SampleMessageDialog {
        Message = {Text = "Goodbye"}
    };

    await DialogHost.Show(sampleMessageDialog, "RootDialog");
}

No loaded DialogHost instances.

Body:
I have developed one custom message box(using material design controls) in my application.
i'll show you the code below of WPF XAML and C#.
it contains three types of message boxes as below.

Yes,No

Ok

Ok,Cancel

Download code from below link.
https://github.com/sandeepjadhav75502/CustomMessageBoxWPF

WPF XAML Code

Heading

<Window x:Class="EVotingDashBoard.MessageBoxCustom"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
        xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
        mc:Ignorable="d"
        Title="MessageBoxWindow" Height="220" Width="500"
        WindowStartupLocation="CenterScreen" WindowStyle="None" Background="White"
        ResizeMode="CanResize" Topmost="True" ShowInTaskbar="False"
        xmlns:materialDesign="http://materialdesigninxaml.net/winfx/xaml/themes"
        TextElement.Foreground="{DynamicResource MaterialDesignBody}"
        TextElement.FontWeight="Regular"
        TextElement.FontSize="10"
        TextOptions.TextFormattingMode="Ideal"
        TextOptions.TextRenderingMode="Auto"
        FontFamily="{DynamicResource MaterialDesignFont}">
    <Grid>
        <Grid.ColumnDefinitions>
            <ColumnDefinition Width="197*"/>
            <ColumnDefinition Width="295*"/>
        </Grid.ColumnDefinitions>
        <Grid.RowDefinitions>
            <RowDefinition Height="auto"/>
            <RowDefinition Height="*"/>
        </Grid.RowDefinitions>
        <materialDesign:Card x:Name="cardHeader" Grid.Row="0" Padding="10" Margin="0" materialDesign:ShadowAssist.ShadowDepth="Depth5"   Background="{DynamicResource PrimaryHueDarkBrush}" Foreground="{DynamicResource PrimaryHueDarkForegroundBrush}" Visibility="Visible" Grid.ColumnSpan="2">
            <StackPanel>
                <TextBlock x:Name="txtTitle" HorizontalAlignment="Center" VerticalAlignment="Stretch" Style="{DynamicResource MaterialDesignTitleTextBlock}" FontSize="20" >Message Title</TextBlock>
            </StackPanel>
        </materialDesign:Card>
        <StackPanel  HorizontalAlignment="Right" Margin="0,5,5,0"  VerticalAlignment="Top" Grid.Column="1">
            <Button x:Name="btnClose" Click="btnClose_Click" Width="35" Height="35"  Background="White" Foreground="{DynamicResource PrimaryHueDarkBrush}" Style="{StaticResource MaterialDesignFloatingActionDarkButton}">
                <materialDesign:PackIcon Kind="Close" />
            </Button>
        </StackPanel>
        <Grid Grid.Row="1" Grid.ColumnSpan="2">
            <Grid Margin="20">
                <Grid.RowDefinitions>
                    <RowDefinition Height="auto"/>
                    <RowDefinition Height="auto"/>
                    <RowDefinition Height="*"/>
                </Grid.RowDefinitions>

                <Grid Grid.Row="0">
                    <Grid.RowDefinitions>
                        <RowDefinition Height="auto"/>
                        <RowDefinition Height="*"/>
                    </Grid.RowDefinitions>

                    <materialDesign:TransitioningContent>
                        <materialDesign:TransitioningContent.OpeningEffects >
                            <materialDesign:TransitionEffect Kind="FadeIn" />
                            <materialDesign:TransitionEffect Kind="SlideInFromBottom" />
                        </materialDesign:TransitioningContent.OpeningEffects>
                        <TextBox x:Name="txtMessage" HorizontalAlignment="Center" IsReadOnly="True" Grid.Row="0" Margin="5" materialDesign:HintAssist.Hint="" FontSize="18" Style="{StaticResource MaterialDesignFloatingHintTextBox}" />
                    </materialDesign:TransitioningContent>

                </Grid>
                <Grid Grid.Row="1" Margin="0,20,0,5">
                    <Grid.ColumnDefinitions>
                        <ColumnDefinition Width="*"/>
                        <ColumnDefinition Width="auto"/>
                        <ColumnDefinition Width="auto"/>
                        <ColumnDefinition Width="*"/>
                    </Grid.ColumnDefinitions>

                    <Button x:Name="btnOk" Click="btnOk_Click" Grid.Column="1" Style="{StaticResource MaterialDesignRaisedButton}" Margin="5" Width="100" Content="OK" ToolTip="Ok"/>
                    <Button x:Name="btnCancel" Click="btnCancel_Click" Grid.Column="2" Style="{StaticResource MaterialDesignRaisedButton}" Margin="5" Width="100" Content="Cancel" ToolTip="Cancel"/>
                    <Button x:Name="btnYes" Click="btnYes_Click" Grid.Column="1" Style="{StaticResource MaterialDesignRaisedButton}" Margin="5" Width="100" Content="Yes" ToolTip="Yes"/>
                    <Button x:Name="btnNo" Click="btnNo_Click" Grid.Column="2" Style="{StaticResource MaterialDesignRaisedButton}" Margin="5" Width="100" Content="No" ToolTip="No"/>
                </Grid>

            </Grid>
        </Grid>
    </Grid>
</Window>

C# Code Behind

 /// <summary>
    /// Interaction logic for MessageBoxCustom.xaml
    /// </summary>
    public partial class MessageBoxCustom : Window
    {
        public MessageBoxCustom(string Message, MessageType Type, MessageButtons Buttons)
        {
            InitializeComponent();
            txtMessage.Text = Message;
            switch (Type)
            {

                case MessageType.Info:
                    txtTitle.Text = "Info";
                    break;
                case MessageType.Confirmation:
                    txtTitle.Text = "Confirmation";
                    break;
                case MessageType.Success:
                    {
                        txtTitle.Text = "Success";
                    }
                    break;
                case MessageType.Warning:
                    txtTitle.Text = "Warning";
                    break;
                case MessageType.Error:
                    {
                        txtTitle.Text = "Error";
                    }
                    break;
            }
            switch (Buttons)
            {
                case MessageButtons.OkCancel:
                    btnYes.Visibility = Visibility.Collapsed; btnNo.Visibility = Visibility.Collapsed;
                    break;
                case MessageButtons.YesNo:
                    btnOk.Visibility = Visibility.Collapsed; btnCancel.Visibility = Visibility.Collapsed;
                    break;
                case MessageButtons.Ok:
                    btnOk.Visibility = Visibility.Visible;
                    btnCancel.Visibility = Visibility.Collapsed;
                    btnYes.Visibility = Visibility.Collapsed; btnNo.Visibility = Visibility.Collapsed;
                    break;
            }
        }

        private void btnYes_Click(object sender, RoutedEventArgs e)
        {
            this.DialogResult = true;
            this.Close();
        }

        private void btnCancel_Click(object sender, RoutedEventArgs e)
        {
            this.DialogResult = false;
            this.Close();
        }

        private void btnOk_Click(object sender, RoutedEventArgs e)
        {
            this.DialogResult = true;
            this.Close();
        }

        private void btnNo_Click(object sender, RoutedEventArgs e)
        {
            this.DialogResult = false;
            this.Close();
        }

        private void btnClose_Click(object sender, RoutedEventArgs e)
        {
            this.DialogResult = false;
            this.Close();
        }
    }
    public enum MessageType
    {
        Info,
        Confirmation,
        Success,
        Warning,
        Error,
    }
    public enum MessageButtons
    {
        OkCancel,
        YesNo,
        Ok,
    }

we can call it like

 private void Button_Close(object sender, RoutedEventArgs e)
 {
        bool? Result = new MessageBoxCustom("Are you sure, You want to close
        application ?", MessageType.Confirmation, MessageButtons.YesNo).ShowDialog();

        if (Result.Value)
        {
            Application.Current.Shutdown();
        }
    }


答:
You wouldn't gain much because in an expression like

```<code>int x = sto("1");
</code>```

There is no (easy) way to deduce the desired type for the template parameter. You would have to write

```<code>int x = sto<int>("1");
</code>```

which to some extend defeats the purpose of providing a generic function. On the other hand, a

```<code>template<typename T>
void sto(std::string x,T& t);
</code>```

would be of good use as you realized. In C++17 there is std::from_chars, which does more or less exactly that (it is no template but a set of overloads and it takes pointers to chars instead of a string, but thats only minor details).

PS
There is no easy way to deduce the desired type in the above expression, but there is a way. I dont think the core of your question was exactly the signature you asked for, and I dont think the following is a good way to implement it, but I knew that there is a way to make the above int x = sto("1"); compile and I was curious to see it in action.

```<code>#include <iostream>
#include <string>

struct converter {
    const std::string& x;
    template <typename T> operator T() { return 0;}
};

template <> converter::operator int() { return stoi(x); }
template <> converter::operator double() { return stod(x); }
converter sto(const std::string& x) { return {x}; }

int main() {
    std::string s{"1.23"};
    int x = sto(s);
    double y = sto(s);
    std::cout << x << " " << y;
}
</code>```

This works as intended, but it has severe downsides, maybe most importantly it allows to write auto x = sto(s);, ie it is easy to use wrong.

Title: Template friendly string to numeric in C++

Body:
You wouldn't gain much because in an expression like

int x = sto("1");

There is no (easy) way to deduce the desired type for the template parameter. You would have to write

int x = sto<int>("1");

which to some extend defeats the purpose of providing a generic function. On the other hand, a

template<typename T>
void sto(std::string x,T& t);

would be of good use as you realized. In C++17 there is std::from_chars, which does more or less exactly that (it is no template but a set of overloads and it takes pointers to chars instead of a string, but thats only minor details).

PS
There is no easy way to deduce the desired type in the above expression, but there is a way. I dont think the core of your question was exactly the signature you asked for, and I dont think the following is a good way to implement it, but I knew that there is a way to make the above int x = sto("1"); compile and I was curious to see it in action.

#include <iostream>
#include <string>

struct converter {
    const std::string& x;
    template <typename T> operator T() { return 0;}
};

template <> converter::operator int() { return stoi(x); }
template <> converter::operator double() { return stod(x); }
converter sto(const std::string& x) { return {x}; }

int main() {
    std::string s{"1.23"};
    int x = sto(s);
    double y = sto(s);
    std::cout << x << " " << y;
}

This works as intended, but it has severe downsides, maybe most importantly it allows to write auto x = sto(s);, ie it is easy to use wrong.


问:
MATLAB: Does there exist a smart way to remove adjacent (x,y) points stored in some array?
Does there? I am thinking specifically about some matrix array where the rows correspond to x and y coordinates, e.g.

```<code>4 3
4 5
5 4
3 4
4 4
</code>```

such that (4,3) and (4,5) etc. are (x,y) points. The problem is this: If one of the points in the list is surrounded adjacently by other points in the list, e.g.

```<code>(~,~) (4,5) (~,~)
(3,4) (4,4) (5,4)
(~,~) (4,3) (~,~)
</code>```

as would be the case for the list above, then I would like to remove it in some efficient manner. It is very easy to see visually if this is satisfied by some point, but how do I do it in code? I am just looking for some suggestions, so if someone has encountered this problem before or have some input I would appreciate to read it!

Best regards,

答:
I'm not sure if you can avoid looping here (not sure if that's what you meant by efficient anyway...). At least i didn't come up with a solution without loops off the top of my head but this should do it.

```<code>vec = [4 3; 4 5; 5 4; 3 4; 4 4; 6 7; 6 8; 6 6; 5 7; 7 7];
for i = 1:length(vec)
    point = vec(i,:);
    mat = vec-point;
    % Calculate diagonal values of the matrix product
    % Note that sum(mat.*mat,2) might be a bit faster. You can try yourself.
    tmp = diag(mat*mat');
    if (length(find(tmp == 1)) == 4)
        % If we find 4 values of 1 in tmp, the point is surrounded
        % E.g., remove the value here if you wish
        point
    end
end
</code>```

edit: Also, note that this won't work properly if you have duplicate points in the vector.

Body:
Does there? I am thinking specifically about some matrix array where the rows correspond to x and y coordinates, e.g.

4 3
4 5
5 4
3 4
4 4

such that (4,3) and (4,5) etc. are (x,y) points. The problem is this: If one of the points in the list is surrounded adjacently by other points in the list, e.g.

(~,~) (4,5) (~,~)
(3,4) (4,4) (5,4)
(~,~) (4,3) (~,~)

as would be the case for the list above, then I would like to remove it in some efficient manner. It is very easy to see visually if this is satisfied by some point, but how do I do it in code? I am just looking for some suggestions, so if someone has encountered this problem before or have some input I would appreciate to read it!

Best regards,

Body:
I'm not sure if you can avoid looping here (not sure if that's what you meant by efficient anyway...). At least i didn't come up with a solution without loops off the top of my head but this should do it.

vec = [4 3; 4 5; 5 4; 3 4; 4 4; 6 7; 6 8; 6 6; 5 7; 7 7];
for i = 1:length(vec)
    point = vec(i,:);
    mat = vec-point;
    % Calculate diagonal values of the matrix product
    % Note that sum(mat.*mat,2) might be a bit faster. You can try yourself.
    tmp = diag(mat*mat');
    if (length(find(tmp == 1)) == 4)
        % If we find 4 values of 1 in tmp, the point is surrounded
        % E.g., remove the value here if you wish
        point
    end
end

edit: Also, note that this won't work properly if you have duplicate points in the vector.


问:
Running iOS app on device causes runtime error
When I try to run my app on an iPhone I get the following error. Running on a simulator is fine.

```<code>  Referenced from: /private/var/containers/Bundle/Application/4108D01F-FE3D-49AD-BDAA-1D020A41DB65/MyApp.app/MyApp
  Reason: no suitable image found.  Did find:
    /private/var/containers/Bundle/Application/4108D01F-FE3D-49AD-BDAA-1D020A41DB65/MyApp.app/Frameworks/ExampleSDK.framework/ExampleSDK: code signature invalid for '/private/var/containers/Bundle/Application/4108D01F-FE3D-49AD-BDAA-1D020A41DB65/SDKDevApp.app/Frameworks/ExampleSDK.framework/ExampleSDK'
</code>```

This is basically worked yesterday, and suddenly it doesn't today.

I already tried out this solution and found this thread but the solution exposed there don't work for me.

I tried out using both Cocoapods and just simply adding the framework to my project.

答:
I observed that it only reproduces on iPhones with iOS 13.3.1
I don't know if it's because of that, but since everything the you guys suggested din't work I will close this and treat it as an iOS 13.3.1 bug until otherwise proven.</p>

Body:
When I try to run my app on an iPhone I get the following error. Running on a simulator is fine.

  Referenced from: /private/var/containers/Bundle/Application/4108D01F-FE3D-49AD-BDAA-1D020A41DB65/MyApp.app/MyApp
  Reason: no suitable image found.  Did find:
    /private/var/containers/Bundle/Application/4108D01F-FE3D-49AD-BDAA-1D020A41DB65/MyApp.app/Frameworks/ExampleSDK.framework/ExampleSDK: code signature invalid for '/private/var/containers/Bundle/Application/4108D01F-FE3D-49AD-BDAA-1D020A41DB65/SDKDevApp.app/Frameworks/ExampleSDK.framework/ExampleSDK'

This is basically worked yesterday, and suddenly it doesn't today.

I already tried out this solution and found this thread but the solution exposed there don't work for me.

I tried out using both Cocoapods and just simply adding the framework to my project.


问:
Does the Qt MQTT package provide an easy way of writing my own broker?
I'm considering trying the MQTT implementation provided by Qt.
I've studied the documentation, the classes, the members of the classes, and the examples. Nowhere did I find anything indicating how to make my own broker.
All the examples, and all the classes and the available source code seem to be limited to creating a client. The examples use some online broker service to test this client.

So, does the Qt MQTT package provide an easy way of writing my own broker?

答:
No, it is for clients. The overview pretty much says so

It enables applications to act as telemetry displays and devices to publish telemetry data.


问:
play MIDI files in python?
I'm looking for a method to play midi files in python.
It seems python does not support MIDI in its standard library.
After I searched, I found some python midi librarys such as pythonmidi.
However, most of them can only create and read MIDI file without playing function.
I would like to find a python midi library including playing method.
Any recommendations? Thanks!</p>

答:
The pygame module can be used to play midi files.

http://www.pygame.org/docs/ref/music.html

See the example here:

http://www.daniweb.com/software-development/python/code/216979

a whole bunch of options available at:

http://wiki.python.org/moin/PythonInMusic

and also here which you can modify to suit your purpose:
http://xenon.stanford.edu/~geksiong/code/playmus/playmus.py

Title: play MIDI files in python?


问:
Is there a "all" or "any" operator for boolean lists in typescript
I want to write an if statement of the form

if (all entries in booleanList are true) {do something}

Just putting in the booleanList does the equivalent of .any()

I could not find an answer on the internet or in a typescript book. Thanks in advance for any help.

答:
You could use the Array.prototype.every() function for that:</p>

```<code>if(booleanList.every(val => val)){
 do something
}
</code>```

Body:
You could use the Array.prototype.every() function for that:

if(booleanList.every(val => val)){
 do something
}


问:
SonarQube: Coverage on New Code never calculated
I have set up SonarQube, Maven and Cobertura to upload unit test coverage at every build run. I want to use the differential views to get coverage for the delta (new code only).

The coverage itself is successfully uploaded, and I can see the delta in lines of code. However, I can't get the "Coverage on new Code" to work.

I tried different values for the leak period, including previous_analysis and previous_version (changing the version from 1.0 to 1.1 in the new analysis). I also used -Dsonar.projectDate to simulate a past date of analysis but still no luck.

Any thoughts?

答:
Adding this sonar.java.binaries=classes directory, most likely target/classes
helped me in fixing this issue. No JaCoCo analysis of project coverage can be done since there is no class files</p>


问:
LINQ to Entities does not recognize the method 'System.Object get_Item(System.String)', store expressions
I am developing a realtor's portal for my semester end project and I wanted to generate a list of my listings where the listedByID is equal to a session which is created when the user is logged in.
here is the code

```<code>public ActionResult Index()
        {
            if ((string)Session["Role"] != "Private Seller")
            {
                return RedirectToAction("Login", "Account");
            }
            var data = db.tbl_listings.Where(x => x.l_listedByID == (int)Session["uID"]);
            return View(data.ToList());
        }
</code>```

The problem is it is throwing this exception:

LINQ to Entities does not recognize the method 'System.Object
  get_Item(System.String)' method, and this method cannot be translated
  into a store expression.

I have tried this as well:

```<code>public ActionResult Index()
        {
            if ((string)Session["Role"] != "Private Seller")
            {
                return RedirectToAction("Login", "Account");
            }
            var data = db.tbl_listings.Where(x => x.l_listedByID == (int)Session["uID"]).ToList();
            return View(data);
        }
</code>```

Any help would be appreciated, I am lost and the problem seems to be in the controller only. The problem arises when the code hits the "ToList()" method.

答:
Try store result of Session["uID"] outside of linq query.

```<code>var uID = (int)Session["uID"];
var data = db.tbl_listings.Where(x => x.l_listedByID == uID).ToList();
</code>```

There is a big chance that the problem here is in Session["uID"], since its indexer and its being captured by expression as a method and not by the value it returns.
Then, it cannot be translated to an actual SQL.

Body:
I am developing a realtor's portal for my semester end project and I wanted to generate a list of my listings where the listedByID is equal to a session which is created when the user is logged in.
here is the code

public ActionResult Index()
        {
            if ((string)Session["Role"] != "Private Seller")
            {
                return RedirectToAction("Login", "Account");
            }
            var data = db.tbl_listings.Where(x => x.l_listedByID == (int)Session["uID"]);
            return View(data.ToList());
        }

The problem is it is throwing this exception:

LINQ to Entities does not recognize the method 'System.Object
  get_Item(System.String)' method, and this method cannot be translated
  into a store expression.

I have tried this as well:

public ActionResult Index()
        {
            if ((string)Session["Role"] != "Private Seller")
            {
                return RedirectToAction("Login", "Account");
            }
            var data = db.tbl_listings.Where(x => x.l_listedByID == (int)Session["uID"]).ToList();
            return View(data);
        }

Any help would be appreciated, I am lost and the problem seems to be in the controller only. The problem arises when the code hits the "ToList()" method.

Body:
Try store result of Session["uID"] outside of linq query.

var uID = (int)Session["uID"];
var data = db.tbl_listings.Where(x => x.l_listedByID == uID).ToList();

There is a big chance that the problem here is in Session["uID"], since its indexer and its being captured by expression as a method and not by the value it returns.
Then, it cannot be translated to an actual SQL.


问:
How did Python read this binary faster the second time?
I'm exploring methods for reading a formatted binary file and was starting with the basics:

```<code>>>> with open(fp, 'rb') as f:
        buffer = f.read()
</code>```

My file is 1.02GB and it took ~90 seconds to read it and store in memory the first time. By chance I accidentally told the interpreter to read the file again (hit Enter too many times) and it read it in 0.5 seconds. The file was closed prior to re-reading unintentionally.

Whats going on here?

答: Most likely the file data was cached and still in memory. Most operating systems will leave data in memory for a while, in case it is asked for again.</p>

Body:
I'm exploring methods for reading a formatted binary file and was starting with the basics:

>>> with open(fp, 'rb') as f:
        buffer = f.read()

My file is 1.02GB and it took ~90 seconds to read it and store in memory the first time. By chance I accidentally told the interpreter to read the file again (hit Enter too many times) and it read it in 0.5 seconds. The file was closed prior to re-reading unintentionally.

Whats going on here?


问:
Passing an arrow function to a component that uses hooks causes useEffect to fire again
How to pass an arrow function as a prop to a component that uses hooks without causing useEffect to fire when it shouldn't?

Codesandbox

```<code>function Apple(props) {
  const { text, cb } = props;
  useEffect(() => {
    pretendFetch().then(result => cb(result));
    // eslint-plugin-react-hooks dictates that `cb` should be within the dependencies array
  }, [cb]);
  return <div>{text}</div>;
}
</code>```

When the component is passed an arrow function as cb it will fire the useEffect on every render.  Ideally it should just use the callback once, but I cannot just pass [] as the dependency array without eslint-plugin-react-hooks issuing a warning.  I've read that useRef can be used to wrap the callback but that seems like an unsatisfying bandaid to this issue.

答: I checked this issue today, having the same problem with you, so I just removed the cb from the useEffect array - in order to trigger it only on mount - and disabled the eslint rule react-hooks/exhaustive-deps.

Body:
How to pass an arrow function as a prop to a component that uses hooks without causing useEffect to fire when it shouldn't?

Codesandbox

function Apple(props) {
  const { text, cb } = props;
  useEffect(() => {
    pretendFetch().then(result => cb(result));
    // eslint-plugin-react-hooks dictates that `cb` should be within the dependencies array
  }, [cb]);
  return
{text}
;
}

When the component is passed an arrow function as cb it will fire the useEffect on every render.  Ideally it should just use the callback once, but I cannot just pass [] as the dependency array without eslint-plugin-react-hooks issuing a warning.  I've read that useRef can be used to wrap the callback but that seems like an unsatisfying bandaid to this issue.


问:
how to use forms in django-cms?
I am an absolute novice to django-cms. I have gone through the tutorial and configured it exactly the same as mentioned in the documentation. Now, I have to build an application which uses a form to upload products.

I dont have a clue as to how to move ahead with it. I want to start it with simple forms as if now, say, a username and password textbox kind of. How can I use django forms in the django-cms page? I have snippet plugin enabled in it too. I need some guidance for this.

Any suggestions plsss.
thanks

答:
I'm new to django-cms too, but the way ojii described in their answer seems like the most reasonable:

Make a CMSPlugin as described above to render the form.

Make the form post to a statically hooked view (or a apphooked view), if the POST is successful, redirect to the page again if you want.

However for me this only a partial solution because I don't only want to redirect back to the cms page containing the plugin in the case of success but also in the case of form errors which need to be displayed. The redirecting part is not the problem (I just redirect back to request.META["HTTP_REFERER"]), but the part of handing over the form (errors) to the cms page containing the plugin is tricky.
The only answer I found for this: I use a session (Writing the form into the session in the static view, and then deleting it again in the plugin's render method). Not the nicest way, but it works. (There would be better ways, if the cms plugins configuration would support some way to redirect instead of rendering, but apparently there is no such option: see http://groups.google.com/group/django-cms/browse_thread/thread/79ab6080c80bbcb5 )

ContentLicense: CC BY-SA 2.5

Title: how to use forms in django-cms?


答:
Sure, it's every:

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/every

```<code>const list = [true, false, true];

const every = list.every(bool => bool === true); // false
// const every = list.every(bool => bool); // false
</code>```

Title: Is there a "all" or "any" operator for boolean lists in typescript

Body:
I want to write an if statement of the form

if (all entries in booleanList are true) {do something}

Just putting in the booleanList does the equivalent of .any()

I could not find an answer on the internet or in a typescript book. Thanks in advance for any help.

Body:
Sure, it's every:

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/every

const list = [true, false, true];

const every = list.every(bool => bool === true); // false
// const every = list.every(bool => bool); // false


问:
Why for loop over a sqlalchemy.orm.collections.CollectionAdapter is extremly slow SQLAlchemy 1.1.18?
I have the following objects definition:

```<code>from sqlalchemy.orm import relationship

class Project():
    __tablename__ = 'projects'

    id = Column(Integer, primary_key=True)
    qws = relationship('ProjectQWS',
                       foreign_keys='ProjectQWS.project_id',
                       cascade='all, delete-orphan',
                       order_by=ProjectQWS.is_main)

class ProjectQWS():

    __tablename__ = 'projects_qws'

    project_id = Column(
        Integer,
        ForeignKey('projects.id', name='fk_qws_project_id', ondelete='CASCADE'),
        primary_key=True,
    )
    qws_id = Column(String(QWS_ID_SIZE), nullable=False, primary_key=True)

    def to_dict(self):
        return {
            'project_id': self.project_id,
            'qws_id': self.qws_id,
        }

</code>```

After querying for Project the for loop over qws collectionAdapter is extremely slow(couple of hundreds milliseconds. But this add up when I'm querying for 1000+ projcts) even if the qws  collection mostly contains 1 element (99% of the time).

```<code>def get_qws_dicts(self):
        result = []
        if self.qws:
            for qws_instance in self.qws:
                result.append(qws_instance.to_dict())
        return result
</code>```

When the qws is empty the for loop is fast.

Any idea what is goin on here?

I use Postgress SQL , Python 3.6 and SQLAlchemy 1.1.18

Thanks

答:
You can just preload related model.
Please try something like this:</p>

```<code>qws = relationship('ProjectQWS',
                       foreign_keys='ProjectQWS.project_id',
                       cascade='all, delete-orphan',
                       lazy='joined',
                       order_by=ProjectQWS.is_main)
</code>```

Body:
I have the following objects definition:

from sqlalchemy.orm import relationship

class Project():
    __tablename__ = 'projects'

    id = Column(Integer, primary_key=True)
    qws = relationship('ProjectQWS',
                       foreign_keys='ProjectQWS.project_id',
                       cascade='all, delete-orphan',
                       order_by=ProjectQWS.is_main)

class ProjectQWS():

    __tablename__ = 'projects_qws'

    project_id = Column(
        Integer,
        ForeignKey('projects.id', name='fk_qws_project_id', ondelete='CASCADE'),
        primary_key=True,
    )
    qws_id = Column(String(QWS_ID_SIZE), nullable=False, primary_key=True)

    def to_dict(self):
        return {
            'project_id': self.project_id,
            'qws_id': self.qws_id,
        }

After querying for Project the for loop over qws collectionAdapter is extremely slow(couple of hundreds milliseconds. But this add up when I'm querying for 1000+ projcts) even if the qws  collection mostly contains 1 element (99% of the time).

def get_qws_dicts(self):
        result = []
        if self.qws:
            for qws_instance in self.qws:
                result.append(qws_instance.to_dict())
        return result

When the qws is empty the for loop is fast.

Any idea what is goin on here?

I use Postgress SQL , Python 3.6 and SQLAlchemy 1.1.18

Thanks

Body:
You can just preload related model.
Please try something like this:

qws = relationship('ProjectQWS',
                       foreign_keys='ProjectQWS.project_id',
                       cascade='all, delete-orphan',
                       lazy='joined',
                       order_by=ProjectQWS.is_main)


问:
Convert DFA to RE
I constructed a finite automata  for the language L of all strings made of the symbols 0, 1 and 2 (Σ = {0, 1, 2}) where the last symbol is not smaller than the first symbol. E.g., the strings 0, 2012, 01231 and 102 are in the language, but 10, 2021 and 201 are not in the language.

Then from that an GNFA so I can convert to RE.

My RE looks like this:

```<code>(0(0+1+2)* )(1(0(1+2)+1+2)* )(2((0+1)2+2))*)
</code>```

I have no idea if this is correct, as I think I understand RE but not entirely sure.

Could someone please tell me if it’s correct and if not why?

答:
There is a general method to convert any DFA into a regular expression, and is probably what you should be using to solve this homework problem.

For your attempt specifically, you can tell whether an RE is incorrect by finding a word that should be in the language, but that your RE doesn't accept, or a word that shouldn't be in the language that the RE does accept. In this case, the string 1002 should be in the language, but the RE doesn't match it.

There are two primary reasons why this string isn't matched. The first is that there should be a union rather than a concatenation between the three major parts of the language (words starting with 0, 1 and 2, respectively:

```<code>(0(0+1+2)*)   (1(0(1+2)+1+2)*)   (2((0+1)2+2))*) // wrong
(0(0+1+2)*) + (1(0(1+2)+1+2)*) + (2((0+1)2+2))*) // better
</code>```

The second problem is that in the 1 and 2 cases, the digits smaller than the starting digit need to be repeatable:

```<code>(1(0 (1+2)+1+2)*) // wrong
(1(0*(1+2)+1+2)*) // better
</code>```

If you do both of those things, the RE will be correct. I'll leave it as an exercise for you to follow that step for the 2 case.

The next thing you can try is find a way to make the RE more compact:

```<code>(1(0*(1+2)+1+2)*) // verbose
(1(0*(1+2))*) // equivalent, but more compact
</code>```

This last step is just a matter of preference. You don't need the trailing +1+2 because 0* can be of zero length, so 0*(1+2) covers the +1+2 case.

Title: Convert DFA to RE

Body:
I constructed a finite automata  for the language L of all strings made of the symbols 0, 1 and 2 (Σ = {0, 1, 2}) where the last symbol is not smaller than the first symbol. E.g., the strings 0, 2012, 01231 and 102 are in the language, but 10, 2021 and 201 are not in the language.

Then from that an GNFA so I can convert to RE.

My RE looks like this:

(0(0+1+2)* )(1(0(1+2)+1+2)* )(2((0+1)2+2))*)

I have no idea if this is correct, as I think I understand RE but not entirely sure.

Could someone please tell me if it’s correct and if not why?

Body:
There is a general method to convert any DFA into a regular expression, and is probably what you should be using to solve this homework problem.

For your attempt specifically, you can tell whether an RE is incorrect by finding a word that should be in the language, but that your RE doesn't accept, or a word that shouldn't be in the language that the RE does accept. In this case, the string 1002 should be in the language, but the RE doesn't match it.

There are two primary reasons why this string isn't matched. The first is that there should be a union rather than a concatenation between the three major parts of the language (words starting with 0, 1 and 2, respectively:

(0(0+1+2)*)   (1(0(1+2)+1+2)*)   (2((0+1)2+2))*) // wrong
(0(0+1+2)*) + (1(0(1+2)+1+2)*) + (2((0+1)2+2))*) // better

The second problem is that in the 1 and 2 cases, the digits smaller than the starting digit need to be repeatable:

(1(0 (1+2)+1+2)*) // wrong
(1(0*(1+2)+1+2)*) // better

If you do both of those things, the RE will be correct. I'll leave it as an exercise for you to follow that step for the 2 case.

The next thing you can try is find a way to make the RE more compact:

(1(0*(1+2)+1+2)*) // verbose
(1(0*(1+2))*) // equivalent, but more compact

This last step is just a matter of preference. You don't need the trailing +1+2 because 0* can be of zero length, so 0*(1+2) covers the +1+2 case.


问:
Why is a ConcurrentModificationException thrown and how to debug it
I am using a Collection (a HashMap used indirectly by the JPA, it so happens), but apparently randomly the code throws a ConcurrentModificationException. What is causing it and how do I fix this problem? By using some synchronization, perhaps?

Here is the full stack-trace:

```<code>Exception in thread "pool-1-thread-1" java.util.ConcurrentModificationException
        at java.util.HashMap$HashIterator.nextEntry(Unknown Source)
        at java.util.HashMap$ValueIterator.next(Unknown Source)
        at org.hibernate.collection.AbstractPersistentCollection$IteratorProxy.next(AbstractPersistentCollection.java:555)
        at org.hibernate.engine.Cascade.cascadeCollectionElements(Cascade.java:296)
        at org.hibernate.engine.Cascade.cascadeCollection(Cascade.java:242)
        at org.hibernate.engine.Cascade.cascadeAssociation(Cascade.java:219)
        at org.hibernate.engine.Cascade.cascadeProperty(Cascade.java:169)
        at org.hibernate.engine.Cascade.cascade(Cascade.java:130)
</code>```

答: Try using a ConcurrentHashMap instead of a plain HashMap

Body:
I am using a Collection (a HashMap used indirectly by the JPA, it so happens), but apparently randomly the code throws a ConcurrentModificationException. What is causing it and how do I fix this problem? By using some synchronization, perhaps?

Here is the full stack-trace:

Exception in thread "pool-1-thread-1" java.util.ConcurrentModificationException
        at java.util.HashMap$HashIterator.nextEntry(Unknown Source)
        at java.util.HashMap$ValueIterator.next(Unknown Source)
        at org.hibernate.collection.AbstractPersistentCollection$IteratorProxy.next(AbstractPersistentCollection.java:555)
        at org.hibernate.engine.Cascade.cascadeCollectionElements(Cascade.java:296)
        at org.hibernate.engine.Cascade.cascadeCollection(Cascade.java:242)
        at org.hibernate.engine.Cascade.cascadeAssociation(Cascade.java:219)
        at org.hibernate.engine.Cascade.cascadeProperty(Cascade.java:169)
        at org.hibernate.engine.Cascade.cascade(Cascade.java:130)

LastEditorDisplayName: Rich B

OwnerDisplayName: Chochos


问:
Find item by key in Javascript
Quick rookie question please.

Suppose I have a javsacript object like so:

```<code>var meh=[["cars",27], ["bikes",85], ["skates",4]];
</code>```

To go through each data object here, I can do this:

```<code>$.each(meh, function(index,value){
    console.log(value) //returns ["cars",27] etc..
 });
</code>```

And considering I know the place of, say, cars, I can do this to access it:

```<code>console.log(meh[0][0]) //shows "Cars"
</code>```

and of course, if I want the value of cars, I need to do this:

```<code>console.log(meh[0][1]) //Shows 27
</code>```

Now, I have the string - Keys, like cars, bikes or skates

But I cant figure out this: How do I access their respective values?

meh["cars"] is returning undefined, since, as I understand, it cant find a description outside each object.

I can do meh[0]["cars"] but it defeats the point as the position of cars might change.

How do I access a value of something with their key please?

thanks.

答:
You should change that to objects </p>

```<code>var meh={"cars" :27 , "bikes" :85, "skates" :4};
</code>```

<p>Now you can simply access it via keys </p>

```<code>alert(meh['cars']); //27
</code>```

Title: Find item by key in Javascript

Body:
Quick rookie question please.

Suppose I have a javsacript object like so:

var meh=[["cars",27], ["bikes",85], ["skates",4]];

To go through each data object here, I can do this:

$.each(meh, function(index,value){
    console.log(value) //returns ["cars",27] etc..
 });

And considering I know the place of, say, cars, I can do this to access it:

console.log(meh[0][0]) //shows "Cars"

and of course, if I want the value of cars, I need to do this:

console.log(meh[0][1]) //Shows 27

Now, I have the string - Keys, like cars, bikes or skates

But I cant figure out this: How do I access their respective values?

meh["cars"] is returning undefined, since, as I understand, it cant find a description outside each object.

I can do meh[0]["cars"] but it defeats the point as the position of cars might change.

How do I access a value of something with their key please?

thanks.

Body:
You should change that to objects

var meh={"cars" :27 , "bikes" :85, "skates" :4};

Now you can simply access it via keys

alert(meh['cars']); //27


问:
Kafka Connect - Could not look up partition metadata
Running Kafka Connect on a Kafka cluster which has auto creation of topics turned off. As far as I could see on another cluster that is working we had the topics  connect-configs, connect-offsets, and connect-status created. So these topics were recreated on the new cluster with same replication factor and partitions.

We are getting an error when starting the service though I have netcat from connect instance to brokers and there was no connection issue there

```<code>Could not look up partition metadata for offset backing store topic in allotted period. This could indicate a connectivity issue, unavailable topic partitions, or if this is your first use of the topic it may have taken too long to create
</code>```

I can see where this is thrown below from the connect utils class. But have checked and these topics are created so a bit lost now

```<code>        producer = createProducer();
        consumer = createConsumer();

        List<TopicPartition> partitions = new ArrayList<>();

        // We expect that the topics will have been created either manually by the user or automatically by the herder
        List<PartitionInfo> partitionInfos = null;
        long started = time.milliseconds();
        while (partitionInfos == null && time.milliseconds() - started < CREATE_TOPIC_TIMEOUT_MS) {
            partitionInfos = consumer.partitionsFor(topic);
            Utils.sleep(Math.min(time.milliseconds() - started, 1000));
        }
        if (partitionInfos == null)
            throw new ConnectException("Could not look up partition metadata for offset backing store topic in" +
                    " allotted period. This could indicate a connectivity issue, unavailable topic partitions, or if" +
                    " this is your first use of the topic it may have taken too long to create
</code>```

答:
the topics were created manually,

Kafka Connect will use the AdminClient to initialize its own topics. There's no reason to do it manually.

If you do, you need to ensure the correct settings, which are documented in both Confluent and Apache Kafka documentation for getting started with Connect

Body:
Running Kafka Connect on a Kafka cluster which has auto creation of topics turned off. As far as I could see on another cluster that is working we had the topics  connect-configs, connect-offsets, and connect-status created. So these topics were recreated on the new cluster with same replication factor and partitions.

We are getting an error when starting the service though I have netcat from connect instance to brokers and there was no connection issue there

Could not look up partition metadata for offset backing store topic in allotted period. This could indicate a connectivity issue, unavailable topic partitions, or if this is your first use of the topic it may have taken too long to create

I can see where this is thrown below from the connect utils class. But have checked and these topics are created so a bit lost now

        producer = createProducer();
        consumer = createConsumer();

        List<TopicPartition> partitions = new ArrayList<>();

        // We expect that the topics will have been created either manually by the user or automatically by the herder
        List<PartitionInfo> partitionInfos = null;
        long started = time.milliseconds();
        while (partitionInfos == null && time.milliseconds() - started < CREATE_TOPIC_TIMEOUT_MS) {
            partitionInfos = consumer.partitionsFor(topic);
            Utils.sleep(Math.min(time.milliseconds() - started, 1000));
        }
        if (partitionInfos == null)
            throw new ConnectException("Could not look up partition metadata for offset backing store topic in" +
                    " allotted period. This could indicate a connectivity issue, unavailable topic partitions, or if" +
                    " this is your first use of the topic it may have taken too long to create


问:
Error occurred when finalizing GeneratorDataset iterator: Cancelled: Operation was cancelled
While running kubeflow pipeline having code that uses tensorflow 2.0. below error is displayed at end of each epoch

W tensorflow/core/kernels/data/generator_dataset_op.cc:103] Error occurred when finalizing GeneratorDataset iterator: Cancelled: Operation was cancelled

Also, after some epochs, it does not show log and shows this error

This step is in Failed state with this message: The node was low on resource: memory. Container main was using 100213872Ki, which exceeds its request of 0. Container wait was using 25056Ki, which exceeds its request of 0.

答: I have the same problem. People claimed that warming is superfluous and it has been removed in the tf-nightly, see here. But the memory leak is still there for each epoch.</p>


问:
How to make an Angular app a module to be integrated into other Angular projects using Azure DevOps?
I have programmed an Angular app, which shall count as a template from now on. It sits in a repo and needs to sync to my other new projects and act as a module -> meaning that changes in the repo shall get updated on the server, where the new project is residing. How do I accomplish this? I am using Azure DevOps for the repo, building and exporting artifacts. It would be perfect if I could integrate the compiled files somehow in the new projects for better performance and not needing to compile two times. I think turning my template project into something like a library would be a good solution. I'm not sure whether any of these references are viable for me:
https://medium.com/@tomsu/how-to-build-a-library-for-angular-apps-4f9b38b0ed11
How reuse Angular modules in other projects
I would prefer to use Azure DevOps.</p>

答:
I wouldn't be able to share the steps for doing this but instead I would be able share the resources. What I believe is that you want to have multiple applications and share dependencies across the applications. If so then you can implement a mono-repo concept with your projects which share or not share common features.

The blog link that you have pasted tells all the right stuff that how you can do it. Other than this creating a dependency like this, you have some great options now.

1- Angular now has a Work Space concept where you have multiple apps and have one source for it's dependencies. You can follow the article that you mentioned and have a common lib.
https://angular.io/guide/file-structure#multiple-projects

2- Another great product was introduced by the team Nrwl, they have a product called NX. I guess they were the first to introduce mono-repo concept for your client or I say JavaScript driven application(but I can be wrong). You can find the documentation here:
https://nx.dev/angular/getting-started/what-is-nx
(With NX you can create shareable libs, components, interfaces and can do other great stuff)


答: The second time your file was cached in memory. This has nothing to do with Python.</p>

Title: How did Python read this binary faster the second time?


问:
HTML Editor with Download Option
I'm looking for a way to add a download feature to my JS that will create a file using the programming that a user might enter in, lets say, a <textarea>. Are there any features in JS that would work similar to this? (HTML Format!!)

```<code>var x = document.write("<p>Hi!</p>");
window.replace(x);
</code>```

And then:

```<code><button onclick="open()">Save</button>
<script>
  var hi = document.write("<p>hi</p>;");
  open() {
    window.open(hi)
  }
</script>
</code>```

After they opened the variable on the new page, the user could use ctrl + s to save the page displayed. Ideas?

Thanks in advance.

答:
<textarea id="text-val" rows="4" style="height: 80%;width: 90%;"></textarea>

<input type="button" id="dwn-btn" value="Save" />
```

I hope this is what you are expecting

Title: HTML Editor with Download Option

Body:
I'm looking for a way to add a download feature to my JS that will create a file using the programming that a user might enter in, lets say, a <textarea>. Are there any features in JS that would work similar to this? (HTML Format!!)

var x = document.write("
Hi!
");
window.replace(x);

And then:

<button onclick="open()">Save</button>

After they opened the variable on the new page, the user could use ctrl + s to save the page displayed. Ideas?

Thanks in advance.

Body:
<textarea id="text-val" rows="4" style="height: 80%;width: 90%;"></textarea><br/><br/>
<input type="button" id="dwn-btn" value="Save" />
<script>
    function download(filename, text) {
        var element = document.createElement('a');
        element.setAttribute('href', 'data:text/plain;charset=utf-8,' + encodeURIComponent(text));
        element.setAttribute('download', filename);

        element.style.display = 'none';
        document.body.appendChild(element);

        element.click();

        document.body.removeChild(element);
    }

    document.getElementById("dwn-btn").addEventListener("click", function() {

        var text = document.getElementById("text-val").value;
        var filename = "example.html";

        download(filename, text);
    }, false);
</script>

I hope this is what you are expecting


问:
Deleting a row in datagrid view
I want to Delete a row in the Gridview which is in the update panel . But instead of the command button ., i took a link button to get a confirmation message. Now if I press ok then the record should be deleted (both from db and frm girdview). I know how to delete from db but not when linkbutton is pressed, and deleting the record. And also the gridview is in update panel.so it should be reflected.

A sample code is appreciated.

Thanks

答:
I presume you have a method which sends a delete query.

Make a RowDeleting event handler, pass your row index using e.RowIndex to the delete method.

Use this e.RowIndex to write a query to delete the 'n'th row of your table. and then bind the data to your gridView.

Title: Deleting a row in datagrid view


问:
LINQ - Order By and Distinct by different fields. Skip & Take distinct values
I'm trying to ORDER BY some fields but SELECT DISTINCT by another field, and after that apply a Skip & Take

Code:

```<code>var result = entities.OrderBy(e => e.OrderField)
                     .Select(e => e.SelectField)
                     .Distinct()
                     .Skip(skip)
                     .Take(take)
                     .ToArray();
</code>```

But I'm getting this exception:

System.NotSupportedException: 'The method 'Skip' is only supported for sorted input in LINQ to Entities. The method 'OrderBy' must be called before the method 'Skip'.'

I understand the reason (the set is being changed between the ordering and the skipping) but can I work around this issue without querying the database more than once (edit: and not fetching more entities than its supposed to)?

EDIT:
I don't think there's an optimal solution for that, so what I did was fetch the values and then paginated them. *sigh*

```<code>var result = entities.OrderBy(e => e.OrderField)
                     .Select(e => e.SelectField)
                     .Distinct()
                     .ToArray()
                     .Skip(skip)
                     .Take(take)
                     .ToArray();
</code>```

答:
Edit: Updated based on the comment.
The following code should work in your case:

```<code>var result = entities
            .OrderBy(e => e.OrderField)
            .Select(e => e.SelectField)
            .GroupBy(e => e)
            .Select(group => group.Key)
            .Skip(skip)
            .Take(take)
            .ToArray();
</code>```

Body:
I'm trying to ORDER BY some fields but SELECT DISTINCT by another field, and after that apply a Skip & Take

Code:

var result = entities.OrderBy(e => e.OrderField)
                     .Select(e => e.SelectField)
                     .Distinct()
                     .Skip(skip)
                     .Take(take)
                     .ToArray();

But I'm getting this exception:

System.NotSupportedException: 'The method 'Skip' is only supported for sorted input in LINQ to Entities. The method 'OrderBy' must be called before the method 'Skip'.'

I understand the reason (the set is being changed between the ordering and the skipping) but can I work around this issue without querying the database more than once (edit: and not fetching more entities than its supposed to)?

EDIT:
I don't think there's an optimal solution for that, so what I did was fetch the values and then paginated them. *sigh*

var result = entities.OrderBy(e => e.OrderField)
                     .Select(e => e.SelectField)
                     .Distinct()
                     .ToArray()
                     .Skip(skip)
                     .Take(take)
                     .ToArray();

Body:
Edit: Updated based on the comment.
The following code should work in your case:

var result = entities
            .OrderBy(e => e.OrderField)
            .Select(e => e.SelectField)
            .GroupBy(e => e)
            .Select(group => group.Key)
            .Skip(skip)
            .Take(take)
            .ToArray();


问:
An error has occurred during web site deployment - Bot framework
I try to set up a bot since yesterday.

I uploaded my knowledge base, everything was allright and the bot started answering questions (tested in webchat).

Yesterday, I made a few changes in the code with the App Service Editor in the QnABots.cs file (changing the welcoming message).

After running the build.cmd, everything was still fine.
I then made other changes in the QnAMakerBasDialog.cs file, with changing the wordings for DefaultNoAnswer or DefaultCardNoMatchText for example. I dit not move any single line of code other than wording.

When running the build.cmd again, got this message :

```<code>\> \build.cmd
        1 file(s) copied.
Installing Kudu Sync
An error has occurred during web site deployment.
</code>```

As the build cannot be made, I even reverted the file to the original (which was still in the Release folder), and yet, the bot is still not working (tested in the webchat + the build not running).

In the Channel section of the Azure panel, got this message :

There was an error sending this message to your bot: HTTP status code ServiceUnavailable

I cannot understand if I did something wrong.
Any ideas ?

Many thanks, have a good day,

答:
So, I fixed it.
Apparently, running the build.cmd directly in the App Service Editor does not work and destroy the build previously made.

You'll have to use the Kudu Console, and from there you can run the build, which is now working fine.

```<code>D:\home>cd site
D:\home\site>cd wwwroot
D:\home\site\wwwroot>build.cmd
</code>```

Bot is back up and running !

Body:
I try to set up a bot since yesterday.

I uploaded my knowledge base, everything was allright and the bot started answering questions (tested in webchat).

Yesterday, I made a few changes in the code with the App Service Editor in the QnABots.cs file (changing the welcoming message).

After running the build.cmd, everything was still fine.
I then made other changes in the QnAMakerBasDialog.cs file, with changing the wordings for DefaultNoAnswer or DefaultCardNoMatchText for example. I dit not move any single line of code other than wording.

When running the build.cmd again, got this message :

\> \build.cmd
        1 file(s) copied.
Installing Kudu Sync
An error has occurred during web site deployment.

As the build cannot be made, I even reverted the file to the original (which was still in the Release folder), and yet, the bot is still not working (tested in the webchat + the build not running).

In the Channel section of the Azure panel, got this message :

There was an error sending this message to your bot: HTTP status code ServiceUnavailable

I cannot understand if I did something wrong.
Any ideas ?

Many thanks, have a good day,

Body:
So, I fixed it.
Apparently, running the build.cmd directly in the App Service Editor does not work and destroy the build previously made.

You'll have to use the Kudu Console, and from there you can run the build, which is now working fine.

D:\home>cd site
D:\home\site>cd wwwroot
D:\home\site\wwwroot>build.cmd

Bot is back up and running !


问:
Excel vba - Format isn't copied to other cell
I got an excel file with an autoincrement on 1 cell, where the numberformat is "000".

```<code>Worksheets("TEST").Range("M17").Value = Worksheets("TEST").Range("M17").Value + 1
Worksheets("TEST").Range("M17").NumberFormat = "000"
</code>```

This works fine, so my first number is: 001 instead of 1.

Now I need to merge this cell to another cell M16 (which displays an input for example: 2020)

```<code>=M16&"/"&M17
</code>```

But for some reason it is losing his NumberFormat, and excel is showing: 2020/1 instead of 2020/001.

I have tried several things, like formatting my cell M18

```<code>Worksheets("TEST").Range("M18").NumberFormat = "0000/000"
</code>```

Or by trying to solve this directly in vba

```<code>Worksheets("TEST").Range("M18").Value = Worksheets("FACTUUR").Range("M16").Value & Worksheets("TEST").Range("M17").Value
Worksheets("TEST").Range("M18").NumberFormat = "0000/000"
</code>```

Or even by changing the format from within Excel itself, but then I get an error message directly (don't know why...)

Any idea on how to solve this?

答:
You are on an excel application configured to work with decimal comma instead of decimal point.

Therefore the formula you type in the cell should have a semicolon

```<code>=M16&"/"&TEXT(M17;"000")
</code>```

Note that the same formula can be assigned to the cell in VBA with a comma:

```<code>Range("M18").Formula="=M16&""/""&TEXT(M17,""000"")"
</code>```

:(

Body:
I got an excel file with an autoincrement on 1 cell, where the numberformat is "000".

Worksheets("TEST").Range("M17").Value = Worksheets("TEST").Range("M17").Value + 1
Worksheets("TEST").Range("M17").NumberFormat = "000"

This works fine, so my first number is: 001 instead of 1.

Now I need to merge this cell to another cell M16 (which displays an input for example: 2020)

=M16&"/"&M17

But for some reason it is losing his NumberFormat, and excel is showing: 2020/1 instead of 2020/001.

I have tried several things, like formatting my cell M18

Worksheets("TEST").Range("M18").NumberFormat = "0000/000"

Or by trying to solve this directly in vba

Worksheets("TEST").Range("M18").Value = Worksheets("FACTUUR").Range("M16").Value & Worksheets("TEST").Range("M17").Value
Worksheets("TEST").Range("M18").NumberFormat = "0000/000"

Or even by changing the format from within Excel itself, but then I get an error message directly (don't know why...)

Any idea on how to solve this?

Body:
You are on an excel application configured to work with decimal comma instead of decimal point.

Therefore the formula you type in the cell should have a semicolon

=M16&"/"&TEXT(M17;"000")

Note that the same formula can be assigned to the cell in VBA with a comma:

Range("M18").Formula="=M16&""/""&TEXT(M17,""000"")"

:(


问:
How can I give time to a progressbar in Kotlin?
I want to use a progressbar in Android Studio and my app is in Kotlin.

How may I give time to a progressbar to be complete?

答:
You can use this with basically;</p>

```<code>Handler().postDelayed({
          menuProgressBar!!.setVisibility(View.INVISIBLE)
     },5000/* 5 second */)
</code>```

Body:
You can use this with basically;

Handler().postDelayed({
          menuProgressBar!!.setVisibility(View.INVISIBLE)
     },5000/* 5 second */)


问:
Is there a "all" or "any" operator for boolean lists in typescript
I want to write an if statement of the form

if (all entries in booleanList are true) {do something}

Just putting in the booleanList does the equivalent of .any()

I could not find an answer on the internet or in a typescript book. Thanks in advance for any help.

答:
Typescript compiles to Javascript, so it doesn't have any features available at runtime that Javascript doesn't have. However, Javascript does have both every and some since ES5, so long as you pass an identity function:

arr.every(x => x) // all
arr.some(x => x)  // any
```

This kind of thing is unlikely to be documented in Typescript books specifically, because there would be no need to duplicate the contents of a Javascript book just to say that Typescript has those features too. If you want to know what functions are available in the standard library, you should consult a Javascript reference, such as the MDN Javascript reference.

Body:
Typescript compiles to Javascript, so it doesn't have any features available at runtime that Javascript doesn't have. However, Javascript does have both every and some since ES5, so long as you pass an identity function:

arr.every(x => x) // all
arr.some(x => x)  // any

This kind of thing is unlikely to be documented in Typescript books specifically, because there would be no need to duplicate the contents of a Javascript book just to say that Typescript has those features too. If you want to know what functions are available in the standard library, you should consult a Javascript reference, such as the MDN Javascript reference.