text:
Q: Possible to pause for less than 1 minutes for SharePoint Workflow? I was wondering if it is possible to have my workflow wait for less than 1 minutes (e.g. 30 seconds?)

A: This can be achieved using the following steps as described here.

*

*Create a workflow variable called "delay_timer": Number

*Use Calculate action to get required delay/pause time and save in workflow variable "delay_timer" (eg: 1 divided by 20 = 3 seconds)

*Pause workflow for "delay_timer" duration.
Also refer this relevant thread.

A: The TimeoutDuration of the Delay activity is a TimeSpan which means that it could in theory be set to milliseconds.
But in practice every time you delay your workflow in only picked up the next time the Workflow timer job runs which by default is every 5 minutes.
You can change how often the timer job runs by using stsadm, but you probably shouldn't set it below 5 minutes and definitly not below 1 minute

A: What about setting an "empty" loop? (i have tried with a comment on an useless workflow variable repeated for 10 k or 20 k depending on how long time I need, it worked fine)


text:
Q: Does it make a sense to use 'new' when creating std::set? Explain, please, me next things.
#include <iostream>
#include <set>

int main() {
    std::set<int>* a = new std::set<int>;

    a->insert(2);
    a->insert(5);

    for ( std::set<int>::iterator it = a->begin(); it != a->end(); it++ ) {
        std::cout << *it << std::endl;
    }

    std::cout << "Deleting a....." << std::endl;

    delete a;

    for ( std::set<int>::iterator it = a->begin(); it != a->end(); it++ ) {
        std::cout << *it << std::endl;
    }

    return 0;
}

$ g++ test6.cpp && a
2
5
Deleting a.....
2
5
3544585

*

*Does it make any sense to use operator new creating std::set? As I read in manuals, std::set has its own Allocator object, which is responsible for dynamic memory allocating using operator new. But interesting to know experienced members point of view.

*Why after deallocating memory using delete a members of std::set are still avaliable and have values 2 and 5 like before delete a. And what is the right way to delete member a.
Thanks.

A: Watch this part of Stroudstrup's talk at Going Native 2013
1)  No, you can just create a local variable a and let it be released at the end of the function through normal control flow
std::set<int> a;
a.insert(2);
a.insert(5);

2) You're getting lucky. It's undefined behavior to access memory that has been released.  Run this code through valgrind and you'll see errors.
int *ip = new int{1};
delete ip;
int a = *ip; // NOT SAFE, maybe 1, maybe 24630751, maybe crash

A: No, the standard library has memory management functionality included, so the programmer does not have to concern themselves with this.
The reason you are still seeing sensible values output after the delete, is because your PC has not written new values over the memory spaces yet. This is why attempting to access memory after it is deleted is under the "undefined behavior" umbrella.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Texture color change on click mouse button as a brash in paint I have a material attached to the game object .
Material has a texture .
I have another  texture of different color .
what I want is that when I click on the game object .
Only the corresponding position's texture will change the color and it will be the color of the another texture that I have .
Actually I want to create a Tool like Eraser in paint .
Eraser erase or white only the position where I press mouse click.

A: you can use RaycastHit.barycentricCoordinate.
record all erase uv positons,notify shader by a Texture.
shader earse color.
see here


text:
Q: How to achieve 2 way data binding on a div's innerhtml property using ngModel? In my angular component ts file I have a model, with a property whose value is html formatted text.
The text is displayed in the UI using inner html property of a div in my component's .html file.
The div is made editable by setting the editable property .
Code snippet :

Here formatJson returns the html formatted JSON text.
The issue :
The changes made in the text are not getting reflected in the corresponding model, even if we have 2 way data binding using ngModel.

What am I doing wrong here ? could you please suggest.

A: contenteditable isn't an input, and two way binding works on inputs.
You have to update your model through input events, as shown here

{{ name }}


text:
Q: Parallel loop tracking results and performance I have a .Net Core MVC app which does some moderately heavy proability calculations.  I am running a parallel loop over a list of ~2.5 million entries.  Since it is a parallel loop, I am using a concurrent bag to hold the result objects.  For each iteration, I then find the entry in my concurrent bag and iterate the value, essentially counting the number of times that result occurred.  Here is a boiled down example of what is happening:
// results class
public class RandResult
{
    public int id { get; set; }
    public int val { get; set; }
}

// list of ints I iterate over
var intList = new List<int>();
for(var i = 0; i < 2500000; i++)
{
    intList.Add(i);
}

var bagResult = new ConcurrentBag<RandResult>()
{
    new RandResult() { id = 0, val = 0 },
    new RandResult() { id = 1, val = 0 },
    new RandResult() { id = 2, val = 0 },
    new RandResult() { id = 3, val = 0 },
    new RandResult() { id = 4, val = 0 }
};

watch.Restart();
Parallel.ForEach(intList, i =>
{
    bagResult.First(b => b.id == i % 5).val++;
});
timers.Add(watch.ElapsedMilliseconds / 1000.0);  // ~1.3 seconds

You can see the timers I placed in the code to help evaluate speed.  Even with this simple calculation here, that loop takes ~1.3 seconds, almost entirely due to the overhead of the concurrent bag.  Given this relative inefficiency, I'm looking for alternatives.  Here is what I've tried so far:
Using a regular List<RandResult> and a lock:
// takes ~0.6sec
var _lock = new object();
Parallel.ForEach(intList, i =>
{
    lock (_lock)
    {
        listResult.First(b => b.id == i % 5).val++;
    }
 });

Using an Interlock was a bit more complicated
// takes ~0.2sec
var dict = new Dictionary<int, int>()
{
    { 0, 0 },{ 1, 1 },{ 2, 2 },{ 3, 3 },{ 4, 4 }
};
int[] indexes = new int[5] { 0, 1, 2, 3, 4 };
int[] vals= new int[5] { 0, 0, 0, 0, 0 };
Parallel.ForEach(intList, i =>
{
    dict.TryGetValue(i % 5, out int k);
    Interlocked.Increment(ref vals[k]);
});

This one is more complicated because the Id values won't be consecutive ints so the Dictionary serves as a reverse lookup.
The question is, are there any other options?
Note:
The actual calculation being done is certainly more complex than i%5 but the real question here is about recording the results so that serves for the example.  Also, even in the full application there will never be more than 10 entries in the List/Bag of RandResult.
Bonus question:  I'm a bit shocked that the ConcurrentBag option was so much slower than everything else.  I understand there is quite a bit of overhead involved with parallelism and concurrency in general but that seems excessive.  Does anyone know why it is so much slower?

A: By switching to a ConcurrentDictionary you can use it's AddOrUpdate function to get efficient lookups and thread safe incrementation.
var dict = new ConcurrentDictionary<int, int>();

Parallel.ForEach(intList, i =>
{
    dict.AddOrUpdate(GiveSomeInt(i), 1, (key, value) => value++);
});

The first time you try to access a index it will add a new value of 1, any future calls to the index will return old value + 1. If two threads try to update the value at the same time the value factory function will get re-run when the slower of the two updates that tries to save its value and will then add 1 to the new updated value.
If you wanted to pre-initialize the dictionary you could also do
var dict = new ConcurrentDictionary<int, int>()
{
    { 0, 0 },{ 1, 0 },{ 2, 0 },{ 3, 0 },{ 4, 0 }
};

Parallel.ForEach(intList, i =>
{
    dict.AddOrUpdate(GiveSomeInt(i), 1, (key, value) => value++);
});

