text:
Q: Object reading from file, violation of SRP? I am writing a physics simulation program in C++. I am a novice in OOP and C++.
In my program, several objects need to be initialized based on data from an input file.
For example, an imaginary input file:
# Wind turbine input file:
number_of_blades = 2
hub_height = 120

# Airfoil data:
airfoil1 = { chord = 2, shape = naca0012}
airfoil2 = { chord = 3, shape = naca0016}

For this example, lets say I have a Turbine class and an Airfoil class. Airfoil objects need to know their chord and their shape, and the turbine object needs to know the height and number of blades.
Should I do this so that each object can build itself from an input file?
e.g.:
class Turbine {
 public:
    Turbine(File input_file);  // reads input file to get the number of blades
 private:
    int num_blades_;
    double height_;
};

or should it be done with a free function:
Turbine create_turbine_from_file(File input_file)
{
    Turbine t;
    t.set_num_blades(input_file.parse_num_blades());
    t.set_height(input_file.parse_height());
    return t;
};

class Turbine {
 public:
    Turbine();

    void set_height();
    void set_num_blades();

 private:
    int num_blades_;
    double height_;
};

What are the advantages disadvantages of each method? Is there a better way?

A: First of all, congratulations for taking programming a step further and wondering about how to do it better (and for asking a good question).  It's a great attitude and absolutely necessary to take your programs a step further.  Kudos!
What you're dealing with here is a problem related to your program's architecture (or design, depending on who you ask).  It's not so much about what it does, but how it does it (i.e. the structure of your program instead of its functionality).  It's very important to be clear about this: you could totally make those classes take File objects as input, and your program could still work.  If you went a step further and added all the exception handling code and took care of edge cases related to files and I/O (which should be done somewhere) in those classes (...but not there), and they became a hodgepodge of I/O and domain logic (domain logic means logic related to the actual problem you're trying to solve), your program could "work".  The goal, if you plan on making this more than a simple, one-off thing, should be that it work properly, meaning that you can change parts of it without affecting others, fix bugs as they surface and hopefully extend it without too much difficulty when and if you find new features and use cases you want to add.
OK, now, the answer.  First: yes, using Files as method parameters in the Turbine class violates the SRP.  Your Turbine and Airfoil classes should not know anything about files.  And, yes, there are better ways to do it.  I'll talk you through one way I would do it first and then go into more detail about why it's better later.  Remember, this is only an example (not really compilable code, but a sort of pseudocode) and one possible way to do it.
// TurbineData struct (to hold the data for turbines)

struct TurbineData
{
    int number_of_blades;
    double hub_height;
}

// TurbineRepository (abstract) class

class TurbineRepository
{
    // Defines an interface for Turbine repositories, which return Vectors of TurbineData structures.
    public:
        virtual std::Vector<TurbineData> getAll();
}

// TurbineFileRepository class

class TurbineFileRepository: public TurbineRepository
{
    // Implements the TurbineRepository "interface".
    public:
        TurbineRepository(File inFile);
        std::Vector<TurbineData> getAll();
    private:
        File file;
}

TurbineFileRepository::TurbineFileRepository(File inFile)
{
    // Process the File and handle everything you need to read from it
    // At some point, do something like:
    // file = inFile
}

std::Vector<TurbineData> TurbineFileRepository::getAll()
{
    // Get the data from the file here and return it as a Vector
}

// TurbineFactory class

class TurbineFactory
{
    public:
        TurbineFactory(TurbineRepository *repo);
        std::Vector<Turbine> createTurbines();
    private:
        TurbineRepository *repository;
}

TurbineFactory::TurbineFactory(TurbineRepository *repo)
{
    // Create the factory here and eventually do something like:
    // repository = repo;
}

TurbineFactory::createTurbines()
{
    // Create a new Turbine for each of the structs yielded by the repository

    // Do something like...
    std::Vector<Turbine> results;

    for (auto const &data : repo->getAll())
    {
        results.push_back(Turbine(data.number_of_blades, data.hub_height));
    }

    return results;
}

// And finally, you would use it like:

int main()
{
    TurbineFileRepository repo = TurbineFileRepository(/* your file here */);
    TurbineFactory factory = TurbineFactory(&repo);
    std::Vector<Turbines> my_turbines = factory.createTurbines();
    // Do stuff with your newly created Turbines
}

OK, so, the main idea here is to isolate, or hide, the different parts of the program from each other.  I especially want to isolate the core part of the program, where the domain logic is (the Turbine class, which actually models and solves the problem), from other details, such as storage.  First, I define a TurbineData structure to hold the data for Turbines that comes from the outside world.  Then, I declare a TurbineRepository abstract class (meaning a class that cannot be instantiated, only used as parent for inheritance) with a virtual method, that basically describes the behavior of "providing TurbineData structures from the outside world".  This abstract class can also be called an interface (a description of behavior).  The TurbineFileRepository class implements that method (and thus provides that behavior) for Files.  Lastly, the TurbineFactory uses a TurbineRepository to get those TurbineData structures and create Turbines:
TurbineFactory -> TurbineRepo -> Turbine // with TurbineData as a means of passing data.

Why am I doing it this way?  Why should you separate file I/O from the inner workings of your program?  Because the two main goals of the design or architecture of your programs are to reduce complexity and to isolate change.  Reducing complexity means making things as simple as possible (but not simpler) so that you can reason about the individual parts properly and separately:  when you're thinking about Turbines, you shouldn't have think about the format in which the files that contain the turbine data are written, or whether the File you're reading is there or not.  You should be thinking about Turbines, period.
Isolating change means that changes should affect the least possible amount of places in the code, so that the chances that bugs happen (and the possible areas where they can happen after you change the code) are reduced to the absolute minimum.  Also, things that change often, or are likely to change in the future, should be separate from the things that aren't.  In your case, for example, if the format in which Turbine data is stored in the files changes, there should be no reason for the Turbine class to change, only classes like TurbineFileRepository.  The only reason Turbine should change is if you added more sophisticated modeling to it, or the underlying physics changed (which is considerably less likely than the file format changing), or something similar.
The detail of where and how the data is stored should be handled separately by classes, such as TurbineFileRepository, that will, consequently, have no idea about how Turbines work, or even why the data they provide is needed.  These classes totally should implement I/O exception handling, and all the kind of boring and incredibly important stuff that happens when your program talks to the outside world, but they should not go beyond that.  The function of TurbineRepository is to hide from TurbineFactory all those details and only provide it with a vector of data.  It's also what TurbineFileRepository implements so that no details about it need be known to whoever wants to use TurbineData structures.  As a nice possible feature change, imagine you wanted to store turbine and airfoil data in a MySQL database.  For that to work, all you'd need to do is implement a TurbineDatabaseRepository and plug it in.  Nothing more.  Cool, huh?
Best of luck with your programming!

A: It should normally be implemented as a free function. That function should normally be named operator>> and take two arguments: in istream and a reference to a Turbine (and return the istream that was passed to it). In a typical case, it'll be a friend of the class, since it needs to be able to directly manipulate internals that (in many cases) the outside world shouldn't touch (directly).
class Turbine {
    // ...

    friend std::istream &operator>>(std::istream &is, Turbine &t) {
        // Simplifying a bit here, but you get the idea.
        return is >> t.num_blades_ >> t.height_;
    }
};

This not only satisfies SRP, but makes the class work with the rest of the standard library. For example, if you wanted to read a file full of specifications of Turbines (not just one), you could do something like this:
std::ifstream in("Turbines.txt");

std::vector<Turbine> turbines {
    std::istream_iterator<Turbine>(in),
    std::istream_iterator<Turbine>()
};


text:
Q: Extending Javascript objects with CoffeeScript I want to add the ability to extend javascript objects by adding a method to the prototype.
The method will receive one or more other objects and will add all of the key/values to this.
This is what I came up with:
Object::extend = (objects...) ->
    @[key] = value for key, value of object for object in objects

or this:
Object::extend = (objects...) ->
    for object in objects
        for key, value of object
            @[key] = value

Both work as expected, and compile into the same javascript code:
var __slice = [].slice;

Object.prototype.extend = function() {
  var key, object, objects, value, _i, _len, _results;
  objects = 1 <= arguments.length ? __slice.call(arguments, 0) : [];
  _results = [];
  for (_i = 0, _len = objects.length; _i < _len; _i++) {
    object = objects[_i];
    _results.push((function() {
      var _results1;
      _results1 = [];
      for (key in object) {
        value = object[key];
        _results1.push(this[key] = value);
      }
      return _results1;
    }).call(this));
  }
  return _results;
};

What I'm not too happy about is the whole results thing that is created per for loop which is completely redundant for my purpose.
Is there a way to get a code more like:
Object.prototype.extend = function() {
  var key, object, objects, value, _i, _len;
  objects = 1 <= arguments.length ? __slice.call(arguments, 0) : [];
  for (_i = 0, _len = objects.length; _i < _len; _i++) {
    object = objects[_i];
    (function() {
      for (key in object) {
        value = object[key];
        this[key] = value;
      }
    }).call(this);
  }
};

Thanks.

Edit
I'm aware that I can simply embed javascript code, but looking for a coffeescript solution.

A: You can try adding an explicit return:
Object::extend = (objects...) ->
    for object in objects
        for key, value of object
            @[key] = value
    return

That produces this:
var __slice = [].slice;

Object.prototype.extend = function() {
  var key, object, objects, value, _i, _len;
  objects = 1 <= arguments.length ? __slice.call(arguments, 0) : [];
  for (_i = 0, _len = objects.length; _i < _len; _i++) {
    object = objects[_i];
    for (key in object) {
      value = object[key];
      this[key] = value;
    }
  }
};

Every CoffeeScript function returns the value of the last expression in the function, CoffeeScript loops are also expressions. That means that CoffeeScript has to build all that _results stuff to produce a return value for your function since you had an implicit return applying to the outer loop. If you remove that implicit return by adding an explicit "return nothing" then the CS→JS compiler seems to be smart enough to not do all that extra _results work.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Open window in WPF asynchronously I have this class that allows only one instance per window stolen from other stackoverflow question:
public static class WindowManager
    {
        public static T GetWindow<T>()
        {
            var t = Application.Current.Windows.OfType<T>().FirstOrDefault();
            if (t == null)
            {
                t = (T)Activator.CreateInstance(typeof(T));
            }
            return t;
        }

        public static T CreateOrFocusWindow<T>()
        {
            var t = GetWindow<T>();
            if (t is Window)
            {
                var window = t as Window;
                if (window.Visibility != Visibility.Visible)
                    window.Show();
                if (window.WindowState == WindowState.Minimized)
                    window.WindowState = WindowState.Normal;
                window.Focus();
            }
            return t;
        }
    }

And now I want to open new window:
private async void Button_OnClick(object sender, RoutedEventArgs e)
        {
            LoadingOn(); //enables progress ring etc
            await Task.Run(() =>
            {
                Dispatcher.Invoke(() =>
                {
                    WindowManager.CreateOrFocusWindow<Window1>();
                });
            });
            LoadingOff(); //disables progress ring etc
        }

But the problem is that UI is locked anyway (constructor of window contains long operation). I don't have any ideas how to bypass it.
There might be a way to simply first create instance of the window, and then call long operation not from constructor, but from OnLoading event, but its completely different approach that requires adding loading spinner to every new window. I just want to open new window when data is ready without nuking the way my code currently works. It looks like its impossible, but I'm not master of C# and WPF yet.


text:
Q: Center of Ossanna Circle The Ossanna circle is given by all points that $I = \dfrac{U_1}{R_1 + jX_1 + \dfrac{X_h^2}{jX_2 + \dfrac{R_2}{s}}}$ will reach (in the complex plane) while the parameter s goes from negative infinity to positve infinity.
Only $s$ is variable, all other values are constants.
By drawing the location curve with tools like Matlab, one can see, that it forms a circle (Ossanna Circle know in electrical engineering).
The center of this circle is somewhere but not the origin of the coordinate system.
How can the coordinates of the center of this circle be calculated?

A: I'm converting variables to lower-case, to save space (and reduce eye strain); I'm also using "$i$" for the imaginary unit.

Begin by calculating the modulus of $I$:
$$|I|^2 = I \cdot \overline{I} =
\frac{u_1^2 \left(\;s^2 x_2^2 + r_2^2 \;\right)}{
s^2( r_1^2 x_2^2 + ( x_h^2 - x_1 x_2)^2)
+ 2 s r_1 r_2 x_h^2
+ r_2^2( r_1^2 + x_1^2) }$$
This (real) expression attains its maximum and minimum values at the endpoints of a diameter of the Ossanna circle that (extended as necessary) passes through the origin. We find the corresponding values of $s$ by checking where the numerator of the derivative (with respect to $s$) vanishes:
$$s^2 r_1 x_2^2 - s r_2 ( x_h^2 - 2 x_1 x_2 ) - r_1 r_2^2  = 0$$
$$\implies\qquad s = \frac{r_2}{2r_1 x_2^2}\left( x_h^2 - 2 x_1 x_2 \pm \sqrt{
  4 r_1^2 x_2^2 + ( x_h^2 - 2 x_1 x_2 )^2}\right)$$
The center of the Ossanna circle, as a complex number, is the average of $I$ evaluated at the two roots $s$. The radius is the modulus of the half-difference of those two values. Intermediate calculations are messy, so I'll jump right to the results:

$$\text{center} = \frac{u_1 \left(\; 2 r_1 x_2 + i ( x_h^2 - 2 x_1 x_2)\;\right)}{2
\left(\; r_1^2 x_2 + x_1^2 x_2 - x_1 x_h^2 \;\right)}
\qquad\text{radius} = \frac{u_1 x_h^2}{2 \left|\;r_1^2 x_2 + x_1^2 x_2 - x_1 x_h^2\;\right|}$$


text:
Q: tcl interpreter parameters contaminated I have a multithreaded C++ program in which the main thread creates two tcl interpreters, interp#1 and interp#2. During parallel running, the main thread and one slave thread each try to invoke different cmds through interp#1 and interp#2 seperately. At some point, memory error happens and program crashes.
The log file tells me that some value of kObjv[] for interp#1 is contaminated by that for interp#2.
I also run helgrind to check possible data races and it dumps plenty of data race risks on beneath tcl lib apis, like: Tcl_NewStringObj/TclFreeObj/ResetObjResult/TclNREvalObjv, etc.
It looks like the underlying memory is shared by interpreters from same thread. Is that true? My program links static tcl 8.6 lib, which was installed with thread enabled.

A: The Tcl library uses thread-bound memory pooling to (hugely!) reduce pressure on global locks, with the consequence that every Tcl interpreter object is also strongly bound to the thread that created it. (This is the Apartment Threading Model, if you're familiar with that.) You cannot safely use a Tcl interpreter from any other thread. If you want to have access to a Tcl interpreter in each thread, each thread should create its own interpreter and use that.
There are a few operations that allow safe inter-thread communication, specifically Tcl_ThreadQueueEvent() and Tcl_ThreadAlert(), which allow you to lodge a message for the other thread to handle when it is ready (every thread with a Tcl interpreter on it has an event queue associated with it inside the Tcl library; this is in the core of the Tcl event notifier engine).
You're recommended to use the Tcl thread package (which should be part of any good Tcl 8.6 installation and is available for older versions too) for inter-thread working in Tcl. Apart from the complexity of getting each side to know what the handle for the other thread is, it's really quite easy to use.


text:
Q: Capturing 'self' strongly in this block is likely to lead to a retain cycle I have reqest with block. But the compiler issues a warning

"Capturing 'self' strongly in this block is likely to lead to a retain
  cycle"

__weak typeof(self) weakSelf = self;
[generalInstaImage setImageWithURLRequest:[NSURLRequest requestWithURL:[NSURL URLWithString:data[@"images"][@"low_resolution"][@"url"]]] placeholderImage:[UIImage imageNamed:@"Default"] success:^(NSURLRequest *request, NSHTTPURLResponse *response, UIImage *image) {
    NSLog(@"success");
    [generalInstaImage setImage: image];
    [weakSelf saveImage:generalInstaImage.image withName:data[@"id"]];

    } failure:^(NSURLRequest *request, NSHTTPURLResponse *response, NSError *error) {
        NSLog(@"fail");
}];

I try example write like weakSelf.generalInstaImage, but then the compiler generates an error and do not compile.

A: Consider this warning:

Capturing self strongly in this block is likely to lead to a retain
  cycle

When you receive the above warning, you should review your block for:

*

*any explicit references to self; or

*any implicit references to self caused by referencing any instance variables.

Let's imagine that we have some simple class property that was a block (this will experience the same "retain cycle" warnings as your question, but will keep my examples a little simpler):
@property (nonatomic, copy) void (^block)(void);

And let's assume we had some other class property we wanted to use inside our block:
@property (nonatomic, strong) NSString *someString;

If you reference self within the block (in my example below, in process of accessing this property), you will obviously receive that warning about the retain cycle risk:
self.block = ^{
    NSLog(@"%@", self.someString);
};

That is remedied via the pattern you suggested, namely:
__weak typeof(self) weakSelf = self;

self.block = ^{
    NSLog(@"%@", weakSelf.someString);
};

Less obvious, you will also receive the "retain cycle" warning if you reference an instance variable of the class inside the block, for example:
self.block = ^{
    NSLog(@"%@", _someString);
};

This is because the _someString instance variable carries an implicit reference to self, and is actually equivalent to:
self.block = ^{
    NSLog(@"%@", self->_someString);
};

You might be inclined to try to adopt weak self pattern here, too, but you can't. If you attempt the weakSelf->_someString syntax pattern, the compiler will warn you about this:

Dereferencing a __weak pointer is not allowed due to possible null value caused by race condition, assign it to strong variable first

You therefore resolve this by using the weakSelf pattern, but also create a local strong variable within the block and use that to dereference the instance variable:
__weak typeof(self) weakSelf = self;

self.block = ^{
    __strong typeof(self) strongSelf = weakSelf;

    if (strongSelf) {
        NSLog(@"%@", strongSelf->_someString);

        // or better, just use the property
        //
        // NSLog(@"%@", strongSelf.someString);
    }
};

As an aside, this creation of a local strong reference, strongSelf, inside the block has other advantages, too, namely that if the completion block is running asynchronously on a different thread, you don't have to worry about self being deallocated while the block is executing, resulting in unintended consequences.
This weakSelf/strongSelf pattern is very useful when dealing with block properties and you want to prevent retain cycles (aka strong reference cycles), but at the same time ensuring that self cannot be deallocated in the middle of the execution of the completion block.
FYI, Apple discusses this pattern in the "non-trivial cycles" discussion further down in the Use Lifetime Qualifiers to Avoid Strong Reference Cycles section of the Transitioning to ARC Release Notes.

You report that you received some "error" when you referenced weakSelf.generalInstaImage in your example. This is the correct way to resolve this "retain cycle" warning, so if you received some warning, you should share that with us, as well as show us how you declared the property.

A: Use __unsafe_unretained typeof(self) weakSelf = self


text:
Q: Understanding git behavior on a checkout; expected an error on a checkout but did not get one My question is on git behavior on checkout and here are the steps to elucidate the behavior I do not understand. I make a dir testdir with files foo and bar each with a single line of text. I do the following:

git init
git add .
git commit
git branch bug

So I have the master branch and an identical bug branch. In master I add a line of text to file foo but do NOT add or commit to master, just a file change on my local tree. Next I do:

git checkout bug

I was expecting to get the following error:

   error: Your local chages to the following file would be overwritten by checkout:
     foo
  Please commit your changes or stash them before you can switch branches.

But I did NOT get the above error, and my question is how come git did not error in this case? Instead I got the following:

  root@revision-control ~/testdir# git checkout bug
  M       foo
  Switched to branch 'bug'

I am in now the bug branch but the foo file has that second line I added when I was in master.
Can anyone explain what happened here and why git let me change branches without the error message? And there are no merge conflict indicators in the file.
Next I change back to the master branch and add then commit the change to the foo file (so master file foo has 2 lines and bug foo has one line). I make a change to foo in master and add a third line of text and now when I try to checkout the bug branch (same git command as above) I get:

user@host ~/testdir# git checkout bug
error: Your local changes to the following files would be overwritten by checkout:
        foo
Please, commit your changes or stash them before you can switch branches.
Aborting

So why is this behavior now different than before and I get the error? (this is the behavior I was expecting initially).

A: According to documentation for git checkout:
git checkout <branch>
Local modifications to the files in the working tree are kept, so that they can be committed to the <branch>.

Switching between branches should be treated as applying patch that represents the difference between them.
In your first case there was no difference.
In you second case there was conflict that checkout command doesn't even try to resolve.

A: I've read that one of the solutions is to remove the files(rm) and then perform a checkout. Otherwise you could also, add and stash them.
forcing the checkout like:
git checkout --force master

could be another option.
Have you tried this link GIT - Fail to checkout to other branch when nothing to commit - when file is in gitignore? Perhaps this can help you further as well.


text:
Q: Grails 3.x Failure bootRun I'm trying to run a project in grails 3.1.11 but i've a error.
FAILURE: Build failed with an exception.

*

*What went wrong:
Execution failed for task ':bootRun'.

Process 'command 'C:\Program Files\Java\jdk1.8.0_111\bin\java.exe'' finished with non-zero exit value 1

*Try:
Run with --stacktrace option to get the stack trace. Run with --info or --debug option to get more log output.

Caused by: java.net.BindException: Address already in use: bind   at
  sun.nio.ch.Net.bind0(Native Method)   at
  sun.nio.ch.Net.bind(Net.java:433)     at
  sun.nio.ch.Net.bind(Net.java:425)

This is my build.gradle
buildscript {
    ext {
        grailsVersion = project.grailsVersion
    }
    repositories {
        mavenLocal()
        maven { url "https://repo.grails.org/grails/core" }
    }
    dependencies {
        classpath "org.grails:grails-gradle-plugin:$grailsVersion"
        classpath "com.bertramlabs.plugins:asset-pipeline-gradle:2.8.2"
        classpath "org.grails.plugins:hibernate4:5.0.10"
    }
}

version "0.1"
group "sias"

apply plugin:"eclipse"
apply plugin:"idea"
apply plugin:"war"
apply plugin:"org.grails.grails-web"
apply plugin:"org.grails.grails-gsp"
apply plugin:"asset-pipeline"

ext {
    grailsVersion = project.grailsVersion
    gradleWrapperVersion = project.gradleWrapperVersion
}

repositories {
    mavenLocal()
    maven { url "https://repo.grails.org/grails/core" }
}

dependencyManagement {
    imports {
        mavenBom "org.grails:grails-bom:$grailsVersion"
    }
    applyMavenExclusions false
}

dependencies {
    compile "org.springframework.boot:spring-boot-starter-logging"
    compile "org.springframework.boot:spring-boot-autoconfigure"
    compile "org.grails:grails-core"
    compile "org.springframework.boot:spring-boot-starter-actuator"
    compile "org.springframework.boot:spring-boot-starter-tomcat"
    compile "org.grails:grails-dependencies"
    compile "org.grails:grails-web-boot"
    compile "org.grails.plugins:cache"
    compile "org.grails.plugins:scaffolding"
    compile "org.grails.plugins:hibernate4"
    compile "org.hibernate:hibernate-ehcache"
    console "org.grails:grails-console"
    profile "org.grails.profiles:web"
    runtime "com.bertramlabs.plugins:asset-pipeline-grails:2.8.2"
    runtime "com.h2database:h2"
    testCompile "org.grails:grails-plugin-testing"
    testCompile "org.grails.plugins:geb"
    testRuntime "org.seleniumhq.selenium:selenium-htmlunit-driver:2.47.1"
    testRuntime "net.sourceforge.htmlunit:htmlunit:2.18"
}

assets {
    minifyJs = true
    minifyCss = true
}

Anyone to help me?? Thanks.

A: I recently faced such problem in GRAILS 3.x version. You can overcome this problem by following these procedures.
Step 1
Stop your application by stop-app  command in cmd or replace run-app command by stop-app  command through 'edit configuration' window
Step 2
Then change the GRAILS default http '8080' port to any customs port, like '8090'. For changing default port you should go

grails-app[main]--> conf-->application.yml

In application.yml file you just keep this under all the code of this file.
server:
  port: 8090

Step 3
Then run your application by run-app command replacing stop-app command through 'edit configuration' window or cmd
Here, stop-app command is needed because application cached the previous command with default environment. When you change something then it doesn't make any sense in application. So, by "stop-app" command it kills all previous process, erases cached.


text:
Q: General solution for relative ~path to absolute url? I have a Uri instance from some request.
And I've got "~/Pages/SomePage.aspx".
var uri = new Uri("http://www.contoso.com/");
var relativeUrl = "~/Pages/SomePage.aspx";

How do I combine the two easily?
What's the context, you may ask? It's a console application where the Uri and the tilde relative path are manually constructed (that's actually a lie to get a "General solution", and not an Page.Resolve, etc. one).
I tried a few things (IE: HttpStyleUriParser) but I didn't get the right result. And I don't want to String.Format("{0}://{1}{2}{3}") my way there.

A: The tilde character ~is used in *nix systems for home directory of currect user.
In a .Net/C#/Windows application you must replace it by current user's home directory.

A: This works for me:
static class Program
{
    static void Main(string[] args)
    {

        var uri = new Uri("http://www.contoso.com/");
        var relativeUrl = new Uri("~/Pages/SomePage.aspx".Replace("~",string.Empty),UriKind.Relative);
        Uri result;
        bool success = Uri.TryCreate(uri, relativeUrl,out result);

        Console.WriteLine(success);
        Console.WriteLine(result.ToString());
    }

}

Output:

True
http://www.contoso.com/Pages/SomePage.aspx


text:
Q: Setting some css properties according to variables I want to add a variable to a css class. Is it possile? I mean I want to do something like the following:
#box[i]
{
   padding: [i]px;
}

(for example: div which is name "box10" is supposed to get padding of 10px.)
I understand this may not be the right syntax, but I hope you can help me achieve the concept setting my class' properties up to a variable value.

A: It's currently not possible to use variables within CSS, however there are a number of other options available.

*

*The simplest option would be to create a CSS style for each of your box IDs.

*You could use JavaScript to add padding to the box, but it is not sensible to include presentation within logic. In jQuery, a loop to do this would look like (assuming your boxes are ):
$('div[id^=box]').each(function() {
    $(this).css('padding',this.id.substr(3)+'px');
});

*You could use a pre-processor tool, such as LESS to set variables in your CSS; but you would still need to specify each selector.
Setting padding based on different box ID values seems like an odd problem to have. It may be worth taking a look at whether your approach to building this page is correct. Don't forget every ID on the page should be unique. If you wish to use the same ID on multiple elements, you should use CSS classes.
If you are trying to create a box sized based on a number of results (such as poll results), then it would be easier to use the style attribute and set a width/padding on each element rather than create an ID for every possible outcome. For example:

A: No, you can't do that with pure CSS, but you can use less for that.
CSS variables are introduced only in W3C draft at this point and didn't supported by browsers yet.

A: u could just use javascript, to detect the "name" and then get the substring so u have the number. then just make something like this:
var box = document.getElementByName("box10");
box.style.padding = box.name.substr(3) + "px";


text:
Q: How to close a asyncio(http) connection in Python 3.7+ How do you close a asyncio loop in Python 3.7+ ? (I'm new to asynchronous programming especially py 3.7+)
I know it's closed using this inthe previous versions.
loop= asyncio.get_event_loop()
loop.run_until_complete(main())
loop.close()

But now that we've got the new Python. I've searched several pages to see how the closure of a connection is established in Py 3.7+. but nothing satisfied me.
Could anyone tell me how the closure of a loop is done in the new version?
asyncio.run(main)

**now how do we close this connection? or is it done by itself?**
asyncio.close() ?

Also, if we are not closing the loop...won't be get 'Runtime Error: Event loop is closed' error?


text:
Q: AAR is no longer being generated with Android Plug in 3.0.0 My app is setup to build a generic main aar that is included in individual customer apps.
Previously the aar would appear at
/{library_name}/build/outputs/aar/core-release.aar
Here is the gradle file for the entire project
buildscript {
    repositories {
        jcenter()
        google()
    }
    dependencies {
        classpath 'com.android.tools.build:gradle:3.0.0'
    }
}

allprojects {
    repositories {
        jcenter()

        maven {
            credentials {
                username ''
                password ''
            }

            url 'https://artifactory.*.com/artifactory/*-libs/'

        }
        google()
    }
}

Here is the gradle for the library that should be generating an aar
apply plugin: 'com.android.library'

dependencies {
    implementation project(':AndroidAsync')
    implementation project(':simplezxing')

    implementation('org.apache.httpcomponents:httpmime:4.5.1') {
        exclude module: "httpclient"
    }
    implementation 'net.danlew:android.joda:2.9.+'
    implementation 'com.squareup.picasso:picasso:2.5.2'
    implementation 'com.google.android.gms:play-services-location:9.0.2'
    implementation 'com.google.android.gms:play-services-gcm:9.0.2'
    implementation 'com.google.android.gms:play-services-maps:9.0.2'
    implementation 'com.android.support:support-v13:25.3.0'

    implementation 'com.jakewharton:butterknife:8.8.1'
    annotationProcessor 'com.jakewharton:butterknife-compiler:8.8.1'

}

android {
    compileSdkVersion 21
    buildToolsVersion '26.0.2'

    defaultConfig {
        multiDexEnabled false
        minSdkVersion 18
        targetSdkVersion 21
        versionCode 1604020110 //Last two digits are build type 0 = Developer, 1 = Development, and 5 rc and 10 for release
        versionName "4.2.1"
    }

    signingConfigs {
        debug {
            storeFile file("keystores/debug.keystore")
        }

        release {
            storeFile file("keystores/*-android.keystore")
            storePassword ""
            keyAlias ""
            keyPassword ""
        }
    }

    lintOptions {
        abortOnError false
    }

    packagingOptions {
        exclude     'META-INF/DEPENDENCIES'
        exclude     'META-INF/LICENSE'
        exclude     'META-INF/LICENSE.txt'
        exclude     'META-INF/NOTICE'
        exclude     'META-INF/NOTICE.txt'
    }

    dexOptions {
        jumboMode true
        javaMaxHeapSize "4g"
    }

    compileOptions {
        sourceCompatibility JavaVersion.VERSION_1_7
        targetCompatibility JavaVersion.VERSION_1_7
    }
}

I did remove some company specific info.
The rest of my build is working fine on jenkins but the aar is just not present as expected.
edit
This builds the aar correctly when I build my jenkins by branch which uses
./gradlew clean build
If I build by product flavor it doesn't build the aar, this uses
./gradlew clean assemble{flavor}


text:
Q: Entity Framework error: The ForeignKeyAttribute on property is not valid I receive error then trying to add AgendaType to database context:

An unhandled exception of type 'System.InvalidOperationException' occurred in EntityFramework.dll
  Additional information: The ForeignKeyAttribute on property 'AgendaType' on type 'MyDb.Agendum' is not valid. The foreign key name 'FK_Agenda_AgendaType' was not found on the dependent type 'MyDb.Agendum'. The Name value should be a comma separated list of foreign key property names.

[Table("AgendaType")]
public partial class AgendaType
{
    [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2214:DoNotCallOverridableMethodsInConstructors")]
    public AgendaType()
    {
        Agenda = new HashSet<Agendum>();
    }

    [Key]
    [DatabaseGenerated(DatabaseGeneratedOption.Identity)]
    public int Id { get; set; }

    [Required]
    [StringLength(2)]
    [Index("IX_AgendaType_Code", 1, IsUnique = true)]
    public string Code { get; set; }

    [Required]
    [StringLength(50)]
    public string Name { get; set; }

    [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly")]
    public virtual ICollection<Agendum> Agenda { get; set; }
}

public partial class Agendum
{
    [Key]
    [DatabaseGenerated(DatabaseGeneratedOption.Identity)]
    public int Id { get; set; }

    public int AgendaTypeId { get; set; }

    [ForeignKey("FK_Agenda_AgendaType")]
    public virtual AgendaType AgendaType { get; set; }
}

However I specified foreign key on property AgendaType, as in provided database scheme. What is incorrect?

A: EDIT: After OP's comments, I dug up a little more.
According to DataAnnotations explanation, [ForeignKey] can be indeed applied to the navigation property or the key property, but not both at the same time (examples in the provided link explain the usage). You should only use the attribute if the name of the foreign key is different than the convention. Do note, that when doing:
[ForeignKey("FK_Agenda_AgendaType")]
public virtual AgendaType AgendaType { get; set; }

then the int foreign key property should be:
public int FK_Agenda_AgendaType { get;set; }

Older parts of the post, kept here to document the history of discussion:
You have to put the [ForeignKey("FK_Agenda_AgendaType")] on the AgendaTypeId property, like this:
[ForeignKey("FK_Agenda_AgendaType")]
public int AgendaTypeId { get; set; }

EDIT: Seems like the ForeignKey name should be different:
[ForeignKey("FK_AgendaType")]
public int AgendaTypeId { get; set; }


text:
Q: Add a simple route I'm trying to add a route that shows some data based on a string parameter like this:
http://whatever.com/View/078x756

How do I create that simple route and where to put it?

A: In your global.asax.cs file, you add the following lines:
routes.mapRoute(
    // The name of the new route
    "NewRoute",

    // The url pattern
    "View/{id}",

    // Defaulte route data
    new { controller = "Home", action = "Index", id = "078x756" });

Make sure you add them before the registration of the default route - the ASP.NET MVC Framework will look throught the routes in order and take the first one that matches your url. Phil Haack's Routing Debugger is a valuable tool when troubleshooting this.

A: Routes are usually configured in the Application_Start method in Global.asax. For your particular case you could add a route before the Default one:
routes.MapRoute(
    "Views",
    "View/{id}",
    new
    {
        controller = "somecontroller",
        action = "someaction",
        id = ""
    }
);

routes.MapRoute(
    "Default",
    "{controller}/{action}/{id}",
    new
    {
        controller = "home",
        action = "index",
        id = ""
    }
);

A: Routes are added in the global.asax.cs
Example of adding a route:
namespace MvcApplication1
{
    // Note: For instructions on enabling IIS6 or IIS7 classic mode,
    // visit http://go.microsoft.com/?LinkId=9394801

    public class MvcApplication : System.Web.HttpApplication
    {
        public static void RegisterRoutes(RouteCollection routes)
        {
            routes.IgnoreRoute("{resource}.axd/{*pathInfo}");

            routes.MapRoute(
                "Default",                                              // Route name
                "{controller}/{action}/{id}",                           // URL with parameters
                new { controller = "Home", action = "Index", id = "" }  // Parameter defaults
            );

            routes.MapRoute(
               "WhatEver"
               "{View}/{id}",
               new {controller = "Home","action = "Index", id="abcdef"}
            );

        }

        protected void Application_Start()
        {
            RegisterRoutes(RouteTable.Routes);
        }
    }
}
}


text:
Q: python: upload file via sftp from behind a socks5 proxy I am trying to look for any sample code that would allow me to upload a file via sftp to a remote machine, with the condition we are behind a SOCKS5 Proxy.
I am trying to figure out if using paraproxy would do the job.


text:
Q: Why when update dictionary in python I want to create a dictionary   with {k:[list]} where k value of i
for the first iteration, it works but  {3:[20,20,20]} but when increase and added to the dictionary
{3:[20,20,20,20],4:[20,20,20,20]} instead of  {3:[20,20,20],4:[20,20,20,20]} and goin
{3:[20,20,20,20,20],4:[20,20,20,20,20],5:[20,20,20,20,20]} instead of
{3:[20,20,20],4:[20,20,20,20],5:[20,20,20,20,20]}
d0 = 20
tempsq=[]
c=[]
anon={}
minm=0
for i in range(3,len(sq)):
    if i<2*kd:
        # print(i)
        cost=compute_I(sq[0:i])
        c.append(cost)
        #from hear
        tempsq.clear()
        for j in range(0,i):
             tempsq.append(d0)
        if not anon:
            anon = {i: tempsq}
            print(anon)
        else:
            anon.update({i:tempsq})
            print(anon)

print(anon)

A: From what I understand you want to create a list:
{3: [20,20,20], 4:[20,20,20,20],...}

You can achieve that running the following:
value = 20
min_iteration = 3
max_iteration = 5

{i : [value]*i for i in range(min_iteration, max_iteration+1)}

Which yields:
{3: [20, 20, 20], 4: [20, 20, 20, 20], 5: [20, 20, 20, 20, 20]}


text:
Q: Search in ArrayList using Comparator I had an interview today and I have given two java classes and asked to search dog details by registration number. I know that Java.util.ArrayList.contains(Object) but do not know how to implement when there are more than one fields.
The second question was: what is the most efficient search techniques you can use in this example? I thought about Collections.binarySearch but not sure that it is the most efficient in this example. If so, how can I implement it?
DogSort.java
public class DogSort {

public static void main(String[] args) {
    ArrayList<Dog> listDog = new ArrayList<Dog>();

    Scanner sc = new Scanner(System.in);

    listDog.add(new Dog("Max", "German Shepherd", "33"));
    listDog.add(new Dog("Gracie","Rottweiler","11"));
    Collections.sort(listDog, Dog.COMPARE_BY_NAME);
                System.out.println(listDog);
    }
}

Dog.java
class Dog {
    private String name;
    private String breed;
    private String registrationNumber;

public Dog(String name, String breed, String registrationNumber) {
        this.name = name;
        this.breed = breed;
        this.registrationNumber = registrationNumber;
    }

public static Comparator<Dog> COMPARE_BY_NAME = new Comparator<Dog>() {
        public int compare(Dog one, Dog other) {
            return one.name.compareTo(other.name);
        }
};
//getter and setter methods for all private variable

}

A: I agree with @Pritam Banerjee's answer. The most efficient search technique is to use HashMap in this scenario. I would recommend to use HashSet but the HashSet#contains method returns boolean, so just use map. Here is the code snippet.

Just for Information When using hash based collection/map dont forget to implement hashCode and equals method properly.

public class DogSearch {
    public static void main(String[] args) {
        Map<String, Dog> dogs = new HashMap<String, Dog>();

        Dog max = new Dog("Max", "German Shepherd", "1001");
        Dog gracie = new Dog("Gracie", "Rottweiler", "1002");
        Dog luca = new Dog("Luca", "Labrador", "1003");
        Dog tiger = new Dog("Tiger", "Beagle", "1004");
        Dog meemo = new Dog("Meemo", "Bulldog", "1005");
        Dog lacie = new Dog("Lacie", "German Shorthaired Pointer", "1006");

        dogs.put(max.getRegistrationNumber(), max);
        dogs.put(gracie.getRegistrationNumber(), gracie);
        dogs.put(luca.getRegistrationNumber(), luca);
        dogs.put(tiger.getRegistrationNumber(), tiger);
        dogs.put(meemo.getRegistrationNumber(), meemo);
        dogs.put(lacie.getRegistrationNumber(), lacie);

        Dog result = dogs.get("1002");

        if (result == null) {
            System.out.println("Dog not found");
        } else {
            System.out.println(result);
        }
    }
}

class Dog {
    private String name;
    private String breed;
    private String registrationNumber;

    public Dog(String name, String breed, String registrationNumber) {
        this.name = name;
        this.breed = breed;
        this.registrationNumber = registrationNumber;
    }

    public static Comparator<Dog> COMPARE_BY_NAME = new Comparator<Dog>() {
        public int compare(Dog one, Dog other) {
            return one.name.compareTo(other.name);
        }
    };

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getBreed() {
        return breed;
    }

    public void setBreed(String breed) {
        this.breed = breed;
    }

    public String getRegistrationNumber() {
        return registrationNumber;
    }

    public void setRegistrationNumber(String registrationNumber) {
        this.registrationNumber = registrationNumber;
    }

    @Override
    public int hashCode() {
        final int prime = 31;
        int result = 1;
        result = prime * result + ((breed == null) ? 0 : breed.hashCode());
        result = prime * result + ((name == null) ? 0 : name.hashCode());
        result = prime * result + ((registrationNumber == null) ? 0 : registrationNumber.hashCode());
        return result;
    }

    @Override
    public boolean equals(Object obj) {
        if (this == obj)
            return true;
        if (obj == null)
            return false;
        if (getClass() != obj.getClass())
            return false;
        Dog other = (Dog) obj;
        if (breed == null) {
            if (other.breed != null)
                return false;
        } else if (!breed.equals(other.breed))
            return false;
        if (name == null) {
            if (other.name != null)
                return false;
        } else if (!name.equals(other.name))
            return false;
        if (registrationNumber == null) {
            if (other.registrationNumber != null)
                return false;
        } else if (!registrationNumber.equals(other.registrationNumber))
            return false;
        return true;
    }

    @Override
    public String toString() {
        return "Dog [name=" + name + ", breed=" + breed + ", registrationNumber=" + registrationNumber + "]";
    }

}

Time Complexity
Insertion : O(1)
Search : O(1)

A: Add it to a HashMap with Registration as Key and Dog object as the value and then search the Map.
O(1) insertion and O(1) searching.
Binary Search O(log n).

A: For the first question ie to search details by registration number here is the code
import java.util.Comparator;
import java.util.TreeMap;

public class DogSort {

    public static void main(String[] args) {
        TreeMap<Integer, Dog> listDogs = new TreeMap<>();
        listDogs.put(33, new Dog("Max", "German Shepherd", "33"));
        listDogs.put(11, new Dog("Gracie", "Rottweiler", "11"));
        System.out.println(listDogs);
        System.out.println(listDogs.containsKey(11));
        System.out.println(listDogs.get(11));
    }
}

class Dog {
    private String name;
    private String breed;
    private String registrationNumber;

    public Dog(String name, String breed, String registrationNumber) {
        this.name = name;
        this.breed = breed;
        this.registrationNumber = registrationNumber;
    }

    public static Comparator<Dog> COMPARE_BY_NAME = new Comparator<Dog>() {
        public int compare(Dog one, Dog other) {
            return one.name.compareTo(other.name);
        }
    };

    @Override
    public String toString() {
        return "Dog [name=" + name + ", breed=" + breed + ", registrationNumber=" + registrationNumber + "]";
    }

}

It is very difficult to get the details of dog by registration number using arraylist, but with map it is quite easy.
And you can override the hashcode and equals method like this but the arraylist compare method works differently.
What you can do is you can write a method which can search details by registration number. The method will have to iterate the list and find the Dog object,and if the list is sorted then you need to implement your own binary search to get the Dog object according to the registration number.
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;

public class DogSort {

    public static void main(String[] args) {
        ArrayList<Dog> listDog = new ArrayList<Dog>();

        listDog.add(new Dog("Max", "German Shepherd", "33"));
        listDog.add(new Dog("Gracie", "Rottweiler", "11"));

        Collections.sort(listDog, Dog.COMPARE_BY_NAME);

        System.out.println(listDog);
        System.out.println(listDog.contains(new Dog("Max", "Rottweiler", "33")));
    }
}

class Dog {
    private String name;
    private String breed;
    private String registrationNumber;

    public Dog(String name, String breed, String registrationNumber) {
        this.name = name;
        this.breed = breed;
        this.registrationNumber = registrationNumber;
    }

    public static Comparator<Dog> COMPARE_BY_NAME = new Comparator<Dog>() {
        public int compare(Dog one, Dog other) {
            return one.name.compareTo(other.name);
        }
    };

    @Override
    public String toString() {
        return "Dog [name=" + name + "]";
    }

    @Override
    public int hashCode() {
        final int prime = 31;
        int result = 1;
        result = prime * result + ((registrationNumber == null) ? 0 : registrationNumber.hashCode());
        return result;
    }

    @Override
    public boolean equals(Object obj) {
        if (this == obj)
            return true;
        if (obj == null)
            return false;
        if (getClass() != obj.getClass())
            return false;
        Dog other = (Dog) obj;
        if (registrationNumber == null) {
            if (other.registrationNumber != null)
                return false;
        } else if (!registrationNumber.equals(other.registrationNumber))
            return false;
        return true;
    }

}


text:
Q: Update data two element in mongo db  {
 "Templates": [
      {
        "ProductId": "63a2b0f87a810608e6ca6d95",
        "RevisionNum": [
            "221222"
        ],
        "EffectiveDate": "2022-12-22T02:45:22.587Z",
        "HardwareVer": "A",
        "SoftwareVer": "1.0",
        "WorkTasks": [],
        "_id": "63a3c4d950b22e564d2b8dee"
     }
],
"_id": "63a3c4d950b22e564d2b8ded",
"__v": 0
}

Update data element by productId one are update value in array ["221222"] to ["111111"] in RevisionNum array other are for HardwareVer in MongoDB and Nodejs

A: You can use arrayFilters as follow:
db.collection.update({},
{
 $set: {
 "Templates.$[y].RevisionNum.$[x]": "1111",
 "Templates.$[y].HardwareVer": "B"
 }
},
{
 arrayFilters: [
 {
   x: "221222"
 },
 {
  "y.ProductId": "63a2b0f87a810608e6ca6d95"
 }
]
})

Explained:
Create two arrayFilters x & y to identify the element that you need to update.
Playground


text:
Q: run-time break error with pointer to a char array C++ - This program gives a run-time break error at line 2.
char * ptr = "hello";
(*ptr)++;            // should increment 'h' to 'i'
cout<<ptr<<endl;     // should display 'iello'

Unhandled exception at 0x004114b0 in test.exe: 0xC0000005: Access violation writing location 0x00417830.
Any idea why it is giving this error? Whereas if I run the following code, it works absolutely fine.
char arr[] = "hello";
char * ptr = arr;
(*ptr)++;           // increments 'h' to 'i'
cout<<ptr<<endl;    // displays 'iello'

A: Because you are trying to change read-only memory. There is a C FAQ which is adequate, even if this is a C++ question.
Basically when saying char *ptr = "hello" the compiler is free to place "hello" in read-only
memory so it's not safe to try to write to it.
Another C FAQ might be useful:

What is the difference between these initializations?
char a[] = "string literal";
char *p  = "string literal";

A: When you declare char * ptr = "hello";
it means ptr is pointing to a constant string
when you say ptr++ ,
You are trying to change the base address  which is not correct


text:
Q: how to integrate a spring boot application into a legacy java application and isolate it? we have a very old java web application (about 15 years old!) with servlet, Spring version 3 and ... technologies, I want to develop a rest API for this application, in order to be able to use modern technologies I decided to develop a new modern spring (boot) web application without an embedded server and bootstrap it using a new servlet that I will define in the legacy app web.xml. I also need to isolate dependencies using Java ClassLoader. it is obvious that the new app has dependencies inside the old one and I need to be able to inject them. I know this is possible (OSGI frameworks use a very similar approach). but I have some questions.
first question(s): is this a correct/sensible strategy for this task? is there any better way?
second question: where can I find some resources to study and learn in order to implement this strategy?

A: I would personally look to update your Java code to use Spring boot and build new controllers, services and new views using Thymeleaf. It may be a bit of upfront work, however, once you port your App to use Spring Boot, you will be able to manage it better.


text:
Q: Change font-size in auto-generated HTML from px to em using javascript I have an HTML generated from a web service which I cannot control.  The HTML has font sizes in px and pt. My requirement is changing all font-sizes to em.
This is what I tried :
I tried to access all <font> tags using :
document.getElementByTagName('font').style.fontSize;

However, it is returning null even though I have many font tags in HTML.
All relevant sources I read assume we have control over CSS or HTML and hence do not apply to my problem.
In short, I want to parse the HTML and find all inline style (font-size) and change from any other type to em.

A: try document.getElementsByTagName.......you are leaving out the s :)

A: If the styling is in HTML then it's inline styles. There's no CSS Wizardry that will override it. What you need to do is directly modify the inline styles.
Here's what you're looking for:
var elem = document.getElementById("elementID");
elem.setAttribute("style", "font-size: 2em");

You'll have problems in IE with setAttribute so if that's a concern ... you'll need to write a fallback to handle it.

A: The problem with your approach is that you are trying to change the style on an entire Node List.
When you call getElementsByTagName you do not get back a single element. You need to iterate over the elements in the node and then use elememt.style.fontSize = size; on each of the elements.
Here is a fiddle that implements that http://jsfiddle.net/Kfd2R/


text:
Q: using enums in jython Trying to use a Java Enum in Jython but I can't figure out how to use them.
when importing I see the enum listed as BotInterface$MOVE so I've put down the line
from amazebot2012.BotInterface import MOVE

In Java I would normally just use it as
bot.move(MOVE.FORWARD);
bot.move(MOVE.BACKWARD);

What is the Jython equivalent once I've imported it?
Trying bot.move(MOVE.FORWARD) gives me the error:

Undefined variable from import: FORWARD

A: Your import and reference seem correct.
I suspect this is a bug in your editing environment, if you're using PyDev/Anapta:
http://jira.appcelerator.org/browse/APSTUD-7502


text:
Q: How to post string to URL I have a string like: <0>book1<0>book2<0><0>book3<1>Version<1>, and I have a URL: abc.com. I want to send a string to the URL from a Windows Phone.
I have searched in Google but I found nothing of any use, because the results were for web pages (.aspx), where as, I am using a C# class (.cs). I want create a method like this:
public void SendPost(string url, string postData)
{
...
}

A: Use WebClient
public void SendPost(string url, string postData)
  {
      WebClient client = new WebClient();
      client.UploadStringCompleted += client_UploadStringCompleted;
      client.UploadStringAsync(new Uri(url), postData);

  }

void client_UploadStringCompleted(object sender, UploadStringCompletedEventArgs e)
{
    if (e.Error != null)
    {
        // error in uploading
    }
}


text:
Q: "It's time that someone looked you in the eyes and told it to you straight." Could anyone tell me why the verbs "look and tell" are in the past tense in the following sentence:

It's time that someone looked you in the eyes and told it to you straight.

A: It's the use of the past for irrealis or counter-factual clauses. It's very much like

If someone looked you in the eyes and told it to you straight ...

So with the past, this is counter-factual, and implies "but nobody is going to do that". Contrast

If, when you get there, somebody looks you in the eyes and tells you straight ....

which is not counter-factual: it may yet happen.
(Historically this is past subjunctive, but since there is now precisely one word in the language for which this is different from the past - were vs was - I don't think this is a helpful description of modern English.)


text:
Q: Open a remote file with vim. Email-like username I have a problem authenticating to my ftp with vim.
That because my username is an email address like this
424242@myhostingsite.com
So I should write
Nread fpt//424242@myhostingsite.com@myftpsite.com/

But I receive a warning and (obviously) It doesn't work.
Is there a way to escape the first @ char?

A: Try:
Nread ftp://"424242@myhostingsite.com"@myftpsite.com/

A: Try:
Nread ftp://424242+myhostingsite.com@myftpsite.com/

A: Yeah. I've got exactly the same problem. It seems that there is one solution but not as comfortable. You can omit the user name and type it when vim ask for it.
If I find other solution i will post it here.


text:
Q: Implementing associations with Rspec/Capybara for Ruby with Rails project I have a model that has a method like the following:
class Post < ActiveRecord::Base
    MAX_LINES = 100
    MAX_POSTS = 5

    def self.can_post?(user)
      user.posts.count( :conditions => ["lines >= ?", MAX_LINES] ) < MAX_POSTS
    end
end

user has_many posts and posts belongs_to user.  I want to build tests for posts_exceeding_max_lines?. I'm following the FactoryGirl readme to create a user and post factory:
FactoryGirl.define do

  # post factory with a `belongs_to` association for the user
  factory :post do
    title "Through the Looking Glass"
    user
  end

  # user factory without associated posts
  factory :user do
    name "John Doe"

    # user_with_posts will create post data after the user has been created
    factory :user_with_posts do
      # posts_count is declared as an ignored attribute and available in
      # attributes on the factory, as well as the callback via the evaluator
      ignore do
        posts_count 5
      end

      # the after(:create) yields two values; the user instance itself and the
      # evaluator, which stores all values from the factory, including ignored
      # attributes; `create_list`'s second argument is the number of records
      # to create and we make sure the user is associated properly to the post
      after(:create) do |user, evaluator|
        FactoryGirl.create_list(:post, evaluator.posts_count, user: user)
      end
    end
  end
end

In my test, I create the user using:
new_posts_count = 5
@user = FactoryGirl.create(:user_with_posts, posts_count: new_posts_count)

However, when I try to print out how many posts I have (with require 'pp'):
pp @user.posts.count

I get 0, no matter what my setting of new_posts_count. How can I change my setup so that I can get a count of 5 posts?

A: *

*shouldn't this method be defined on the User?

*what does all this have to do with the factory?

*use an optional parameter instead of a constant

user
class User < ActiveRecord::Base
  def posts_exceeding_max_lines?(max_lines = 100, max_posts = 5)
    posts.count(:conditions => ["lines >= ?", max_lines] ) < max_posts
  end
end


text:
Q: What is the best way to store messages in db and emit them with socket.io? I have a chat app, something like Whatsapp. I'm considering two ways to store messages in db and also emit them. My approach now is that client emits new message, server is listening then store that message in database and return whole message back to server. Server after that emits new message to all clients in session/group. So bascially it server first stores messages in db and then emits them back to clients.
this is my code on server:
//this is just basic example on how it works for now
io.on("connection", socket => {
    socket.on("message", async (message) =>{
        db.query("call insertnewMessage(params)",(res)=>{
            if(res[0]){
                socket.emit("newMessage",{newMessage: res[0]});
            }
        })
    }
}

Second approach is to first with normal http request send message to REST api (not socket server), rest api query database to insert message, returns new message to server and server returns whole new message to client and then client emits new message to socket server? In this approach socket server does not need to query db and I actually know that message is sent ( it is inserted in db).
I read from somewhere that every new connection is actually new instance of socket on server. Wouldn't it made that if I have code from my example, and if every connection is new instance, that if I send new message to server and have for example 5 clients, it would be inserted 5 times in db because every socket connection will query db if they are independent? Am i missing something here and can someone make this clearer please.

A: I'm going through this right now. I actually went with broadcasting to the user as for my application, availability is more important than persistence.
The user should be able to hear messages in their chat messages even if the database fails.
Thus, I emit/broadcast the message and then save to the database.


text:
Q: Dynamically add and remove events in angular.js I'm new to angular.js and still struggling to catch best practices. In this particular case I'm unsure what would be angular way to dynamically add and remove event handlers.
I've created an simplified example that mimic my problem. In this example user can select from one of the items in a list. To select an item, user clicks on button that will display list. Clicking on a list, selection will be changed and list hidden.
But, what I want to do now is enable user to click anywhere on a page to hide list. Using jQuery approach I would add click event handler on body or document that would change view state and hide popup list.
I've created an example on jsfiddle with this approach. My question is: Is this good practice in angular.js? It feels kind of hackish.
Also, please note that I don't want to have a event handler present on document all the time, only when list is displayed.

A: Using practices described in angular.js guide, I've created directive that should handle the show/hide events.
.directive('toggleListDisplay', function($document) {
    return function(scope, element, attr) {
        var hideList = function (event) {
            scope.listDisplayed = false;
            $document.off('click', hideList);
            scope.$apply();
        };

        element.on('click', function(event) {
            event.stopPropagation();
            scope.listDisplayed = !scope.listDisplayed;
            if (scope.listDisplayed) {
                $document.on('click', hideList);
            } else {
                $document.off('click', hideList);
            }
            scope.$apply();
        });
    };
});

This directive will add click event handler on element, and will start looking for a click on a document untill list is displayed. When it is not displayed anymore, it will stop watching for click event on document.
Working example can be found on jsfiddle.


text:
Q: Sunspot sort by multiple date fields I have setup sunspot for my application wherein we have two date field
fields
date_of_a
date_of_b

and i want to sort records by date field with precedence in given order only i.e a > b > c ....
so i setup my search like
Sunspot.search(Model) do
  order_by(:date_of_a, :desc)
  order_by(:date_of_b, :desc)
  ..
end

now let's say i have 4 documents which have
document 1 => date_of_a = 10/2/10
document 2 => date_of_a = 10/2/12
document 3 => date_of_b = 10/2/15
document 4 => date_of_a = 10/2/9

and when i try to search it gives me records in following sequence
document 2 => date_of_a = 10/2/12
document 1 => date_of_a = 10/2/10
document 3 => date_of_b = 10/2/15  #this document doesn't have `date_of_a`
document 4 => date_of_a = 10/2/9

but this is not what i want i want it to sort as per latest date no matter which date it is
so the required result is like
document 3 => date_of_b = 10/2/15  #this document doesn't have `date_of_a`
document 2 => date_of_a = 10/2/12
document 1 => date_of_a = 10/2/10
document 4 => date_of_a = 10/2/9

A: Create a method that returns the max of the two dates. Then index on that method:
def latest_date
  [date_of_a, date_of_b].max
end

searchable do
  date :latest_date
end


text:
Q: phpMyAdmin and node.js I have created aa database called users in phpmyadmin and a table called personalinformation. I can connect to the database just fine using node.js javascript with this code:
var mysql = require('mysql');
var con = mysql.createConnection({
host: "localhost",
user: "user",
password: "****",
database: "users",

});

con.connect(function(err) {
if (err) throw err;
console.log("Connected!");

});

the table is already populated with some data. I now want to add extra data into the table. I used this code but its telling me that the table doesnt exist
var mysql = require('mysql');

var con = mysql.createConnection({
host: "localhost",
user: "user",
password: "password",
database: "users",

});

con.connect(function(err) {
if (err) throw err;
console.log("Connected!");

var sql = "INSERT INTO personalinformation (title, firstname, surname, mobile, email) VALUES ?";
var values = [
    ['Mr', 'John', 'Whelan', '0868337', 'john@gmail.com'],
    ['Mr', 'Peter', 'Lawless', '0885947', 'peter@gmail.com'],
    ['Ms', 'Amy', 'Apple', '08736855', 'amy@gmail.com']

];
con.query(sql, [values], function(err, result) {
    if (err) throw err;
    console.log("Number of records inserted: " + result.affectedRows);
});

});

the table structure is like this:
title     firstname      surname     mobile           email
 mr        john           whelan     0976577567      john@home.com

etc and there error message is Error: ER_NO_SUCH_TABLE: Table 'users.personalinformation' doesn't exist
My database is called users and the table is called personalinformation so im confused as to why its saying it doesnt exist

A: Perhaps you have more than one drive, and the settings must be provided with the port of the mysql


text:
Q: Uncommon word describing India I am looking for an uncommon word describing India. So far I came up with "diversity", but I fear this is too common.
Just to give a bit background to my question I am a grammarian at a Toastmasters and I just came back from the trip to India. For those who do not know Toastmasters, a grammarian role is to look for correct and incorrect use of language in the speeches and to introduce a word of the day. An uncommon word that should expand a vocabulary of meeting participants.
This is my first question on the English Language & Use. Apologies if this is inappropriate for this exchange.

A: Multicultural. A potpourri of people. A mélange of multiculturalism. A concatenation of cultures. A pasticcio of peoples (or people groups). A varietal country. A case study in cultural anthropology.

A:
multifarious - >
   of many and various kinds.

*

*having or occurring in great variety :  diverse
  (M-W)

Consisting of a number of different kinds as in :
assorted, diverse, heterogeneous, motley, multiform, varied, variegated, ethnic mosaic. (TFD)

A: RECHERCHE

/rəˌSHerˈSHā,rəˈSHerˌSHā/ adjective
rare, exotic, or obscure.
  "a few linguistic terms are perhaps a bit recherché for the average readership"
synonyms: obscure, rare, esoteric, abstruse, arcane, recondite, exotic, strange, unusual, unfamiliar, out of the ordinary
Google

A: rainbow: a wide variety or range; gamut; having a diverse membership; including representatives from multiple racial and ethnic groups
manifold: of many kinds; numerous and varied

A:
India is a land of many tongues and has been called "as a tower of veritable languages" or a "Museum of languages".


text:
Q: how can i retrieve username from another collection by using join in laravel //viewing tickets generated by them
        $user= Auth::user()->_id;
        $tickets = ticket::where(function ($query) use ($user) {
            $query->where('user', '=', $user);
        })->get();

  //  created ticket by which user
    $atickets = ticket::where(function ($query) use ($user) {
        $query->where('user_assigned', '=', $user);
    })->get();

    return view('ticketviews', compact('tickets','atickets'));

$atickets returns record details such as user_id and ticket details, now i need to display the username for that particular record stored in another collection mongodb. Can anyone suggest me the code to do that.

A: Create relation in your model
Insert this to your ticket model
public function user(){
 return $this->hasOne('PATH_TO_USER_MODEL', 'foreign_key', 'local_key');
}
After that you can access to user data, like:
$tickets = ticket::where('user_assigned', Auth::user()->_id)->with('user')->get();

After you can access to your user data like $tickets->user->name

A: @ATIKON, its working i changed the code to
$user= Auth::user()->_id;
        $tickets = ticket::where('user', '=', $user)->get();
    foreach($tickets as $t){
        $use = $t->user;
        $us = User::where('_id', '=', $use)->get();
        foreach($us as $a)
        {
            $username=$a->name;
            $t['name']=$username;
        }
    }
    foreach($tickets as $t) {
        $use1 = $t->user_assigned;
        $us1 = User::where('_id', '=', $use1)->get();
        foreach ($us1 as $a1) {
            $username1 = $a1->name;
            $t['namea'] = $username1;
        }
    }

thanks alot for helping out


text:
Q: More available space than expected using btrfs RAID10? I had just created a btrfs RAID10 array in my Ubuntu 14.04 box for the first time by using the command:
mkfs.btrfs -d raid10 -m raid10 /dev/sda /dev/sdb /dev/sdc /dev/sdd

My 4 hard drives are each 2TB drives. Under RAID10, I had expected to see usable space of about 3.6TB in total. Yet, for some reason, I'm seeing a total usable of 7.3TB (refer to /dev/sda below):
Filesystem      Size  Used Avail Use% Mounted on
/dev/sde1        42G  1.7G   38G   5% /
none            4.0K     0  4.0K   0% /sys/fs/cgroup
udev            7.8G   12K  7.8G   1% /dev
tmpfs           1.6G  1.2M  1.6G   1% /run
none            5.0M     0  5.0M   0% /run/lock
none            7.9G     0  7.9G   0% /run/shm
none            100M     0  100M   0% /run/user
/dev/sda        7.3T   13G  7.3T   1% /mnt/tmp

Is this unexpected behavior?
Other information:
bofh@stronghold:~$ sudo btrfs fi show
Label: none  uuid: a3a65325-0184-46d8-bef7-7ed066c9e320
    Total devices 4 FS bytes used 29.14GiB
    devid    1 size 1.82TiB used 16.03GiB path /dev/sda
    devid    2 size 1.82TiB used 16.01GiB path /dev/sdb
    devid    3 size 1.82TiB used 16.01GiB path /dev/sdc
    devid    4 size 1.82TiB used 16.01GiB path /dev/sdd

When I try to list out the RAID type I'm using, I see both "RAID10" and "single"
bofh@stronghold:~$ sudo btrfs fi df /mnt/tmp
Data, RAID10: total=52.00GiB, used=48.77GiB
Data, single: total=8.00MiB, used=0.00
System, RAID10: total=16.00MiB, used=16.00KiB
System, single: total=4.00MiB, used=0.00
Metadata, RAID10: total=2.00GiB, used=64.12MiB
Metadata, single: total=8.00MiB, used=0.00

Another rather weird thing is that btrfs device scan doesn't throw up any results:
bofh@stronghold:~$ sudo btrfs device scan
Scanning for Btrfs filesystems
bofh@stronghold:~$

I'm using Ubuntu 14.04 server which I just installed new and ran a dist-upgrade.
Any advice appreciated!

A:
I'm seeing a total usable of 7.3TB

That's correct.
The short answer is that you are seeing the raw space available for putting the mirror copies into, so split it in half to get the 3.6TB you expected.
Calculating disk free space is notoriously confusing with btrfs.  The official btrfs FAQ has a question on why it is difficult to calculate free space in btrfs.
A btrfs filesystem can contain chunks of files with different raid levels.  You can have some files with no mirror copies ("single" or "raid0") and other files that are mirrored ("raid1").
You actually have this in your filesystem right now.

When I try to list out the RAID type I'm using, I see both "RAID10" and "single"

This is telling you that a small amount of your data in your file system is NOT mirrored ("single").  You need to do a btrfs balance to fix this.  I would recommend doing:

btrfs balance start -dconvert=raid1,profiles=single -mconvert=raid1,profiles=single -sconvert=raid1,profiles=single --force /mnt/tmp

This will convert the single-copy data to mirrored, for both the file data, metadata, and system data (d, m and s).  The "profiles" parameter will make it just affect the data that is currently single-copy.


text:
Q: Add delimiters at end of each line I've a csv file like below.
id,id1,id2,id3,id4,id5
1,101,102,103,104
2,201,202,203
3,301,302

Now what i want to add comma(,) to each line to make all line with same number of delimiters. So desired output should be.
id,id1,id2,id3,id4,id5
1,101,102,103,104,
2,201,202,203,,
3,301,302,,,

Using
awk -F "," ' { print NF-1 } ' file.csv | sort -r | head -1

I am able to find the max occurance of delimiter but not sure how to compare each line and append comma if its less than max.

A: With GNU awk (as I do not know if this works for other implementations)
$ # simply assign value to NF
$ awk -F, -v OFS=',' '{NF=6} 1' ip.txt
id,id1,id2,id3,id4,id5
1,101,102,103,104,
2,201,202,203,,
3,301,302,,,

If first line determines number of fields required:
$ awk -F, -v OFS=',' 'NR==1{f=NF} {NF=f} 1' ip.txt
id,id1,id2,id3,id4,id5
1,101,102,103,104,
2,201,202,203,,
3,301,302,,,

If any line determines max field:
$ cat ip.txt
id,id1,id2
1,101,102,103
2,201,202,203,204
3,301,302

$ awk -F, -v OFS=',' 'NR==FNR{f=(!f || NF>f) ? NF : f; next} {NF=f} 1' ip.txt ip.txt
id,id1,id2,,
1,101,102,103,
2,201,202,203,204
3,301,302,,

A: You are already using the variable NF which indicates how many fields there are on a line.
awk -F , 'NF<6 { OFS=FS; for (i=NF+1; i<=6; i++) $i="" }1' filename

We start looping at the first undefined field and set it to an empty string, until we have six fields. Then the 1 at the end takes care of printing the now fully populated line.  The OFS=FS is necessary to make the output field separator also be a comma (it is a space by default).

A: Unified awk approach (based on number of fields of the 1st header line):
awk -F',' 'NR==1{ max_nf=NF; print }
           NR>1{ printf "%s%.*s\n", $0, max_nf-NF, ",,,,,,,,," }' file

The output:
id,id1,id2,id3,id4,id5
1,101,102,103,104,
2,201,202,203,,
3,301,302,,,

Or via loop:
awk -F',' 'NR==1{ max_nf=NF; print }
           NR>1{ n=max_nf-NF; r=""; while (n--) r=r","; print $0 r }' file

A: awk -F"," '{i=NF;c="";while (i++ < 6) {c=c","};print $0""c}' file

Output:
id,id1,id2,id3,id4,id5
1,101,102,103,104,
2,201,202,203,,
3,301,302,,,

A: Following awk may also help you on same.
awk -F, '
FNR==1{
  val=NF;
  print;
  next
}
{
  count=NF;
  while(count<val){
    value=value",";
    count++};
  print $0 value;
  value=count=""
}
'   Input_file

Output will be as follows:
id,id1,id2,id3,id4,id5
1,101,102,103,104,
2,201,202,203,,
3,301,302,,,


text:
Q: Error while editing ViewObject query in Expert mode I am using Oracle's BC4J framework, in that I get following error while editing ViewObject query in JDeveloper.

A: This problem occurs when JDveloper IDE has problem doing a certain task, you can check the Error Details to know more about this problem, but usually if you Press Continue and continue working everything should be alright with you.


text:
Q: Enumerative characterisation of boolean lattices II This is a sequel of this post.
The boolean lattice $B_n$ is graded with rank numbers $\binom{n}{0}, \binom{n}{1}, \dots, \binom{n}{n}$, and $n2^{n-1}$ edges.
Question: Is a graded lattice with the above rank numbers and $n2^{n-1}$ edges, equivalent to $B_n$?
If it is not true, it would be useful (to me) to know up to which $n$ it is true.

A: True for $n \le 4$. For $n \le 3$ it is straightforward.
For $n=4$, inspect all 16-element vertically indecomposable graded lattices (listed here). The list has 1900132 lattices; of them, 103411 have rank sequence 1,4,6,4,1, and 249 have exactly 32 edges. But only 1 lattice has both, that's the $B_4$.


text:
Q: Drools rules logic not working as expected Hierarchy:
If any employee is paid 100k, Organization.maxSalary = 100k.
If any employee is paid 50k, Organization.maxSalary = 50k if no one else receives 100k.
DRL
rule "Salary 100000"
    when
        $org: Organization()
        $empDetail: EmployeeDetail() from $org.employeeDetail
        $employee: Employee( $org.maxSalary != 100000,
                             salary == 100000
                           ) from $empDetail.employees
    then
        System.out.println("Salary 100000: " + $org.maxSalary);
        $org.maxSalary = 100000;
end

rule "Salary 50000"
    when
        $org: Organization()
        $empDetail: EmployeeDetail() from $org.employeeDetail
        $employee: Employee( $org.maxSalary != 100000
                          && $org.maxSalary != 50000,
                             salary == 50000
                           ) from $empDetail.milestoneDetails
    then
        System.out.println("Salary 50000: " + $org.maxSalary);
        $org.maxSalary = 50000;
end

Input JSON 1:
{
  "Organization": {
    "EmployeeDetail": {
      "Employees" : [
        {
          "name": "willie"
          "salary": "50000",
        },
        {
          "name": "john"
          "salary": "100000",
        },
        {
          "name": "jack"
          "salary": "50000",
        },
        {
          "name": "jim"
          "salary": "50000",
        }
      ]
    }
  }
}

Expected console output: Salary 100000: null
Actual console output: Salary 100000: null
All good.
Input JSON 2:
{
  "Organization": {
    "EmployeeDetail": {
      "Employees" : [
        {
          "name": "willie"
          "salary": "50000",
        },
        {
          "name": "jack"
          "salary": "50000",
        },
        {
          "name": "jim"
          "salary": "50000",
        }
      ]
    }
  }
}

Expected console output: Salary 50000: null
Actual console output:
Salary 50000: null
Salary 50000: 50000
Salary 50000: 50000

In both cases, the JSON result is good with Organization.maxSalary set correctly. But why is the console output weird?

A: You want to fire the rule by checking the org.maxSalary. However you should not check the $org.maxSalary from inside the Employee object, as this is not an Eployee's property but Orgranization's.
Also, after setting the maxSalary on org, you should update the Organization fact with the new value (maxSalary). update() makes the rules engine aware that a fact has been modified.
Here is the complete rules code
rule "Salary 100000"
    when
        $org: Organization(maxSalary != 100000)
        $empDetail: EmployeeDetail() from $org.employeeDetail
        $employee: Employee( salary == 100000
                           ) from $empDetail.employees
    then
        System.out.println("Salary 100000: " + $org.maxSalary);
        $org.maxSalary = 100000;
        update($org);
end

rule "Salary 50000"
    when
        $org: Organization(maxSalary != 100000 && maxSalary != 50000)
        $empDetail: EmployeeDetail() from $org.employeeDetail
        $employee: Employee(
                             salary == 50000
                           ) from $empDetail.employees
    then
        System.out.println("Salary 50000: " + $org.maxSalary);
        $org.maxSalary = 50000;
        update($org);

end

Output on the Json2 is
Salary 50000: null

I also do not understand the logic of having
 System.out.println("Salary 50000: " + $org.maxSalary);
 $org.maxSalary = 50000;

instead of
 $org.maxSalary = 50000;
 System.out.println("Salary 50000: " + $org.maxSalary);

It seems weird to first print an empty maxSalary and then assign the amount to maxSalary.


text:
Q: Display pic in web page captured from webcam I'm using jquery-webcam-plugin (not familiar with jQuery). I want to take picture  in webcam and want to display that picture in the same web page instantly, possibly replacing some default image by image captured from webcam, without any server communication, is that possible? if possible please suggest.
If the image captured from webcam is saved locally, can I use that image path?
I'm using the following code(along with the related API/plugin):

//FOLLOWING IS THE HTML SNIPPET

    <button onclick="showWebcam();">Use Webcam Instead</button>
    <button onclick="javascript:capture_image();">Take a picture!</button>

<input id="capture_image" type="hidden" value="" name="capture[image]">

    // some default image, which will be replaced by image captured by webcam

<canvas id="canvas" width="320" height="240"></canvas>

Any suggestion is appreciated. please rectify me if I'm doing wrong.

A: The source code explains how it works. The photo is not stored on the filesystem, but rather is stored as a base64-encoded Javascript variable.


text:
Q: How can i parse this value from string into Array in javascript let x = "[{\"{\\\"value\\\":\\\"+2333333333\\\",\\\"phone_number_type\\\":null}\"}]"
let parseX=JSON.parse(x)
console.log(x)

//I want the output to [{"value":"2333333333","phone_number_type":null}]

A: I would expect JSON.parse to throw an error because the JSON string in x is invalid JSON. See JSON.org for more details. The [{{...}}] is invalid it should be [{...}]

A:   //I have resolved this problem so what we can do is :

x='[{"\\"value\\":\\"aliwasiq41@gmail.com\\",\\"email_address_type\\":null}"}]';
x=x.replaceAll('\\', '');
x=x.replace('{"',"")
x=x.replace('"}',"")
console.log(JSON.parse(str));

//In this way you can parse the value to
 [{"value":"2333333333","phone_number_type":null}]


text:
Q: Linked List pushback member function implementation I am a novice programmer and this is my second question on Stack Overflow.
I am trying to implement a pushback function for my Linked List by using a tail pointer. It seems straightforward enough, but I have a nagging feeling that I am forgetting something or that my logic is screwy. Linked Lists are hard!
Here is my code:
template <typename T>
void LinkedList<T>::push_back(const T n)
{
Node *newNode;  // Points to a newly allocated node

// A new node is created and the value that was passed to the function is stored within.
newNode = new Node;
newNode->mData = n;
newNode->mNext = nullptr;
newNode->mPrev = nullptr;

//If the list is empty, set head to point to the new node.
if (head == nullptr)
{
    head = newNode;
    if (tail == nullptr)
    {
        tail = head;
    }
}
else  // Else set tail to point to the new node.
    tail->mPrev = newNode;
}

Thank you for taking the time to read this.

A: Your pointing the wrong mPrev to the wrong node. And you never set mNext of the prior tail node if it was non-null to continue the forward chain of your list.
template <typename T>
void LinkedList<T>::push_back(const T n)
{
    Node *newNode;  // Points to a newly allocated node

    // A new node is created and the value that was passed to the function is stored within.
    newNode = new Node;
    newNode->mData = n;
    newNode->mNext = nullptr;
    newNode->mPrev = tail; // may be null, but that's ok.

    //If the list is empty, set head to point to the new node.
    if (head == nullptr)
        head = newNode;
    else
        tail->mNext = newNode; // if head is non-null, tail should be too
    tail = newNode;
}


text:
Q: IronPython Package "System.UnauthorizedAccessException" when updating config.ini I am building an IronPython package that contains a config.ini file in the package directory. The config file is used to maintain user settings but when I try to update the file I get a permissions error:
IOError: System.IO.IOException: Access to the path 'C:\Program Files\IronPython 2.7\Lib\site-packages\...\_config.ini'

I have seen answers to similar questions which, for the most part, suggest running the command line as admin or using error='ignore with open.
with open(Paths.config_path, 'w+', errors='ignore') as configfile:

I don't want to tell my colleagues to run either the cmd.exe or their IDE as admin to use the package. I also don't want to just ignore the error and not update their settings. The basic structure worked fine for a similar CPython project and I would like to re-use the idea here. Is there a way to work around this?
In case it makes a difference:

*

*I am building the package with ipy setup.py bdist_wheel

*I use the MANIFEST.in to include the file. recursive-include proj *.ini
The setup file:
from setuptools import setup, find_packages
from prost import _meta

setup(name='...',
      version=_meta.__version__,
      packages=find_packages(),
      include_package_data=True,
      package_data={'prost': [r'bin/*.*', r'_config.ini']})

Thanks for the help.

A: Changed:
ipy -m pip install --upgrade my..-1.0.0.2-py2-none-any.whl

to
ipy -X:Frames -m pip install --upgrade dist\my..-1.0.0.2-py2-none-any.whl

and it worked.


text:
Q: Firebase Token Authentication error I am using firebase storage to upload files , but when I upload I am getting this error
E/StorageUtil: error getting token java.util.concurrent.ExecutionException: com.google.android.gms.internal.zzand: Please sign in before trying to get a token.

I googled it but couldn't get answer for it!
I have signed in, in firebase.

A: I think you didn't sign before uploading files. In onCreate() of launcher activity, try this code
FirebaseAuth mAuth = FirebaseAuth.getInstance();

Then in onStart(),
FirebaseUser user = mAuth.getCurrentUser();
if (user != null) {
  // do your stuff
} else {
  signInAnonymously();
}

signInAnonymously()
private void signInAnonymously() {
    mAuth.signInAnonymously().addOnSuccessListener(this, new  OnSuccessListener<AuthResult>() {
            @Override
            public void onSuccess(AuthResult authResult) {
                // do your stuff
            }
        })
        .addOnFailureListener(this, new OnFailureListener() {
            @Override
            public void onFailure(@NonNull Exception exception) {
                Log.e(TAG, "signInAnonymously:FAILURE", exception);
            }
        });
}

This may solve your problem
Note: Initially enable anonymous sign-in in your firebase project. Authentication -> Sign-in method

A: Below steps worked for me:

*

*Generated proper google-services.json from firebase with package ID

*In build.gradle(app)
 dependencies {

 compile 'com.google.firebase:firebase-storage:10.2.0'
 compile 'com.google.firebase:firebase-auth:10.2.0'
 compile 'com.google.firebase:firebase-core:10.2.0'
 compile 'com.google.firebase:firebase-database:10.2.0'
 compile 'com.firebase:firebase-client-android:2.4.0'
 }

*Make sure you add below dependencies in build.gradle(project root folder)
dependencies {

classpath 'com.android.tools.build:gradle:2.2.3'
classpath 'com.google.gms:google-services:3.0.0'

}

*While downloading file in your activity add following code:
// Declaration reference
private StorageReference storageRef;

private void downloadImageFromFireBase()
{
showProgressDialog("Downloading image..");

storageRef = storage.getReferenceFromUrl("gs://XXX.appspot.com/").child("av"+ datePassed +".jpg");
showImageFromFireBaseDataBase();
}

private void showImageFromFireBaseDataBase()
{
    try {
        final File localFile = File.createTempFile("images", "jpg");
        final Bitmap[] bitmap = new Bitmap[1];
            storageRef.getFile(localFile).addOnSuccessListener(new OnSuccessListener<FileDownloadTask.TaskSnapshot>() {
                @Override
                public void onSuccess(FileDownloadTask.TaskSnapshot taskSnapshot) {
                    Log.e("Test", "success!");
                    bitmap[0] = BitmapFactory.decodeFile(localFile.getAbsolutePath());
                    raysImage.setImageBitmap(bitmap[0]);
                }
            }).addOnFailureListener(new OnFailureListener() {
                @Override
                public void onFailure(@NonNull Exception exception) {
                    Log.e("Test", "fail :( " + exception.getMessage());
                }
            });
        }catch(IOException e){
        Log.e("ImageView",e.toString());
        }
    }

A: Maybe you just can't "get started" to firebase. I saying that because I created a project, connect to firebase storage by Android Studio IDE, but I have to "get started" manually on console.

A: You must first sign in to FirebaseAuth.
You can sign in anonymously,
but if you want to sign in user's google id, try like this.
I created a manager class for ease of use.

*

*Make (Your)GoogleUserManager class

object YourGoogleUserManager {

    private lateinit var gso: GoogleSignInOptions
    private lateinit var firebaseAuth: FirebaseAuth

    fun init(context: Context) {
        firebaseAuth = FirebaseAuth.getInstance()
        gso = GoogleSignInOptions
            .Builder(GoogleSignInOptions.DEFAULT_SIGN_IN)
            .requestIdToken(context.getString(R.string.default_web_client_id))
            .build()
    }

    fun startGoogleSignInForResult(
        fragment: Fragment,
        onSuccess: (AuthResult) -> Unit,
        onFail: (Exception) -> Unit
    ): ActivityResultLauncher<Intent> {
        return fragment.registerForActivityResult(
            ActivityResultContracts.StartActivityForResult()
        ) {
            val task = GoogleSignIn.getSignedInAccountFromIntent(it.data)
            handleGoogleSignInResult(task, onSuccess, onFail)
        }
    }

    fun signIn(
        activityResultLauncher: ActivityResultLauncher<Intent>,
        activity: Activity
    ) {

        val googleSignInClient = GoogleSignIn.getClient(activity, gso)

        activityResultLauncher.launch(googleSignInClient.signInIntent)
    }

    private fun handleGoogleSignInResult(
        task: Task<GoogleSignInAccount>,
        onSuccess: (AuthResult) -> Unit,
        onFail: (Exception) -> Unit
    ) {
        try {
            val account = task.getResult(ApiException::class.java)
            val credential = GoogleAuthProvider.getCredential(account?.idToken, null)
            firebaseAuth.signInWithCredential(credential)
                .addOnSuccessListener {
                    CatHolicLogger.log("success to firebase google sign in")
                    onSuccess(it)
                }
                .addOnFailureListener {
                    CatHolicLogger.log("fail to firebase google sign in")
                    onFail(it)
                }
        } catch (e: ApiException) {
            CatHolicLogger.log("fail to firebase google sign in")
            onFail(e)
        }
    }

    fun signOut() {
        firebaseAuth.signOut()
    }
}

*Initialize manager in your application.

class YourApplication : Application() {

    ...

    override fun onCreate() {
        super.onCreate()

        initGoogleUserManager()
    }

    ...

    private fun initGoogleUserManager() {
        YourGoogleUserManager.init(this)
    }
}

*Use manager in your Fragment(or Activity)

class YourFragment : Fragment() {

    ...
    ...

    private val startGoogleSignInForResult =
        YourGoogleUserManager.startGoogleSignInForResult(this, onSuccess = {
            // your job after success to sign in
        }, onFail = {
            // your job after fail to sign in
        })

    ...
    ...

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)

        binding.signInButton.setOnClickListener {
            YourGoogleUserManager.signIn(startGoogleSignInForResult, requireActivity())
        }
    }
}

A: I was facing the same issue and it was caused because by default firebase will only allow uploading files from user's that have been authenticated.
Above the storage util exception there might be a log similar to this:
E/StorageUtil: error getting token java.util.concurrent.ExecutionException: com.google.android.gms.internal.zzajb: Please sign in before trying to get a token.

We had our own authentication process without using firebase so we decided to change the storage rules in firebase console.
service firebase.storage {
  match /b/{bucket}/o {
    match /{allPaths=**} {
    allow read, write;
    }
  }
}

Note: Changing the rules will allow any user to upload files to your firebase cloud server.

A: It could be something as simple as internet connection, that is if all your code is correct and you have authenticated all users on firebase.


text:
Q: How to dynamically Change Column name(column header) with filter in Qlik Sense I have a Filter in my dashboard as Financial Year. In that filter there are currently two years. 2021 and 2022 however as data is loaded there will be 2023 also so I want column name RANK to change dynamically to the year I select from filter pane. For eg. If year 2022 is selected from filter pane it should show RANK 2022. Please anyone help me with this
COMPANY NAME       RANK 2022
A                  21
B                  4
C                  7
Title should change dynamically
If year 2022 is selected
COMPANY NAME       RANK 2022
A                21
B                4
C                7
if year 2023 is selected
COMPANY NAME       RANK 2022
A                  21
B                  4
C                  7

A: If I'm understanding correctly, you could try one of these options by updating the Label property for your [Rank] field:
Only() function
='Rank ' & Only([Financial Year])
This uses the Only() function to display the currently possible [Financial Year] only if one year is possible. That means that if you select multiple years, the [Rank] values will still filter correctly to those selected years but the column name will not display the years since it will return a value if there is only one unique value to return. Note that this is an aggregation function so it's not strictly based on what's selected. If your data model changed such that there was only one [Financial Year] value loaded, the header would display that year even if you weren't actually selecting it. That's why I use the term "possible" instead of "selected."

Concat() function
='Rank ' & Concat(distinct [Financial Year], ', ')
This will make the header display all distinct, possible years as a comma-separated list. This means if you have multiple possible or selected years, they'll all be shown in the header. Just like the Only() function, this is an aggregation, so it's not strictly based on selections.

GetFieldSelections() function
='Rank ' & GetFieldSelections([Financial Year], ', ')
This function works similarly to the Concat() function, except that it is not based on possible values but instead based strictly on selected values.

if(), GetFieldSelections(), and GetSelectedCount() functions
='Rank ' &
if( GetSelectedCount([Financial Year]) > 1, 'Multiple Years',
if( GetSelectedCount([Financial Year]) = 1, GetFieldSelections([Financial Year])))

This uses an if() statement to see how many years are selected. If more than one year is selected, it will display the text "Multiple Years." If only one year is selected, it will display that year. If no years are selected, it will not display anything.