text:
Q: setting variable to avoid function execution I have 2 Elements image and div overlapping each other,when I click on div it calls  transitIT()  which rotates div but again if I do next click too fast then image clicked is called I don't understand how, I tried using event.stopPropagation() and setting  clickedEnabled to avoid image click but image click event  is getting called.
$(document).on('click', '#front', function(event) {
event.stopPropagation();
//alert('Front Clicked globe='+globe);
 transitIT(this);
 });

 $(document).on('click', 'img', function() {
  alert('htmlcalled image Clicked Called='+clickEnabled);

/*to check if div is transitioning state*/
    if (!clickEnabled){return;}

    //Doing some alignement for image               ...........

     });

A: I suggest you to test the element id, because you don't know in which order both callbacks will be actually called.
  $(document).on('click', 'img', function() {
    if (this.id !== "front")
    {
      alert('htmlcalled image Clicked Called='+clickEnabled);
    }
 });

A: You can do this to prevent the event bubbling:
$(document).on('click', 'img', function (event) {
    if (event.target.tagName !== 'IMG') return;

    alert('htmlcalled image Clicked Called=' + clickEnabled);
    //Doing some alignement for image ...........
});


text:
Q: How to search for a package with pacman? I just installed Archlinux and want to install netstat. However using the command pacman -Ss netstat outputs irrelevant package names. A search on internet revealed that netstat is owned by net-tools. Installing net-tools gave me access to netstat.
How should one proceed to find the package name to install with pacman when only the final bash command is known ?

A: The best way that I have found until now is to use the pkgfile command.
You could install it by:
# sudo pacman -S pkgfile

according to the official arch wiki,

pkgfile is a tool for searching files from packages in the official repositories.

(files being the binaries you mentioned as bash commands).
You can also update its database by running:
# pkgfile -u

or you could just enable its systemd timer for it to update automatically:
# systemctl enable pkgfile-update.timer
# systemctl start pkgfile-update.timer

awsome, right ?! :)
Example
# pkgfile netstat
core/net-tools
extra/munin-node

# pkgfile netstat --verbose
core/net-tools 1.60.20160710git-1       /usr/bin/netstat
extra/munin-node 2.0.26-2               /usr/lib/munin/plugins/netstat

redpajama_set_name: RedPajamaStackExchange


text:
Q: I can't set an MVC checkbox as checked in jquery In MVC, I'm using helpers to create a checkbox like so
@Html.CheckBox("MDCCheckbox", true, new { @class = "LineCheckbox" })
@Html.Label("MDCCheckbox", "MDC")

Nothing fancy.
I want to be able to (un)check the box in jquery.
I can uncheck it very easily, but I can't set it to checked.
It's something with the way MVC renders the html, but I can't figure it out.
I know that I can just create the elements myself, but I want to know what I'm doing wrong.
This is how that razor is rendered into html (with a matching input element to pass true/false to the server).
<input checked="checked" class="LineCheckbox" id="MDCCheckbox" name="MDCCheckbox" type="checkbox" value="true" />
<input name="MDCCheckbox" type="hidden" value="false" />
<label for="MDCCheckbox">MDC</label>

I've created a fiddle to make it easier to play with and test.  I can't even get it to work in the fiddle.
fiddle
Here is the jquery
$(".check").click(function () {
    $(".LineCheckbox").attr("checked", true);
});
$(".uncheck").click(function () {
    $(".LineCheckbox").removeAttr("checked");
});

A: Use .prop()
$(".check").click(function () {
    $(".LineCheckbox").prop("checked", true);
});
$(".uncheck").click(function () {
    $(".LineCheckbox").prop("checked", false);
});

DEMO
A good read .prop() vs .attr()

A: Use .prop()
$(".check").click(function () {
    $(".LineCheckbox").prop("checked", true);
});

You can see the difference between .prop() and .attr()
Fiddle Demo

A: Use .prop() to set property checked instead:
$(".check").click(function () {
    $(".LineCheckbox").prop("checked", true);
});
$(".uncheck").click(function () {
    $(".LineCheckbox").prop("checked", false);
});

A: you can use this:
$(".check").click(function () {
    $('.LineCheckbox').prop('checked', true);
});
$(".uncheck").click(function () {
     $('.LineCheckbox').prop('checked', false);
});