To answer your bonus question, ConcurrentBag is not optimized at all to frequently be enumerated over, every time you call bagResult.GetEnumerator() (which .First( does behind the scenes) it has to clone the bag and generate a frozen in time snapshot. It is optimized to push and pop stuff in to a pool of items. Using .First( was killing your performance.

A: Not sure why you're using a concurrent bag.  It's not like you are adding or removing items.  And I don't think it solves any parallelism issues for you-- the only thing the bag gives you is thread-safe access to the bag, not thread-safe access to the RandResult items inside the bag.
If it were me, I'd use a simple dictionary, with a key of id.  Or, if id is always a sequential integer, use an array.  That would be much faster.
As for the concurrency issue-- all you need to do is use Interlocked.Increment instead of val++.  That will give you enough thread safety for this specific problem. You do not need to synchronize access to the bag/list/dictionary/array at all, since all threads use only read-only access with respect to that object.  Depending on your platform, Interlocked.Increment not incur any overhead at all, since increments are automatically atomic in many situations-- they are 99% likely to be automatically atomic on a Windows system using the current CLR.
var results = new int[5];

var intList = new List<int>();
for(var i = 0; i < 2500000; i++)
{
    intList.Add(i);
}

watch.Restart();
Parallel.ForEach(intList, i =>
{
    Interlocked.Increment(ref results[i % 5]);
});
timers.Add(watch.ElapsedMilliseconds / 1000.0);  // ~1.3 seconds

Additional performance note: Since the elements in your results list are so close together in memory, they are likely to cause CPU cache contention.  Typically your CPU will use cache bursts to move small chunks of memory into L1 or L2 cache (which is separate per core); while it is cached, access to those memory locations on the main memory board will be locked out.  So essentially all of your cores will lock each other out if they are working on parts of the memory that are within a certain distance (a "cache line") of each other; this can result in performance that is so bad that it is even slower than running the algorithm in series.  This problem is called "false sharing."
To avoid the issue, you might want to pad the items in your result list so they are large enough to exceed the cache burst size (which is CPU-dependent).  Since the array will only contain 10 items, you could pad them each with a big 128 byte block of nothingness and not incur much overhead.
For more on this issue, see this article.


text:
Q: user permissions with icingaweb2 (with SSO authentication) We're curently setting up Icinga2 and Icingaweb2 as our global monitoring.
To authenticate the users, we use an Apache module (Single Sign On) which let only allowed users to access the web ui.
Icingaweb2 is configured with /etc/icingaweb2/authentication.ini :
[icingaweb2]
strip_username_regexp = ""
backend             = "external"

Only one user is declared as global admin in /etc/icingaweb2/roles.ini :
[admins]
users               = "bancal"
permissions         = "*"

For each server monitored with Icinga is defined a UserGroup which defines who will receive email alerts. These persons are client-users.
What we'd like to set is :

*

*Every global-admin has admin view on all hosts (this is already the case)

*Every client-users has an admin view on the hosts he is member of and no view on other hosts monitored.

Is there a way to achive this?

A: We've finally done it with a quite simple config.
Since hosts are grouped in Hostgroups, users are granted access to these Hostgroups with the following config in /etc/icingaweb2/roles.ini :
[group1]
users              = "user1,user2"
permissions         = "monitoring/command/*,module/*"
monitoring/filter/objects = "(hostgroup_name=hosts-group1-test|hostgroup_name=hosts-group1-prod)"

One user can be added to several of these config blocks.


text:
Q: Blue highlighting not appear with custom UITextView I created a subclass of UITextView to add a custom UIMenuItem. The problem is that when I press my custom action to display custom item, the text is not highlighted. Any idea?

ActionsTextView.h
#import <UIKit/UIKit.h>

@protocol ActionsDelegate <NSObject>

- (void)addDreamSignalWithText:(NSString *)text range:(NSRange)range;

@end

@interface ActionsTextView : UITextView

#pragma mark - Delegate
@property IBOutlet id<ActionsDelegate>actionsDelegate;

#pragma mark - Methods
- (void)addDreamSignalAction:(id)sender;

@end

ActionsTextView.m
#import "ActionsTextView.h"

@implementation ActionsTextView

- (BOOL)canBecomeFirstResponder {

    return YES;
}

- (BOOL)canPerformAction:(SEL)action withSender:(id)sender {

    if (action == @selector(addDreamSignalAction:)) {
        return YES;
    }

    return NO;

}

#pragma mark - Methods
- (void)addDreamSignalAction:(id)sender {

    if ([_actionsDelegate respondsToSelector:@selector(addDreamSignalWithText:range:)]) {
        [_actionsDelegate addDreamSignalWithText:[self.text substringWithRange:self.selectedRange]
                                           range:self.selectedRange];
    }

    // Deselect text
    self.selectedTextRange = nil;

}

@end

Thanks!!

A: Thanks to rmaddy, I found the solution.
Here is the code:
ActionsTextView.h
#import <UIKit/UIKit.h>

@protocol ActionsDelegate <NSObject>

- (void)addDreamSignalWithText:(NSString *)text range:(NSRange)range;

@end

@interface ActionsTextView : UITextView

#pragma mark - Delegate
@property IBOutlet id<ActionsDelegate>actionsDelegate;

#pragma mark - Methods
- (void)addDreamSignalAction:(id)sender;

#pragma mark - Notifications
- (void)menuControllerWillShow:(NSNotification *)notification;

@end

ActionsTextView.m
#import "ActionsTextView.h"

@implementation ActionsTextView

- (BOOL)canBecomeFirstResponder {

    return YES;
}

- (BOOL)canPerformAction:(SEL)action withSender:(id)sender {

    if (action == @selector(addDreamSignalAction:)) {
        return YES;
    }

    return NO;

}

#pragma mark - Methods
- (void)addDreamSignalAction:(id)sender {

    if ([_actionsDelegate respondsToSelector:@selector(addDreamSignalWithText:range:)]) {
        [_actionsDelegate addDreamSignalWithText:[self.text substringWithRange:self.selectedRange]
                                           range:self.selectedRange];
    }

    // Deselect text
    self.selectedTextRange = nil;

}

#pragma mark - Notifications
- (void)menuControllerWillShow:(NSNotification *)notification {

    if (self.selectedRange.length == 0) {

        [self select:self];

    }

}

@end


text:
Q: Check conditions in multiple columns and rows When we look at the mtcars dataset in R:
head(mtcars)
                   mpg cyl disp  hp drat    wt  qsec vs am gear carb
Mazda RX4         21.0   6  160 110 3.90 2.620 16.46  0  1    4    4
Mazda RX4 Wag     21.0   6  160 110 3.90 2.875 17.02  0  1    4    4
Datsun 710        22.8   4  108  93 3.85 2.320 18.61  1  1    4    1
Hornet 4 Drive    21.4   6  258 110 3.08 3.215 19.44  1  0    3    1
Hornet Sportabout 18.7   8  360 175 3.15 3.440 17.02  0  0    3    2
Valiant           18.1   6  225 105 2.76 3.460 20.22  1  0    3    1

I want to select the Mazda models with 6 cylinders (cyl is 6) and see which of those cars has the most horse power hp. Or, alternatively, I want to see which Merc model with 4 cylinders has the highest hp.
How can I do that? Do I subset? Or maybe grep?

A: You want to check two conditions: The model name of the car and the cylinder numbers, right?
You can subset the data to the rows that satisfy your (double) condition and then see which of the remaining rows has the highest values for the column hp
bestcar <- function(carname, cyl_nr){
    inds  <- (grepl(carname, rownames(mtcars)) & mtcars$cyl == cyl_nr)
    subdf <- mtcars[inds, ]
    rownames(subdf)[which.max(subdf$hp)]
}

bestcar("Mazda", 6)
# "Mazda RX4"
bestcar("Merc", 4)
# "Merc 230"


text:
Q: Laravel 7 Api incomplete? I started with Laravel 7 a few weeks ago. It happened to me multiple times that after reading about a topic on the Laravel website, I wanted to check the details of a function, for example:
Illuminate\Support\Facades\Route::group()

So I went to the Laravel API, and could find the Route facade, but not the group function.
What am I doing wrong? Where do you check for example the exact signature of a function?
Thanks!

A: The method group in Route::group() is inherited from another class, RegistrarGroup.
See the docblock method in the source file, vendor/laravel/framework/src/Illuminate/Support/Facades/Route.php:

@method static \Illuminate\Routing\Router|\Illuminate\Routing\RouteRegistrar group(\Closure|string|array $attributes, \Closure|string $routes)

so, this is what you look for in the API documentation:
https://laravel.com/api/7.x/Illuminate/Contracts/Routing/Registrar.html#method_group

A: That is because a Facade, by definition, is only an 'interface' to the methods exponed by another object, so you will not find the actual methods available by visiting the facade code.
Usually you can find the actual class that a facade resolves to (when not mocked) by checking the docblock in the source code and navigate to that class.
A very useful tool to overcome this problem and provide autocompletion (and inspection) for facades on your IDE is the package https://github.com/barryvdh/laravel-ide-helper


text:
Q: Setting Decimal places with normalized number by Series.value_counts() I'm trying to get percentage of my data.
    counts
Win
BLUE 90729
RED  86010

I used df['counts'].value_counts(normalize = True)
and it returns
86010    0.5
90729    0.5
Name: matchid, dtype: float64

how can i calculate them up to at least 2 decimal places?

A: Divide the counts by their sum:
df['counts'] / df['counts'].sum()
#       counts
#Win
#BLUE  0.51335
#RED   0.48665

In your original solution, there is one instance of 90729 and one instance of 86010. That is why value_counts returns 1 for 90729 and 1 for 86010 (after normalization, both become precisely 0.5).

A: df['perc'] = df['counts'].apply(lambda x: x/np.sum(df['counts']))

Output:
BLUE    0.51335
RED     0.48665


text:
Q: How many heroes in the Marvel universe have used the 'Spider-' prefix? I know Peter Parker was the original Spider-Man, but I've read about a few others, Spider-Man Noir for one. And recently that Miles Morales is the new Spider-Man.
How many Spider-Men / Spider-Women (Spider-Persons?) do we know exist in the Marvel universe?

A: Frankly? Too many to list here.
But from the Wikipedia page on Alterntaive Version of Spider-Man, notable Spider-Folk include;

*

*Peter Parker, the original Spider-Man.

*Ben Reilly, a clone of Peter Parker who acted as Spider-Man for a time.

*Miles Morales, who took over the Spider-Man name after Peter Parker's death in the Ultimate Universe.

*Mac Gargan, the Dark Avengers version of Spider-Man.

*Jessica Drew, the original Spider-Woman.

*Dr. Otto Octavius, who acted as Spider-Man after taking over Peter Parkers body.

*Peter Parquagh, who is Spider-Man in 1602.

*Miguel O'Hara, who is Spider-Man in 2099.

*Pete Ross, an amalgamation of Superboy and Spider-Man called Spider-Boy.

*Hostess Twinkies Cakes Advertisement Spider-Man, a commercial purpose only Spider-Man who always defeats his enemies with Hostess-brand Cakes.

*And of course, Peter Porker, the Spectacular Spider-Ham, who deserves a full paragraph of explanation;

Peter Porker was born a spider (simply named Peter). He resided in the basement lab of May Porker, a slightly goofy animal scientist who had created "the world's first atomic powered hairdryer", hoping that "the introduction of nuclear fusion into America's beauty salons" would "revolutionize the hair care industry". After dousing her head with water and activating the dryer, May Porker accidentally irradiated herself, and in a fit of delusion, bit Peter, who then found himself transformed into an anthropomorphic swine much like May Porker herself. Running from the Porker homestead disoriented, Peter soon came to realize that he still retained a spider's abilities.

A: If you would have asked this question last year, it would have been easier to answer. Unfortunately, the Spider-Verse event created dozens of new spider heroes.
Peter Parker is your basic and Miles Morales came over from the Ultimate Universe. Right now, Jessica Jones (Spider Woman), Gwen Stacy (Spider Gwen) and Miguel O'Hara (Spider Man 2099) have their own comics. Cindy Moon (Silk) had a comic very recently, but I think it's cancelled now.
In recent memory, Doctor Octopus became Spider-Man in Superior Spider-Man. Ollie Osnick, who was a DocOck wannabe, became Spider-Kid and later Steel Spider. Scarlet Spider is a very messy one... I'll let you read up on it yourself.
Once Spider-Verse hit, there was a UK Spider-Man, Spider-Punk, Spider-Ben, etc. You can see a (not complete) list here:
http://www.newsarama.com/20656-spider-verse-s-spider-men-we-try-to-name-them-all.html
However your question asks about the Marvel Universe, which just got destroyed, so most of those are technically not extant anymore. In the Marvel Universe there are only 4 (If you treat Secret Wars as having ended even though it's still going on but the sequels are already out). If you add the one who will be in the MCU, that makes 5.
Here is the wiki list:
https://en.wikipedia.org/wiki/Alternative_versions_of_Spider-Man

A: 17 "Spider-" prefix heroes, +2 with variant prefixes, +7 with "Spider" in the name
By my count, there were 12 before the Spider-Verse storyline (where many alternate-universe equivalents to Spider-Man were met) and another 5 met during it. There were also 2 that had variant prefixes (e.g. alternate spellings) and 7 that had Spider in the name, but it was not a prefix. In many cases, multiple heroes have taken on a role.
Before Spider-Verse

*

*Spider-Man

*

*Peter Parker (The Amazing Spider-Man), Ben Reilly (Clone Saga), Doctor Octavius (The Superior Spider-Man), Miles Morales (Ultimate Spider-Man), Peter Parquagh (Spider-Man 1602), Miguel O'Hara (Spider-Man 2099), and many other minor, temporary, or parallel universe incarnations.

*Spider-Woman

*

*Jessica Drew, Julia Carpenter, Mattie Franklin, Charlotte Witter, Mary Jane Watson (alternate-universe version encountered in Exiles)

*Spider-Girl

*

*May "Mayday" Parker, daughter of Peter and MJ

*Spider-Boy

*

*Pete Ross, amalgam of Spider-Man and DC's Superboy (DC vs. Marvel)

*Spider-Kid

*

*Oliver Osnick, a child who tried to be like Spider-Man

*Spider-Queen

*

*Adriana Soria, creator of the Spider-Island virus

*Spider-King

*

*Steve Rogers (Transformed by Spider-Island virus)

*Spider Hero

*

*Eric Brooks (a.k.a. Blade), created as a disguise

*Spider-Carnage

*

*Ben Reilly (Web of Carnage)

*Spider-Wasp

*

*Shathra, a being from the Astral Plane

*Spider-Monkey

*

*A spider-monkey version of Spider-Man (Marvel Apes)

*Spider-Ham

*

*Peter Porker, a pig version of Spider-Man

Introduced During Spider-Verse
With names that previously existed:

*

*Spider-Man

*

*Aaron Aikman, Patton Parnell, Cosmic Spider-Man, Cyborg Spider-Man, Hostess Twinkies Cakes Advertisement Spider-Man

*Spider-Woman*

*

*Gwen Stacy

*Spider-Girl

*

*Penelope Parker

* Although her comic series is called Spider-Gwen, the character herself goes by "Spider-Woman".
Completely new:

*

*Spider-UK

*

*Billy Braddock

*Spider-Wolf

*Spider Moon-Man

*Spider-Punk (a.k.a. The Anarchic Spider-Man)

*Spider-Ma'am

*

*Aunt May

Others with variant prefixes

*

*Spyder-Man

*

*Peter Urich (Armor Wars)

*Spidey-Man

*

*A satiricial version of Peter Parker (Not Brand Echh)

Others having Spider in the name

*

*Scarlet Spider

*

*Ben Reilly (Clone Saga), Kaine (Scarlet Spider vol 2)

*Steel Spider

*

*Oliver Osnick

*The Spider (Ultimate Comics: Avengers)

*Devil-Spider (a.k.a. Hobgoblin)

*Lady-Spider

*

*May Reilly (Spider-Verse)

*Man-Spider

*

*Peter Parker (Spider-Verse)

*Old Man Spider (Spider-Verse)

Technology
While not a character, there have been several pieces of technology with the "Spider-" prefix or a variation on the name.

*

*Spider-Armor

*

*Used by Peter Parker

*Spider-Mobile

*

*Built by Peter Parker with the help of Johnny Storm

*Spider-Slayer

*

*Robots designed to kill Spider-Man, first made by Dr. Spencer Smythe

*SP//dr

*

*A psychically-controlled vehicle used by Penni Parker (Spider-Verse)


text:
Q: I declared method but its showing error while calling I call a method Submit() in onCreate portion which is initialized next to onCreate. "invalid method declaration,return type required" error is showing at calling spot. See my code and help me to solve it. Thnaks in advance
btn_submit.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            String data = "("+
                    "\"name\":" + "\"" + ET_name.getText().toString() +
 ")";
  }
        Submit(data);
 });

 private void Submit(String data) {
    final String saveData = data;
    String URL="http://172.0.0.1:8000/invoices/";

A: You have an error on onClick curly braces , you should call Submit inside them not out them.
btn_submit.setOnClickListener(new View.OnClickListener() {
    @Override
    public void onClick(View v) {
        Submit(data);
    }
});


text:
Q: pip is not recoginzed as an internal or external command I have tried setting my System variable Path=C:\Python27\Scripts\
I also have set User Variable Path=C:\Python27\
I can see it return correctly when I echo %PATH%
What else is needed for pip to work correctly?

A: You need to install pip too.
For convinience you can use some package manager to get started and going. Google for python package managers (anacond etc)

A: So I found my issue. Was running cmd prompt from P4 directly which was my issue. When running cmd prompt outside of P4 I was able to run pip with no issues.


text:
Q: Google Vision API: Handle native crash Anybody knows how can I handle exceptions coming from native method calls?
I'm running the Barcode Reader example from Google Vision API, it works very well reading some 2d - pdf417 codes, but in some cases it crashes with a native exception attempting to use NewStringUTF like this:
    art/runtime/java_vm_ext.cc:410] JNI DETECTED ERROR IN APPLICATION: input is not valid Modified UTF-8: illegal start byte 0x90
    art/runtime/java_vm_ext.cc:410]     in call to NewStringUTF
    art/runtime/java_vm_ext.cc:410]     from com.google.android.gms.vision.barcode.internal.NativeBarcode[] com.google.android.gms.vision.barcode.internal.NativeBarcodeDetector.recognizeNative(int, int, byte[], com.google.android.gms.vision.barcode.internal.NativeOptions)
    art/runtime/java_vm_ext.cc:410] "Thread-4533" prio=5 tid=19 Runnable
    art/runtime/java_vm_ext.cc:410]   | group="main" sCount=0 dsCount=0 obj=0x12c8e0a0 self=0x7f849f4200
    art/runtime/java_vm_ext.cc:410]   | sysTid=9051 nice=0 cgrp=default sched=0/0 handle=0x7f7b7bf440
    art/runtime/java_vm_ext.cc:410]   | state=R schedstat=( 1663092757 5060164 94 ) utm=165 stm=1 core=2 HZ=100
    art/runtime/java_vm_ext.cc:410]   | stack=0x7f7b6bd000-0x7f7b6bf000 stackSize=1037KB
    art/runtime/java_vm_ext.cc:410]   | held mutexes= "mutator lock"(shared held)
    art/runtime/java_vm_ext.cc:410]   native: #00 pc 00000000004897a8  /system/lib64/libart.so (_ZN3art15DumpNativeStackERNSt3__113basic_ostreamIcNS0_11char_traitsIcEEEEiP12BacktraceMapPKcPNS_9ArtMethodEPv+200)
    art/runtime/java_vm_ext.cc:410]   native: #01 pc 0000000000458644  /system/lib64/libart.so (_ZNK3art6Thread4DumpERNSt3__113basic_ostreamIcNS1_11char_traitsIcEEEEP12BacktraceMap+224)
    art/runtime/java_vm_ext.cc:410]   native: #02 pc 000000000030c9e4  /system/lib64/libart.so (_ZN3art9JavaVMExt8JniAbortEPKcS2_+1004)
    art/runtime/java_vm_ext.cc:410]   native: #03 pc 000000000030d29c  /system/lib64/libart.so (_ZN3art9JavaVMExt9JniAbortVEPKcS2_St9__va_list+116)
    art/runtime/java_vm_ext.cc:410]   native: #04 pc 0000000000141f9c  /system/lib64/libart.so (_ZN3art11ScopedCheck6AbortFEPKcz+144)
    art/runtime/java_vm_ext.cc:410]   native: #05 pc 000000000014a1d0  /system/lib64/libart.so (_ZN3art11ScopedCheck5CheckERNS_18ScopedObjectAccessEbPKcPNS_12JniValueTypeE.constprop.116+11084)
    art/runtime/java_vm_ext.cc:410]   native: #06 pc 0000000000153418  /system/lib64/libart.so (_ZN3art8CheckJNI12NewStringUTFEP7_JNIEnvPKc+468)
    art/runtime/java_vm_ext.cc:410]   native: #07 pc 0000000000005774  /data/data/com.google.android.gms/files/com.google.android.gms.vision/barcode/libs/arm64-v8a/libbarhopper.so (_ZN9barhopper9JniObject14SetStringFieldEPKcRKNSt3__112basic_stringIcNS3_11char_traitsIcEENS3_9allocatorIcEEEE+168)
    art/runtime/java_vm_ext.cc:410]   native: #08 pc 00000000000036f8  /data/data/com.google.android.gms/files/com.google.android.gms.vision/barcode/libs/arm64-v8a/libbarhopper.so (???)
    art/runtime/java_vm_ext.cc:410]   native: #09 pc 0000000000004c8c  /data/data/com.google.android.gms/files/com.google.android.gms.vision/barcode/libs/arm64-v8a/libbarhopper.so (Java_com_google_android_gms_vision_barcode_internal_NativeBarcodeDetector_recognizeNative+84)