text:
Q: Compare two Curve in survival analysis I have question regarding kaplan meier curve to compare two curve
I have Event variable ( which the patient have relapse or not ) the total number is 51 we have 16 events ( relapse ) and 35 censored . and when I run the kaplan meier :
progression free survival analysis which is = 49% by the end of period of our observation.
so  I want to group this survival by the "type of relapse"
The variable I used for grouping is:
Type of relapse the total number is 16 ether (regional recurrence  (n=15) or Distant recurrence ( n=1))
the problem here when I run the  kaplan meier curve by using the type of relapse as grouping variable ( which include the information of only 16 patients who relapsed (  regional recurrence  (n=15) or Distant recurrence ( n=1) ) so the censored patient where excluded and the result from two curves ( reginal or distains = 0% by the end of study instead of 49% )
so the question is what the best way to compare the two curves (regional recurrence Distant recurrence ) ? it's okay to be 0 and exclude the censored

A: In this particular situation, with only 1 distant recurrence, you aren't going to be able to say much useful in the comparison of recurrence times between loco-regional and distant recurrence. I'd recommend showing the recurrence-free survival curve for all individuals and highlighting the event (drop in the survival curve) for the 1 distant recurrence.
More generally, if loco-regional and distant recurrences could be considered mutually exclusive events, the best approach is to model them as competing risks, as explained for example in the R competing survival events vignette. The vignette notes:

A common mistake with competing risks is to use the Kaplan-Meier separately on each event type while treating other event types as censored.

That argues against your suggestion of simply censoring the observation time of the distant recurrence.
Further complicating this situation is that loco-regional and distant recurrences aren't necessarily mutually exclusive in practice. You might find one first on physical examination, but then find the other with technologies like PET scans. Then you need to apply your understanding of the subject matter and think carefully about the details of the hypothesis you want to test.


text:
Q: Are the swords shown in Game of Thrones faithful to those in A Song of Ice and Fire? After answering this question: Is Needle's portrayal in Game of Thrones faithful to the books? (And is it a shortsword?) I found out that the shows portrayal of Needle does not align with the books portrayal.
With this in mind are there any swords in the show that are faithful to those in the books?

A: Yes
As it turns out there are some swords that align with GRRM's vision of it from the books.
Robb Stark's Sword
GRRM mentions this on his blog on this post:

The Sword of Robb Stark is never described in any detail in my novels... but if I ever had paid it any mind, it probably would have looked quite a lot like the one seen in the show, which Valyrian Steel has replicated. So this one can almost be considered "novel authentic" as well as "show authentic."

This was a comment on the sword replica on Valyrian Steel though the replica is faithful to the one used in the show:

Longclaw
Though not exactly the same when you look at the replicas the sword keeps the main spirit alive so I'd say it is faithful.

The pommel was a hunk of pale stone weighted with lead to balance the long blade. It had been carved into the likeness of a snarling wolf's head, with chips of garnet set into the eyes. The grip was virgin leather, soft and black, as yet unstained by sweat or blood. The blade itself was a good half foot longer than those Jon was used to, tapered to thrust as well as slash, with three fullers deeply incised in the metal. Where Ice was a true two-handed greatsword, this was a hand-and-a-halfer, sometimes named a "bastard sword." Yet the wolf sword actually seemed lighter than the blades he had wielded before. When Jon turned it sideways, he could see the ripples in the dark steel where the metal had been folded back on itself again and again. "This is Valyrian steel, my lord," he said wonderingly. His father had let him handle Ice often enough; he knew the look, the feel.
A Game of Thrones, Jon VIII

Daario's Ladies
Like Longclaw this isn't an exact copy but it does seem similar enough that they can be considered to be faithful to the books.

"Because you are so beautiful." His hands were large and strong, and there was something in his hard blue eyes and great curving nose that suggested the fierceness of some splendid bird of prey. "Prendahl talked too much and said too little." His garb, rich as it was, had seen hard wear; salt stains patterned his boots, the enamel of his nails was chipped, his lace was soiled by sweat, and she could see where the end of his cloak was fraying. "And Sallor picked his nose as if his snot was gold." He stood with his hands crossed at the wrists, his palms resting on the pommels of his blades; a curving Dothraki arakh on his left hip, a Myrish stiletto on his right. Their hilts were a matched pair of golden women, naked and wanton.
A Storm of Swords, Daenerys IV

Shagga Son of Dolf's Battle Axes
This one is actually quite straight forward, both quotes from the books and show appear to come to the same conclusion on Shagga's weapons.

Lord Lefford frowned. "I saw that great hairy one today, the one who insisted that he must have two battle-axes, the heavy black steel ones with twin crescent blades."
"Shagga likes to kill with either hand," Tyrion said as a trencher of steaming pork was laid in front of him.
A Game of Thrones, Tyrion VIII

The show also uses a similar quote:

Kevan Lannister: "The great hairy one insisted he must have two battle-axes, heavy black steel, double-sided."
Tyrion Lannister: "Shagga likes axes."
Game of Thrones, Season 1 Episode 9, "Baelor"

Swords that aren't faithful
For completeness sake I am also going to cover some of the main swords in the series. These are ones that are named and shown or belong to a main character (also mostly ones that Valyrian Steel have also created replicas for).
As a general comment I just want to repeat that Valyrian Steel is:

Your source of officially licensed replica weapons and armor from HBO® 's hit TV series Game of Thrones® , and George R.R. Martin's A Song of Ice and Fire book series.

As such their depictions of the weapons should be pretty accurate, especially since apparently they work with GRRM to design them:

We manufacture weapon and armor replicas from George R.R. Martin's bestselling book series. Each item is an individually serialized limited edition and comes with a certificate of authenticity personally autographed by Mr. Martin himself. Each item is designed while working closely with Mr. Martin to make sure they fit his vision.

Also that their A Song of Ice and Fire swords come with the following notices, the following is for needle:

This is the exclusive officially licensed Needle, Sword of Arya Stark, from "A Song of Ice and Fire." All swords come with a certificate of authenticity personally autographed by George R.R. Martin. Each sword is a limited edition of 2500 pieces and the back of the blade has been laser etched in very fine print with the edition number and a copyright notice so you know it is authentic.

As such it appears that GRRM agrees that these are the versions of the swords that are true to the books.
Each of the following blades are different in the show compared to the books:
Ice

Lord Eddard Stark dismounted and his ward Theon Greyjoy brought forth the sword. "Ice," that sword was called. It was as wide across as a man's hand, and taller even than Robb. The blade was Valyrian steel, spell-forged and dark as smoke. Nothing held an edge like Valyrian steel.
A Game of Thrones, Bran I

As you can see from the above pictures the hilt is completely different. The book version has a white grip with gold and silver decoration in the middle, it also appears to be made of suede. The crossguard is quite short to the sword width of has the words "Winter is Coming" written across it, lastly, it has a folded, patterned blade characteristic of Valyrian Steel. In the show however, the hilt has a large plain crossguard and a large brown grip. This grip also appears to be made of leather.
Widows Wail

His father glanced up. "I did. Come have a look at this." A bundle of oilcloth lay on the table between them, and Lord Tywin had a longsword in his hand. "A wedding gift for Joffrey," he told Tyrion. The light streaming through the diamond-shaped panes of glass made the blade shimmer black and red as Lord Tywin turned it to inspect the edge, while the pommel and crossguard flamed gold. "With this fool's jabber of Stannis and his magic sword, it seemed to me that we had best give Joffrey something extraordinary as well. A king should bear a kingly weapon."
A Storm of Swords, Tyrion IV

There isn't a replica for the book version of Widows Wail yet but we can expect it to be different as the blade is meant to be red and the show blade is not.
Oathkeeper

"A crimson sword might flash prettily in the sun, but if truth be told I like these colors better," said Tyrion. "They have an ominous beauty . . . and they make this blade unique. There is no other sword like it in all the world, I should think."
"There is one." The armorer bent over the table and unfolded the bundle of oilcloth, to reveal a second longsword.
Tyrion put down Joffrey's sword and took up the other. If not twins, the two were at least close cousins. This one was thicker and heavier, a half-inch wider and three inches longer, but they shared the same fine clean lines and the same distinctive color, the ripples of blood and night. Three fullers, deeply incised, ran down the second blade from hilt to point; the king's sword had only two. Joff's hilt was a good deal more ornate, the arms of its crossguard done as lions' paws with ruby claws unsheathed, but both swords had grips of finely tooled red leather and gold lions' heads for pommels.
A Storm of Swords, Tyrion IV

Again like Widows Wail it isn't faithful as it doesn't have the characteristic red blade from the books. Looking at the hilts, they too are completely different. In the show it is one piece of a golden lion and quite decorative. Whereas, in the books it has a simple gold crossguard with a lion on each end, a red grip and gold detailed pommel.
Valrian Steel Dagger

The blade Joff chose was nice and plain. No goldwork, no jewels in the hilt, no silver inlay on the blade. King Robert never wore it, had likely forgotten he owned it. Yet the Valyrian steel was deadly sharp . . . sharp enough to slice through skin, flesh, and muscle in one quick stroke. I am no stranger to Valyrian steel. But he had been, hadn't he? Else he would never have been so foolish as to pick Littlefinger's knife.
A Storm of Swords, Tyrion VIII

There is no replica of the book version yet, however, I have found this quote from GRRM claiming that they are different:

A handsome blade, I think. Though rather completely different from the dagger in the books, which was far plainer (though made of Valryian steel, with a dragonbone grip).
GRRM: Not A Blog - Swords for Sale

Dawn - The Sword of Morning's Sword

Ser Arthur Dayne, the Sword of the Morning, had a sad smile on his lips. The hilt of the greatsword Dawn poked up over his right shoulder.
...
"And now it begins," said Ser Arthur Dayne, the Sword of the Morning. He unsheathed Dawn and held it with both hands. The blade was pale as milkglass, alive with light.
A Game of Thrones, Eddard X

Although there isn't a replica of the book version, in the show Ser Arthur Dayne dual wields two swords so it's possible they changed the sword into two. However, When Ned rides upto the Kingsguard Arthur has a sword out in front of him. This looks to be Dawn.

If it is then the shows version doesn't look to be faithful to the books as it doesn't look to be a greatsword and does not have a pale milkglass blade.
Jaime Lannister's Sword
Although there is a lack of information in the books about his sword it appears as though it isn't faithful.

Jaime Lannister poked at Ned's chest with the gilded sword that had sipped the blood of the last of the Dragonkings. "Would she? The noble Catelyn Tully of Riverrun murder a hostage? I think … not." He sighed. "But I am not willing to chance my brother's life on a woman's honor." Jaime slid the golden sword into its sheath.
A Game of Thrones, Eddard IX

It isn't totally clear and open to interpretation but knowing that Oathkeeper and Widows Wail are both red I'd assume that it means for the blade to have been golden. Also it is mentioned as being golden on numerous occasions leading more credit to it actually having a golden blade.

The polished skulls of the last dragons staring down sightlessly from the walls of the throne room while the Kingslayer opened Father's throat with a golden sword.
A Game of Thrones, Daenerys I

As such the show version doesn't seem to match this description.

Swords where it's unclear
The following swords are unclear as to whether or not they are faithful.
Khal Drogo's Arakh
There isn't much description on Drogo's weapons, the only bit I could find was his "brides gifts":

Haggo gave her a great leather whip with a silver handle, Cohollo a magnificent arakh chased in gold, and Qotho a double-curved dragonbone bow taller than she was.
A Game of Thrones, Daenerys II

As it's unclear whether or not this was the Khal's arakh of choice I can't say for sure whether the show was faithful. However, the show replica is not to that description.

Heartsbane
There is little to no description of the sword in the books other than it's a Valyrian steel greatsword.

Drumm nodded, one hand on the hilt of his Red Rain. "Lord Tarly bears the greatsword Heartsbane, forged of Valyrian steel, and he is always in Lord Tyrell's van."
A Feast for Crows, The Reaver

As such it's unclear whether of not the shows version is faithful to the books.

King Robert Baratheon's War Hammer
This is the odd one of the bunch in that it isn't technically a sword but I think it still fits within the scope of the question. It's also the only one where it is clear from the books perspective of what it should look like but not the show. The following image is of the books replica:


text:
Q: Rewrite Rule with first and/or second subdirectory I would like these URLs to be valid...
example.com/
example.com/results/
example.com/results/live/
example.com/results/live/123
example.com/results/ended/
live, ended, etc will always be alphabetic
123 will always be digits (page number value)
What I want to do is drop a php file into /results/ and pass "live" and "123" as two variables. I can get that working but if I omit the "/123" then I also want "/live" to continue to work. The problem is that the directory doesn't exist and doesn't contain two variables so it is rejected. I have tried chaining but couldn't get that to work.
A simplified htaccess file is shown below
<IfModule mod_rewrite.c>
RewriteEngine OnRewriteBase /
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^results/([A-Za-z]+)/([0-9]+)/?$ /results/index.php?format=$1&pagenum=$2 [L]
</IfModule>
Options All -Indexes
ErrorDocument 404 /errors/404

I have dabbled with using "-" instead of a directory delimiter, same problem
In essence I happy with the way that any missing files or folders are currently being handled but I'd like to create an exception for this directory
If I can't figure this out another long winded option is to create actual subdirectories inside "/results/" with their own php file and manage the pagination as just one variable.
Any pointers?

A: Try this instead:
RewriteEngine On
RewriteBase /
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^results/([A-Za-z]+)/?(?:([0-9]+)/?|)$ /results/index.php?format=$1&pagenum=$2 [L]

The (?:([0-9]+)/?|) is a conditional look-ahead. It makes the last part (e.g. /1234) optional. If it's not there, pagenum will be blank.


text:
Q: Passing Two List to a Python function I am trying to run python package pyabc(Approximate Bayesian Computation) for model selection between two list of values i.e model_1=[2,3,4,5] and model_2=[3,4,2,5]. The main function of pyabc is ABCSMC which states that
Definition : ABCSMC(models: Union[List[Model], Model], parameter_priors:
Union[List[Distribution], Distribution, Callable], distance_function: Union[Distance,
Callable]=None, population_size: Union[PopulationStrategy, int]=100, summary_statistics:
Callable[[model_output], dict]=identity, model_prior: RV=None)

I don't know where to define and pass my two lists model_1 and model_2 in the below mentioned code. I tried it several times but not able to do  it as I am new to Python. I am following an example and its code in mentioned below.
import os
import tempfile
import scipy.stats as st
import pyabc

# Define a gaussian model
sigma = .5

def model(parameters):
    # sample from a gaussian
    y = st.norm(parameters.x, sigma).rvs()
    # return the sample as dictionary
    return {"y": y}

# We define two models, but they are identical so far
models = [model, model]

# However, our models' priors are not the same.
# Their mean differs.
mu_x_1, mu_x_2 = 0, 1
parameter_priors = [
    pyabc.Distribution(x=pyabc.RV("norm", mu_x_1, sigma)),
    pyabc.Distribution(x=pyabc.RV("norm", mu_x_2, sigma))
]
abc = pyabc.ABCSMC(
    models, parameter_priors,
    pyabc.PercentileDistance(measures_to_use=["y"]))

db_path = ("sqlite:///" +
           os.path.join(tempfile.gettempdir(), "test.db"))
history = abc.new(db_path, {"y": y_observed})
print("ABC-SMC run ID:", history.id)
# We run the ABC until either criterion is met
history = abc.run(minimum_epsilon=0.2, max_nr_populations=5)

A: Model selection in pyABC aims to decide among different model candidates which model describes a common set of observed data best. In your above code, you would thus typically use different models in the list of models models = [model1, model2]. I am not sure what you mean by model selection over lists?
For the underlying algorithm and problem that it tries to solve, see also the original paper https://doi.org/10.1093/bioinformatics/btp619.


text:
Q: Difference between Async/Await and Dispatcher I am working on a WPF application and I am running into freezing issues, by now I have learned that its a single threaded application, but i am getting confused with terminologies
I simple terms
Difference between Async/Await and Dispatcher
I want to explain my point of view so its clear on both ends my misunderstanding , until now I have learned that most applications are STA (in c#), and you have to use asynchronous programming, which can very well involve

*

*A single thread that shifts work on the UI thread by prioritizing work that has already completed and then using a worker thread to notify the UI thread that the heavy work is done

*Also a truly multi threaded application where a thread needs to be created to complete the task on it

I think for most part my concept is at least solid to say the least where I lack is applying these abilities
for instance i though that previously to enable asynchronous programming we had to use delegates to be called from the main method, which evolved into a dispatcher cutting of delegates which further evolved into async and await cutting 'ANY SINGLE USE OF' dispatcher (even that literal keyword)
so all i used were "async" word at the declaration of the function, followed by the "task", then awaiting some intense process by sticking an "await" word before it finally encapsulating that intense work with Task.Run(() => IntenseWork())
but now I am confused that you have to use Dispatcher word because UI elements can only be accessed by dispatcher , and use Dispatcher.Invoke(IntenseWork()), then there is Dispatcher.Begininvoke and Dispatcher.AsyncIncoke
DOUBT:
in which case async/await and task.run isn't going to be enough and is task parallel library even going to be used here

I asked questions and reserched and am stuck at these conclusions, these r my previous questions
Asynchronous Navigation
Using async and await to achieve asynchronicity in example problem

A: You are asking about two different technologies from different periods.
The common problem is that the UI is single threaded and should only be accessed from the main (UI) thread.
You can and should offload non-UI work to another thread as much as possible. But there usually are results that need to be displayed afterwards.
The old (but still valid) approach is to hand a delegate to Dispatcher.Invoke(), or Control.Invoke() in WinForms.
The newer approach, applicable to Task.Run() and all DoSomethingAsync() I/O methods is to use await:
// use async void only for eventhandlers
async void LoadButton_Click(object s, RouteEventArgs e)
{
   // get input from controls here
   var results = await Task.Run(() => HeavyWorkWithoutUI());
   // update UI with results here
}

The WPPF and WinForms support is that your toplevel methods will run on the UI thread before and after an await. The heavy method will run on another thread. During the await your UI remains responsive.
So await is just a little more convenient, letting you write more readable code with less effort.


text:
Q: Avoid duplication of ActiveRecord::Base.connection_pool.with_connection I have some functions that are using ActiveRecord to persist some data.
def create_location(user_location)
  ActiveRecord::Base.connection_pool.with_connection do
    loc = Location.new(user_location.attrs)
    loc.save!
  end
end

How can I avoid duplication of code?
Because now on each method I'll have to wrap everything inside ActiveRecord::Base.connection_pool.with_connection.


text:
Q: Returning a JSON float value I am parsing a JSON file with Python. One of they keys I am trying to parse has a float value, and I am getting the following error: TypeError: list indices must be integers, not str. Below is the code, JSON, and full traceback.
Code:
import json

with open('output.json') as f:
    data = json.load(f)

for host in data['ASSET_DATA_REPORT']['HOST_LIST']['HOST']:
    print(host['VULN_INFO_LIST']['VULN_INFO']['CVSS_FINAL'])

JSON:
    {
   "ASSET_DATA_REPORT":{
      "HOST_LIST":{
         "HOST":[
            {
               "IP":{
                  "network_id":"0"
               },
               "TRACKING_METHOD":"EC2",
               "ASSET_TAGS":{
                  "ASSET_TAG":[
                     "EC2 Running",
                     "IF - Database - MySQL"
                  ]
               },
               "DNS":"i-xxxxxxx",
               "EC2_INSTANCE_ID":"i-xxxxxx",
               "EC2_INFO":{
                  "PUBLIC_DNS_NAME":"ec2-xxxxxxxx.amazonaws.com",
                  "IMAGE_ID":"ami-xxxxxx",
                  "VPC_ID":"vpc-xxxxxx",
                  "INSTANCE_STATE":"RUNNING",
                  "PRIVATE_DNS_NAME":"ip-xxxx.ec2.internal",
                  "INSTANCE_TYPE":"m3.xlarge"
               },
               "VULN_INFO_LIST":{
                  "VULN_INFO":[
                     {
                        "CVSS_FINAL":"3.6"
                     }
                  ]
               }
            }
         ]
      }
   }
}

Traceback:
Traceback (most recent call last):
  File "json_format.py", line 11, in <module>
    print(host['VULN_INFO_LIST']['VULN_INFO']['CVSS_FINAL'])
TypeError: list indices must be integers, not str

A: The dictionary containing the "CVSS_FINAL" key is actually itself in a list. Try:
print(host['VULN_INFO_LIST']['VULN_INFO'][0]['CVSS_FINAL'])

As an aside, if you want to store this value as type float in Python (rather than string), you could do:
value = float(host['VULN_INFO_LIST']['VULN_INFO'][0]['CVSS_FINAL'])


text:
Q: Installation of SpacCy Language Model in python not working I'm following the Rasa Core "Building a simple Bot" tutorial. (https://core.rasa.com/tutorial_basics.html) It requires the installation of the SpaCy Language model:
python -m spacy download en_core_web_md
However, I get "AttributeError: module 'thinc.linalg' has no attribute 'Mat'"
Have you any idea what is causing this?

A: Latest Spacy has a requirement of thinc as:
thinc>=6.10.1,<6.11.0

Double check the requirements.txt and check which modules are installed with pip list. If the issue is with incorrect version of thinc then run
pip uninstall thinc
pip install thinc==6.10.1


text:
Q: How do I debug existing C programs with Visual Studio 2010 Professional? how can I use the Visual Studio Debugger on existing C programs I found in a textbook? I want to debug these little examples one by one, but without the overhead of creating a full project for each example.
Example: Let's say I compile "helloworld.c" from the Visual Studio command prompt ("cl.exe helloworld.c"). This gives me helloworld.obj and helloworld.exe. I would like to know if there is a way to use the VS debugger on "helloworld.exe". So far, I have only worked with the debugger on full-blown projects; I have no idea how to debug small "stand-alone" test programs without the Visual Studio project overhead. (I hope this is not a dumb question, as the VS Debugger might only be available for the full project.)
Thank you for any ideas.

A: Why don't you create one project for testing the sample codes? You can create a single .c-file for all the samples. This would look something like
void sampleA()
{
 //hello world
}

void sampleB()
{
 //hello everybody else
}

void main(int argc, char** argv)
{
//  sampleA();
  sampleB();
}

A: What I do when I have to use VS is to reuse the plain.c project I created a long time ago.
Just paste new code there and go. Throw the code in another file if you want to keep it.

A: It is not impossible, but you'll have to learn a lot more about how to exactly build a program from the command line to get the best debugging experience.  There are a bunch of options that are real time savers and greatly improve the odds that you'll discover bugs.
Which is a little beside the point right now, learn C instead of spending time learning a boring tool with way too many options.  Creating a new project takes 5 seconds after a wee bit of practice.  Use the Win32 Console Application project template.
One small setting you have to change if you want to compile as C instead of C++.  Right-click the project, Properties, C/C++, Advanced, Compile As = Compile as C Code.

A: If you're set on not using projects then you can do this.  It just gets more difficult as the number of code files increases.
First, to do any meaningful source-level debugging, you will need to generate debug symbols.  Add the "/Zi" switch to your cl.exe command line:
cl.exe /Zi helloworld.c

This will generate helloworld.exe, helloworld.obj, and helloworld.pdb (these are the debugging symbols).
Next you will open Visual Studio 2010.  Use File -> Open -> File... and select helloworld.exe.  It will generate a wrapping solution with one project for your EXE file.
In Solution Explorer, right click on the EXE file and select Debug -> Step Into new instance.
It should pop up a source window and show you the first line of your program.  Now, debug away!

A: The debugger is part of Visual Studio, so you'll have to start it up anyway. However, for the debugger to work properly with your source code, you need to also generate a PDB file (see here). You get this by including /Zi or /ZI as argument to cl.exe (see here).

A: The "overhead" is hardly more effort that it took to post this question!
Simply start with the "Empty Project" template and add the single source file you wish to debug by right-clicking on the project browser sources folder.  It takes mere seconds.


text:
Q: Spark Dataframe GroupBy and compute Complex aggregate function Using Spark dataframe , I need to compute the percentage by using the below
complex formula :
Group by "KEY " and calculate "re_pct" as  ( sum(sa) / sum( sa / (pct/100)  ) ) * 100
For Instance , Input Dataframe is
val values1 = List(List("01", "20000", "45.30"), List("01", "30000", "45.30"))
  .map(row => (row(0), row(1), row(2)))

val DS1 = values1.toDF("KEY", "SA", "PCT")
DS1.show()

+---+-----+-----+
|KEY|   SA|  PCT|
+---+-----+-----+
| 01|20000|45.30|
| 01|30000|45.30|
+---+-----+-----+

Expected Result :
+---+-----+--------------+
|KEY|    re_pcnt         |
+---+-----+--------------+
| 01|   45.30000038505   |
+---+-----+--------------+

I have tried to calculate as below
    val result = DS1.groupBy("KEY").agg(((sum("SA").divide(
  sum(
    ("SA").divide(
      ("PCT").divide(100)
    )
  )
)) * 100).as("re_pcnt"))

But facing Error:(36, 16) value divide is not a member of String ("SA").divide({
Any suggestion on implementing the above logic ?

A: You can try importing spark.implicits._ and then use $ to refer to a column.
val spark = SparkSession.builder.getOrCreate()
import spark.implicits._

val result = DS1.groupBy("KEY")
  .agg(((sum($"SA").divide(sum(($"SA").divide(($"PCT").divide(100))))) * 100)
  .as("re_pcnt"))

Which will give you the requested output.
If you do not want to import you can always use the col() command instead of $.

It is possible to use a string as input to the agg() function with the use of expr(). However, the input string need to be changed a bit. The following gives exactly the same result as before, but uses a string instead:
val opr = "sum(SA)/(sum(SA/(PCT/100))) * 100"
val df = DS1.groupBy("KEY").agg(expr(opr).as("re_pcnt"))

Note that .as("re_pcnt") need to be inside the agg() method, it can not be outside.

A: Your code works almost perfectly. You just have to put the '$' symbol in order to specify you're passing a column:
val result = DS1.groupBy($"KEY").agg(((sum($"SA").divide(
  sum(
    ($"SA").divide(
      ($"PCT").divide(100)
    )
  )
)) * 100).as("re_pcnt"))

Here's the output:
result.show()
+---+-------+
|KEY|re_pcnt|
+---+-------+
| 01|   45.3|
+---+-------+


text:
Q: Erro 1054 Laravel Estou tendo um problema em paginação, quando vou mudar a pagina, ele da um erro 1054
Controller
public function lista(Request $request)
    {

       $pessoasQuery = pessoas::query();

       foreach ($request->all() as $campo => $valor)
       {
         if ('status' == '')
          {

            $pessoasQuery->where('status', 'atv');

          }
         if ($valor == '')
         {}else
          {
            if (in_array($campo, ['observacao', 'nome_fantasia', 'razao_social' , 'cpf_cnpj']))
            {
              $pessoasQuery->where($campo, 'like', '%' . $valor . '%');
              continue;
            }
           $pessoasQuery->where($campo, $valor);
          }
       }
       //$pessoasQuery= pessoas::paginate(5);
       $clientes = $pessoasQuery->where('tipo_pessoa', '=', 'cliente')->paginate(2);

        //$clientes = pessoas::paginate(2);
      return view('Pessoa.clientes') -> with('clientes', $clientes);
      // return view('Pessoa.clientes', compact(['clientes']));
    }

View
    @foreach ($clientes as $cliente)

         {{ $cliente->id }}
         {{ $cliente->razao_social }}
         {{ $cliente->nome_fantasia }}
         {{ $cliente->cpf_cnpj }}
         {{ \App\Utils\Formatador::formataTipo($cliente->tipo) }}
         {{ $cliente->observacao }}

            id }}" >

      @endforeach

    {{$clientes->count()}}
    {{$clientes->links()}}

@stop

Erro

"SQLSTATE[42S22]: Column not found: 1054 Unknown column 'page' in 'where clause' (SQL: select count(*) as aggregate from pessoas where page = 2 and tipo_pessoa = cliente) ◀"

A: Você está passando o parâmetro "page" na sua consulta, isso aconteceu por causa da forma que você fez utilizando um foreach para percorrer todos os campos do request e jogando cada campo na consulta.
O código abaixo deve resolver o seu problema.
$campos = $request->all(); // Atribui todos os parâmetros passado no request

// Você deve chamar esse método antes de realizar a consulta
// Esse método vai dizer em qual página você está.
Paginator::currentPageResolver( function() use ( $campos['page'] ) {
    return $campos['page'];
});

// No lugar de você percorrer todos os campos do request,
// você pode usar o método when do Laravel,
// esse método só é executado quando o valor passado no primeiro parâmetro
// seja diferente de null
$clientes = $pessoasQuery->where('tipo_pessoa', '=', 'cliente')
                         ->when( $campos['observacao'], function( $query ) use( $campos['observacao'] ) {
                            return $query->where( 'observacao', 'like', '%' . $campo['observacao'] . '%');
                         })->paginate(2);

P.S: Você pode usar o método when em todos os campos.


text:
Q: Shows remote connection corectly but error: failed to push some refs error I am trying to set up git and did some test, by adding a Remote connection as below.
On the loal machine
git init

Initialized empty Git repository in C:/CRMNext/Git/speech_to_text_auto_2/.git/
git status

On branch master
No commits yet
Untracked files:
  (use "git add ..." to include in what will be committed)
        README.md.txt
git add .

git status

On branch master
No commits yet
Changes to be committed:
  (use "git rm --cached ..." to unstage)
        new file:   README.md.txt
git remote add origin git@github.com:Sarrae1406/speech_to_text_auto_2.git

git remote -v
origin  git@github.com:Sarrae1406/speech_to_text_auto_2.git (fetch)
origin  git@github.com:Sarrae1406/speech_to_text_auto_2.git (push)

git push origin master
error: src refspec master does not match any
error: failed to push some refs to 'git@github.com:Sarrae1406/speech_to_text_auto_2.git'

Whats missing to complete a push to Github ?


text:
Q: dynamic DatepickerView and DynamicPicker view for multiple textview here I am trying to develop a dynamic UIPickerView &
UIDatePicker for multiple UITextFields in a UIViewController. In my UIViewController I have five UITextFields and by clicking on every UITextField, I open UIPickerView but my problem is that I want code in which
UIPickerView set dynamically in UIViewController. Because here I have
also take 5 different date pickerview for that and open it there
particular position by showing & hiding each other as per condition.
For example - I have 5 UITextFields in the UIViewController. If I select the second UITextField then the Y position below three UITextFields can be set
automatically rather than set frame of every UITextField. Then if I
select the fourth UITextField the Y postion of the only fifth UITextField
change the three UITextFields above fourth UITextField would not change. For
more description I see the attach image:

A: use scroll view  or autolayout for this type of problem. or you can use table view in which add the text field and pickerview.


text:
Q: Clear all queryParams with new Router v3 Angular2 I'm trying to figure out how to use the Angular2 router navigation (router 3.0.0-alpha.7) with query parameters.
I can easily navigate to a route with a queryParam with this line:
this._router.navigate(['/login'], {queryParams: {redirect: 'route1'}});

In the '/login' component, I do some login which will redirect to the redirect route, namely route1 here. However, after the redirection, the redirect query parameters stays in the URL, i.e. I'm now at page /route1?redirect=route1. I want to remove the redirect parameter here.
Moreover, if I then navigate to another page with the same redirect queryParam, it doesn't overwrite the previous one, but adds another ?redirect=... in the url. Namely:
this._router.navigate(['/another-route'], {queryParams: {redirect:'route2'}});

leads me to /another-route?redirect=route2?redirect=route1
Is it possible to clear the queryParams when navigating between routes?
I tried this._router.navigate(['/route1'], {queryParams: {redirect: null}});, or {queryParams: null} etc but no success.

A: Actually ... you should NOT "expect the router to clear query params".
Clearly you DO expect that. But that's because you don't know about an important router design decision ... probably because, unfortunately, we haven't told you about it in the docs yet.  We're working on correcting that now.
QueryParams are for parameters that are global across navigations; they do not change.
MatrixParams are for parameters that belong to the current navigation; these do change.
What belongs in global QueryParams? Stuff that comes from the server are candidates. Like auth tokens that belong on every interaction.
But required route params (the :id in customer/:id) and optional matrix params (like the ;name=Jo* in /customers;name=Jo*) are local to one navigation.  That's how you might specify a navigation for customers with an optional name filter.
Whether or not you agree with this approach, it is fundamental to the v.3 router design.
I suggest adjusting your expectations rather than fighting it.

A: I struggled with this as well. You would expect the router to clear query params by default when navigating to another route...
You can do either
this._router.navigate(['/route1'], {queryParams: {}});

or
this._router.navigateByUrl('/route1');

or when using routerLink:
<a [routerLink]="['/applications']" [queryParams]="{}"> Applications</a>

A: You can simply use preserveQueryParams: false parameter to ignore query params
this.router.navigate(['target'], {preserveQueryParams: false});


text:
Q: Add a field to coupon settings and display the value on Woocommerce admin order list I am having some really hard times trying to make it work.
I've had an idea in back of my head to:

*

*be able to assign single user to a coupon code through an extra field in general coupon tab, which is listing unassigned users to coupon codes
I dont want to use third party extensions, custom-fields, etc. I was hoping I'll be able to do it through meta data but I failed. Not sure how to get it done properly.

*add two extra columns on orders page and display both coupon code and user assigned to it.
After some time reading docs and xDebugging in phpstorm I have also failed to get it done.
 function order_sellers_and_coupons_columns_values($column)
 {
    global $post, $the_order;

    if ($column == 'order_coupon_code') {
        $coupons = $the_order->get_used_coupons(); // not sure how to get coupon object by the coupon code
        echo (count($coupons)) ? $coupons[0] : '';
    }
 }

 // even though I see the order objects have an items and coupon lines property,
 // which is an object, i can't get access to it
 $the_order->items["coupon_lines"]

I am not asking for ready-to-go solution, but to show me the way how to get it done.
Thanks in advance for any kind of help.

A: In WooCommerce admin single coupon pages, we add an extra field for the seller (dealer):
// Add a custom field to Admin coupon settings pages
add_action( 'woocommerce_coupon_options', 'add_coupon_text_field', 10 );
function add_coupon_text_field() {
    woocommerce_wp_text_input( array(
        'id'                => 'seller_id',
        'label'             => __( 'Assing a seller (dealer)', 'woocommerce' ),
        'placeholder'       => '',
        'description'       => __( 'Assign a seller / dealer to a coupon', 'woocommerce' ),
        'desc_tip'    => true,

    ) );
}

// Save the custom field value from Admin coupon settings pages
add_action( 'woocommerce_coupon_options_save', 'save_coupon_text_field', 10, 2 );
function save_coupon_text_field( $post_id, $coupon ) {
    if( isset( $_POST['seller_id'] ) ) {
        $coupon->update_meta_data( 'seller_id', sanitize_text_field( $_POST['seller_id'] ) );
        $coupon->save();
    }
}

Then using the following you will add to admin orders list the coupon code (when it's used in the order) with the seller / dealer name:
// Adding a new column to admin orders list
add_filter( 'manage_edit-shop_order_columns', 'custom_shop_order_column' );
function custom_shop_order_column($columns)
{
    $reordered_columns = array();

    // Inserting columns to a specific location
    foreach( $columns as $key => $column){
        $reordered_columns[$key] = $column;
        if( $key ==  'order_status' ){
            // Inserting after "Status" column
            $reordered_columns['coupons'] = __( 'Coupon','theme_domain');
        }
    }
    return $reordered_columns;
}

// Adding used coupon codes
add_action( 'manage_shop_order_posts_custom_column' , 'custom_orders_list_column_content', 10, 2 );
function custom_orders_list_column_content( $column, $post_id )
{
    global $the_order;

    if ( $column == 'coupons' ) {
        $coupons = (array) $the_order->get_used_coupons();
        $dealers = [];

        foreach( $coupons as $coupon_code ) {
            $coupon    = new WC_Coupon( $coupon_code );
            $dealers[] = $coupon->get_meta('seller_id');
        }

        if( count($coupons) > 0 )
            echo implode( ', ', $coupons );

        if( count($dealers) > 0 )
            echo '
(' . implode( ', ', $dealers ) . ')';
    }
}

All code goes in functions.php file of your active child theme (or active theme). Tested and works.

On Admin coupon single pages:

On Admin edit orders list:


text:
Q: IIS Impersonation not working when app pool runs with domain account I have an ASP.net application running in an windows intranet environment.  I have a requirement to perform certain database updates as the currently logged in user.
IIS/server info:

*

*IIS version 10

*Windows server 2019

*ASP.net web forms application

*.NET 4.7

*Windows authentication enabled

*Impersonation and anonymous authentication are disabled

*The app pool uses integrated pipeline

*The app pool runs with a domain service account for it's identity, which has rights to access other resources as needed.

Other details:

*

*All of my database connection strings are set such that integrated security=true

*in active directory, have configured constrained delegation between the web server and the SQL server, allowing MSSQLSvc : 1433 and MSSQLSvc (no port)

*The domain service account is a member of the local administrators group on the web server (for testing purposes only)

When i perform the database updates that need to be done as the currently logged in user, i impersonate them in this way:
 var windowsIdentity = User.Identity as WindowsIdentity;
 WindowsIdentity.RunImpersonated(windowsIdentity.AccessToken, () =>
 {
     // perform database update
 });

This throws an exception -
System.Data.SqlClient.SqlException: Login failed for user 'NT AUTHORITY\ANONYMOUS LOGON'
If i change the app pool identity to use AppPoolIdentity  (the default app pool identity) the impersonation works properly.
Why does this impersonation work with AppPoolIdentity, but not my domain service account?

A: I've had similar issues before, I see your are using Kerberos, once you get it you'll be fine!
Something that worked for me in a similar scenario to yours is to open up IIS, go to your site, click Configuration Editor icon. In the top two headings, first click the "from" drop down and select "ApplicationHost.config  and in the "section" heading to the left of "From", click the drop down, then expand the folders:
system.WebServer->security->authentication->windowsAuthentication,
From the options here, you can select "useAppPoolCredentials" and set it to TRUE, in your case.

When you have "useAppPoolCredentials" set to true you are telling IIS that it needs to use its application pool identity, which you are defining as the domain service account to decrypt the authorization ticket that is returned. The user profile typically doesn't have the provisions to do this.
Another thing to try if that doesn't work is to toggle the "Load User Profile" setting in the advanced settings of the app pool, I'm not sure if True or False will fix your issue, but it has seemed to help with similar issues before. I would try the above first and if that doesn't work then try this:

I didn't see anything mentioned about SPN's, are you using those? They can be required when running a domain account as the app pool ID. The below article documents that step as well as many others for getting this to work:
https://techcommunity.microsoft.com/t5/iis-support-blog/setting-up-kerberos-authentication-for-a-website-in-iis/ba-p/324644
Also, here are a few of many articles that greatly assisted me with getting this all to work at my job.
https://learn.microsoft.com/en-us/archive/blogs/chiranth/setting-up-kerberos-authentication-for-a-website-in-iis
https://learn.microsoft.com/en-us/previous-versions/windows/it-pro/windows-2000-server/cc961723(v=technet.10)?redirectedfrom=MSDN
Hope this helps.
UPDATE: For those still seeking help with this issue, we found a workaround for our system that did not require impersonation/delegation:
Instead we created another API endpoint, a "midpoint" that receives the request from the initial endpoint, without impersonation. In this scenario we were able to create an intermediate Sys Account to run as the app pool ID of the midpoint which is then the ID used to query the db, and this is the only access that sys account has, and this was enough for security team to be ok with it. We realized that logging the individual making the call would not be necessary when we use a special privileged system account, based on our protocols.


text:
Q: iptables: checking if a IP is blocked in firewall If a IP is blocked in iptables by its "IP" it is easy to grep iptables like
iptables -L -n | grep "a.b.c.d"

but if the IP has been blocked using a IP range like :
iptables -A INPUT -s "163.172.000.000/16" -j DROP

well, then this method does not work any more. what method could be used?

A: You could use ipaddr with python.
First you list the rules you are interested in with iptables -S (that will list single IPs as /32, which comes in handy):
Then you feed the blocks to this python script, check_ip.py. It checks if the first parameter (the address) belongs to the second parameter (the block) and exits with code 0 or 1.
#!/bin/python3

import ipaddress
import sys

sys.exit(ipaddress.ip_address(sys.argv[1]) in ipaddress.ip_network(sys.argv[2],strict=False))

You can then connect those two pieces.
The following is a quickly written bash command line, but you could also move the whole code to python, or use xargs, ...
iptables -S | grep DROP | awk '{print $4,$0}' | while read a b; do python3 check_ip.py IP.ADDR.TO.CHECK $a || echo $b; done

A: My recommendation is to precede the firewall rule with another rule designed to log such packet drops. Instead of:
iptables -A INPUT -s "163.172.000.000/16" -j DROP

The preferred way to reject traffic should be:
iptables -N logNdrop
iptables -A logNdrop -j LOG --log-level 5 --log-prefix 'Packet dropped: '
iptables -A logNdrop -j DROP
iptables -A INPUT -s "163.172.000.000/16" -j logNdrop

That will allow you to look for IP blocking occurrences in files such as /var/log/messages, depending on how your syslog daemon is configured:
# egrep 'Packet dropped: .* SRC=163.172.181.190 ' /var/log/messages
# tail -F /var/log/messages | egrep 'Packet dropped: .* SRC=163.172.181.190 '


text:
Q: onKeyDown() error, al presionar atrás, pregunte si deseo cerrar Tengo onKeyDown para cerrar mi aplicación, resulta que al presionar, se cierra de manera inmediata.
Lo que necesito es que al presionar atrás, pregunte si deseo cerrar.
@Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
    if (keyCode==event.KEYCODE_BACK){
        AlertDialog.Builder builder= new AlertDialog.Builder(this);
        builder.setMessage("Desea Salir De La APlicacion")
                .setPositiveButton("si", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialogInterface, int i) {
                        Intent intent=new Intent(Intent.ACTION_MAIN);
                        intent.addCategory(Intent.CATEGORY_HOME);
                        intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                        startActivity(intent);
                    }
                })
                .setNegativeButton("Cancelar", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        dialog.dismiss();
                    }
                });
        builder.show();
    }
    return super.onKeyDown(keyCode, event);
}