I would like to handle the crash in order to catch it and give some feedback to the user.

A: Unfortunately there is no way to handle exceptions from not your own native code.
I had the similar issue with google-vision. And I reported the issue to google vision github https://github.com/googlesamples/android-vision
Sadly but this library has some bugs. In my case it was the bug in the barcode text parser.
It will be cool if you report your problem too.
It may be interesting that there is a way to catch exception from your own native code: Catching exceptions thrown from native code running on Android

A: There is an issue with Google's vision library which causes it to crash when scanning certain QR Codes. (See https://github.com/googlesamples/android-vision/issues/136). If you only need to scan normal barcodes, you can do something like this to avoid the vision library detecting QR Codes at all:
    val barcodeFormatsToScan = Barcode.CODE_128 or Barcode.CODE_39 or Barcode.CODE_93 or Barcode.CODABAR or Barcode.DATA_MATRIX or Barcode.EAN_13 or
            Barcode.EAN_8 or Barcode.ITF or Barcode.UPC_A or Barcode.UPC_E or Barcode.PDF417 or Barcode.AZTEC
    val barcodeDetector = BarcodeDetector.Builder(context).setBarcodeFormats(barcodeFormatsToScan).build()
    val barcodeFactory = BarcodeTrackerFactory(fragment_barcode_scanner_graphic_overlay as GraphicOverlay<BarcodeGraphic>, true, callback)
    barcodeDetector.setProcessor(MultiProcessor.Builder<Barcode>(barcodeFactory).build())


text:
Q: Как сделать маршрутизацию без get запросов Есть проект, на котором используется devExtreme и так получилось, что на проекте нет Get запросов, только Post
Проблема в том, что при переходе на какую либо страницу отсутствует возможность вернуться назад по стрелке в браузере и в адресной строке есть только дефолтный контроллер, возможно ли как-то решить эту проблему без Get запросов?


text:
Q: Azure SignalR binding for WebJob .Net Core 3 not working I have a .Net Core 3.0 console project which includes WebJob function that has an output binding to Azure Signal R.  The app builds OK, but when I run it and try to send a message out via SignalR I get the following error:
{System.MissingMethodException: Method not found: 'System.String Microsoft.Azure.SignalR.AuthenticationHelper.GenerateAccessToken(System.String, System.String, System.Collections.Generic.IEnumerable`1<System.Security.Claims.Claim>, System.TimeSpan, System.String)'.
at Microsoft.Azure.SignalR.Management.RestApiAccessTokenGenerator.Generate(String audience, Nullable`1 lifetime)
at Microsoft.Azure.SignalR.Management.RestApiProvider.GenerateRestApiEndpoint(String path, Nullable`1 lifetime)
at Microsoft.Azure.SignalR.Management.RestApiProvider.GetSendToGroupEndpoint(String groupName, Nullable`1 lifetime)
at Microsoft.Azure.SignalR.Management.RestHubLifetimeManager.SendGroupAsync(String groupName, String methodName, Object[] args, CancellationToken cancellationToken)
at Microsoft.AspNetCore.SignalR.Internal.GroupProxy`1.SendCoreAsync(String method, Object[] args, CancellationToken cancellationToken)
at Microsoft.Azure.WebJobs.Extensions.SignalRService.AzureSignalRClient.SendToGroup(String groupName, SignalRData data)
at Microsoft.Azure.WebJobs.Extensions.SignalRService.SignalRAsyncCollector`1.AddAsync(T item, CancellationToken cancellationToken)
at InSysWebJobP300DataProcessor.Helper.ProcessMinuteData(Message message, ConnectionMultiplexer redisConnection, IAsyncCollector`1 signalRMessages, ILogger log) in E:\InergySystems\GitHub\InSysCore\InSysWebJobP300DataProcessor\Helper.cs:line 125}

The SignalR service is registered in Program.Main with:
static void Main(string[] args)
{
    var builder = new HostBuilder();
    builder.ConfigureWebJobs(b =>
    {
        b.AddAzureStorageCoreServices();
        b.AddServiceBus().AddSignalR();
    });
    builder.ConfigureLogging((context, b) =>
    {
        b.ClearProviders();
        b.AddConfiguration(context.Configuration.GetSection("Logging"));
        if (context.HostingEnvironment.IsDevelopment())
        {
            b.AddConsole();
        }
    });

    var host = builder.Build();
    using (host)
    {
        host.Run();
    }
}

I have a function with the following signature:
[FunctionName("ProcessMinuteData")]
public async Task RunAsync([ServiceBusTrigger("data", Connection = "AzureWebJobsServiceBusConnection")]Message message, [SignalR(HubName = "insyshub")] IAsyncCollector<SignalRMessage> signalRMessages, ILogger log)

The messages are received from the service bus are processed fine, but trying to push out a message via SignalR using the following, results in the error above:
await signalRMessages.AddAsync(new SignalRMessage
{
    GroupName = "GroupName",
    Target = "targetMethod",
    Arguments = new[] { JsonConvert.SerializeObject(message) }
});