A: De acuerdo a lo que deseas:

Lo que necesito es que al presionar atrás, pregunte si deseo cerrar.

no debes usar onKeyDown() , debes usar onBackPressed() para detectar en verdad cuando presionas el botón para regresar, dentro de este método debes agregar el mensaje:
@Override
public void onBackPressed() {
    new AlertDialog.Builder(this)
            .setTitle("¿Salir?")
            .setMessage("¿Estas seguro que deseas salir?")
            .setNegativeButton(android.R.string.no, null)
            .setPositiveButton(android.R.string.yes, new DialogInterface.OnClickListener() {
                public void onClick(DialogInterface arg0, int arg1) {
                    finish(); //finaliza Activity.
                }
            }).create().show();
}


text:
Q: How to replace "unsupported tokens in pdf strings" from the argument of a macro? I'm trying to write a class where the arguments of the \title{} and \author{} commands, used for the title page, automatically call \hypersetup{} to set the title and the author in the PDF metadata.
So far I use this piece of code (the \apptocmd command is from etoolbox)
\apptocmd{\title}{
  \hypersetup{
    pdftitle={#1}
  }
}{}{}

It works well, but often it happens that the user wants to insert a newline in the title to tune its appearance:
\title{My very long long \\ title}

While everything still works, I get a warning about the newline being an unsupported token for pdf strings. The user is then forced to do:
\title{My very long long \texorpdfstring{\\}{} title}

to have the warning silenced.
So the question is: can I automatically remove (or better, replace) tokens that are not allowed in PDF strings according to hyperref, and to pass the filtered string to \hypersetup to avoid the warning?
If a generic solution is not possible or too difficult, I'd want at the very least to just remove newlines or to replace them with spaces (I've tried to simply redefine the \\ command in a group before calling \hypersetup but I still get the warning).