Note that the app does not need to receive messages via SignalR, just push them out.
I have the following NuGet packages installed:
<PackageReference Include="Microsoft.AspNetCore.SignalR" Version="1.1.0" />
<PackageReference Include="Microsoft.Azure.SignalR" Version="1.2.1" />
<PackageReference Include="Microsoft.Azure.WebJobs" Version="3.0.14" />
<PackageReference Include="Microsoft.Azure.WebJobs.Extensions" Version="3.0.5" />
<PackageReference Include="Microsoft.Azure.WebJobs.Extensions.Http" Version="3.0.2" />
<PackageReference Include="Microsoft.Azure.WebJobs.Extensions.ServiceBus" Version="4.0.0" />
<PackageReference Include="Microsoft.Azure.WebJobs.Extensions.SignalRService" Version="1.0.2" />
<PackageReference Include="Microsoft.Azure.WebJobs.Extensions.Storage" Version="3.0.10" />
<PackageReference Include="Microsoft.Azure.WebJobs.Logging.ApplicationInsights" Version="3.0.14" />
<PackageReference Include="Microsoft.Extensions.Logging.Console" Version="3.0.1" />

A: It seems that since Microsoft.Azure.SignalR 1.2.0 you now need to include Microsoft.Azure.SignalR.Management if you want to use the approach I am using detailed in the question.
Before 1.2.0 you didn't need to include Microsoft.Azure.SignalR.Management.


text:
Q: WCF SOAP webservice - why do I not need to to use XML? I am learning WCF and using the messaging protocol SOAP (HTTP and XML).
I understand that this a a XML based protocol. The thing I am seeing across guides is that you need to send a XML Soap Envelope to make a request so the service can respond with XML back. However, when I set the client side up to use the service, I don't pass any XML in at all and the response I get is a string.
Dim client As webservice.Service1Client = New webservice.Service1Client()

' I was expecting this to be XML and I would need to parse it...
' In the service side I do say "Return string" - but should I be stating "Return type of XML"?

Dim response As String = client.serviceMethod("test")

This all works but I am just wondering if this is the correct procedure? I am bit worried that I am not creating XML and the service isnt return an Envelope  of XML.
Thanks

A:
I was expecting this to be XML and I would need to parse it

If you call your service using something like fiddler or SoapUI you will be able to see the SOAP XML request and response messages in their raw form.
When you consume a SOAP service in WCF however, you are abstracted away from this bare message interchange by the framework.
You don't need to think about XML anymore, you only need to think in terms of request/response semantics and the data types returned (in your case, a System.String) by the service operation you are calling.
WCF is still conducting a complex conversation based on the exchange of a series of SOAP messages, you just don't need to see any of that.


text:
Q: Getting the value of an object in a TFL API array I've created a map in Leaflet of bike points in London using TFL's API, and I want to add more than just the name of the bikepoints in the pop-up window boxes I've created, specifically the number of bikes and empty docks at each bikepoint. I know which point in the array represents each value, but when I designate it in pop-up array, it shows undefined. I've tried the Number() function to get value, but then I get NaN.
How can I get the value of the object I want from this API?


text:
Q: Using PerformanceCounters to target specific drives Guys, I have the following code:
using System.Diagnostics;

private PerformanceCounter diskRead = new PerformanceCounter();
private PerformanceCounter diskWrite = new PerformanceCounter();

diskRead.CategoryName = "PhysicalDisk";
diskRead.CounterName = "Disk Reads/sec";
diskRead.InstanceName = "_Total";

diskWrite.CategoryName = "PhysicalDisk";
diskWrite.CounterName = "Disk Writes/sec";
diskWrite.InstanceName = "_Total";

This code keeps track of Disk Reads per second and Disk Writes per second and it works fine. My question is, how do I keep track of reads and writes of one specific drive? I have 3 hard drives in my computer and right now its returning a total of all 3 drives combined. How can I specifically chose which drive I want to monitor?

A: You should replace "_Total" with the appropriate drive number:

  diskRead.InstanceName = "0";

Should've checked that. You need to specify the name like "0 C: D:". Yikes.
Edit 2:
You can get the names with
    var cat = new System.Diagnostics.PerformanceCounterCategory("PhysicalDisk");
    var instNames = cat.GetInstanceNames();

And it is probaly safe to filter out the names that start with a number. (_Total is also in the list).

A: Use a specific InstanceName, not _Total.  Use Perfmon.exe to find the instance names.


text:
Q: opengl -- setting up glad on Ubuntu I followed this tutorial to write a simple project using GLFW and glad but I don't know how to set up glad in my project. I am currently using Eclipse.
To be more precise, I am trying to ask how to correctly include glad in a project

A: Make sure you include the GLFW header. Also include the GLAD header BEFORE the GLFW header.


text:
Q: PS3 needs long warm-up before it can read game disks My PS3 always needs a long warm-up (i.e. several hours) before it can read game disks. Before that delay, when I insert a game disk, it repeatedly tries to read the disk, but cannot. After some hours the game disk can be read and everything works as expected. This is the same with every game disk.
There is no issue with (video) DVDs however; the device can read them instantly after boot up.
What can be the reason for this behavior?
Is there a way to fix this?

A: You most likely need to replace the blu-ray lens laser in your PS3. If it's reading DVD's and regular CD's fine, but it only affects bluray games and movies. It's the laser.
The PS3 is a 10+ year old system and many of them go bad due to use. I've fixed a bunch of these at my repair shop before and what happens is the blue light on the lens just doesn't light up if you opened up your PS3 and observe the disc spinning while being read. To detect the DVD and CD lasers, you can use your phone camera and view the invisible infrared laser shown on the spinning disc to verify.
The laser looks like this:

The repair is a bit tricky if you've never opened up a PS3 before as there are a bunch of screws and flex cables you need to loosen. Otherwise you can just follow a Youtube tutorial.


text:
Q: ¿Cómo cierro/destruyo una aplicación? Tengo la siguiente función que inicia una ventana con una barra de carga indeterminada en un archivo llamado Barra_carga.py.
    import tkinter as tk
    from tkinter import Label, ttk

    def carga():
        cargando = tk.Tk()
        cargando.title("Barra de progreso en Tk")
        ancho_cargando = 260
        alto_cargando = 100
        x_cargando = cargando.winfo_screenwidth() // 2 - ancho_cargando // 2
        y_cargando = cargando.winfo_screenheight() // 2 - alto_cargando // 2
        posicion = str(ancho_cargando) + "x" + str(alto_cargando) + "+" + str(x_cargando) + "+" + str(y_cargando)
        cargando.geometry(posicion)
        cargando.resizable(0,0)
        mensaje = Label(cargando,text="Espere por favor").place(x=90,y=20)
        progressbar = ttk.Progressbar(cargando,mode="indeterminate")
        progressbar.place(x=30, y=60, width=200)
        progressbar.start(2)

        return cargando

Y tengo el siguiente código que inicia un escaneo de archivos de sistema y luego inicia la barra de carga:
import subprocess
import Barra_carga

proceso = subprocess.Popen("sfc /scannow", shell=True)
cargando = Barra_carga.carga

Intenté con el siguiente código obtener la respuesta del proceso al finalizar y funciona perfectamente ya que mientras no termina devuelve None, pero cuando intento cerrar el proceso de la barra de carga no se cierra a pesar de que ya terminó el proceso.
while proceso.poll() == None:
     cargando().mainloop()
else:
     cargando().destroy()

He intentado de todo y no logro hacer que se cierre el proceso.
¿Alguna idea de cómo lograrlo?

A: Lo que podés hacer es inicializar la interfaz, usar el mainloop (que por cierto traba el código hasta que se cierra la ventana) y checkear en otra tarea (esto usando el modulo threading) si el proceso sigue inicializado. Si terminó, entonces es tiempo de cerrar la ventana.
Un código que implementa esto:
import tkinter as tk
from tkinter import Label, ttk
import subprocess
import threading

def close_if_finish():
    # usamos un while que no hace nada para esperar
    # que deje de cumplirse la condición
    while proceso.poll() == None:
         pass
    root.destroy()

root = tk.Tk()
proceso = subprocess.Popen(["spotify"])
threading.Thread(target=close_if_finish).start()
root.mainloop()

Aclaraciones:

*

*No está 100% probado. Lo probé haciendo un proceso que abra Spotify y la ventana se cierra inmediatamente, presumiblemente por que el proceso termina antes.

*No uso clases, pero se puede adaptar para que sean usadas.


text:
Q: How WP guesses which ID to use for new post? I'm puzzled with the following. Say, post_ID of my last post is 100. Now I remove all posts from my WordPress blog and even clear all revisions and so on from database if any, so now I have nothing in my wp_posts and wp_term_relationship. I expect to get post_ID = 1 for a new post. But I get post_ID = 101. Looks like WordPress stores ID for next post somewhere, but I've already spent half a day trying to figure out: where?

A: It's just an auto incrementing column in the MySQL database. MySQL is using an internal counter, it's nothing to do with WordPress.
http://dev.mysql.com/doc/refman/5.0/en/example-auto-increment.html
Update
To reset your post ids, run the following (substituting in your tablename):
ALTER TABLE tablename AUTO_INCREMENT = 1


text:
Q: How to find Dryest Pixel of an ImageCollection in Google Earth Engine? (Dryest pixel composite) I want to create a composite with the dryes pixels of an ImageCollection. I know how to make a greenest pixel composite, but I have no clue how to make a dryest pixel composite.
Is there a function similar to ee.ImageCollection.qualityMosaic(qualityBand), but for the dryest pixel?
Code for greenest:
var collection = ee.ImageCollection("LANDSAT/LC08/C01/T1_TOA");
var filtered = collection.filterDate('2015-04-01', '2015-07-01');

// Greenest Pixel Composite
function addNDVI(input) {
 var ndvi = input.normalizedDifference(['B5', 'B4']);
 return input.addBands(ndvi);
}

var with_ndvi = filtered.map(addNDVI);
var greenest = with_ndvi.qualityMosaic('nd');
Map.addLayer(greenest, {max:0.3, bands:["B4", "B3", "B2"]}, 'RGB');


text:
Q: Intuitive understanding of the difference between consistent and asymptotically unbiased I am trying to to get an intuitive understanding and feel for the difference and practical difference between the term consistent and asymptotically unbiased.  I know their mathematical/statistical definitions, but I'm looking for something intuitive.  To me, looking at their individual definitions, they almost seem to be the same thing.  I realize the difference must be subtle but I just don't see it. I'm try to visualize the differences, but just can't.  Can anyone help?

A: I would like to clarify that consistency in general does not imply asymptotic unbiasedness. Consider an estimator for $0$ taking value $0$ with probability $(n-1)/n$ and value $n$ with probability $1/n$. It is a biased estimator since the expected value is always equal to $1$ and the bias does not disappear even if $n\to\infty$. However, it is a consistent estimator since it converges to $0$ in probability as $n\to\infty$.
Asymptotic unbiasedness does not imply consistency either as it is mentioned in other answers. For example, the periodogram is an asymptotically unbiased estimator of the spectral density, but it is not consistent.
Roughly speaking, consistency means that for large values of $n$ we are going to be close to the true value of the parameter with a high probability, i.e. estimates are going to be close to the true value of the parameter. Asymptotic unbiasedness means that for large values of $n$ on average we are going to be close to the true value of the parameter, i.e. the average of estimates is going to be close to the true value of the parameter, but not necessarily the estimates themselves.

A: They are related ideas, but an asymptotically unbiased estimator doesn't have to be consistent.
For example, imagine an i.i.d. sample of size $n$ ($X_1, X_2, ..., X_n$) from some distribution with mean $\mu$ and variance $\sigma^2$. As an estimator of $\mu$ consider $T = X_1 + 1/n$.
(Edit: Note the $X_1$ there, not $\bar{X}$)
The bias is $1/n$ so $T$ is asymptotically unbiased, but it is not consistent.

A: Asymptotic unbiasedness $\impliedby$ consistency + bounded variance
Consider an estimator $\hat{\theta}_n$ for a parameter $\theta$.  Asymptotic unbiasedness means that the bias of the estimator goes to zero as $n \rightarrow \infty$, which means that the expected value of the estimator converges to the true value of the parameter.  Consistency is a stronger condition than this; it requires the estimator (not just its expected value) to converge to the true value of the parameter (with convergence interpreted in various ways).  Since there is generally some non-zero variance in the estimator, it will not generally be equal to (or converge to) its expected value.  Assuming the variance of the estimator is bounded, consistency ensures asymptotic unbiasedness (proof), but asymptotic unbiasedness is not enough to get consistency.  To put it another way, under some mild conditions, asymptotic unbiasedness is a necessary but not sufficient condition for consistency.
Asymptotic unbiasedness + vanishing variance $\implies$ consistency
If you have an asymptotically unbiased estimator, and its variance converges to zero, this is sufficient to give weak consistency.  (This follows from Markov's inequality, which ensures that convergence in mean-square implies convergence in probability).  Intuitively, this reflects the fact that a vanishing variance means that the sequence of random variables is converging closer and closer to the expected value, and if the expected value converges to the true parameter (as it does under asymptotic unbiasedness) then the random variable is converging to the true parameter.

A: There are "unbiased but not consistent" estimators as well as "biased but consistent" estimators:
https://en.wikipedia.org/wiki/Consistent_estimator#Unbiased_but_not_consistent
So, they are not the same thing.
Also, there is a long discussion about this topic here:
What is the difference between a consistent estimator and an unbiased estimator?

A: If the estimator is bounded then consistency implies asymptotic unbiasness by the dominated convergence theorem.

A: Asymptotic unbiased: As $n \rightarrow \infty$, bias converges to $0$.
Consistent: As $n \rightarrow \infty$, variance of the estimator converges to $0$.


text:
Q: Изменение многозначного словаря через функцию (Python) Пишу себе библиотеку для удобной работы с json-файлом.
Создаю функцию, чтобы значения можно было изменять в файле сразу.
Она выглядит так:
def upload(self, note, key, new_value, noteListIndex=None, place=None, placeListIndex=None, file=self.default_file)

Пример использования:
m.upload(note='profiles', noteListIndex=0, key='name', new_value='No more John')

# note='profiles' -> Означает, что мы будем использовать словарь информации по пользователям
# noteListIndex=0 -> Первый пользователь в списке
# key='name' -> Изменяемый ключ в Информации о Пользователе
# new_value -> Новое значение изменяемого Ключа (key)
# Пояснение всем аргументам будет ниже. Это был пример аргументов в реальной ситуации

Изменяемая часть словаря выглядит так:
{
    'profiles': [{'id': 123, 'name': 'John'}],
    'other': {...},
    'something_else': {...},
    ...
}

Пояснения:
# note -> Тема последующих значений (Главная)
# noteListIndex -> Индекс элемента списка, если note содержит список
# place -> Имя ключа внутри note (Указывается, если ключ после note не является Строкой или Числом)
# placeListIndex -> Индекс элемента списка, если place содержит список
# key -> Ключ
# new_value -> Новое значение Ключа (key)

В данной ситуации нужно изменить file['profiles'][0]['name'], но ведь может быть и другая часть словаря для изменения (и новые пути, собственно).
Я сделал:
def is_digit(self, num): # Функция для определения, можно ли использовать переменную как Число
    return True if (str(num).isdigit()) else False

def upload(self, note, key, new_value, noteListIndex=None, place=None, placeListIndex=None, file=self.default_file): # Сам метод
    data = self.upload_data(file=self.default_file) # Получаем словарь из json-файла
    new_data = {} # Конечный словарь
    way = data[note] # Переменная для изменения значения
    if noteListIndex or (self.is_digit(noteListIndex) and noteListIndex>=0): way = way[noteListIndex] # Если указан noteListIndex, то войти в него
    if place: way = way[place]  # Если указан place, то войти в него
    if placeListIndex or (self.is_digit(placeListIndex) and placeListIndex>=0): way = way[placeListIndex] # Если placeListIndex указан, то войти в него
    new_data = way # Получаем путь
    new_data[key] = new_value # Изменяем значение
    m.save_data(new_data, file=self.default_file) # Сохраняет изменённый json-файл
    return new_data # Возвращаем новые данные (требуется ситуативно)

Но данный метод вернёт Словарь, в котором был изменён key, в этом и проблема. Но я не знаю, как можно перенести данное изменение в полноценный словарь.
Кто-либо может подсказать, как это сделать?


text:
Q: Django выдаёт ошибку при запуске сервера При запуске сервера вылетает ошибка
You have 13 unapplied migration(s). Your project may not work properly until you apply the migrations for app(s): auth, contenttypes, firstapp, sessions.

Но сервер всё ещё загружается и позволяет переходить по ссылкам, но css и js в них нет возможно по другой причине
при запуске py manage.py migrations выдаёт большую ошибку:
Apply all migrations: admin, auth, contenttypes, firstapp, sessions
Running migrations:
Applying contenttypes.0002_remove_content_type_name...Traceback (most recent call last):
File "C:\Users\gff10\AppData\Local\Programs\Python\Python38\lib\site-packages\django\db\backends\utils.py", line 86, in _execute
return self.cursor.execute(sql, params)
File "C:\Users\gff10\AppData\Local\Programs\Python\Python38\lib\site-packages\django\db\backends\mysql\base.py", line 74, in execute
return self.cursor.execute(query, args)
File "C:\Users\gff10\AppData\Local\Programs\Python\Python38\lib\site-packages\MySQLdb\cursors.py", line 209, in execute
res = self._query(query)
File "C:\Users\gff10\AppData\Local\Programs\Python\Python38\lib\site-packages\MySQLdb\cursors.py", line 315, in _query
db.query(q)
File "C:\Users\gff10\AppData\Local\Programs\Python\Python38\lib\site-packages\MySQLdb\connections.py", line 239, in query
_mysql.connection.query(self, query)
MySQLdb._exceptions.OperationalError: (1054, "Unknown column 'name' in 'django_content_type'")

The above exception was the direct cause of the following exception:

Traceback (most recent call last):
File "manage.py", line 21, in <module>
main()
File "manage.py", line 17, in mainexecute_from_command_line(sys.argv)File "C:\Users\gff10\AppData\Local\Programs\Python\Python38\lib\site-packages\django\core\management\__init__.py", line 401, in execute_from_command_lineutility.execute()File "C:\Users\gff10\AppData\Local\Programs\Python\Python38\lib\site-packages\django\core\management\__init__.py", line 395, in executeself.fetch_command(subcommand).run_from_argv(self.argv)
File "C:\Users\gff10\AppData\Local\Programs\Python\Python38\lib\site-packages\django\core\management\base.py", line 328, in run_from_argv
self.execute(*args, **cmd_options)
File "C:\Users\gff10\AppData\Local\Programs\Python\Python38\lib\site-packages\django\core\management\base.py", line 369, in execute
output = self.handle(*args, **options)
File "C:\Users\gff10\AppData\Local\Programs\Python\Python38\lib\site-packages\django\core\management\base.py", line 83, in wrapped
res = handle_func(*args, **kwargs)
File "C:\Users\gff10\AppData\Local\Programs\Python\Python38\lib\site-packages\django\core\management\commands\migrate.py", line 231, in handle
post_migrate_state = executor.migrate(
File "C:\Users\gff10\AppData\Local\Programs\Python\Python38\lib\site-packages\django\db\migrations\executor.py", line 117, in migrate
state = self._migrate_all_forwards(state, plan, full_plan, fake=fake, fake_initial=fake_initial)
File "C:\Users\gff10\AppData\Local\Programs\Python\Python38\lib\site-packages\django\db\migrations\executor.py", line 147, in _migrate_all_forwards
state = self.apply_migration(state, migration, fake=fake, fake_initial=fake_initial)
File "C:\Users\gff10\AppData\Local\Programs\Python\Python38\lib\site-packages\django\db\migrations\executor.py", line 245, in apply_migration
state = migration.apply(state, schema_editor)
File "C:\Users\gff10\AppData\Local\Programs\Python\Python38\lib\site-packages\django\db\migrations\migration.py", line 124, in apply
operation.database_forwards(self.app_label, schema_editor, old_state, project_state)
File "C:\Users\gff10\AppData\Local\Programs\Python\Python38\lib\site-packages\django\db\migrations\operations\fields.py", line 249, in database_forwards
schema_editor.alter_field(from_model, from_field, to_field)
File "C:\Users\gff10\AppData\Local\Programs\Python\Python38\lib\site-packages\django\db\backends\base\schema.py", line 564, in alter_field
self._alter_field(model, old_field, new_field, old_type, new_type,
File "C:\Users\gff10\AppData\Local\Programs\Python\Python38\lib\site-packages\django\db\backends\base\schema.py", line 710, in _alter_field
self.execute(
File "C:\Users\gff10\AppData\Local\Programs\Python\Python38\lib\site-packages\django\db\backends\base\schema.py", line 142, in execute
cursor.execute(sql, params)
File "C:\Users\gff10\AppData\Local\Programs\Python\Python38\lib\site-packages\django\db\backends\utils.py", line 100, in execute
return super().execute(sql, params)
File "C:\Users\gff10\AppData\Local\Programs\Python\Python38\lib\site-packages\django\db\backends\utils.py", line 68, in execute
return self._execute_with_wrappers(sql, params, many=False, executor=self._execute)
File "C:\Users\gff10\AppData\Local\Programs\Python\Python38\lib\site-packages\django\db\backends\utils.py", line 77, in _execute_with_wrappers
return executor(sql, params, many, context)
File "C:\Users\gff10\AppData\Local\Programs\Python\Python38\lib\site-packages\django\db\backends\utils.py", line 86, in _execute
return self.cursor.execute(sql, params)
File "C:\Users\gff10\AppData\Local\Programs\Python\Python38\lib\site-packages\django\db\utils.py", line 90, in __exit__
raise dj_exc_value.with_traceback(traceback) from exc_value
File "C:\Users\gff10\AppData\Local\Programs\Python\Python38\lib\site-packages\django\db\backends\utils.py", line 86, in _execute
return self.cursor.execute(sql, params)
File "C:\Users\gff10\AppData\Local\Programs\Python\Python38\lib\site-packages\django\db\backends\mysql\base.py", line 74, in execute
return self.cursor.execute(query, args)
File "C:\Users\gff10\AppData\Local\Programs\Python\Python38\lib\site-packages\MySQLdb\cursors.py", line 209, in execute
res = self._query(query)
File "C:\Users\gff10\AppData\Local\Programs\Python\Python38\lib\site-packages\MySQLdb\cursors.py", line 315, in _query
db.query(q)
File "C:\Users\gff10\AppData\Local\Programs\Python\Python38\lib\site-packages\MySQLdb\connections.py", line 239, in query
_mysql.connection.query(self, query)
django.db.utils.OperationalError: (1054, "Unknown column 'name' in 'django_content_type'")

Мне перекинули БД MySQL, с уже созданными столбцами типа django session. MySqlconnector подключал.
Как это исправить?

A: а база-то наполнена данными? Если нет, просто почисти её, удали все файлы из папок migrations во всех приложениях проекта и снова миграни всё.
Если данные есть, то сначала выгрузи базу и повтори верхний пункт, потом залей базу снова


text:
Q: How can I use a variable used in another unit within a different method? I have a method that requires a local variable processed in another unit, but I don't know how to reference it correctly. Depending on the result of the if condition, the variable obtained changes.
function Connecting.SendSomething(Var1 : Boolean;Var2 : boolean) : integer;
begin
  Result := 0;
  if 2+2 = 4 then
    Result := 1
  else
    Result := 2;
  ...
end;

Result is only mentioned there. Nowhere else in the unit code was it used, so I'm guessing that's the integer variable. The point is that I want to use Result inside an if conditional in a different unit's method.
Please bear in mind that the secondary unit is correctly included on top, the names of the variables have been changed to put them here and the code is simplified as to omit sensitive data.
Over there I'm using Connecting.SendSomething() inside a basic button's method with (TRUE, TRUE) and (TRUE, FALSE) values as parameters, I just don't know how to "reel in" Result.

A: Result refers to the integer that SendSomething() returns:
Procedures and Functions (Delphi): Function Declarations

The statement block of the function is governed by the same rules that apply to procedures. Within the statement block, you can use variables and other identifiers declared in the localDeclarations part of the function, parameter names from the parameter list, and any identifiers within whose scope the function declaration falls. In addition, the function name itself acts as a special variable that holds the return value of the function, as does the predefined variable Result.
As long as extended syntax is enabled ({$X+}), Result is implicitly declared in every function. Do not try to redeclare it.

So, only SendSomething() and its immediate caller can access the Result value, eg
if Connecting.SendSomething(true, true) = 1 then

Unless SendSomething() explicitly passes its Result as a parameter to another procedure/function, eg:
function Connecting.SendSomething(Var1 : Boolean;Var2 : boolean) : integer;
begin
  Result := 0;
  if 2+2 = 4 then
    Result := 1
  else
    Result := 2;
  ...
  DoSomethingWith(Result);
  ...
end;


text:
Q: Cluster Groups based on overlap I have the following data:
Group_id  item_id
     001      699
     001      533
     001      782

     002      699
     002      533
     002      782
     002      999

I want to assign group_id 001 and 002 in one cluster because they have a large overlap between item_id's.
Group_id and item_id are just arbitrary numbers. So I am not sure if it makes sense to calculate distance between the item_ids numbers?

A: Since you mentioned "hierarchical-clustering" in the tags I assume you want to use hierarchical clustering for this task.
Distance Matrix
Hierarchical clustering can cluster groups based on their pairwise distance matrix. So what you need to do is to prepare a matrix of distances between all pairs of group_ids.
Distance between each pair
In order to construct the distance matrix you need some way to measure the distances between each pair of group_ids. In your scenario you want to cluster groups based on the overlaps of their elements. One way to do this would be the Jaccard similarity which is an intersect over a union of elements.
With your example the Jaccard similarity between group_ids 001 and 002 would be computed like so:

*

*Find the number of common elements: in your case - 3

*Find the number of total unique elements in both groups: in your case - 4

*Jaccard's similarity is 3/4

Note that Jaccard's similarity shows how similar two groups are. You will probably need to turn this into a matrix of distances. Since Jaccard's similarity ranges from 0 to 1 - you can transform them into distances by subtracting them from 1: 1 - Jaccard similarity
Hierarchical Clustering
Once you have the required distance matrix - you can continue with hierarchical clustering. There might be some parameters left to decide on (like a linkage function to use when combining two groups into a single cluster) but these are mostly problem dependant.


text:
Q: Can deep learning TensorFlow models be trained in Python, pickled and used for prediction in C++? I have learnt a neural net based model using TensorFlow in Python.

I would like to store this model in a file and be able to load it into
  memory in a C++ program for prediction later.

I am doing a comparative study of my machine learning model versus a standard algorithm written in C++. For this reason, I would like to load the model and do the prediction in C++ since I don't want the internals of the programming language to cause differences in the runtimes of the implementations.

Are there other ways to keep the comparisons language-neutral?

A: Yes. I think you can do it using bazel (google's tool for TF). Once you make sure that you are saving checkpoints, build the project. It would create executable file for you to use in c++.


text:
Q: The following packages have unmet dependencies Whenever I try to install or remove anything I get this error
The following packages have unmet dependencies:
libgpg-error0: Depends: libc6 (>= 2.14) but 2.15-0ubuntu10.12 is installed
libgpg-error0:i386: Depends: libc6 (>= 2.1.3) but 2.15-0ubuntu10.12 is installed


text:
Q: Ajax Forms with rails 4, :remote => true and JQuery - What are the Best Practices? I'm building a multi-part form with ajax in Rails 4, and I'd like to know if I'm doing this the correct way.
Here's the strategy I've used so far.  My controller is called ajaxform.
At the top of my ajaxform_controller.rb, inside the class definition but not in a function, I have
respond_to :js

Stage One
The link from another view to this tool is routed with
get 'ajaxform' => 'ajaxform#stage_one'

The primary view, "stage_one.html.erb" contains the first part of the form, defined with a form_tag using the :remote => true option.  The controller method of the same name is empty.
<%= form_tag("/stage_one_form", method: 'post', :remote => true) do %>
    <%= label_tag(:stage_one_data, "Stage one data: ") %>
    <%= select_tag(:stage_one_data, options_for_select([['Option1', :option1], ['Option2', :option2], ['Option3', :option3]], 1)) %>
    <%= submit_tag 'Next' %>
<% end %>

Hidden span tags: To the right of the "Next" button, there is a hidden span tag with an id attribute of "stage_two_waiting".  When the form submits, routes.rb tells the application to go to stage_two_waiting, which will display a "please wait..." message inside the span tag.
Below it, there's another hidden span tag with an id of "stage_two_form" — this is where stage two of our form will render after we get the data back from a query based on the stage one selection.
Stage Two
post 'stage_one_form' => 'ajaxform#stage_two_waiting'

stage_two_waiting is a partial view with two files: a stage_two_waiting.js.erb and a _stage_two_waiting.html.erb.  An underscore at the beginning of the html.erb file indicates that it is a partial, but the .js.erb file of the same name does not have an underscore.
Here is stage_two_waiting.js.erb
$('span#stage_two_waiting').append("<%= escape_javascript (render partial: 'stage_two_waiting') %>");
$('span#stage_two_waiting').slideDown(350);
$("#trigger_stage_two").trigger("submit.rails");

The first two lines cause _stage_two_waiting.html.erb to render inside the span tag on the stage one form with a nifty slideDown effect.  The third line triggers submission of a hidden form in _stage_two_waiting.html.erb, which passes the data along to the next form and routes to it:
<%= form_tag("/stage_two_waiting_form", :id => 'trigger_stage_two', method: 'post', :remote => true) do %>

    <%= hidden_field_tag(:stage_one_data, params[:stage_one_data])%>
<% end %>

When the JQuery triggers that hidden form submission, routes.rb specifies the location of the actual stage two form itself:
post 'stage_two_waiting_form' => 'ajaxform#stage_two_form'

stage_two_form also has two files, stage_two_form.js.erb and _stage_two_form.html.erb.  Before these files can render, the controller needs to place a REST call.
def stage_two_form
    stage_one_selected_option = params[:stage_one_data]
    rest_response = `curl -k -X GET https://myrestservice.net/v1/myfunction/#{stage_one_selected_option}`

    #convert the rest response into an array of select list options for the stage two form
    @stage_two_options = Array.new
    @stage_two_options.push "parsed information from rest_response would go in here"

    respond_with(@stage_two_options) do |format|
      format.js
    end
end

stage_two_form.js.erb looks like this:
$('span#stage_two_form').append("<%= escape_javascript (render partial: 'stage_two_form') %>");
$('span#stage_two_form').slideDown(350);

The routing doesn't fire off this Javascript until the controller method is completely finished executing.  Until then, the user just sees the "please wait..." message.  Once the method is done, the javascript renders the form and its instance variable, @stage_two_options
  <%= form_tag("/stage_two_form", method: 'post', :remote => true) do %>
      <%= label_tag(:stage_two_data, "Available options based on stage one: ") %>
      <%= select_tag(:stage_two_data, options_for_select(@stage_two_options.transpose[0].collect)) %>
      <%= hidden_field_tag(:stage_one_data, params[:stage_one_data]) %>
      <%= submit_tag 'Next' %>
  <% end %>

The hidden_field_tag passes along the selection that was made all the way back in stage one, just in case it's needed by stage three.  We could also write a second hidden_field_tag to pass the entire array of options that the controller method provided, if it will be needed later.
      <%= hidden_field_tag(:stage_two_options, @stage_two_options) %>

The route when posting this form looks like:
post 'stage_two_form' => 'ajaxform#stage_three_waiting'

Further stages
Stage three also has a total of four files, two for the waiting message and two for the form.  They are stage_three_waiting.js.erb, _stage_three_waiting.html.erb, stage_three_form.js.erb, and _stage_three_form.html.erb.  As before, the stage three waiting partial has a hidden form inside of it to pass along any needed params from stage two.  Both stage three partials are rendered inside of the span tags in _stage_two_form.html.erb with JQuery append.  This process can continue on for as many stages as needed.
Problems
It seems a little excessive to me that each "stage" of a multi-part form should rely on code that's located in up to five different places: two files for a "please wait..." message, two more files for the form itself, code inside the controller method.  It also seems odd to need to pass data from one stage to the next as a parameter in hidden fields.  It's unwieldy, and the form isn't working in safari 8 for some reason either, because it keeps routing as HTML and ignoring the JQuery.
Conclusion
I have a suspicion that I'm not doing this in the most graceful way — Any help would be appreciated.
The question is — Is it okay to pass data in params from one partial view to another to another using those hidden fields, or is there a cleaner way to do this that doesn't involve so many different files and hidden fields?

A: Global variables An alternative to passing parameters from partial view to partial view through the hidden fields would be to use global variables (beginning with $) in the controller.  This makes them available to any of the controller's views and all their functions in the controller itself
ajaxform_controller.rb
def stage_two_form
    # define a global variable that we expect to use later from a different partial
    $global_selected_option = params[:stage_one_data]
    ...
end

def stage_three_form
    # the "stage_three_form" method still has access to the global variable
    $stage_three_option = $global_selected_option + ' In stage 3'
end

_stage_three_form.html.erb

The original option was: <%= $global_selected_option %>

<%= form_tag("/stage_three_form", method: 'post', :remote => true) do %>
      <%= label_tag(:stage_three_selection, "#{$stage_three_option}") %>
      ...
<% end %>


text:
Q: Prevent JavaScript to be refreshed every time the page is loaded I have the following code:

Now my problem is that every time I refresh the page the variable gets reset. Is there a way to set the variable once for a certain amount of time, so it doesn't get reset?
Thanks

A: There are several ways to achieve this. You could use cookies to save the variable - see here for more info and check upon the next request, if a cookie was set.
Other than that, you could also utilize URL parameters to retain state
location.hash = your_var;

And check upon the next request, if location.hash has been set. There are several other possibilities for that, I only showed you two ways to do such a thing.

A: Guess the easiest way would be using cookies, you can achieve that easily using jQuery cookie plugin, this one for example, which makes the saving as easy as:
$.cookie("example", "foo");

and reading:
$.cookie("example")


text:
Q: Can't recongnize my SSD device file in /dev I am using Ubuntu and can't find my SSD device file. The /dev directory has following contents:
agpgart
audio
audio1
audio2
audio3
audioctl
char
console
core
dsp
dsp1
dsp2
dsp3
fd
full
kmem
kmsg
log
loop0
loop1
loop2
loop3
loop4
loop5
loop6
loop7
mem
midi0
midi00
midi01
midi02
midi03
midi1
midi2
midi3
mixer
mixer1
mixer2
mixer3
mpu401data
mpu401stat
null
port
ptmx
pts
ptyp0
ptyp1
ptyp2
ptyp3
ptyp4
ptyp5
ptyp6
ptyp7
ptyp8
ptyp9
ptypa
ptypb
ptypc
ptypd
ptype
ptypf
ram
ram0
ram1
ram10
ram11
ram12
ram13
ram14
ram15
ram16
ram2
ram3
ram4
ram5
ram6
ram7
ram8
ram9
random
rmidi0
rmidi1
rmidi2
rmidi3
sequencer
shm
smpte0
smpte1
smpte2
smpte3
sndstat
stderr
stdin
stdout
tty
tty0
tty1
tty10
tty11
tty12
tty2
tty3
tty4
tty5
tty6
tty7
tty8
tty9
ttyp0
ttyp1
ttyp2
ttyp3
ttyp4
ttyp5
ttyp6
ttyp7
ttyp8
ttyp9
ttypa
ttypb
ttypc
ttypd
ttype
ttypf
urandom
xconsole
zero

Can some one suggest which should represent my SSD file?
Edit: mount command gives following output:
/dev/simfs / simfs rw,relatime 0 0
proc /proc proc rw,relatime 0 0
sysfs /sys sysfs rw,relatime 0 0
none /dev/pts devpts rw,nosuid,noexec,relatime,mode=600,ptmxmode=000 0 0
none /proc/sys/fs/binfmt_misc binfmt_misc rw,nosuid,nodev,noexec,relatime 0 0
none /run tmpfs rw,nosuid,noexec,relatime,size=943720k,mode=755 0 0
none /run/lock tmpfs rw,nosuid,nodev,noexec,relatime,size=5120k 0 0
none /run/shm tmpfs rw,relatime 0 0

Edit 2: Contents of /etc/fstab are:
proc  /proc       proc    defaults    0    0
none  /dev/pts    devpts  rw,gid=5,mode=620    0    0
none  /run/shm    tmpfs   defaults    0    0

A: None of them.
/dev/simfs indicates that your Ubuntu is running on a "simfs" device, which is a virtual OpenVZ filesystem. The entire "server" is just an OpenVZ container on the host hardware – probably alongside several dozen more containers belonging to other customers – and does not have access to the actual filesystem structure, much less the hardware.
So it can only access a small part of the real disk, through the simfs device.


text:
Q: How to add multiple expressions inside text field with conditional in jaspersoft? I have a document that needs to be dynamic, so I added some textfields and I will pass as a parameter one number for what text it should be, I am using REPORT_PARAMETER_MAP for my footnotes, and I will need to put the footnotes after passing the text for the textfield.
The problem is that Jaspersoft doesn't let me add more than one expression inside one conditional.
My textfield is doing this:
$P(param1) == 0 ? null : $P(param1) == 1 ? (
     "text for number one";
     $P{REPORT_PARAMETERS_MAP}.put("id_1", $V(footnote))
) : "text for other numbers"

For some reason jaspersoft doesn't understand what I am trying to do, and it doesn't accept ";", if I'm doing something wrong please explain to me.

A: You can't code using ; in a textField expression, all path's are expected to return a result (similar to excel formula). This type of expressions makes it almost impossibile to call void methods.
However, you can hack it some if method have return value
In your case  $P{REPORT_PARAMETERS_MAP}.put("id_1", $V(footnote)) you are calling the put method on the Map api. As you can see it returns.

the previous value associated with key, or null if there was no mapping for key

Since it returns a value you can nest this call in your ternary expression, hence instead of just returning "text for number one"
 ($P{REPORT_PARAMETERS_MAP}.put("id_1", $V(footnote))==null || true)?"text for number one":""

As you can see this expression always evaluates to true, it will always return "text for number one" but it also put the value in the Map.
Simple jrxml example demonstrating technique
<?xml version="1.0" encoding="UTF-8"?>
<jasperReport xmlns="http://jasperreports.sourceforge.net/jasperreports" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://jasperreports.sourceforge.net/jasperreports http://jasperreports.sourceforge.net/xsd/jasperreport.xsd" name="TestParams" pageWidth="595" pageHeight="842" columnWidth="555" leftMargin="20" rightMargin="20" topMargin="20" bottomMargin="20" uuid="f85bc6aa-5060-4485-bd99-bd5de1734ef1">
    <property name="com.jaspersoft.studio.data.defaultdataadapter" value="One Empty Record"/>
    <parameter name="Param1" class="java.lang.Integer">
        <defaultValueExpression><![CDATA[1]]></defaultValueExpression>
    </parameter>
    <queryString>
        <![CDATA[]]>
    </queryString>
    <title>
        <band height="79" splitType="Stretch">
            <textField>
                <reportElement x="0" y="0" width="545" height="30" uuid="fc021fc5-85aa-4ea3-8372-3231fe4aeb84"/>
                <textFieldExpression><![CDATA[($P{Param1}!=null && $P{Param1}==1)?($P{REPORT_PARAMETERS_MAP}.put("Hi","Hello world")!=null || true)?"We put Hi!":"":"Param1 was not 1"]]></textFieldExpression>
            </textField>
        </band>
    </title>
    <summary>
        <band height="42" splitType="Stretch">
            <textField>
                <reportElement x="0" y="0" width="544" height="30" uuid="56d3ab2d-19c9-4314-84b3-e6103e54446f"/>
                <textFieldExpression><![CDATA[$P{REPORT_PARAMETERS_MAP}.get("Hi")]]></textFieldExpression>
            </textField>
        </band>
    </summary>
</jasperReport>


text:
Q: Eclipse Juno - not parsing C++11, current SO solutions doesn't work So far I have tried these tricks: (from other SO questions)

*

*C/C++ Build -> Settings -> Tool Settings -> GCC C++ Compiler -> Miscellaneous -> Other Flags. Put -std=c++0x (or for newer compiler version -std=c++11 at the end)

*C/C++ General -> Paths and Symbols -> Symbols -> GNU C++. Click "Add..." and paste GXX_EXPERIMENTAL_CXX0X (ensure to append and prepend two underscores) into "Name" and leave "Value" blank.

*answer to this question
Other noticeable things:

*

*When I open C++11 header like <memory> it is visible that __cplusplus macro shadows the text below it, including <backward/auto_ptr.h> instead of all C++11 stuff; hovering mouse over macro shows that __cplusplus expands to 199711L

*parser has no problems with this lines:
int* p = nullptr;
virtual void InheritedFunction() override;

*It seems that parser understands correctly C++11 features (lambdas work) but somehow things like std::shared_ptr are blocked by not-including appropriate headers because __cplusplus macro expands wrong

*Eclipse can't resolve my external libraries #includes. All paths are correct, they are the same as before reinstalling Eclipse

*\/
 "The settings are not used by indexer" - but why? Also I don't have anything like "MBS" on the providers tab

A: Solved by changing so many things in settings that I don't remember for sure what was the actual cause.
Probably this:
Window -> Preferences -> C/C++ -> Indexer -> Build configuration for the indexer
I changed from "Use build configuration specified in the project's indexer settings" to "Use active build configuration"
Somehow the "The settings are not used by indexer" has disappeared and I can freely edit __cplusplus value now
Also, my unresolved external libraries are now found


text:
Q: Mule - Receive email not working I know this question has been raised before, but I couldn't really find solution to this issue till now.
I am trying to get messages from outlook exchange for parsing.
I have a very simple flow to get the mails from outlook and it seems to work partially (It authenticates properly, and also checks all the necessary folders but it doesn't retrieve the mail from IMAP server).
This is the flow I am using...
 <imap:connector name="imapConnector" checkFrequency="500"
        backupEnabled="true" backupFolder="inbox.backup"
        mailboxFolder="INBOX" moveToFolder="processed" deleteReadMessages="false"
        defaultProcessMessageAction="SEEN" />
    <flow name="testFlow" doc:name="testFlow">
        <imap:inbound-endpoint host="ip"
            port="143" user="username" password="pwd" doc:name="IMAP" />
        <file:outbound-endpoint path="C:\"
            responseTimeout="1000" doc:name="File" />
    </flow>

The app seems to run without any errors, but its not retrieving any emails instead just sits there forever as below... Can someone help me?
**********************************************************************
* Application: test                                                  *
* OS encoding: Cp1252, Mule encoding: UTF-8                          *
*                                                                    *
* Agents Running:                                                    *
*   JMX Agent                                                        *
**********************************************************************
INFO  2013-02-06 18:26:45,814 [main] org.mule.module.launcher.DeploymentService:
++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
+ Started app 'test'                                       +

++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++

A: I had the same issue. Try this:

*

*stop mule

*delete or move all messages from the folder mule is listening on (in your case INBOX)

*restart mule

*send a new message to where mule is listening to

A: There seem to be quite some literature around connecting to MS Exchange with JavaMail, which is what Mule uses behind the scene. Read for example:

*

*http://kenai.com/projects/javamail/pages/Exchange

*http://www.oracle.com/technetwork/java/faq-135477.html#Exchange-login

*Java Mail API Cannot Read Inbox
So be sure your username is correctly formatted and also maybe use "Inbox" instead of "INBOX" (not sure it helps, but in examples, people do that).


text:
Q: How can I obtain this inequality (from Evan's PDEs) I am self studying PDEs from Evans' "Partial Differential Equations" textbook. Currently, I am going through Theorem 1 from Section 5.7 (Rellich-Kondrachov compactness theorem) and am having difficulty obtaining an inequality from the third step.
The author uses an $L^p$-interpolation identity (which I still follow) to obtain
$$
   \left\Vert u_m^\epsilon - u_m \right\Vert_{L^q(V)}
\leq \left\Vert u_m^\epsilon - u_m \right\Vert_{L^1(V)}^\theta
\left\Vert u_m^\epsilon - u_m \right\Vert_{L^{p^\ast}(V)}^{1-\theta}
$$
where $p^{\ast}$ is the Sobolev-conjugate to $p$.

He then invokes the Gagliardo-Nirenberg-Sobolev inequality to yield
  $$
 \left\Vert u_m^\epsilon - u_m \right\Vert_{L^q(V)}  \leq C \left\Vert u_m^\epsilon - u_m \right\Vert_{L^1(V)}^\theta
$$
  for all $m$ and all $\epsilon$. This last step is where I get stuck.

The constant $C > 0$ seems to come from the fact that the sequence $(u_m)_m$ is uniformly bounded in $W^{1,p}(V)$. However, for the inequality to hold, wouldn't the collection $\left( u_m^\epsilon \right)$ also need to be uniformly bounded? If so, I have no idea how to go about proving this.
ASSUMPTIONS:

*

*We are working in $\mathbb{R}^n$ and it is assumed that $1\leq p < n$.

*$V$ is a pre-compact subset of $\mathbb{R}^n$, the functions $u_m$ and $u_m^\epsilon$ all have compact support in $V$.

*$u_m^\epsilon = \eta_\epsilon \ast u_m$ where $\eta_\epsilon$ are molifiers. I have already shown that $u_m^\epsilon \to u_m$ in $L^1(V)$ uniformly in $m$.

*It holds that $\sup_m \left\Vert{u_m}\right\Vert_{W^{1,p}(V)} < \infty$.


text:
Q: Get super class reference in `@typescript-eslint/parser` AST Given the following class hierarchy:
class Foo {
  fooMember = 1;
}

class Bar extends Foo {
  barMember = 2;
}

The AST output of @typescript-eslint/parser references the extends Foo statement as a superClass with the following properties:
superClass: Identifier {
  type: "Identifier",
  name: "Foo",
  range: [ 50 53 ]
}

Is it possible to extract the ClassDeclaration corresponding to Foo from this entry, and if so, how?
Is the same solution applicable if the extended class is imported?
Conceptually this should be possible, given that Typescript correctly infers errors such as public-private definition mismatch between parent-child classes etc.


text:
Q: Three ways to make Thumbnail browser... help me choose I have 3 ways to make thumbnail browser. Each seems to me like a good way to make it but which route would you as an experienced wpf developer recommend?

*

*The easiest is IValueConverter which takes path as input and binds to image source.
<Image Source="{Binding FullPath, Converter={StaticResource UriToBitmapConverter}, Mode=OneTime, IsAsync=True}" ... />

public class UriToBitmapConverter : IValueConverter
{
 public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
 {
    if (value == null) return null;
    BitmapImage img = GetImage((string)value);
    return img;
}

*Control extending image. Uses dependency property to supply path
public class MyImage : System.Windows.Controls.Image
{
  public MyImage()
  {
    this.Loaded += new RoutedEventHandler(MyImage_Loaded);
  }
  void MyImage_Loaded(object sender, RoutedEventArgs e)
  {
    Task.Factory.StartNew(() =>
    {
       var source = GetImage(mypath);
       this.Dispatcher.Invoke(() => this.Source = source);
    });
  }
...
}

*having conversion in a class where I store all the file data, and thumbnail also
<Image Source="{Binding Path=MyImage, Mode=OneTime, IsAsync=True}"/>

public class FileData : INotifyPropertyChanged
{
    private string fullPath;
    public BitmapSource MyImage
        {
            get
            {
                if (_myimage == null)
                    _myimage = GetImage(fullpath);
                return _myimage;
            }
        }

Option 2 seems the best for me as the cleanest way and easy way to load each thumbnail in another thread. Still none of them seem good for browsing network drives and changing folders during long image extractions as I see no way to properly cancel operation.

A: I would use WPF to load the image by binding the path string to Image.Source. Using an ItemsControl you can set the ItemTemplate to how you want you items to be displayed, in this case you want an image with the source bound to the FullPath which is of type string. No converter is necessary.
<ItemsControl DataContext="{Binding Items}">
  <ItemsControl.ItemsPanel>
    <ItemsPanelTemplate>
      <VirtualizingStackPanel Orientation="Horizontal"/>
    </ItemsPanelTemplate>
  <ItemsControl.ItemTemplate>
    <DataTemplate>
      <Image Source="{Binding FullPath}"/>
    </DataTemplate>
  </ItemsControl.ItemTemplate>
 </ItemsControl>

If you are looking to only load the images that are visible, then I suggest you create a Panel that can handle virtualization and use that as your ItemsPanelTemplate. An other suggestion for this control to load faster is to create a UserControl that will load the Image in the background and use it in the DataTemplate. Both of these will improve the performance of your application.


text:
Q: SQL Server Agent not to catch stderr/stdout from python I have a CmdExec job in SQL Agent that runs Python application. Python itself writes JSON formatted logs to files and then Filebeat service transfers these logs to Elastic.
Everything works fine in case we have handled exception or system exit in Python script:
try:
    #something
except Exception:
    logging.exception("Some exception")

or
sys.exit(1)

The problem starts when script fails with unhandled exception. SQL Agent in this case catches the output, writes stack trace to internal msdb table and doesn't output anything to log files (and as result to Filebeat + Elastic).
Have you ever faced such thing? How to duplicate/keep this error in log file?

A: Answer:
SQL Agent just gets sys.stderr output.
You need either override sys.stderr or use sys.excepthook with custom function.


text:
Q: javascript forEach - same code acts differently on chrome windows / IOS let { classList } = document.body;

classList.forEach((className) => {
    if (className.startsWith('somePrefix')) {
        classList.remove(className);
    }
});

The above code will run just fine on non-IOS browsers, but will fail with:
TypeError: Cannot read property 'startsWith' of undefined
on IOS browsers (tested on iphone 6s IOS 10 Safari and Chrome), in case one class or more is removed.
It happens because on non-IOS browsers, once you remove an element during iteration it will know to reduce the number of iterations by 1, whereas on IOS it'll try to continue with the original number of iterations with undefineds.
I'm not looking for a solution (very easy to solve) but for an explanation of why it happens, what is implemented differently on IOS and how? (could be forEach, classList.remove, etc)
Thanks.


text:
Q: Does this follow a binomial distribution? Q. Four roads start from a junction. Only one of them leads to a mall. The remaining roads ultimately lead back to the starting point. A person not familiar with these roads wants to try the different roads one by one to reach the mall. What is the probability that his second attempt will be correct?
My Answer: Let X be the random variable where his second attempt will be correct. So $X\sim BIN(n=4, p=1/4)$ . Does this makes sense? If so, then I'll have
$P(X=2) = f(2) = \left(\begin{array}{c}4\\ 2\end{array}\right)\ (\frac{1}{4})^2(\frac{3}{4})^2 = 27/128$
Am I doing it right?

A: So, I will explain a solution that does not introduce a binomial random variable. Concretely, there is only one road that will lead him to the mall and three other roads that will not lead him to the mall, but back to the starting position.
The problem is asking: what is the probability $A$ that in his first attempt, he chooses one of these three incorrect roads and in his second attempt he chooses the one correct road.
So, the probability that he chooses an incorrect road is $\dfrac{3}{4}$ and the probability that he chooses a correct road after choosing an incorrect road is $\dfrac{1}{3}$.
So, $P(A)=\dfrac{3}{4}\cdot\dfrac{1}{3}=\dfrac{1}{4}$
Imagine if we wanted to extend this question to the case when he forgets about the road that he chooses. Suppose that we want to find the probability that he finds the correct road in his third attempt. Then, $P(A)=\left(\dfrac{3}{4}\right)^2\cdot\dfrac{1}{4}$ because he has to fail twice before choosing the correct road.
What are these probabilities resembling? Well, since, in this case, if he were to choose the correct road in the $n$th attempt, then $P(A)=\left(\dfrac{3}{4}\right)^{n-1}\cdot\dfrac{1}{4}$. This probability would resemble a geometric distribution because it involves him failing a certain number of times before succeeding.

A: Presumably the traveler won't choose the same road again on his second try, so this is sampling without replacement. For the second choice to be correct, the first has to be incorrect, so the probability is, assuming that the choices are uniformly distributed, $\frac34\cdot\frac13=\frac14$.


text:
Q: Fail to assign *IO() object to WRITEDATA, pycurl Anyone else noticed that the pycurl example doesn't work on Python 2.*?
import pycurl
from StringIO import StringIO

buffer = StringIO()
c = pycurl.Curl()
c.setopt(c.URL, 'http://pycurl.sourceforge.net/')
c.setopt(c.WRITEDATA, buffer)
c.perform()
c.close()

body = buffer.getvalue()
# Body is a string in some encoding.
# In Python 2, we can print it without knowing what the encoding is.
print(body)

Then I get a failure like this
Traceback (most recent call last):
  File "./get_python2.py", line 9, in <module>
    c.setopt(c.WRITEDATA, buffer)
TypeError: invalid arguments to setopt

Assigning WRITEFUNCTION & others seem to function as advertised. Anyone know what's going on here?

A: I think the docs kind of indicate you have to use WRITEFUNCTION when you don't have a true file object:

On Python 3 and on Python 2 when the value is not a true file object, WRITEDATA is emulated in PycURL via WRITEFUNCTION.

So you'd need to use:
c.setopt(c.WRITEFUNCTION, buffer.write)

Edit:
The PycURL Quickstart uses WRITEDATA as an example with StringIO, but it requires PycURL >= version 7.19.3:

As of PycURL 7.19.3 WRITEDATA accepts any Python object with a write method

A: Try
    c.setopt(c.WRITEFUNCTION, buffer.write)
I had exactly the same problem and it worked this way.
pycurl (7.19.0)


text:
Q: How to get "\n" as an input and cout as new line I want to get the string "hello \n world" as an input, and cout the \n in the string as a new line. When I write \n in the terminal, it can compile as a new line.
#include <iostream>
using namespace std;

int main(){
    string st;
    getline(cin, st);
    return 0;
}

A: When you pass "\n" as a console input, it is considered as two separate characters - '\' and 'n'.
To achieve what you want, you will need to replace these two characters with new-line character manually.
You can achieve that like this:
#include <iostream>
#include <string>

int main(int argc, char** argv) {

    std::string line;
    std::getline(std::cin, line);

    // find the index where "\n" sequence starts
    const size_t index = line.find("\\n");
    // from there, replace two chars (size of the sequence)
    // with new string - containing only '\n' character
    std::cout << line.replace(index, 2, "\n");

}

When executed, this will be the output (with first line being the input):
hello \n world
hello
 world

This behavior can be simply generalized in creating a function, which takes string, sought sequence and replacing sequence as parameters and returns new string with replaced sequence. Something like:

std::string replace_sequence_in_with(const std::string& line,
                                     const std::string& sequence,
                                     const std::string& replaceWith) {
    const auto index = line.find(sequence);
    if (index == std::string::npos) {
        throw std::invalid_argument("Subsequence " + sequence + " not found.");
    }
    return line.replace(index, sequence.size(), replaceWith);
}


text:
Q: Set persistent notification for certain app The problem: I recieve skype messages while afk and I don't notice the little orange dot in the trayicon when I'm back.
The question: I'd like to make Skype's notifications persistent on screen (until I dismiss them) so that I don't miss them. Is it possible to make notifications sent by apps persistent?
I'm on: Ubuntu 18.04 LTS using Skypeforlinux (Skype version 8.22.0.2)
Any other solution to make me notice skype's notifications (like make blinking dock icon) is welcomed
P.S. it is not a duplicate of older similar question since those refer to a different skype version that didn't used the system notification by default. Now it does and it isn't possible to customize it anymore (I was used to setup a messagebox whenever a message from a new chat was sent)

A: I use Grown-up notifications
combined with Permanent notifications extensions to solve your same problem. (:

A: You can have persistent notifications  simply by turning on "permanent notifications" in Tweaks application.
To install tweaks:
sudo apt update
sudo apt install gnome-tweaks

To install the gnome extensions:
sudo apt install gnome-shell-extensions

Then press Super key, search for tweaks & turn on permanent notifications option in it.
For detailed procedure to install tweaks: https://linuxhint.com/installing_gnome_extensions_ubuntu/


text:
Q: Image filesize becomes bigger after Upload (PHP, Joomla) When I upload an Image with Joomla the .jpg has a much bigger filesize on the server than it had when it was on my harddrive. It usually is about 2-3 times bigger, although the dimensions are the same or smaller. Of course this is not good for the performance of the website. I could imagine that some library changes the compression of the image but I don't know where to start looking.
I use Joomla 3 and PHP 5.4 on an Apache Webserver.
Thanks for your help!