A: It can be done with hyperref's \pdfstringdefDisableCommands:
\documentclass{article}
\usepackage{etoolbox}
\usepackage{hyperref,xpatch}

\xapptocmd{\title}{%
  \hypersetup{ pdftitle={#1} }%
}{}{}

\pdfstringdefDisableCommands{%
  \def\\{}%
}

\title{My very long long \\ title}
\author{Me}
\date{\today}

\begin{document}

\maketitle

\end{document}

The example does not remove the extra space in the pdftitle, though…


text:
Q: Any way to open Web Part Properties via a URL? Normally, we add a web part to the page. To edit the properties, we edit the page and click on "Edit Web Parts".
Can we open the Web Part properties page via a query string like we can open the web part in maintenance mode by appending "?Contents=1" at the page URL?

A: You can open the page in edit mode by appending ?mode=edit, but you cannot specify which web part to show the tool pane for.

A: See if the answer posted here helps:
Editing default.aspx when Site Actions dropdown is hidden


text:
Q: How To Input A Space in A .bat File I've been messing around with .bat files for awhile, however I'm still clueless whenever I try to make a program out of a .bat file like a text based game for instance, I'm limited to one word per response I'm curious if there is anyway around that all I want to do is make a proper "if" statement that can be typed out by the user without it crashing the program
rough example: "if %Messages% == Who Are You? GOTO :Answer"

A: You have to put quotes around strings containing spaces:
if "%Messages%" == "Who Are You?" goto Answer
...
goto End
:Answer
...
:End


text:
Q: Deployed application shuts itself down immediately I have a Go rest API application. And I Dockerized it and deployed it to Kubernetes.
It is working as it should on my local.
But in Kubernetes, the application shuts down itself, and the pod is restarted.
It doesn't print anything, any log, or any fail.
import (
" github.com/gorilla/mux"
"net/http"
"log"

)
func main() {
    controller := controllers.Controllers{}
    router := mux.NewRouter()
    router.HandleFunc("/customer", controller.GetCustomer()).Methods("GET")
    router.HandleFunc("/customer", controller.InsertCustomer()).Methods("POST")
    router.HandleFunc("/healthcheck", controller.HealthCheck())

    addr := ":" + os.Getenv("PORT")
    srv := &http.Server{Addr: addr, Handler: router}

    go func() {
        if err := srv.ListenAndServe(); err != nil {
            log.Fatalf("listenAndServe failed: %v", err)
        }
    }()
    println("reached here")
}

Surprisingly it prints the "reached here" line when I look at the logs.
I checked the env variable, and it is also correct.
I suspect that the call to listenAndServe fails, but I couldn't find a reasonable answer for that.

A: When the main() function ends, your app ends as well. It does not wait for other non-main goroutines to finish. See Spec: Program execution:

Program execution begins by initializing the main package and then invoking the function main. When that function invocation returns, the program exits. It does not wait for other (non-main) goroutines to complete.

Since you start the listerer in a new goroutine, there's nothing "blocking" main(), there's nothing left to do (after printing "reached here"), so your app ends. Note that the builtin println() prints to the standard error, that's why you may not see any logs (standard output and standard error may be saved / redirected to different places).
The easiest "fix" is to start listening in main():
srv := &http.Server{Addr: addr, Handler: router}

if err := srv.ListenAndServe(); err != nil {
    log.Fatalf("listenAndServe failed: %v", err)
}


text:
Q: Common Issues in Developing Cluster Aware non-web-based Enterprise Applications I've to move a Windows based multi-threaded application (which uses global variables as well as an RDBMS for storage) to an NLB (i.e., network load balancer) cluster. The common architectural issues that immediately come to mind are

*

*Global variables (which are both read/ written) will have to be moved to a shared storage. What are the best practices here? Is there anything available in Windows Clustering API to manage such things?

*My application uses sockets, and persistent connections is a norm in the field I work. I believe persistent connections cannot be load balanced. Again, what are the architectural recommendations in this regard?

A: I'll answer the persistent connection part of the question first since it's easier. All good network load-balancing solutions (including Microsoft's NLB service built into Windows Server, but also including load balancing devices like F5 BigIP) have the ability to "stick" individual connections from clients to particular cluster nodes for the duration of the connection.  In Microsoft's NLB this is called "Single Affinity", while other load balancers call it "Sticky Sessions".  Sometimes there are caveats (for example, Microsoft's NLB will break connections if a new member is added to the cluster, although a single connection is never moved from one host to another).
re: global variables, they are the bane of load-balanced systems. Most designers of load-balanced apps will do a lot of re-architecture to minimize dependence on shared state since it impedes the scalabilty and availability of a load-balanced application.  Most of these approaches come down to a two-step strategy:  first, move shared state to a highly-available location, and second, change the app to minimize the number of times that shared state must be accessed.
Most clustered apps I've seen will store shared state (even shared, volatile state like global variables) in an RDBMS. This is mostly out of convenience. You can also use an in-memory database for maximum performance. But the simplicity of using an RDBMS for all shared state (transient and durable), plus the use of existing database tools for high-availability, tends to work out for many services.  Perf of an RDBMS is of course orders of magnitude slower than global variables in memory, but if shared state is small you'll be reading out of the RDBMS's cache anyways, and if you're making a network hop to read/write the data the difference is relatively less. You can also make a big difference by optimizing your database schema for fast reading/writing, for example by removing unneeded indexes and using NOLOCK for all read queries where exact, up-to-the-millisecond accuracy is not required.
I'm not saying an RDBMS will always be the best solution for shared state, only that improving shared-state access times are usually not the way that load-balanced apps get their performance-- instead, they get performance by removing the need to synchronously access (and, especially, write to) shared state on every request. That's the second thing I noted above: changing your app to reduce dependence on shared state.
For example, for simple "counters" and similar metrics, apps will often queue up their updates and have a single thread in charge of updating shared state asynchronously from the queue.
For more complex cases, apps may swtich from Pessimistic Concurrency (checking that a resource is available beforehand) to Optimistic Concurrency  (assuming it's available, and then backing out the work later if you ended up, for example, selling the same item to two different clients!).
Net-net, in load-balanced situations, brute force solutions often don't work as well as thinking creatively about your dependency on shared state and coming up with inventive ways to prevent having to wait for synchronous reading or writing shared state on every request.
I would not bother with using MSCS (Microsoft Cluster Service) in your scenario. MSCS is a failover solution, meaning it's good at keeping a one-server app highly available even if one of the cluster nodes goes down, but you won't get the scalability and simplicity you'll get from a true load-balanced service.  I suspect MSCS does have ways to share state (on a shared disk) but they require setting up an MSCS cluster which involves setting up failover, using a shared disk, and other complexity which isn't appropriate for most load-balanced apps. You're better off using a database or a specialized in-memory solution to store your shared state.

A: Regarding persistent connection look into the port rules, because port rules determine which tcpip port is handled and how.
MSDN:

When a port rule uses multiple-host
  load balancing, one of three client
  affinity modes is selected. When no
  client affinity mode is selected,
  Network Load Balancing load-balances
  client traffic from one IP address and
  different source ports on
  multiple-cluster hosts. This maximizes
  the granularity of load balancing and
  minimizes response time to clients. To
  assist in managing client sessions,
  the default single-client affinity
  mode load-balances all network traffic
  from a given client's IP address on a
  single-cluster host. The class C
  affinity mode further constrains this
  to load-balance all client traffic
  from a single class C address space.

In an asp.net app what allows session state to be persistent is when the clients affinity parameter setting is enabled; the NLB directs all TCP connections from one client IP address to the same cluster host. This allows session state to be maintained in host memory;
The client affinity parameter makes sure that a connection would always route on the server it was landed initially; thereby maintaining the application state.
Therefore I believe, same would happen for your windows based multi threaded app, if you utilize the affinity parameter.

*

*Network Load Balancing Best practices

*Web Farming with the
Network Load Balancing Service
in Windows Server 2003 might help you give an insight

A: *

*Concurrency (Check out Apache Cassandra, et al)

*Speed of light issues (if going cross-country or international you'll want heavy use of transactions)

*Backups and deduplication (Companies like FalconStor or EMC can help here in a distributed system. I wouldn't underestimate the need for consulting here)


text:
Q: python sorting dictionary by length of values I have found many threads for sorting by values like here but it doesn't seem to be working for me...
I have a dictionary of lists that have tuples. Each list has a different amount of tuples. I want to sort the dictionary by how many tuples each list contain.
>>>to_format
>>>{"one":[(1,3),(1,4)],"two":[(1,2),(1,2),(1,3)],"three":[(1,1)]}
>>>for key in some_sort(to_format):
       print key,
>>>two one three

Is this possible?

A:

dict= {'a': [9,2,3,4,5], 'b': [1,2,3,4, 5, 6], 'c': [], 'd': [1,2,3,4], 'e': [1,2]}
dict_temp = {'a': 'hello', 'b': 'bye', 'c': '', 'd': 'aa', 'e': 'zz'}

def sort_by_values_len(dict):
    dict_len= {key: len(value) for key, value in dict.items()}
    import operator
    sorted_key_list = sorted(dict_len.items(), key=operator.itemgetter(1), reverse=True)
    sorted_dict = [{item[0]: dict[item [0]]} for item in sorted_key_list]
    return sorted_dict

print (sort_by_values_len(dict))

output:
[{'b': [1, 2, 3, 4, 5, 6]}, {'a': [9, 2, 3, 4, 5]}, {'d': [1, 2, 3, 4]}, {'e': [1, 2]}, {'c': []}]

A: >>> d = {"one": [(1,3),(1,4)], "two": [(1,2),(1,2),(1,3)], "three": [(1,1)]}
>>> for k in sorted(d, key=lambda k: len(d[k]), reverse=True):
        print k,

two one three

Here is a universal solution that works on Python 2 & Python 3:
>>> print(' '.join(sorted(d, key=lambda k: len(d[k]), reverse=True)))
two one three


text:
Q: Compatibility PyQt5 and PyQt4 I'm having some compatibility problems with PyQt5, as expected some of the scripts I wrote are not working.
My biggest issues are with these two PyQt4 functions:
layer.pendingFields()

layer = QgsMapLayerRegistry.instance().mapLayersByName('Layer_Name')[0]

Is there a comparable function in PyQt5?
Does it work like the old functions?
In general it would be great to have something like a dictionary, where you could look  for the old function and see the relate translation or substitutes in PyQt5.

A: I'm assuming when you say "PyQt5", you mean you are using QGIS 3.x. In which case:
layer.pendingFields()

becomes:
layer.fields()

And:
layer = QgsMapLayerRegistry.instance().mapLayersByName('Layer_Name')[0]

becomes:
layer = QgsProject.instance().mapLayersByName('Layer_Name')[0]

You can read here about the API changes and here for the PyQt4 and PyQt5 differences.


text:
Q: Laravel 5 sentinel: How can disable "activation" and "throttle" checkpoints? is there a way to disable "activation" and "throttle" check in sentinel?
Thank you for any help you can provide for this.

A: Just find a checkpoints array on sentinel config and comment it.
'checkpoints' => [

    //'throttle',
    //'activation',

],

A: try it :

Open file Kernel.php from "app/Http/"

and comment it
  'api' => [
        //'throttle:60,1',
        'bindings',
    ],


text:
Q: C# Treeview checking if node exists I'm trying to populate a treeview from an XmlDocument.
The Root of the tree is set as 'Scripts' and from the root the next level should be 'Departments' which is within the XML script.  I can get data from the XML document no problem.  My question is when looping through the XmlDocument and adding nodes to the root node, I want to ensure that if a department is already within the treeview then it is not added again.  I should also add that each Department also has a list of scripts that need to be child nodes of the department.
My code so far is:
        XmlDocument xDoc = new XmlDocument();
        xDoc.LoadXml(scriptInformation);
        TreeNode t1;
        TreeNode rootNode = new TreeNode("Script View");
        treeView1.Nodes.Add(rootNode);
        foreach (XmlNode node in xDoc.SelectNodes("//row"))
        {
            t1 = new TreeNode(node["DEPARTMENT"].InnerXml);
           //How to check if node already exists in treeview?

        }

Thanks.

A: if(treeView1.Nodes.ContainsKey("DEPARTMENT")){
//...
}

EDIT: Recursive method:
 bool exists = false;
        foreach (TreeNode node in treeView1.Nodes) {
            if (NodeExists(node, "DEPARTMENT"))
                exists = true;
        }
    private bool NodeExists(TreeNode node, string key) {
        foreach (TreeNode subNode in node.Nodes) {
            if (subNode.Text == key) {
                return true;
            }
            if (node.Nodes.Count > 0) {
                NodeExists(node, key);
            }
        }
        return false;
    }

A: Depending upon the size of your XML file, you could consider using an associated List for fast lookup. As you add each node to the TreeView also add it to the List.

A: You can do something like this:
TreeNode parentNode = t1.Parent;
if (parentNode != null}
{
    if(parentNode.Nodes.Cast<TreeNode>().ToList().Find(t => t.Text.Equals(node["DEPARTMENT"].InnerXml) == null)
    {
        //Add node
    }
}
else
{
    bool isFound = true;
    if (treeView1.Nodes.Cast<TreeNode>().ToList().Find(t => t.Text.Equals(node["DEPARTMENT"].InnerXml) == null)
    {
        isFound = false;
    }

    if(!isFound)
    {
        //Add node
    }
}

A: If your XML document has a set structure where 'Departments' will always be indexed at 1;
ie:
index:[0] Scripts
    index:[1] Department
        index:[2] Script
    index:[1] Department2
        index:[2] Script

Then you could encapsulate the following code into a method where 'name' is a string parameter and the return type is boolean.
foreach (TreeNode node in uxTreeView.Nodes[0].Nodes) {
    if (node.Name.ToLower() == name.ToLower()) {
        return true;
    }
}
return false;

The idea is you would call that function each time you encounter a 'Department' node in your Xml, before creating the TreeNode.
Full example:
private bool DepartmentNodeExists(string name) {
    foreach (TreeNode node in uxTreeView.Nodes[0].Nodes) {
        if (node.Name.ToLower() == name.ToLower()) {
            return true;
        }
    }
    return false;
}

Lastly, the easy way:
private bool DepartmentNodeExists(string name) {
    if (uxTreeView.Nodes[0].ContainsKey(name)) {
        return true;
    }
    else {
        return false;
    }
}

These are all just refactored and encapsulated into their own named methods, you of course could just call:
if (uxTreeView.Nodes[0].ContainsKey(name)) {
    // do not create TreeNode
}

...during your parsing of your XML. PS. These examples all assume that you have the first root node in the TreeView already created and added to the TreeView.

A: http://www.vbdotnetforums.com/listviews-treeviews/13278-treeview-search.html#post39625
http://forums.asp.net/t/1645725.aspx/1?Check+if+child+Node+exists+on+treeview

A: Not sure about the document structure...
Couldn't you use Linq to Xml, load the document and get the distinct row ( row = department?) and consider only those elements to create a TreeNode? It is more efficient than trying to find if a node with such a text has already been added.
ex:
 var rows =      (  from row  in XDocument.Load(document).Root.Elements("row")
                    select row
                 ).Distinct(new SampleElementComparerOnNameAttribute());

Here the EqualityComparer is made on the "name" attribute value assuming the doc structure to be
<rows><row name='dep1'><script>script1</script><script>script2</script></row><row name='dep1'><script>script3</script><script>script4</script></row></rows>

A: I use,
string department = node["DEPARTMENT"].InnerXml;
TreeNode node = parentNode.Nodes[department] ?? parentNode.Nodes.Add(department, department);

That line guarantees that a lookup of the value department will be done first, if not found it creates it.  You have to do the double entry in Add() so it will have a key value you can do the lookup with the .Nodes[department].

A: It depends on the structure of your input. Since you don't show how exactly you add your subnodes I can only point you towards either the Contains or the ContainsKey method of the Nodes property, either of the treeView1 itself, or of any subnodes you add. You should use an overload of the Add method to specify a key name to simplify lookup.


text:
Q: Can't make  fit the screen width in the UITextView/HTML through NSAttributedString I try to load HTML with images to the UITextView, but images don't want to fit the width of screen, they are toooo large. Attribute width for IMG tag and CSS don't help :(
Here's the code:
            var content = "<meta charset='utf-8'><title>«Первый поворот налево или направо?» Секреты успеха Льюиса Хэмилтона</title>
Иногда его превосходство заметно сразу – как в случае с потрясающей скоростью вхождения в первый поворот на Гран При Австралии нынешнего года, а иногда не столь очевидно.

Льюис Хэмилтон
"
        let htmlData = NSString(string: content).data(using: String.Encoding.unicode.rawValue)
        let options = [NSAttributedString.DocumentReadingOptionKey.documentType: NSAttributedString.DocumentType.html]
        let attributedString = try! NSAttributedString(data: htmlData!, options: options, documentAttributes: nil)
        txtView.attributedText = attributedString

A: Set CSS img for max-width, max-height, width, height to 100% worked for me.
let content: String = "<!DOCTYPE html>" +
    "" +
    "<meta charset='UTF-8'>" +
    "" +
    "" +
    ""


text:
Q: SSH agent forwarding during docker build While building up a docker image through a dockerfile, I have to clone a github repo. I added my public ssh keys to my git hub account and I am able to clone the repo from my docker host. While I see that I can use docker host's ssh key by mapping $SSH_AUTH_SOCK env variable at the time of docker run like
docker run --rm -it --name container_name \
  -v $(dirname $SSH_AUTH_SOCK):$(dirname $SSH_AUTH_SOCK) \
  -e SSH_AUTH_SOCK=$SSH_AUTH_SOCK my_image

How can I do the same during a docker build?

A: For Docker 18.09 and newer
You can use new features of Docker to forward your existing SSH agent connection or a key to the builder. This enables for example to clone your private repositories during build.
Steps:
First set environment variable to use new BuildKit
export DOCKER_BUILDKIT=1

Then create Dockerfile with new (experimental) syntax:
# syntax=docker/dockerfile:experimental

FROM alpine

# install ssh client and git
RUN apk add --no-cache openssh-client git

# download public key for github.com
RUN mkdir -p -m 0600 ~/.ssh && ssh-keyscan github.com >> ~/.ssh/known_hosts

# clone our private repository
RUN --mount=type=ssh git clone git@github.com:myorg/myproject.git myproject

And build image with
docker build --ssh default .

Read more about it here: https://medium.com/@tonistiigi/build-secrets-and-ssh-forwarding-in-docker-18-09-ae8161d066

A: Unfortunately, you cannot forward your ssh socket to the build container since build time volume mounts are currently not supported in Docker.
This has been a topic of discussion for quite a while now, see the following issues on GitHub for reference:

*

*https://github.com/moby/moby/issues/6396

*https://github.com/moby/moby/issues/14080
As you can see this feature has been requested multiple times for different use cases. So far the maintainers have been hesitant to address this issue because they feel that volume mounts during build would break portability:

the result of a build should be independent of the underlying host

As outlined in this discussion.

A: This may be solved using an alternative build script. For example you may create a bash script and put it in ~/usr/local/bin/docker-compose or your favourite location:
#!/bin/bash

trap 'kill $(jobs -p)' EXIT
socat TCP-LISTEN:56789,reuseaddr,fork UNIX-CLIENT:${SSH_AUTH_SOCK} &

/usr/bin/docker-compose $@

Then in your Dockerfile you would use your existing ssh socket:
...
ENV SSH_AUTH_SOCK /tmp/auth.sock
...
  && apk add --no-cache socat openssh \
  && /bin/sh -c "socat -v UNIX-LISTEN:${SSH_AUTH_SOCK},unlink-early,mode=777,fork TCP:172.22.1.11:56789 &> /dev/null &" \
  && bundle install \
...
or any other ssh commands will works

Now you can call our custom docker-compose build. It would call the actual docker script with a shared ssh socket.

A: This one is also interesting:

*

*https://github.com/docker/for-mac/issues/483#issuecomment-344901087
It looks like:

*

*On the host

mkfifo myfifo
nc -lk 12345 <myfifo | nc -U $SSH_AUTH_SOCK >myfifo

*

*In the dockerfile

RUN mkfifo myfifo
RUN while true; do \
  nc 172.17.0.1 12345 <myfifo | nc -Ul /tmp/ssh-agent.sock >myfifo \
done &

RUN export SSH_AUTH_SOCK=/tmp/ssh-agent.sock

RUN ssh ...


text:
Q: How to bind model to the Spatie role? Is it possibe to attach specific model to the role in Spatie laravel permissions?
I need to get model depends role. For example if user has role doctor I need to get Doctor model. The same for clinic role.

A: Its a little hard to know what you are hunting for without knowing how you've set up the architecture underneath this, but you can get to the Doctors... not sure about binding directly though.
I assume you have created a Spatie role and assigned it to a Doctor class (which I assume is an extended User or similar, and is using HasRoles):
$role = Role::create(['name' => 'doctor']);

Grab a doctor and assign the role as normal:
$doctor = Doctor::find(xxx);
$doctor->assignRole($role);

I think the below may help:
$role= Role::findByName('doctor');
$roleClass= $role->getModel();

For the Docs with role doctor
$docs= Doctor::role('doctor')->get();

If you are looking to distinguish between class (Doctor, User), you'll need to run an extra command on a$doc (or even a superset like User::role collection) like get_class but this will depend on how you've set the query and flow up.  I'm not sure there is a direct method in Spatie to do exactly how you wish, but if you are OK with pulling a superset collection of users which might include the Doctor class, you can do it in two steps at least.


text:
Q: Why is getWindow() not able to be resolved? I can't resolve the getWindow(); method for some reason...
import java.applet.Applet;

import netscape.javascript.JSObject;

public class Class466 {
public static void method6020(Applet applet, String string, int i)
        throws Throwable {
    try {
        JSObject.getWindow(applet).eval(string);
    } catch (RuntimeException runtimeexception) {
        throw Class346.method4175(runtimeexception, new StringBuilder()
                .append("tf.a(").append(')').toString());
    }
}

public static Object method6021(Applet applet, String string, short i)
        throws Throwable {
    try {
        return JSObject.getWindow(applet).call(string, null);
    } catch (RuntimeException runtimeexception) {
        throw Class346.method4175(runtimeexception, new StringBuilder()
                .append("tf.f(").append(')').toString());
    }
}

public static Object method6022(Applet applet, String string,
        Object[] objects, byte i) throws Throwable {
    try {
        return JSObject.getWindow(applet).call(string, objects);
    } catch (RuntimeException runtimeexception) {
        throw Class346.method4175(runtimeexception, new StringBuilder()
                .append("tf.b(").append(')').toString());
    }
}

Class466() throws Throwable {
    throw new Error();
}
}

A: In jdk1.7.0_11, I noticed that there are two separate jars within
../jre/lib/

that contain the netscape.javascript.JSObject.class, namely

*

*jfxrt.jar

*plugin.jar

In the case of my IDE (IntelliJ), when I created a project SDK for Java it added both the jfxrt.jar and the plugin.jar jars to the classpath.
As the jfxrt.jar appears alphabetically before plugin.jar in the classpath, my application code was not resolving
JSObject.getWindow(...)

properly.
As we're not using JavaFX within our application I simply removed the jfxrt.jar from my projects Java SDK classpath.

A: Is the "MAYSCRIPT" applet tag parameter declared ?
<APPLET code="XYZApp.class" codebase="html/" align="baseline"
 width="200" height="200" MAYSCRIPT>

A: I think you have to add:
import java.awt.Window;
import java.awt.event.WindowEvent


text:
Q: Is there a way to compare a date stored as a string with the tm structure included in the ctime library? In my c++ project about an Airline Reservation System, I have a class member variable for the date stored as a string (i.e. "4/20/2022") and now I need to store the time as well so I added  ctime library. The problem is I cannot compare them because the ctime structure for date&time gives the date   as separate member variables.
Is there a way to compare them?
Here is an example:
time_t ko = time(nullptr);
struct tm time_date_struct = *localtime(&ko);
struct destination_structure {
    int offer_id,seat[size];
    std::string departure;//store time
    std::string arrival;//store time
    std::string from_day; // date as string (4/20/2022)
    std::string to_day; // date as string (4/21/2022)
    destination_structure* next;
};

//...

if(current->from_day < time_date_struct && current->to_day && current->departure < time_date_struct.tm_hour) {
    //...
}

update
compile this sample

A: *

*For C++20 <chrono>, see the bottom half of this answer.

ctime structure gives them as separate member variables.

First, there's no structure named ctime. You were describing std::tm.

To create a std::tm from given values(year, month, day), you would do something like:
int year = 2022, month = 2, day = 2;

std::tm calendar_time{};
calendar_time.tm_year = year - 1900;
calendar_time.tm_mon = month - 1;
calendar_time.tm_mday = day;

This would assign year, month, and day correspondingly, while keeping the hour, minute, second as 0. Note that you need to minus a number for year and month, because std::tm uses 1900 as the base year, and January as the base month.
Similarly, you can assign hour/min/sec to calendar_time with .tm_hour/.tm_min/.tm_sec.
However, std::tm can't be used to compare with another std::tm. Instead, you would need to first convert them into a std::time_t:
auto time_since_epoch = std::mktime(&calendar_time);

Now you can compare the time you create with current time:
auto now = std::time(nullptr);

if (now > time_since_epoch)
    std::cout << "time_since_epoch was in the past!";
else
    std::cout << "time_since_epoch will be in the future!";

Demo: https://godbolt.org/z/vocGM4WE8

Alternatively, you can format a string from std::time with the help of std::put_time:
auto now = std::time(nullptr);

std::stringstream ss;
ss << std::put_time(std::localtime(&now), "%D");
auto now_str = ss.str();

This would create a string in the format of mm/dd/yyyy. Now you can do a string comparison between this and other strings. However, this is not recommended, as this could easily fail if your strings are not formatted in the exact same way(which will be a problem in your case, since you stored the date as 4/20/2022 instead of 04/20/2022).
Demo: https://godbolt.org/z/bz36TPfzq

C++20 <chrono>
With the <chrono> library, creating a date/time object became really simple :
auto now = std::chrono::system_clock::now();
auto another_date = std::chrono::month{2} / 22 / 2022;

if (now > std::chrono::sys_days{another_date})
    std::cout << "another_date was in the past!";
else
    std::cout << "another_date will be in the future!";

That's all you need!
Demo: https://godbolt.org/z/bMzv9crxh

And you can easily add the time to the date as well:
auto date_time = sys_days{month{2} / 22 / 2022} + hours{4} + minutes{13} + seconds{40};
std::cout << date_time;  // prints: 2022-02-22 04:13:40

Sad news is not all compilers fully supports the c++20 <chrono> yet. A workaround is to use the date library, written by the same author of <chrono> , for now.
Demo: https://godbolt.org/z/sWzo5GrE1

A: chrono::time_point data type can be used for comparing time, calculating durations etc.
Your should parse your string into into this data type first, as well as you'll need to format it back to the string according to the  fomat you need maually.
For example:
#include <chrono>
#include <iomanip>
#include <iostream>
#include <sstream>

static std::chrono::time_point<std::chrono::system_clock> parse_time(const std::string& str)
{
    std::stringstream in;
    if( '/' == str[1] ) {
        in.put('0');
    }
    in << str;
    std::tm tmp = {};
    in >>  std::get_time(&tmp, "%m/%d/%Y");
    if(in.fail()) {
        throw std::runtime_error("Date parsing failed");
    }
    return std::chrono::system_clock::from_time_t( std::mktime(&tmp) );
}

static std::size_t diff(const std::chrono::time_point<std::chrono::system_clock>& start,const std::chrono::time_point<std::chrono::system_clock>& end)
{
     return std::chrono::duration_cast<std::chrono::days>(end - start).count();
}

std::ostream& operator << (std::ostream& to,const std::chrono::time_point<std::chrono::system_clock>& what)
{
    std::time_t tmp = std::chrono::system_clock::to_time_t(what);
    to << std::put_time( std::localtime(&tmp), "%d %b %Y" );
    return to;
}

int main(int argc, const char** argv)
{
    std::chrono::time_point<std::chrono::system_clock> lhs =  parse_time("4/20/2022");
    std::chrono::time_point<std::chrono::system_clock> rhs = parse_time("4/21/2022");

    std::cout << "Left Hand Statement date: " << lhs << std::endl;

    std::cout << "Right Hand Statement date: " << rhs <<  std::endl;

    std::cout << std::endl;

    if(lhs < rhs) {
        std::cout << lhs << " is before " << rhs << std::endl;
    }

    if(rhs > lhs) {
        std::cout << rhs << " is after " << lhs << std::endl;
    }

    std::cout << diff(lhs,rhs) << " days between " << lhs << " and " << rhs << std::endl;

    return 0;
}


text:
Q: Синхронная обёртка для асинхронного объекта Есть класс Someone, в конструкторе которого есть callback функция, в которую возвращается ошибка или объект:
var some = new Someone({...}, (err, data) => {
  ...
});

Мне надо придумать как бы сделать некую запускалку для создания такого объекта, которую можно было бы использовать вот так:
const some = require('./some');

var someClient = some.createClient({...});
someClient.action();

В функции createClient должен создаваться экземпляр класса Someone, а когда экземпляр вернет data, то именно data должна вернуться в someClient. До тех пор, пока не вернется data или ошибка, someClient.action() запускаться не должен - nodejs должна подождать, а не рваться асинхронно запускать нижестоящий код до тех пор пока не отработала обертка.
Как это сделать?
UPD:
Пробую делать обертку так:
const Someone = require('./Someone');

function some(config) {
  return new Promise((resolve, reject) => {
      new Someone(config, (err, data) => {
        if (err) {
          reject(err);
        } else {
          resolve(data);
        }
      });
  }).then(data => {
    return data;
  }).catch(err => {
    return err;
  });
}

async function createClient(config) {
  return await some(config);
};

module.exports = {
  createClient: createClient
}

В someClient возвращается не data а Promise. Что я делаю не так?


text:
Q: Couchbase LiveQuery doesn't work with other keyPath than "rows" I have a problem: I use Xcode and Swift in addition to the latest Couchbase Mobile Solution. LiveQuery also works perfectly, if I use the String "rows" in order to register the Observer and then listen to it. But I have a view in my app, where I need two livequerys. So I intended to make two livequeries with two different key paths, for example the first one "getTopicComments", and the second one "getTopicDetails", so I could differenciate between them like below. But as I said, it only works for the key path "rows". Am I misunderstanding sth? Because I totally don't understand why it doesn't work with another String. In my opinion and as I read in the documentation of couchbase it shouldn't be relevant which String I use when registering the live query.
liveQueryOne.addObserver(self, forKeyPath: "getTopicComments", options: .new, context: nil)
liveQueryTwo.addObserver(self, forKeyPath: "getTopicDetails", options: .new, context: nil)

and
override func observeValue(forKeyPath keyPath: String?, of object: Any?, change: [NSKeyValueChangeKey : Any]?, context: UnsafeMutableRawPointer?) {
if (keyPath == "getTopicComments") {
} else if (keyPath == "getTopicDetails") {
}
}

A: "rows" is a KVO observable property on CBLLiveQuery. That is why you can add an observer and look for KVO notifications. The idea behind live queries is that the app can be automatically notified of changes to database that affect the results of the query. The "rows" property will be updated when database updates and that's why you observe this property to be informed of changes. The keyPaths that you added above do not exist in CBLLiveQuery, so you will not see any notifications.