text:
Q: Angular - Filtering Global Data Service for Multiple Component Instances I have a sample Angular app with a global data service that I am trying to share between multiple instances of a component by filtering it.  This is a prototype for my bigger application, but I'm having the same issue in both.  I have tried to use a pipe filter, but I get an error message.  For now, I'd like some guidance on best practice in this situation as this is my first time trying to do this.  If it is pipe filtering, then I'd like help on the error message.
My example uses a test API that returns ToDo items.  I want to use the service for a component that shows completed items in one instance and incomplete items in another.  There is also filtering by userId just because I felt I needed another element to this.
Service:
    import { Injectable } from '@angular/core';
    import { HttpClient } from '@angular/common/http';
    import { Observable, BehaviorSubject } from 'rxjs';

    export interface Todo {
      userId: number;
      id: number;
      title: string;
      completed: boolean;
    }

    @Injectable({
      providedIn: 'root'
    })
    export class TodosService {
      private _todos$: BehaviorSubject<Todo[]> = new BehaviorSubject(null);

      constructor(private http: HttpClient) { }

      // Public Methods
      get todos() {
        return this._todos$.asObservable();
      }

      loadData() {
        this._listTodos()
          .subscribe(
            res => {
              this._todos$.next(res);
            },
            err => console.log('Error receiving todo items.', err)
          );
      }
      addTodo(todo: Todo) {
        this._addTodo(todo).subscribe( item => {
          const d = this._todos$.getValue();
          d.push(item);
          this._todos$.next(d);
        });
      }

      // Private methods
      _listTodos(): Observable<Todo[]> {
        return this.http.get<Todo[]>('https://jsonplaceholder.typicode.com/todos');
      }
      _addTodo(todo: Todo): Observable<Todo> {
        return this.http.post<Todo>('https://jsonplaceholder.typicode.com/todos', todo);
      }
    }

Component:

        <button (click)="addTodo()">Add Todo</button>

    <ng-container *ngIf="(todosService.todos | todoFilter$: complete: userId | async) as todos">

Completed: {{ complete }} UserId: {{ userId }}

                {{ todo.id}} - {{ todo.userId }} - {{ todo.title }}

    </ng-container>

    import { Component, OnInit, Input, OnChanges } from '@angular/core';
    import { Todo, TodosService} from '../../services/todos.service';
    @Component({
      selector: 'app-todo',
      templateUrl: './todo.component.html',
      styleUrls: ['./todo.component.css']
    })
    export class TodoComponent implements OnChanges {
      @Input() complete: false;
      @Input() userId: number = null;

      constructor(private todosService: TodosService) { }

      ngOnChanges() {
        this.load();
      }

      async load() {
        await this.todosService.loadData();
      }

      addTodo() {
        const t: Todo = {
          id: 999,
          userId: this.userId,
          title: 'Css Add',
          completed: this.complete
        };
        this.todosService.addTodo(t);
      }

    }

Pipe Filter (throws error:  Cannot read property 'filter' of null.  kws is null apparently but I'm not sure why if items$ is populated?):
    import { Pipe, PipeTransform } from '@angular/core';
    import { Todo } from '../services/todos.service';
    import { Observable } from 'rxjs';
    import { map } from 'rxjs/operators';

    @Pipe({
      name: 'todoFilter$'
    })
    export class TodoFilterPipe implements PipeTransform {

      transform(items$: Observable<Todo[]>, complete: boolean, userId: number): any {
        if (!items$ || items$ == null || items$ === undefined) { return null; }

        return items$.pipe(map(
          kws => kws.filter(kw => (kw.completed === complete && (!userId || kw.userId === userId))
          ))
        );
      }
    }

App Component Sample Page:
<app-todo complete="false"></app-todo>
<app-todo complete="true" userId="1"></app-todo>

Please tell me what is the best way to do this?

A: I believe you get the error because the initial value of the todo stream is null:
 private _todos$: BehaviorSubject<Todo[]> = new BehaviorSubject(null);

The early return in your pipe:
 if (!items$ || items$ == null || items$ === undefined) { return null; }

Will not ignore the null, since the observable items$ is not null, but the first value emitted by it is (kws).
I would change so that instead of null, the initial value of the todos are an empty array. That would also simplify the template (no need for the ngIf, it would always have a value.)
In terms of the design I'm not sure, hopefully someone else can give you a better answer, here are a few thoughts:

*

*The app-todo component, is it really not two different components? Perhaps the inner list of todos is the shared part. Depends on your goal of course.

*Remove the pipe and keep the filtering in the service: Instead of just having the todo method, add notCompleted and completed methods (or something) that return the filtered todos.

*I like to think in "smart" and "dumb" components (just google for a bunch of articles on it). In this context I think it basically means that perhaps the app-todo component would, instead of knowing about the pipes, show completed todos or not, the todo service, etc. would just receive an array of Todos as its input (already passed through the async pipe in the parent component). If a new todo is added, it could be an output on the component.


text:
Q: Would package installerID of an app change if an app is shared via apk sharing, like ShareIt? I am trying to recognise from app if the app was not installed from play store and some other source. I first read this answer Detect if an app is installed from Play store
But then, this answer https://stackoverflow.com/a/16862957 said amazon:

finally sets PackageManager.getInstallerPackageName() to
  "com.amazon.venezia"

So is it optional to change the package installer name?
If yes, then if the app is shared via apk then is the package name installer changed?
For example if the app was shared via shareit, would the package name installer change?
I just want to be sure that if I use the method in the first answer, I can also identify installs by such sharing.
If it won't change when shared via apk, is there a way to find out whether it was shared via apk?

A: The package name will be whatever it is set by the developer.
Some third party stores will add their own tag like "freeapk.com.company.appname", but as far as submission and downloading from Google play or Amazon, the only way to know which store it came from would be to see if the developer created two different versions of the app.

redpajama_set_name: RedPajamaStackExchange


text:
Q: NSSplitViewController based application almost never launches with the correct size I have this app that uses a NSSplitViewController as the root and has a  NSTabViewController connected as its detailViewController.
This app is set to launch at 1024x768. The left pane should launch at 320x768 and the right pane (where the tabViewController is), should launch at 704x768.
From 10 times I run this app, 9 times it will launch with the incorrect size (about 500x500). Other strange thing is that this app should not be scalable, but if you hover the mouse near the window border you see cursor indication to scale.
I want this to launch at the correct size and have no scalable option.
Both of these settings are on interface builder but are being ignored.
You can download a sample project that demonstrates the problem, here. Stop and run the project several times to see the problem.
How do I solve this?

A: I couldn't say for sure what's causing the problem, but one way you may be able to solve it is to add some constraints. Interface Builder doesn't allow you to constrain the default NSView instances that it inserts into the left and right panels of the split view, so you'll need to add your own. The screen-shot below
is taken from your demo, but after I've done the following:

*

*Added a subview to the left split (My Content View), and pinned it's edges to the edges of its superview (the view Xcode automatically adds to the splitview)

*Added an explicit width constraint of 320 pixels to My Content View

When I load the app both splits are visible, the divider doesn't budge, and the window can't be resized.
Update - a better solution
Although constraints are one way to solve this problem, I think the root of the problem lies in a bit of unexpected behaviour in Interface Builder. When you drag an NSSplitViewController object onto the canvas, and make it the target of the window controller's content window relationship, the split-view controller's view outlet is not actually set. One consequence of this appears to be that, when you load the app, the divider will appear to be right over to one side. To resolve this, set the aforementioned view outlet to point at the split view:

I've created a demo project with a setup similar to that in the questioner's demo app.

A: For reference, the same problem occurs if the window content segue points to an NSTabViewController scene. New windows open with a size of 500x500.
I solved it by placing a plain view controller with a container view between my window and my main tab view controller. The window will then use the size of the container view as initial size.
Here is what I did in detail:

*

*Added a new view controller scene to the storyboard

*Made that view the size I want my window to use initially

*Added a container view to the new view controller scene & added 4 constraints to have the container cover the view completely

*Connected the window's content segue to the new view controller

*Finally connect the container view to my actual tab view controller scene

Before:
[Window Controller Scene] → [Tab View Controller]

After:
[Window Controller Scene] → [View Controller Scene] → [Tab View Controller]
                             (with Container View)


text:
Q: How call method from __new__ constructor in python? I am trying to call get_driver_path inside __new__ method, and I get this error when I try to run the full code:
TypeError: unbound method get_chrome_driver() must be called with
WebBrowserManager instance as first argument (got str instance instead

Here is the code:
def __new__(self, driver = 'firefox'):
    if not self._instance:
        self._instance = super(WebBrowserManager, self).__new__(self)
        self._profile.native_events_enabled = True
        self.data = {}
        self._system = platform.system()
        if self._local:
            if driver == 'firefox':
                self.browser = webdriver.Firefox(self._profile)
            elif driver == 'chrome':
                self.browser = self.get_chrome_driver(self._system, driver)
            elif driver == 'ie':
                assert self._system == 'Windows', 'Tests on Internet Explorer are only supported on Windows'
                self.browser = webdriver.Ie(self.get_driver_path(driver))
    return self._instance

def get_driver_path(self, driver):
    driver_name = ''
    if driver == 'ie':
        driver_name = 'IEDriverServer.exe'
    elif driver == 'chrome':
       driver_name = 'chromedriver.exe'
    driver_path = "selenium_drivers\\" + driver_name
    os.environ["webdriver." + driver + ".driver"] = driver_path
    return driver_path

A: Since you made it an instance method, you would need to call it on the instance you created in the __new__ method (which is static; e.g. not bound to an instance or a class):
self.browser = webdriver.Ie(self._instance.get_driver_path(driver))

You could make that method static or a class method instead, at which point you can use it via the first argument to __new__ (which is the class, not an instance; usually you don't use the name self but cls instead):
@staticmethod
def get_driver_path(driver):

Note that a staticmethod then doesn't take a self argument, but your get_driver_path() implementation doesn't use that anyway.


text:
Q: What is the appropriate word to describe society's toughest problem? I am looking for an adjective to use in the following context:

I was pondering on ways of addressing society's most ______ issues.

A:
I was pondering on ways of addressing society's most challenging issues.

(Toughest instead of most challenging also works.)
Another term that may fit what you are looking for is "wicked," as in "wicked problems," a term largely attributed to Rittel & Webber's 1973 paper "Dilemmas in a General Theory of Planning."  The term recently got a bunch of press coverage from its appearance in a Science article contemplating how to solve such problems with large crowds of people.

1: Rittel, H. W. J., & Webber, M. M. (1973). Dilemmas in a General Theory of Planning. Policy Sciences, 4, 155–169. http://link.springer.com/article/10.1007/BF01405730#page-1

A:
I was pondering on ways of addressing society's most pressing issues.

A:
I was pondering on ways of addressing society's most profound issues.

A: How about using the word "pernicious"?

A: innate-is one solution. Most of us trying to make positive changes were born into what is.

A: "Pressing" would equate to "most urgent" (as in pressed for time)
"Toughest" already works well but I guess to expand you have to know on what basis they are the toughest.
"challenging" = difficult to solve
"prevalent" = widespread
"distressing", "damaging", "worrying"
It really depends on the context you want to infer.
Perhaps you need to start by defining what the most xxx problems are, then you can search out an adjective for them.


text:
Q: Java - regular expression to match between two / I have a requirement to match all the incoming requests and filter out certain requests based on request URL. Currently I'm trying to use a regular expression like /app/webapp/users/*/resource/path to match /app/webapp/users/<some_user_id>/resource/path. But the none of the incoming requests seem to match the regex.  What is the problem with the regex I'm trying to use? (I'm using String class' matches method to do the comparison).

A: /*/ looks more like a glob than a regex to me. That will match any number of slashes, whereas I expect you want it to match any number of characters between the slashes. Try /.+/ instead, or possibly /[^/]+/ if you want to make it only match a single level (i.e. if /app/webapp/users/foo/bar/baz/resource/path shouldn't match).
EDIT: As Joachim mentioned, another way of only matching a single level is to use /.+?/ to make it a "reluctant" match.


text:
Q: Define constant based on device type I have a Constants.h file which contains some global constants in fact. Since my application is built both for iPhone and iPad, i would like to define the same constants (ie with the same name) differently for the two device types.
For a complete explanation:
/******** pseudo code *********/

if (deviceIsIPad){
    #define kPageMargin 20
}
else {
    #define kPageMargin 10
}

How can I do this?
Thanks.
L.

A: #define are resolved at compile time, ie on your computer
Obviously, you can't make them conditional the way you want. I recommend creating static variable and setting them on the +(void)initialise method of your class.
And for the condition, use something like
if (UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPad) {
    // iPad
} else {
    // iPhone or iPod touch.
}

So that would go
static NSInteger foo;

@implementation bar

+(void)initialise{
    if (UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPad) {
        // iPad
        foo = 42;
    } else {
        // iPhone or iPod touch.
        foo = 1337;
    }
}

@end

A: It's impossible to get device type during preprocessing step. It is determined dynamically during runtime. You have two options:

*

*Create two different targets (for iPhone and iPad respectively) and define macro there.

*Create macro that inserts expression like this:

 #define IS_IPAD    (UI_USER_INTERFACE_IDIOM()==UIUserInterfaceIdiomPad)

 #define kMyConstant1 (IS_IPAD ? 100 : 200)
 #define kMyConstant2 (IS_IPAD ? 210 : 230)
 #define kMyConstant3 (IS_IPAD ? @"ADASD" : @"XCBX")

A: Hi write this code in appdelegate class
    +(NSString *)isAppRunningOnIpad:(NSString *)strNib{
    NSString *strTemp;
    NSString *deviceType = [UIDevice currentDevice].model;
    if ([deviceType hasPrefix:@"iPad"]){
        strTemp=[NSString stringWithFormat:@"%@I",strNib];
    }
    else{
        strTemp=strNib;
    }
    return strTemp;
}

call this from your class using this line
SecondVC *obj_secondvc = [[SecondVC alloc] initWithNibName:[AppDelegate isAppRunningOnIpad:@"SecondVC"] bundle:nil];

A: Use UIDevice Macros - http://d3signerd.com/tag/uidevice/
Then you can write code like;
if ([DEVICE_TYPE isEqualToString:DEVICE_IPAD]) {

}

or
if (IS_SIMULATOR && IS_RETINA) {

}

A: You can't do this with defines, as they're expanded at compilation time. However, you can define variables and set their initial value based on the user interface idiom:
// SomeClass.h
extern CGFloat deviceDependentSize;

// SomeClass.m
- (id)init
{
    // ...
    if ([[UIDevice currentDevice] userInterfaceIdiom] == UIUserInterfaceIdiomPad])
        deviceDependentSize = 1024.0f; // iPad
    else
        deviceDependentSize = 480.0f; // iPhone

    // etc.
}


text:
Q: Can I expect some heap memory locations to have faster access than others in C++? Suppose I am using a fixed-size memory-pool in C++ to preallocate memory and prevent calls to new and delete. It follows some simple logic:

*

*Allocate n memory blocks

*Push all memory blocks to a stack

*When the users requests memory, pop a block from the stack

*When the user returns memory, push the block to the stack

*If the stack is empty and the user requests memory, crash the application

Now, stack operations are very fast, but this scheme may be inefficient if some memory locations are faster to read and write than others. I think this might be the case due how the CPU works.
For example, suppose this is my memory-pool:
Stack:
2 4 5

Pool:
0 1 2 3 4 5
X X - X - -

Sections 2, 4 and 5 are unused, and 5 is on the top of the stack.
My current system would give the user block 5 on request, but block 2 might be faster to use because it is closer to the other memory that is in use.
My questions are:

*

*Is some heap memory faster to read and write than other areas?

*If so, what data-structures would be better than a stack to prioritize some memory blocks over others?

A: The heap memory is not faster or slower than the stack memory. Calling to the operating system for allocation is expensive.
If you want to write an optimized/fast code it is preferable to use sequential data to optimize the processor cache. Thats all. The best means to do that is std::array- with almost no overhead and std::vector-with some overhead but it gives you the option to resize. You can also use std::vector::reserve to do only one allocation when you know the number of the entries.


text:
Q: How to send out a http reponse I am a php newbie and I came across some problems when use php with apache.
   I don't want to use browser to send or receive http request so that I have to manually deal with this problem. On server side, I can use file_get_content("php://input") to extract body from the http request, but how can I build the http response? The method is "post" and I want to insert a xml string to the response body. Thank you for help!

A: Example:
See: http://php.net/manual/en/function.header.php
For HTTP codes, Google them up.

A: Simply echo "whatever" will return that back to the users browser. Remember that PHP is an interpreted language originally for inline scripting (i.e. mixing with HTML) prior to sending to the browser. So a file:
<?php echo "here"; ?>

will just return that reply to the users browser when they go to the appropriate URL. Adding any parsing etc. can be done in addition to this basic application logic.


text:
Q: can someone help me solve q4 from smo junior Let $x$, $y$ and $z$ be positive integers satisfying
$$x^2+y^2+z^2=2(xy+1) \quad\text{and}\quad  x+y+z=2022$$
If $x_1$ and $x_2$ are two distinct solutions for $x$, what is the value of $x_1+x_2$?
I'm stuck, I don't even know where to begin

A: For a given y,z,
$$x^2 - 2xy + y^2 + z^2 - 2 = 0$$
is a quadric equation in x.
Use the quadric formula from completing the square to find two solutions for x.
Adding those two solutions eliminates the radicals to give a very simple answer.


text:
Q: an open subspace of a complete metric space I came across this problem:
Suppose $Y$ is an open subspace of  a complete metric space $(X,d)$.
Prove that $Y$ is completely metrizable.
Can anyone help me?

A: HINT: The idea is to stretch distances close to the boundary of $Y$, so that sequences in $Y$ that converge to points outside $Y$ are no longer Cauchy. Without loss of generality assume that $d$ is bounded. Define
$$f:Y\to\Bbb R:y\mapsto\frac1{d(y,X\setminus Y)}\;,$$
and consider the function
$$\rho:Y\times Y\to\Bbb R:\langle y,z\rangle\mapsto d(y,z)+|f(y)-f(z)|\;.$$

A: If the Cauchy sequence in Y converges to a point in the subspace Y by the metric d, then the added term from the HINT above for the Y metric is as small as one pleases and $\rho$ approaches d.  When the Cauchy sequence in Y converges by d to a boundary point of Y, the added term does not converge and the sequence by the $\rho$ metric is not Cauchy.  Thus the only sequences that are Cauchy in (Y,$\rho$) are those that  converge in Y by the d metric, to which the $\rho$ metric converges.


text:
Q: How to disable pinch scale in UIImagePickerController I use UIImagePickerController to take photos in my ios app. But I don't want the camera view to scale when pinch gesture occur. what can I do? thx!

A: Try adding an overlay that captures the touches:
   picker = [[UIImagePickerController alloc] init];
   [picker setSourceType:UIImagePickerControllerSourceTypeCamera];
   [picker setCameraOverlayView:overlayView];
   [picker setShowsCameraControls:NO];
   [picker setDelegate:self];
   [self.view addSubview:picker.view];

A: You can simply disabled interaction on the picker's view.
picker.view.userInteractionEnabled = NO;


text:
Q: trying to align an icon to be right next to a text I am trying to align an icon right next to a text. I have used the :before tag but it doesn't seem to work? Is it because I am using google icons? Below is the code I want to replicate

.review {
  width: 317px;
  height: 25%;
}

.review h2 {
  color: white;
  font-style: normal;
  font-weight: bold;
  font-size: 30px;
  line-height: 23px;
  margin-left: 15px;
}

.review p {
  color: white;
  font-style: normal;
  font-weight: bold;
  font-size: 16px;
  line-height: 16px;
  text-transform: capitalize;
  transition: 0.3s;
  /* margin: 20px; */
}

Reviews

  check_box_outline_blank

Most Recent

Most Relevant

A: Please google first before asking a question on SO. Just by googling your problem, I found your answer in the first link. It is another question on SO. Click here.
Just put both items inside a
 element and use the css class display: inline-block as you can see in the example.

  check_box_outline_blank

Most Recent

A: Sorry, Your Question is not very clear, but the use of google icons should not be an issue. My advice would be to use css grid for layout issues (since the code that you have provided is html and css).
Here is a helpful link:
https://www.w3schools.com/css/css_grid.asp
grid-column should solve your problem: have 2 columns, the first one for your image and the second one for your text. You can additionally add grid-row for better layouts

A: I think you want icon with links.
Put it inside the paragraph tag.


text:
Q: Boltzmann "soft max" distribution Formula is here:
$$
p(i)=\frac{e^\frac{f(i)}{T}}{\displaystyle \sum_j e^\frac{f(j)}{T}}
$$
Prove:
1) Each $p(i)$ is a number between $0$ and $1$, no matter what the fitness is (positive or negative). This scheme does not require that fitness has to be positive.
2) The sum of all the $p(i)$'s is $1$, i.e. this is a probability distribution.
3) No matter what $T$ is:

*

*If two items have same fitness, they have same probability of being picked.

*If all fitnesses are the same, we pick random item.

4) No matter what the fitnesses are:

*

*As $T\to\infty$ we tend to pick random item.

*As   $T\to0$  we tend to pick only the best item. That is, its probability is $1$, the probability of all others is $0$.
If there are $m$ joint best items, we pick them with probability $1/m$, and all others with probability $0$.

A: Below is a probably excessively detailed answer.  The first few items are plain algebra.  The $4$th question needs some knowledge about the behaviour of the exponential function.  If you need more detail there, please leave a comment.
To make typing easier, let
$$a_i=e^{\frac{f(i)}{T}}.$$
(Actually, it is not just to make typing easier. Simpler looking expressions are easier to grasp.) Let $n$ be the number of terms in your sum. Note that
$$p(i)=\frac{a_i}{a_1+a_2+\cdots+a_n}.$$
(1):  For any $x$, $e^x \gt 0$. so all of the $a_i$ are positive.  If $n=1$ (one term only!), then $p(1)=a_1/a_1=1$.  If $n>1$, then since the $a_i$ are positive, $a_i \lt \sum a_i$, so $p(i)=a_i/(a_1+\cdots +a_n)\lt 1$.
(2):The sum $p(1)+p(2)+\cdots +p(n)$ is equal to
$$\frac{a_1}{a_1+a_2+\cdots +a_n}+\frac{a_1}{a_1+a_2+\cdots +a_n}+\cdots+\frac{a_n}{a_1+a_2+\cdots +a_n}.$$
Thus
$$p(1)+p(2)+\cdots +p(n)=\frac{a_1+a_2+\cdots+a_n}{a_1+a_2+\cdots +a_n}=1.$$
More compactly,
$$\sum p(i)=\sum \frac{a_i}{\sum a_i}=\frac{\sum a_i}{\sum a_i}=1.$$
(3): If $f(i)=f(j)$ (same fitness) for some particular $i$ and $j$ then $a_i=a_j$, so $p(i)=p(j)$.  The fact that $p(i)=p(j)$ means that the probability that $i$ is picked is the same as the probability that $j$ is picked.
If $f(i)=f(j)$ for all $i$, $j$, that means that $p(i)=p(j)$ for all pairs $(i,j)$, meaning that everyone has the same probability of being picked.
(4): This is the only part that requires that we look in more detail at the definition.
Limit as $T\to \infty$: As $T\to \infty$,  $f(i)/T \to 0$, so $e^{f(i)/T}\to 1$. (Recall that $e^0=1$.)   So each $a_i$ approaches $1$. This means that each $p(i)$ approaches $1/(1+1+\cdots +1)$.  So each $p(i)$ approaches $1/n$.  Thus, when $T$ is very large, all items have nearly equal probability of being picked.
Limit as $T\to 0$: First a technical remark.  Look at $e^{1/T}$ when $T$ is close to $0$.  If $T$ is positive, then $e^{1/T}$ is huge.  If $T$ is very large negative, then $e^{1/T}$ is close to $0$.  So it matters very much on which side of $0$ we are!  I will assume that the problem really means to ask about what happens when $T$ approaches $0$ from the right, that is, through positive values.
Suppose that there is a single best item. For definiteness, assume that item $1$ is the unique best item.  Then $f(1) \gt f(i)$ for all $i\gt 1$.  The probability of picking item $1$ is $p(1)$, where
$$p(1)=\frac{e^{\frac{f(1)}{T}}}  {e^{\frac{f(1)}{T}}+e^{\frac{f(2)}{T}}+\cdots+e^{\frac{f(n)}{T}}}.$$
Divide "top" and "bottom" by $e^{\frac{f(1)}{T}}$, or equivalently multiply top and bottom by $e^{-\frac{f(1)}{T}}$. We obtain
$$p(1)=\frac{1} {1+ e^{\frac{f(2)-f(1)}{T}}+ e^{\frac{f(3)-f(1)}{T}}\cdots+e^{\frac{f(n)-f(1)}{T}}}.$$
Finally, let $T$ approach $0$ from the right. Look now for example at the term
$e^{\frac{f(2)-f(1)}{T}}$ in the denominator, or any of the other terms in the denominator except for the initial $1$. Recall that since item $1$ is the unique most fit one, we have $f(2) \lt f(1)$, and therefore $f(2)-f(1)<0$.  So when $T$ is very close to $0$ but positive, $e^{\frac{f(2)-f(1)}{T}}$ is very close to $0$, since we are looking at an $e^y$ where $y$ is large negative.
So as $T$ approaches $0$ from the right, all of the denominator dies except for the first term, and therefore $p(1)$ approaches $1$.
Almost exactly the same idea will work if there are $m$ "fittest" items, say items $1$ to $m$.  The difference is that when we divide top and bottom, there will be $m$ $1$'s in the denominator, not just the single $1$ that we had in the unique best item case.


text:
Q: WPF/MVVM Load same UserControl multiple times in tab control I'm quite new to WPF/MVVM and have a lot to learn still, but I'm hitting an issue at the moment that i can't seem to find good answers for. Most probably because I'm asking the wrong questions.
What I have:
I have a main form with some buttons which load user controls. One of these user controls contains a TabControl.
This TabControl has a manually populated first Tab, which I've excluded from below snippet, but all other tabs should be populated with another user control, which will load database data depending on its viewmodel constructor.
XAML:
             <TabItem Header="Two"
                     Name="Two"
                     HorizontalAlignment="Stretch"
                     VerticalAlignment="Stretch"
                <ContentControl cal:View.Model="{Binding LoadedControl}"></ContentControl>
            </TabItem>

            <TabItem Header="Three"
                     HorizontalAlignment="Stretch"
                     VerticalAlignment="Stretch"
               <ContentControl cal:View.Model="{Binding LoadedControl}"></ContentControl>
            </TabItem>
            <TabItem Header="Four"
                     HorizontalAlignment="Stretch"
                     VerticalAlignment="Stretch"
               <ContentControl cal:View.Model="{Binding LoadedControl}"></ContentControl>
            </TabItem>

C#

        private DocumentTemplateControlViewModel _loadedControl;

        public DocumentTemplateControlViewModel LoadedControl
        {
            get { return _loadedControl; }
            set
            {
                if (value == _loadedControl)
                    return;

                _loadedControl = value;
                NotifyOfPropertyChange(() => LoadedControl);
            }
        }

        public int SelectedTabIndex
        {
            get
            {
                return _selectedTabIndex;
            }
            set
            {

                Task.Run(() => LoadData());
                _selectedTabIndex = value;
                LoadedControl = new DocumentTemplateControlViewModel(Templates, _selectedTabIndex);
             }

Now, This works as I intended it to work for Tab Two, but if I add the same line of
<ContentControl cal:View.Model="{Binding LoadedControl}">

to Tab Three,Four,etc.. (as I've done in the XAML snippet above) it will only work on the last tab that I've added the binding to, and Tab two,three will be blank.
I also tried to achieve the same thing with Caliburn Micro ActivateItem but this means i can also only declare one ActiveItem in my TabControl XAML as well.
TLDR: What is the best way to dynamically show a new user control viewmodel within a tabitem?
Thanks so much

A: Derive your view model from Conductor<IScreen>.Collection.OneActive and add the DocumentTemplateControlViewModel objects that you want to bind to the tabs to the Items property:
public class ShellViewModel : Conductor<IScreen>.Collection.OneActive
{
    public ShellViewModel()
    {
        Items.Add(new DocumentTemplateControlViewModel { DisplayName = "1" });
        Items.Add(new DocumentTemplateControlViewModel { DisplayName = "2" });
        Items.Add(new DocumentTemplateControlViewModel { DisplayName = "3" });
    }
}

DocumentTemplateControlViewModel must implement IScreen and the easiest way to do this is to derive from Screen:
public class DocumentTemplateControlViewModel : Screen
{
}

In the XAML you could then simply add a TabControl with a ContentTemplate, e.g.:
<TabControl Name="Items">
    <TabControl.ContentTemplate>
        <DataTemplate>
            <TextBlock Text="{Binding DisplayName}" />
        </DataTemplate>
    </TabControl.ContentTemplate>
</TabControl>

You may replace the TextBlock with a UserControl or any other UI element.


text:
Q: Django set user is_active to false when creating an employee separation I have an extended User model that is related to the employee Separation model and I would like to set that User as inactive with the SeparationCreateView. It's like when an employee leaves the company, it is recorded with this separation view and it is disabling employee access to the app automatically.
class Employee(models.Model):
    user = models.OneToOneField(User, on_delete=models.CASCADE)

class Separation(models.Model):
    employee = models.ForeignKey(Employee, on_delete=models.CASCADE)

Separation create view is working but it is not setting the user is_active to false
class SeparationCreateView(LoginRequiredMixin, CreateView):
    model = Separation
    form_class = SeparationForm
    template_name = 'coreHR/separation.html'
    success_url = reverse_lazy('corehr:separations')

    def form_valid(self, form):
        separation = form.save(commit=False)
        separation.employee.user.is_active = False
        separation.save()
        return super().form_valid(form)

What am I doing wrong here? Any help is highly appreciated.

A: You need to save the corresponding employee, so:
class SeparationCreateView(LoginRequiredMixin, CreateView):
    # ⋮

    def form_valid(self, form):
        user = form.save().employee.user
        user.is_active = False
        user.save()
        return super().form_valid(form)
we can make this slightly more efficient with:
from django.contrib.auth import get_user_model

class SeparationCreateView(LoginRequiredMixin, CreateView):
    # ⋮

    def form_valid(self, form):
        separation = form.save()
        User = get_user_model()
        User.objects.filter(
             employee__separation=separation
        ).update(is_active=False)
        return super().form_valid(form)
the latter will not run signals attached to the user model.


text:
Q: Insert Python dictionary into another dictionary, to generate .plist file? I'm trying to generate a .plist file with plistlib library, available in macOS Python 2.7.
The following code works:
#!/usr/bin/env python

from plistlib import writePlist

patches = [
    {
        'Arch': 'x86_64',
        'Base': 'early'
    },
    {
        'Arch': 'x86_64',
        'Base': 'late'
    }
]

result = [
    {
        'Arch': 'x86_64',
        'BundlePath': 'Alpha.kext'
    },
    {
        'Arch': 'x86_64',
        'BundlePath': 'Beta.kext'
    }
]
for i in patches:
    result.append(dict(i))

settings = {
    'Kernel': {
        'Add': result
    }
}
writePlist(settings, 'config.plist')

And produces a config.plist file with the content:
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
    <key>Kernel</key>
    <dict>
        <key>Add</key>
        <array>
            <dict>
                <key>Arch</key>
                <string>x86_64</string>
                <key>BundlePath</key>
                <string>Alpha.kext</string>
            </dict>
            <dict>
                <key>Arch</key>
                <string>x86_64</string>
                <key>BundlePath</key>
                <string>Beta.kext</string>
            </dict>
            <dict>
                <key>Arch</key>
                <string>x86_64</string>
                <key>Base</key>
                <string>early</string>
            </dict>
            <dict>
                <key>Arch</key>
                <string>x86_64</string>
                <key>Base</key>
                <string>late</string>
            </dict>
        </array>
    </dict>
</dict>
</plist>

However, my config.plist requires to have the patches dictionaries inside another dictionary:
            <dict>
                <dict>
                    <key>Arch</key>
                    <string>x86_64</string>
                    <key>Base</key>
                    <string>early</string>

The correct config file must look like (see lines 21 and 22 in an editor):
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
    <key>Kernel</key>
    <dict>
        <key>Add</key>
        <array>
            <dict>
                <key>Arch</key>
                <string>x86_64</string>
                <key>BundlePath</key>
                <string>Alpha.kext</string>
            </dict>
            <dict>
                <key>Arch</key>
                <string>x86_64</string>
                <key>BundlePath</key>
                <string>Beta.kext</string>
            </dict>
            <dict>
                <dict>
                    <key>Arch</key>
                    <string>x86_64</string>
                    <key>Base</key>
                    <string>early</string>
                </dict>
                <dict>
                    <key>Arch</key>
                    <string>x86_64</string>
                    <key>Base</key>
                    <string>late</string>
                </dict>
            </dict>
        </array>
    </dict>
</dict>
</plist>

How can I edit my setup.py file to produce the proper dictionary inside dictionary output? In case you wander why I split the code, is because this is a very simplified format, the actual code quite more complex. Therefore, I need a solution within the above code design. Thank you for your help.

A: The desired output does not look correct. Your "dictionary of dictionary" does not have a key with it. I suspect it should be something like
<dict>
    <key>Patches</key>
    <array>
        <dict>
            <key>Arch</key>
            ...
        </dict>
        <dict>
            <key>Arch</key>
            ...
        </dict>
    </array>
</dict>

If so, here is how you could do that, using the key of "Patches".
patches = [
    {
        'Arch': 'x86_64',
        'Base': 'early'
    },
    {
        'Arch': 'x86_64',
        'Base': 'late'
    }
]

result = [
    {
        'Arch': 'x86_64',
        'BundlePath': 'Alpha.kext'
    },
    {
        'Arch': 'x86_64',
        'BundlePath': 'Beta.kext'
    }
]
result.append({"Patches": patches})

settings = {
    'Kernel': {
        'Add': result
    }
}
writePlist(settings, 'config.plist')

Output
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
        <key>Kernel</key>
        <dict>
                <key>Add</key>
                <array>
                        <dict>
                                <key>Arch</key>
                                <string>x86_64</string>
                                <key>BundlePath</key>
                                <string>Alpha.kext</string>
                        </dict>
                        <dict>
                                <key>Arch</key>
                                <string>x86_64</string>
                                <key>BundlePath</key>
                                <string>Beta.kext</string>
                        </dict>
                        <dict>
                                <key>Patches</key>
                                <array>
                                        <dict>
                                                <key>Arch</key>
                                                <string>x86_64</string>
                                                <key>Base</key>
                                                <string>early</string>
                                        </dict>
                                        <dict>
                                                <key>Arch</key>
                                                <string>x86_64</string>
                                                <key>Base</key>
                                                <string>late</string>
                                        </dict>
                                </array>
                        </dict>
                </array>
        </dict>
</dict>
</plist>


text:
Q: array in joption pane dropdown - Java? Hi I am trying to access an array and show it in a dropdown list using joptionpane. I have it sort of working using:
for (int i = 0; i < data.length; r++)
{

    Object list = JOptionPane.showInputDialog(null, "Select Code",
    "Code", JOptionPane.QUESTION_MESSAGE, null, data[i][0], data[0][0]);
}

This brings up a dropdown list...but with only one piece of data and displays it about 5times (array length). How could I get this to display each data just in one dropdown?
Edit - Forgot to say when using data[i][0] it brings an error, as it only lets me use data[i] ? - "cannot find symbol"
Thanks

A: It shouldn't be a loop.
public static Object showInputDialog(Component parentComponent,
                                     Object message,
                                     String title,
                                     int messageType,
                                     Icon icon,
                                     Object[] selectionValues,
                                     Object initialSelectionValue)

are you sure you are passing the selectionValues object array and initialSelectionValue Object?
What is the type of data? Assuming data[0] is an array, try
JOptionPane.showInputDialog(null, "Select Code",
    "Code", JOptionPane.QUESTION_MESSAGE, null, data, data[0]);

Can you tell what exactly is your data's type? This example from JDK
Object[] possibleValues = { "First", "Second", "Third" };
Object selectedValue = JOptionPane.showInputDialog(null,
            "Choose one", "Input",
            JOptionPane.INFORMATION_MESSAGE, null,
            possibleValues, possibleValues[0]);

works perfectly well for me.

A: This is from the Java API:
public static Object showInputDialog(Component parentComponent,
                                     Object message,
                                     String title,
                                     int messageType,
                                     Icon icon,
                                     Object[] selectionValues,
                                     Object initialSelectionValue)

Note that the selectionValues is a single dimensional array.  When you feed in data[i][0], you are giving it a single value.  When you feed in data[i] you are giving in a single row of the array, as a one dimensional array.  (Recall that java doesn't have n-Dimensional arrays, only arrays of arrays.)
You probably need to build a new one dimensional array, and feed that in.
Alternatively, if possible, convert the rows of your arrays to some object, and implement the toString() method in that class to display what you want.


text:
Q: Is any Language better than PHP for Web Development? PHP has Thousands of Functions related to Web Development baked right in from Simple Ones like filter_var() , htmlentities() to json_encode() similar_text() and levenshtein() distance for Percentage matching. There are so many array() and string() functions that it is really mind-blowing !
Now comes complete OOP support in PHP5 and Native Unicode in  PHP6.
Because try writing for example a Cookie in Java or a Servlet and you know what I am talking about. For String and Array handling most probably I am inventing some for-loop Algorithm in Java when in PHP I always find some ready-made function. Recent examples for me have been array_count_values() [Nothing similar in Java for finding aggregate of a Cart] and array_chunk() [ Try wrestling with Java Tokenizers here] . similar_text() Function in PHP is itself a beauty when you need to find How much 2 Strings matcheach other percentage-wise.
Does any other Web Development Language has such Vastness and Sheer Expanse as PHP ?

A: There is no language better than another.
There is one language which fits your application requirements and knowledge better, and that's the one you should choose.


text:
Q: Have div maintain screen width and height I am looking to create a website in which it has a main div in which both the width and the height is always the size of the screen. No matter what is contained within this div it must contain this width and height.
If you look at this example of what I want.

My aim is for the navigation section to be contained in the large blue part on the left and for the main page content to be displayed within the white box and for this white div to only scroll sideways. I have searched for days on trying to get this to work but something always goes wrong. Examples of things I have tried are:
How to make the main content div fill height of screen with css
how to make a full screen div, and prevent size to be changed by content?
How to make a div to fill a remaining horizontal space?
If somebody can help with this or at least point me in the right direction for guidance it would be awesome. Thanks in advance.

A: 1. Using CSS3 flexbox

/*QuickReset*/ *{margin:0; box-sizing:border-box;} html,body{height:100%;}

/*
OP: -I am looking to create a website in which it has a
main div in which both the width and the height is
always the size of the screen
A: -let this be body!
*/
body{
  background: #0ae;
  display: flex;
  flex-flow: row nowrap;
  padding: 40px;
}

/*
OP: -My aim is for the navigation section to be
contained in the large blue part on the left
A: -Thanks to CSS3 flexbox on body all you need is a desired menu width:
*/
aside{
  width: 140px;      /* or any size you want, px, %, ... */
}

/*
OP: -and for the main page content to be displayed within
the white box and for this white div to only scroll sideways
A: -add overflow:auto; to make it scroll and flex:1 to grow to available size
*/
article{
  background: #fff;
  overflow: auto;    /* make element scrollable */
  flex: 1;           /* let the browser grow this element */
}

/* just to demonstrate sideways scroll */
article{
  display: flex;
  flex-flow: row nowrap;
}
section{
  min-width:100%;
}

  Menu

"and I want this CONTENT area to scroll sideways"

YEY

2. The old-school way (compatible down to IE8)

/*QuickReset*/ *{margin:0;box-sizing:border-box;} html,body{height:100%;}

body{ /* your app */
  padding:40px;
  background: #0ae;
}

#aside{ /* your menu */
  float:left;
  width: 100px;
}
#content{ /* white content area */
  overflow: auto;
  margin-left: 100px;  /* menu is 100px remember? */
  height:100%;
  background: #fff;
}

/* Just to test horizontal scrollability */
#content{
  white-space:nowrap;
}
.page{
  white-space: normal;
  display: inline-block;
  vertical-align: top;
  width: 100%;
  height:100%;
  margin-right: -4px;
  /* Todo: make scroll vertically each page if needed */
}

  Menu

Content A

Content B

A: after setting the main div css overflow properties the way you like them,
you can always javascript it (as in the given example)- and it will be fully backward compatible.


text:
Q: asp mvc file upload (with validation)

As you can see my model (TestFileUploadModel) and my controller action (FileUpload)
-> 3th screen before i submit: file is selected
-> 4th screen after i submit: name field is required, but file is cleared..
Anyone who was an idea how to solve this? (or a workaround?)

A: As stated in the comment by user bzlm you can check with JQuery if the file has value and prevent the submit of the form.
You can attach a function at the submit of your form and do this check
if ($("#MyInputFileField").val()) {
  //do your things
}
else
{
  //PreventDefault and show error message
}

EDIT:
Look here for an answer that should be similar to your question
for an example using jquery validation plugin check this


text:
Q: Mongo shell can't connect to server This must be a simple problem, but I've very carefully followed the excellent and simple documentation provided at https://docs.c9.io/setting_up_mongodb.html and read EVERY cloud9-ide tagged question that includes 'MongoDb' - to no avail. I'd appreciate any help possible.
Following the directions referenced above, I appear to be able to get mongo running fine.  (See below.)
However, when I try the shell - as instructed - I get the following error:
cliffchaney@sacs:~/workspace $ mongo --host $IP
MongoDB shell version: 2.6.4
connecting to: 0.0.0.0:27017/test
2014-09-10T17:53:55.570+0000 Error: couldn't connect to server 0.0.0.0:27017 (0.0.0.0), address resolved to 0.0.0.0 at src/mongo/shell/mongo.js:148
exception: connect failed

Any suggestions?
As noted, it appears that I can get mongod running.  After following the previously mentioned instructions, I can execute the following (though I do get a warning):
cliffchaney@sacs:~/workspace $ ./mongod
2014-09-10T17:52:29.370+0000 ** WARNING: --rest is specified without --httpinterface,
2014-09-10T17:52:29.370+0000 **          enabling http interface
warning: bind_ip of 0.0.0.0 is unnecessary; listens on all ips by default
2014-09-10T17:52:29.376+0000 [initandlisten] MongoDB starting : pid=1345 port=27017 dbpath=data 64-bit host=cliffchaney-sacs-983224
2014-09-10T17:52:29.376+0000 [initandlisten] db version v2.6.4
2014-09-10T17:52:29.376+0000 [initandlisten] git version: 3a830be0eb92d772aa855ebb711ac91d658ee910
2014-09-10T17:52:29.376+0000 [initandlisten] build info: Linux build7.nj1.10gen.cc 2.6.32-431.3.1.el6.x86_64 #1 SMP Fri Jan 3 21:39:27 UTC 2014 x86_64 BOOST_LIB_VERSION=1_49
2014-09-10T17:52:29.376+0000 [initandlisten] allocator: tcmalloc
2014-09-10T17:52:29.376+0000 [initandlisten] options: { net: { bindIp: "0.0.0.0", http: { RESTInterfaceEnabled: true, enabled: true } }, storage: { dbPath: "data", journal: { enabled: false } } }
2014-09-10T17:52:29.389+0000 [initandlisten] waiting for connections on port 27017
2014-09-10T17:52:29.389+0000 [websvr] admin web console waiting for connections on port 28017
2014-09-10T17:53:29.389+0000 [clientcursormon] mem (MB) res:51 virt:238
2014-09-10T17:53:29.389+0000 [clientcursormon]  mapped:80
2014-09-10T17:53:29.389+0000 [clientcursormon]  connections:0
2014-09-10T17:58:29.399+0000 [clientcursormon] mem (MB) res:52 virt:239
2014-09-10T17:58:29.399+0000 [clientcursormon]  mapped:80
2014-09-10T17:58:29.399+0000 [clientcursormon]  connections:0
2014-09-10T18:03:29.410+0000 [clientcursormon] mem (MB) res:52 virt:239
2014-09-10T18:03:29.410+0000 [clientcursormon]  mapped:80
2014-09-10T18:03:29.410+0000 [clientcursormon]  connections:0*

A: You can access the shell prompt by simply running
$ mongo

Without the --host argument.


text:
Q: How to handle conflicting basic auth from NGINX reverse proxy with JWT auth from Django? we have a standard Django web app running behind a reverse proxy.
I want to setup a two layer authentification : one from the nginx reverse proxy to shield the application (presently a HTTP Basic authentication -yes we plan to upgrade to something stronger like SSL client certificate or smartcards-), and one at the application level
However we are currently running into a issue because the HTTP Basic Authorization header is conflicting with the Django Authorization header
The problem arises because the JWT auth from Django requires us to fill the "Authorization" header with the token while NGINX uses another type of authentication.
I'm looking for the best way to solve this problem and have the following questions :

*

*is it possible to require Django to use an alternative HTTP header to carry its authentication token (instead of "Authorization")

*or, conversely, is it possible to configure our nginx to use an alternative header for the HTTP Basic authentication (but it seems unlikely as it is done at the browser level) or to require the nginx to do the header translation : i.e. converting back and forth header before pushing them to the Django app.

*or, even better, can we configure Django to stop using tokens and use the user authentified by nginx?

I'm looking for a solution that allows nginx to handle security and be responsible about it while adding another layer on top of it in Django what would be the best solution to try ?
Thanks


text:
Q: Underscore.js find unique values in array of objects; Return unique items and their count I am using _underscore.js to find all unique items in an array, but I can't figure out how to also get the number of unique items returned.
_PERSONARRAY = [{name:"tom",age:7}{name:"john",age:9}{name:"becky",age:2}{name:"sam",age:7}]

_UNIQUEAGEARRAY = _.chain(_PERSONARRAY).map(function(person) { return person.age }).uniq().value();

In this case _UNIQUEAGEARRAY will equal:
[7,9,2]

What I actually need returned is something like:
[{uniqueAge:7,numberOfPeople:2}{uniqueAge:9,numberOfPeople:1}{uniqueAge:2,numberOfPeople:1}]

Thanks for help.  Also, I'm assuming _underscore.js is quick at doing this??  If it's stupid slow tell me cause I'd be open to other solutions.

A: A nice solution is to use the optional iterator function to underscore's uniq function:
let people = [
  {name: "Alice", age: 21},
  {name: "Bob", age: 34},
  {name: "Caroline", age: 21}
];
_.uniq(people, person => person.age);

Docs: http://underscorejs.org/#uniq

A: I think you're looking for the countBy function:
_UNIQUEAGEARRAY = _.countBy(_PERSONARRAY, "age");

It produces the result:
{"2":1,"7":2,"9":1}

JSFiddle demo: http://jsfiddle.net/4J2SX/

A: You can use underscore's groupBy if you want (might not be a good idea for a large dataset since it keeps a list of all the grouped items)
Example:
var d = _.groupBy(_PERSONARRAY, function(p){
    return p.age;
});

If you want to map this to your exact format try doing a map after the groupBy:
var x = _.map(d, function(people, age) {
    return {uniqueAge: age,  numberOfPeople: people.length};
});

jsFiddle: http://jsfiddle.net/jsgkC/2/

A: groupBy function is useful.
_personsList = [{name:"anjo",age:5},{name:"george",age:3},{name:"jack",age:5}];
_uniqAgeList = _.groupBy(_personsList, "age");

will produce output
{
    "3":[{"name":"george","age":3}],
    "5":[{"name":"anjo","age":5},{"name":"jack","age":5}]
}

jsfiddle :http://jsfiddle.net/4J2SX/199/


text:
Q: How to get Activity Instance in Module class using AndroidInjector? I have sample project in which I am using dagger-android AndroidInjector to Inject dependencies.
In this sample app I have a class Navigator which does all the Activity to Activity navigation and it requires the instance of current Activity in it's Constructor.
I have a AppModule class which provides the Instances to the other component, which is also responsible for providing the instance of Navigator to my presenter, but the Navigator constructor takes Activity as parameter from the AppModule.
How can I access the activity instance to the Navigator constructor.
I have tried Injecting the instance of Activity directly in Navigator by annotating the Activity member variable with @Inject annotation but that throws error while building the project.
error: [dagger.android.AndroidInjector.inject(T)] android.app.Activity cannot be provided without an @Inject constructor or from an @Provides-annotated method. android.app.Activity is injected at
I have referred other SA post but that doesn't help with my query or may be I am failed to understand the solution given there.
Below are the post I followed
How to inject current activity in a collaborator using Dagger 2.11 Android injector
How to get MainActivity inside a module using AndroidInjector
Below is the code which I have implemented:
Application.Java
public class MyApplication extends Application implements HasActivityInjector {

    @Inject
    DispatchingAndroidInjector<Activity> androidInjector;

    @Override
    public void onCreate() {
        super.onCreate();
        DaggerAppComponent
                .builder()
                .application(this)
                .build()
                .inject(this);
    }

    @Override
    public AndroidInjector<Activity> activityInjector() {
        return androidInjector;
    }
}

MainActivity.java
public class MainActivity extends BaseActivity implements BaseView {

    @Inject
    Context application;

    @Inject
    MainPresenter mainPresenter;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        AndroidInjection.inject(this);
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        ButterKnife.bind(this);
    }
}

MyPresenter.Java
public class MyPresenter extends BasePresenter<IActivityView> {

    private final NavigationRouter mNavigationRouter;

    @Inject
    public MyPresenter(Navigator navigatr) {
        mNavigationRouter = navigationRouter;
    }

}

Navigator.Java
//This is how my Navigator is currently.
public class Navigator{

    Activity mActivity;

    @Inject
    public Navigator(Activity activity){
    mActivity = activity;
    }

}

ActivityBuilder.java
@Module
public abstract class ActivityBuilder {

    @ContributesAndroidInjector
    abstract MainActivity bindMainActivity();

    @ContributesAndroidInjector
    abstract LoginActivity bindLoginActivity();
}

AppModule.Java
@Module
public class AppModule {
//How can i have the instance of current activity in this module class.
    @Provides
    @Singleton
    NavigationRouter providesNavigationRouter(Activity activity) {
        //Here I want the instance of current activity
        return new NavigationRouter(activity);
    }
}

AppComponent.Java
@Component(modules = {
        AndroidInjectionModule.class,
        AppModule.class,
        ActivityBuilder.class})
@Singleton
public interface AppComponent {

    @Component.Builder
    interface Builder {
        @BindsInstance
        Builder application(Application application);

        AppComponent build();
    }

    void inject(MyApplication application);
}

Any help on this will be much appreciated.
I have update the code snippet for more clarity

A:
In this sample app I have a class Navigator which does all the
  Activity to Activity navigation and it requires the instance of
  current Activity in it's Constructor

I'm a little confused on how this is expected to work. Does this mean that each Activity creates its own Navigator? If the Activity is supplied via the constructor then I can't think of any other way this would be feasible.
Anyway, assuming you do want to create a Navigator for each of your Activities, then your Dagger setup would look like this:
MainActivityModule.java
@Module
public abstract class MainActivityModule {
    @Binds @Named(MainActivity.class.getSimpleName()) abstract Navigator navigator(MainActivity ma);
}

ActivityBuilder.java
@Module
public abstract class ActivityBuilder {
    @ContributesAndroidInjector(modules = MainActivityModule.class)
    abstract MainActivity bindMainActivity();
}

MainActivity.java
public class MainActivity extends BaseActivity implements BaseView {

    @Inject Navigator navigator; //This will hold a reference to MainActivity

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        AndroidInjection.inject(this); //Or AndroidSupportInjection...
    }
}

Edit:
I made a couple of points the comments that show a "Navigator" class that takes a single Activity in via its constructor isn't feasible. You could instead try this:
@Singleton
public final class Navigator {

    private WeakReference<BaseActivity> ref = null;

    @Inject
    Navigator(){}

    void setForegroundActivity(BaseActivity base) {
        this.ref = new WeakReference<>(base);
    }

    void transitionTo(Class<? extends BaseActivity> next) {
        if(ref == null) return;
        final BaseActivity current = ref.get();
        if(current != null) {
            current.transitionTo(next);
        }
    }
}

public class MyApp extends Application implements Application.ActivityLifecycleCallbacks {

    @Inject Navigator navigate;

//...
   void onActivityResumed(Activity activity) {
        if(activity instanceof BaseActivity) {
            navigate.setForegroundActivity((BaseActivity) activitiy);
        }
    }

}

public class AnExampleClass {

    private final Navigator navigate;

    @Inject
    AnExampleClass(Navigator navigate) {
        this.navigate = navigate;
    }

    //...
    void someMethodRequiringATransition() {
        navigator.transitionTo(AnotherActivity.class);
    }

}

public class AnExampleActivity extends BaseActivity {

    @Override
    public void transitionTo(Class<? extends BaseActivity> next) {
        if(AnotherExampleActivity.class.equals(next)) {
            //Do stuff specific to transitioning to "Another Example Activity"
        }
    }

}

I use WeakReferences because storing an Activity in a singleton is dangerous, and effectively begs memory leaks. However, you could use the ActivityLifecycleCallbacks to remove Activities as they move into "onPause" as well.


text:
Q: How to check EOF condition when using istream::ignore() function? My test file contains just 2 characters: a and \n:
$ hexdump -C a.txt
00000000  61 0a                                             |a.|
00000002

I want to test istream::ignore function:
(1) I use ifs.ignore(2) to skip a and \n:
#include <iostream>
#include <fstream>
#include <limits>

using namespace std;

int main() {
    std::ifstream ifs("a.txt");

    while (!ifs.eof())
    {
        std::cout << "Not end of file\n";
        ifs.ignore(2);
    }
    return 0;
}

Test result is like this:
$ ./a.out
Not end of file

Program only enter loop once, and it fits my expectation.
(2) I use std::numeric_limits<std::streamsize>::max(), '\n' to skip a and \n:
#include <iostream>
#include <fstream>
#include <limits>

using namespace std;

int main() {
    std::ifstream ifs("a.txt");

    while (!ifs.eof())
    {
        std::cout << "Not end of file\n";
        ifs.ignore(std::numeric_limits<std::streamsize>::max(), '\n');
    }
    return 0;
}

But this time the program enters loop 2 time:
$ ./a.out
Not end of file
Not end of file

I can't understand this. Per my understanding:
ifs.ignore(std::numeric_limits<std::streamsize>::max(), '\n');

should pass all characters, and ifs.eof() should return true the second time.

A: std::basic_istream::ignore will only set eofbit if it encounters the end of the stream. In your case, it instead encounters the \n, discards this, then returns without examining the stream further. It has therefore not encountered the end of the stream in the first iteration, since it stops inspecting after extracting delim; for all it knows, there could be more data after the \n, because it hasn't tried to look at it yet.


text:
Q: Look for big files not in the .git directory I am tracking some big files with git annex. What I usually do is:
find . -type f -size +10M | xargs -r git annex add

The problem I have is that find encounters the big files in the .git directory:
» find . -type f -size +10M
./.git/annex/objects/47/fx/SHA256E-s1208418304--5bca6a4c23b7c92976076e1a2490e81a6181301c86d2c2737840bb5b50a285d1.vmdk/SHA256E-s1208418304--5bca6a4c23b7c92976076e1a2490e81a6181301c86d2c2737840bb5b50a285d1.vmdk
./.git/annex/objects/ZZ/Q5/SHA256E-s3262054400--63bc227c3247ed9dfcb41d5ed20b887cf0ba2ef207dfae0ba95160efcbc89581.vmdk/SHA256E-s3262054400--63bc227c3247ed9dfcb41d5ed20b887cf0ba2ef207dfae0ba95160efcbc89581.vmdk
./.git/annex/objects/zj/mK/SHA256E-s6072303616--efdb32d49d31557a84f66fdb9871e24b63aa97b19956f050e2516cf392cd2467.vdi/SHA256E-s6072303616--efdb32d49d31557a84f66fdb9871e24b63aa97b19956f050e2516cf392cd2467.vdi

And git annex tries to re-add them.
How can I tell find to ignore (prune) the files in the .git directory, while still filtering for big files (+10M). I am unable to construct the right command.

A: find . -type f -size +10M -not -path "./.git/*" should do the trick

A: Remove .git/ from the descent candidate list.
find . -name .git -type d -prune -o -type f -size +10M -print0 | xargs -0 ...


text:
Q: iPhone 13, youtube app community posts don't load For some reason the youtube community posts don't load in the iPhone app for me.

My girlfriend has the same iPhone, running the same OS and she's on the same network, her youtube app works fine. What could be wrong?
It was actually worse, because even the previews of videos wouldn't load, so, I reinstalled the app, and they started loading, but the community posts don't load..


text:
Q: Why I can call 'print' from 'eval' For code:
#!/usr/bin/python

src = """
print '!!!'
import os
"""

obj = compile(src, '', 'exec')
eval(obj, {'__builtins__': False})

I get output:
!!!
Traceback (most recent call last):
  File "./test.py", line 9, in <module>
    eval(obj, {'__builtins__': False})
  File "", line 3, in <module>

ImportError: __import__ not found

Both 'print' and 'import' are language construct. Why does 'eval' restrict using of 'import' but doesn't restrict 'print'?
P.S. I'm using python 2.6
UPDATE: Question is not "Why does import not work?" but "Why does print work?" Are there some architecture restrictions or something else?

A: The __import__ method is invoked by the import keyword:  python.org
If you want to be able to import a module you need to leave the __import__ method in the builtins:
src = """
print '!!!'
import os
"""

obj = compile(src, '', 'exec')
eval(obj, {'__builtins__': {'__import__':__builtins__.__import__}})

A: In your eval the call to import is made successfully however import makes use of the __import__ method in builtins which you have made unavailable in your exec. This is the reason why you are seeing
ImportError: __import__ not found

print doesn't depend on any builtins so works OK.
You could pass just __import__ from builtins with something like:
eval(obj, {'__builtins__' : {'__import__' :__builtins__.__import__}})

A: print works because you specified 'exec' to the compile function call.

A: import calls the global/builtin __import__ function; if there isn't one to be found, import fails.
print does not rely on any globals to do its work. That is why print works in your example, even though you do not use the available __builtins__.


text:
Q: How do I get an NSManaged Object ID from an array and delete it? I have an array of NSManagedObject called coreTasks. I want to be able to whenever I remove an object from the array to be able to remove the object from my coreData entity because at launch of the application the coredata entity will populate my array so my contextualaction below is not permanently deleting the object.
    func deleteAction(at: IndexPath) -> UIContextualAction {
    let deleteActionImage = UIImage(named: "Delete")?.withTintColor(.white)
    let action = UIContextualAction(style: .destructive , title: "Delete") { (action, view, completion) in

        coreTasks.remove(at: at.row)
        self.homeTableView.deleteRows(at: [at], with: .automatic)
        completion(true)
    }
    action.image = deleteActionImage
    action.backgroundColor = Colors.reddelete
    return action
}

A: To delete an object you have to call this method:
func deleteCoreTasks(withUUID uuid: UUID) {
        let fetchRequest: NSFetchRequest<CoreTasks> = CoreTasks.fetchRequest()
        fetchRequest.predicate = NSPredicate(format: "%K == %@", "uuid", uuid as CVarArg)

        do {

            let coreTasks = try context.fetch(fetchRequest)

            if let coreTask = coreTasks.first {
                 context.delete(coreTask)
            }

            try context.save()

        } catch {
            print(error.localizedDescription)
        }

    }

*

*First, you have to find your object in your DB. In the method I
wrote I'm using an UUID, but you can find that with in other ways
(depends on your model).

*Second, delete the object.

*Third, save the context (important!)

A: You don't need the object ID, just delete the record in the context and save the context.
func deleteAction(at indexPath: IndexPath) -> UIContextualAction {
    let deleteActionImage = UIImage(named: "Delete")?.withTintColor(.white)
    let action = UIContextualAction(style: .destructive , title: "Delete") { (action, view, completion) in
        let context = (UIApplication.shared.delegate as! AppDelegate).persistentContainer.viewContext
        let objectToDelete = coreTasks.remove(at: indexPath.row)
        self.homeTableView.deleteRows(at: [indexPath], with: .automatic)
        context.delete(objectToDelete)
        try? context.save()

        completion(true)
    }
    action.image = deleteActionImage
    action.backgroundColor = Colors.reddelete
    return action
}


text:
Q: understanding if statement I have few lines of code in a theme, I did not understood, can anyone explain me this.
$screen = get_current_screen(); // understood this
if ( $screen && 'post' == $screen->base && 'page' == $screen->id ) { // not sure about this line
// code to execute something
}

As per I have understood the code is executed when post type is post or page, I am not sure how, I need to add another custom post type (player) in that if statement.

A:
the code is executed when post type is post or page

No, only if the post type is page (because of the 'page' == $screen->id).
Because that if statement actually checks if the current admin screen is the one for editing or creating a Page (post type of page), where the URL looks like so: (note that the post type is not visible in the URL when a post/Page/CPT is being edited)
http://example.com/wp-admin/post.php?post=2&action=edit

*

*On such screens — editing or creating a post/Page/CPT, $screen->id is equivalent to $screen->post_type which is the post type (slug).

*And $screen->base is post which is the base name of the file name in the current URL — base name is the file name without the extension — so if the file name is post.php, the base name is post. However, when creating a post/Page/CPT, the file name is actually post-new.php, but still the $screen->base is post (and not post-new) because WordPress strips the -new part.

*Additionally, you can distinguish between editing and creating by checking the screen's action; i.e. whether $screen->action is edit or add (e.g. 'edit' == $screen->action to check if the action is editing).

I need to add another custom post type (player) in that if
  statement

Just change the:
'page' == $screen->id

to:
in_array( $screen->id, array( 'post', 'page', 'player' ) )

Or the full code:
if ( $screen &&                // 1. we've got a valid screen
    'post' == $screen->base && // 2. the screen base is either post.php or post-new.php
    // and 3. the post type is one of the array values.
    in_array( $screen->id, array( 'post', 'page', 'player' ) )
) {
    // your code here
}

I hope that helps, and you can check the get_current_screen()'s function reference here. :)


text:
Q: Stacks - Evaluating Postfix Expressions in C My task was to implement int isOperator(char *);
Operands get Pushed, and Operators get Top, Popped and the expressions gets Pushed.
  Example:
  6 5 2 3.14 + 8 * + 3 + *
  Pushing: 6.000000
  Pushing: 5.000000
  Pushing: 2.000000
  Pushing: 3.140000
  Pushing: 2.000000+3.140000=5.140000

Is there something wrong with my implementation?
Here is my intOperator(char*).
int isOperator(char *s){

int i;
char Ops[] = { '+', '-', '*', '/' };

for (i = 0; i < 4; i++)
{
    if (s == Ops[i])
        return (1);
    return (0);
}
}

Here is my implementation for pushing and popping operands and operators.
    S = CreateStack();
n = sizeof(postfixExpression) / sizeof(postfixExpression[0]); // Compute array size
for (i = 0; i<n; i++){ // Print elements of postfix expressions
    printf("%s ", postfixExpression[i]);
}
printf("\n");

for (i = 0; i<n; i++){

    if (isalnum(postfixExpression[i])){
        Push(atof(postfixExpression[i]), S);
        printf("Pushing: %d", atof(postfixExpression[i]));
    }
    else if (isOperator(postfixExpression[i]))
    {
        rightOperand = Top(S);
        Pop(Top(S));
        leftOperand = Top(S);
        Pop(Top(S));

        switch (isOperator(postfixExpression[i])){
        case '+':
            Push(leftOperand + rightOperand, S);
            printf("Pushing: %d+%d=%d", leftOperand, rightOperand, leftOperand + rightOperand);
            break;
        case '-':
            Push(leftOperand - rightOperand, S);
            printf("Pushing: %d-%d=%d", leftOperand, rightOperand, leftOperand - rightOperand);
            break;
        case '*':
            Push(leftOperand * rightOperand, S);
            printf("Pushing: %d*%d=%d", leftOperand, rightOperand, leftOperand * rightOperand);
            break;
        case '/':
            Push(leftOperand / rightOperand, S);
            printf("Pushing: %d/%d=%d", leftOperand, rightOperand, leftOperand / rightOperand);
            break;
        default:
            break;
        }

    }
    else
        break;
}

printf("%s\n", S);
DisposeStack(S);
return 0;

A: A much simpler implementation is this:
int isOperator(char *s)
{
    return strchr("+-*/", s[0]) && s[1] == '\0';
}

That returns 1 (true) if the first character in s is an operator and the second is the null terminator (meaning no other content following the operator character, for strict checking).
As for the stack logic, you should make sure the stack is not empty when you pop.


text:
Q: Getting invalid argument error for print function I am getting invalid argument error while trying to print dictionary values.
dict={"a":1,"b":2,"c":3}
print(*dict)
print(**dict)

TypeError                                 Traceback (most recent call last)
<ipython-input-49-92f0ed7852d8> in <module>
      1 dict={"a":1,"b":2,"c":3}
      2 print(*dict)
----> 3 print(**dict)

TypeError: 'a' is an invalid keyword argument for print()

A: The **dict is used to "Unpacks the contents of a dictionary into the function call, see the reference here:**Dictionary
def add (a=0, b=0, c= 0):
   return a + b + c
dict={"a":1,"b":2,"c":3}
print(*dict)
unpacking = add(**dict)
print(unpacking)

The printed unpacking value will be equal to 6.
You can use dict.values() to get the values of the dictionary. E.g. print (dict.values()) will return
dict_values([1, 2, 3])


text:
Q: Spring Web Application got initialized twice I found my spring web project got initialized twice on tomcat and here are the messages printed
first time:
 INFO: Initializing Spring root WebApplicationContext
 INFO 2015-01-08 15:18:04 ContextLoader Root WebApplicationContext: initialization started
 INFO 2015-01-08 15:18:04 XmlWebApplicationContext Refreshing Root WebApplicationContext: startup date [Thu Jan 08 15:18:04 GMT+08:00 2015]; root of context hierarchy
 INFO 2015-01-08 15:18:04 XmlBeanDefinitionReader Loading XML bean definitions from file [/home/pinkdahlia/develop/apache-tomcat-7.0.55/webapps/vips-mobile-mlisting-backend/WEB-INF/classes/spring-shiro.xml]
 INFO 2015-01-08 15:18:04 XmlBeanDefinition Reader Loading XML bean definitions from file [/home/pinkdahlia/develop/apache-tomcat-7.0.55/webapps/vips-mobile-mlisting-backend/WEB-INF/classes/spring-datasources.xml]
 INFO 2015-01-08 15:18:04 XmlBeanDefinitionReader Loading XML bean definitions from file [/home/pinkdahlia/develop/apache-tomcat-7.0.55/webapps/vips-mobile-mlisting-backend/WEB-INF/classes/spring-commons.xml]
 INFO 2015-01-08 15:18:05 XmlBeanDefinitionReader Loading XML bean definitions from file [/home/pinkdahlia/develop/apache-tomcat-7.0.55/webapps/vips-mobile-mlisting-backend/WEB-INF/classes/spring-mybatis.xml]
 INFO 2015-01-08 15:18:05 XmlBeanDefinitionReader Loading XML bean definitions from file [/home/pinkdahlia/develop/apache-tomcat-7.0.55/webapps/vips-mobile-mlisting-backend/WEB-INF/classes/spring-xmemcached.xml]
 INFO 2015-01-08 15:18:05 XmlBeanDefinitionReader Loading XML bean definitions from file [/home/pinkdahlia/develop/apache-tomcat-7.0.55/webapps/vips-mobile-mlisting-backend/WEB-INF/classes/spring-aop.xml]
 INFO 2015-01-08 15:18:05 PropertiesFactoryBean Loading properties file from URL [file:/home/pinkdahlia/develop/config/BackendConf.properties]

And the second time:
 INFO: Initializing Spring root WebApplicationContext
 INFO 2015-01-08 15:18:13 ContextLoader Root WebApplicationContext: initialization started
 INFO 2015-01-08 15:18:13 XmlWebApplicationContext Refreshing Root WebApplicationContext: startup date [Thu Jan 08 15:18:13 GMT+08:00 2015]; root of context hierarchy
 INFO 2015-01-08 15:18:13 XmlBeanDefinitionReader Loading XML bean definitions from file [/home/pinkdahlia/develop/apache-tomcat-7.0.55/webapps/vips-mobile-mlisting-backend/WEB-INF/classes/spring-shiro.xml]
 INFO 2015-01-08 15:18:13 XmlBeanDefinitionReader Loading XML bean definitions from file [/home/pinkdahlia/develop/apache-tomcat-7.0.55/webapps/vips-mobile-mlisting-backend/WEB-INF/classes/spring-datasources.xml]
 INFO 2015-01-08 15:18:13 XmlBeanDefinitionReader Loading XML bean definitions from file [/home/pinkdahlia/develop/apache-tomcat-7.0.55/webapps/vips-mobile-mlisting-backend/WEB-INF/classes/spring-commons.xml]
 INFO 2015-01-08 15:18:13 XmlBeanDefinitionReader Loading XML bean definitions from file [/home/pinkdahlia/develop/apache-tomcat-7.0.55/webapps/vips-mobile-mlisting-backend/WEB-INF/classes/spring-mybatis.xml]
 INFO 2015-01-08 15:18:13 XmlBeanDefinitionReader Loading XML bean definitions from file [/home/pinkdahlia/develop/apache-tomcat-7.0.55/webapps/vips-mobile-mlisting-backend/WEB-INF/classes/spring-xmemcached.xml]
 INFO 2015-01-08 15:18:13 XmlBeanDefinitionReader Loading XML bean definitions from file [/home/pinkdahlia/develop/apache-tomcat-7.0.55/webapps/vips-mobile-mlisting-backend/WEB-INF/classes/spring-aop.xml]
 INFO 2015-01-08 15:18:14 PropertiesFactoryBean Loading properties file from URL [file:/home/pinkdahlia/develop/config/BackendConf.properties]

An here is the content in my web.xml:
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns="http://java.sun.com/xml/ns/javaee"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://java.sun.com/xml/ns/javaee
                      http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd"
         version="3.0"
         metadata-complete="true">

    <context-param>
        <param-name>contextConfigLocation</param-name>
        <param-value>
            classpath*:spring-*.xml
        </param-value>
    </context-param>

    <context-param>
        <param-name>log4jConfigLocation</param-name>
        <param-value>classpath:log4j.properties</param-value>
    </context-param>

    <listener>
        <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
    </listener>

    <filter>
        <filter-name>encodingFilter</filter-name>
        <filter-class>org.springframework.web.filter.CharacterEncodingFilter
        </filter-class>
        <init-param>
            <param-name>encoding</param-name>
            <param-value>utf-8</param-value>
        </init-param>
    </filter>
    <filter-mapping>
        <filter-name>encodingFilter</filter-name>
        <url-pattern>/*</url-pattern>
    </filter-mapping>

    <filter>
        <filter-name>shiroFilter</filter-name>
        <filter-class>org.springframework.web.filter.DelegatingFilterProxy</filter-class>
        <init-param>
            <param-name>targetFilterLifecycle</param-name>
            <param-value>true</param-value>
        </init-param>
    </filter>

    <filter-mapping>
        <filter-name>shiroFilter</filter-name>
        <url-pattern>/*</url-pattern>
    </filter-mapping>

    <servlet>
        <servlet-name>mvc</servlet-name>
        <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
        <load-on-startup>1</load-on-startup>
    </servlet>
    <servlet-mapping>
        <servlet-name>mvc</servlet-name>
        <url-pattern>/</url-pattern>
    </servlet-mapping>

    </web-app>

and final is my mvc-servlet.xml file:
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:context="http://www.springframework.org/schema/context"
    xmlns:p="http://www.springframework.org/schema/p"
    xmlns:aop="http://www.springframework.org/schema/aop"
    xmlns:mvc="http://www.springframework.org/schema/mvc"
    xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.0.xsd
                       http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-4.0.xsd
                       http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.0.xsd
                       http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop.xsd">

    <aop:config proxy-target-class="true"></aop:config>

    <context:property-placeholder location="file:${vips.backend.config}"/>

    <context:component-scan base-package="com.vip.mlisting" use-default-filters="false">
        <context:include-filter type="annotation" expression="org.springframework.stereotype.Controller"/>
        <context:include-filter type="annotation" expression="org.springframework.web.bind.annotation.ControllerAdvice"/>
    </context:component-scan>

    <mvc:annotation-driven>
        <mvc:argument-resolvers>
            <bean class="com.vip.mlisting.system.resolver.CurrentUserMethodArgumentResolver"/>
        </mvc:argument-resolvers>
        <mvc:message-converters>
            <bean class="org.springframework.http.converter.StringHttpMessageConverter">
                <property name="supportedMediaTypes">
                    <list>
                        <value>application/json;charset=UTF-8</value>
                    </list>
                </property>
            </bean>
        </mvc:message-converters>
    </mvc:annotation-driven>

        <mvc:resources mapping="/static/**" location="/WEB-INF/static/"/>

    <!-- the prefix and suffix of ViewResolver -->
    <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver" p:order="1">
        <property name="viewClass" value="org.springframework.web.servlet.view.JstlView"/>
        <property name="contentType" value="text/html"/>
        <property name="prefix" value="/WEB-INF/jsp/" />
        <property name="suffix" value=".jsp" />
    </bean>

    <bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver"></bean>
</beans>

I've tried as hard as I can to find a solution on google, but nothing effective, can anyone help, thanks very much.

A: That's because of 2 contexts
servlet-level spring context

and
global Spring context common to the whole application

In your web.xml
<servlet>
    <servlet-name>mvc</servlet-name>
    <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
    <load-on-startup>1</load-on-startup>
</servlet>

See also
Why does Spring MVC need at least two contexts?
Spring MVC web app: application context starts twice


text:
Q: Capture network traffic using fiddler in Window Subsystem for Android (WSA) Fiddler is not capturing network traffic of WSA. I want to set proxy in WSA so I can capture network traffic in fiddler, also before setting proxy in WSA, I also need to install Telerik Fiddler Certificate in WSA, how can I do this?

*

*I tried enabling Advanced Networking option in WSA but it didn't worked and network stopped working in WSA

*I also googled for how can I set proxy using adb but did not find anything


text:
Q: "java.net.BindException: Address already in use" while trying to profile with Java VisualVM I'm trying to profile a java program with the Java VisualVM profiler on mac.
Part of the Message has been reported in the past here .
The exception I'm getting is the following:
objc[20398]: Class JavaLaunchHelper is implemented in both /Library/Java/JavaVirtualMachines/jdk1.8.0_20.jdk/Contents/Home/bin/java and /Library/Java/JavaVirtualMachines/jdk1.8.0_20.jdk/Contents/Home/jre/lib/libinstrument.dylib. One of the two will be used. Which one is undefined.
Profiler Agent: JNI OnLoad Initializing...
Profiler Agent: JNI OnLoad Initialized successfully
Profiler Agent: Waiting for connection on port 5140 (Protocol version: 14)
Profiler Agent Error: Exception when trying to establish connection with client:
java.net.BindException: Address already in use

I don't fully understand the error. Are there any possible solutions?
Thank you.

A: Probably because you have forgotten to close the serversocket in the catch clause. Try restarting your IDE and add serversocket.close in the catch.

A: "Address already in use" means that you have another process that is already listening on port 5140.
Look if you have already the same process running or use a tool like http://alternativeto.net/software/portsmonitor/ to see which process already listens on port 5140


text:
Q: Property is reset on COM+ object if ContextUtil.SetComplete() is called I've got two classes deployed as COM+ components, let's say ClassA and ClassB. ClassA has some public properties. ClassB sets values for those properties and calls a method of ClassA. The method itself does not modify the value of the property.
After the call the values of the properties are reset to default values for the corresponding types. This only happens if the called method includes statement ContextUtil.SetComplete(). Once I comment out the statetment the values of the properties remain same as they were before the method call, which is what I expect.
Do I overllok some basic concept of COM+ objects and their contexts? I would expect the property value to remain the same in any case.
Here's the simplified listing for the code:
Option Strict Off
Option Explicit On

Imports System.EnterpriseServices

<Transaction(TransactionOption.Required)> _
Public Class ClassA
    Inherits ServicedComponent

    Private _propertyA As String

    Public Property PropertyA() As String
        Get
            Return Me._propertyA
        End Get
        Set(ByVal Value As String)
            Me._propertyA = Value
        End Set
    End Property

    Public Sub MethodA()
        ' Do something
        ContextUtil.SetComplete() ' If this is called the Str property is reset after return from this call
    End Sub
End Class

<Transaction(TransactionOption.Required)> _
Public Class ClassB
    Inherits ServicedComponent

    Public Sub MethodB()
        Dim a As ClassA = New ClassA()
        a.PropertyA = "A"
        a.MethodA()
        ' After this call the value of a.PropertyA is reset to Nothing if ContextUtil.SetComplete() was called inside MethodA()
    End Sub
End Class

A: Have you tried calling Commit on the Transaction, IE: ContextUtil.MyTransactionVote = TransactionVote.Commit. It could be that you are making changes and then setting the Context to complete before the changes have actually been committed.


text:
Q: Generating clean markup with Literal and string.Format In order to generate clean markup, I often resort to using code similar to this:
<asp:Literal ID="ltItem" runat="server">

{2}
</asp:Literal>

And in the codebehind:
...
lt.Text = string.Format(lt.Text,
    cssClass,
    item.Url,
    Server.HtmlEncode(item.Caption)
);

Some of the advantages are:

*

*clean html markup, no ASP.Net WebForm id's etc

*designer can do minor modifications in the aspx without developer intervention

*code is precompiled (as opposed to use inline code or databind statements)

Disadvantages:

*

*somewhat cryptic

*fragile - when a parameter is removed in the markup, string.Format throws an exception

Therefore my question:
Is this a common way to generate clean markup? Are there better alternatives? Is the databinding syntax approach preferable?

A: It seems that you're fighting with your framework. ASP.NET web forms were designed to automatically resolve client-side ids and allow property-based UI customization that feels like Windows forms. These features often make a mess of the rendered HTML but the result is tolerated because of the perceived benefits.
If you don't perceive the benefits and find yourself fighting the ASP.NET web forms approach, consider another framework. There's no sense using a framework that doesn't share your values and goals.
If you want total control of your rendered HTML, consider ASP.NET MVC. Control of HTML output is one of its stated goals. In addition, it's designed to enforce separation of concerns.
If you're open to a non-Microsoft framework, there are many available including:

*

*MonoRail - a framework inspired by Ruby on Rails

*Maverick.NET - a .NET port of Java's Maverick framework

A: Correct me if I am wrong but using MVC won't gives you precompiled code isn't it ?
I do the same when using webforms and I had several issues with it.


text:
Q: How can I let WPF Window stay in front of certain window but not topmost? here is the situation
my WPF Main window is always visible and several small windows should be floating on the Main Window.
So these small windows are children of Main Window and their z-index should be always one greater than Main Window even if the focus is on the main window rather than children but smaller z-index than other applications (e.g. file browser or chrome etc.)
I've tried Window's TopMost property but it makes really top most than everything else even more than application's MessageBox.
any good idea for making these children windows are just floating in front of only parent window?
thanks in advance

A: it should automatically open above the owner window. Or set the child to be topmost


text:
Q: How to run PHP locally on MacOS I need a php sandbox on my local.
But I have to make just one class in PHP.
In NODE.JS I can do the following:
test.js
// my test js script
console.log('hello world')

I can run it like this:
~$ node test.js
~$ hello world
~$

I would like to do something like this:
test.php
echo('hello world');

I would like to run it like this:
~$ php test.php
~$ hello world
~$

Is there any way to do this, without installing apache and everything?
I just like to have a php sandbox on my mac.

A: download and install xampp or any alternative that runs an Apache server on local machine should do the trick.
edit:
Just googled a little myself, apparently you can just download php and run the web server from cli now, $ php -S localhost:8000

A: OSX comes with php installed :
$ which php # => /usr/bin/php

So you can run your php file. But don't forget to include your code between <?php ... ?>.
// test.php
<?php
echo("Hello world")
?>

So now you can run in your terminal:
$ php test.php
$ Hello world%

Apache is not needed.

A: First of all, you have to check if php is installed on your mac. Use the following command to check this :
php --version

Since PHP is installed by default on mac, you should get something like this:

PHP 7.4.10 (cli) (built: Sep  3 2020 18:19:30) ( NTS ) Copyright (c)
The PHP Group Zend Engine v3.4.0, Copyright (c) Zend Technologies
with Zend OPcache v7.4.10, Copyright (c), by Zend Technologies

Once you've done that, you can create a PHP file containing just one line :
<?php echo "Hello world\n"; ?>

Output:

Hello World

You only need PHP. You do not need anything else.

A: You can install only pah with Homebrew.
Make sure the brew is updated
brew update
brew upgrade

Install PHP 7.2
brew install php72

Wait for the installation to finish, you're now running on PHP 7.2. You may run $ php -v to check the current PHP version on your machine.
now create file test.php
<?php
 echo "hello";

and run
php path/to/test.php

A: Apache and php are already installed on MacOS
Alternatively You can use docker or just find sandbox on-line, e.g. https://sandbox.onlinephpfunctions.com/

A: I had a similar problem when I came into Mac, and before using Homebrew my temporary solution is mamp. Simply a quick solution that helped me work.
then there are articles that explain well how to create a lamp en mac development environment: Setup Local (L)AMP Stack on Mac with Homebrew

A: Try opening a localhost. You can use XAMPP etc...

A: I would recommend Docker...
Since it's running in a virtual machine already, it's the perfect sandbox. And you can add new services or change the setup, like trying new PHP versions, different webservers, or other operating system quite easily.


text:
Q: Scoping email to subdomain in devise rails I am using devise for authentication in rails app, and my app can have many subdomains.
Currently it is using email as authentication, and email should be unique for the whole app.
Now is there any way I can scope uniqueness of email address to subdomain, not the whole app?
I tried:
validates_uniqueness_of :email, :scope => :account_id

But didn't work. It still seeks uniqueness of email to whole app, not the specific subdomain when registering a new user.
Any help would be highly appreciated.

A: Ok I did this way.
Edited config.authentication_keys in devise.rb as
config.authentication_keys = [ :login, :account_id ]

Also I created hidden field to include account_id in login form
<%= f.hidden_field :account_id, :value => @account.id %>

Here @account hold the account related to current subdomain.
And added the following protected method in user.rb to override find_for_database_authentication class method
protected
def self.find_for_database_authentication(warden_conditions)
conditions = warden_conditions.dup
login = conditions.delete(:login)
account_id = conditions.delete(:account_id)
where(conditions).where(["lower(username) = :value OR lower(email) = :value", { :value => login.downcase }]).where("account_id = ?", account_id).first
end

If there is better solution then feel free to comment guys..
Cheers!

A: How are you saving your users, are you setting the account on the user model before trying to save it? If not then you will be scoping to an account_id of nil - hence it will look like there is no scope.


text:
Q: RazorGenerator, UsePhysicalViewsIfNewer and performance Has anyone tested UsePhysicalViewsIfNewer on a big system with lots of Views (thousands)?
If it has to check the disk each time doesn't make this slower? Does switching it off have any appreciable impact?

A: It's designed to be a dev-time feature (in particular if you're using RazorGenerator.MsBuild). It's meant to stop you from having to rebuild the application every time you change a view. I haven't tried using it in a real-world application, but turning it off in a production app should be the right thing to do.


text:
Q: Creating a log function with a custom base I have a formula and this formula uses a log function with a custom base for example log with a base of b and value of x. In objective-c, I know there are log functions that calculate without a base and base of either 2 or 10.
Is there a function that has the ability to calculate a log function with a custom/variable base? or maybe there is an alternative method of completing this formula.
The basic idea of my formula is this log(1+0.02)(1.26825) (1+0.02 is the base). This should equal 12.000.

A: You can calculate arbitrary logarithms with logbx = logcx / logcb, where c is one of the more readily available bases such as 10 or e.
For your particular example, loge1.26825 = 0.237637997 and loge1.02 = 0.019802627. That's 12.000 (within the limits of my calculator's accuracy): 0.237637997 / 0.019802627 = 12.000326876.
In fact, 1.0212 is actually 1.268241795 and, if you use that value, you get much closer to 12:

*

*loge1.268241795 = 0.237631528

*loge1.02 = 0.019802627

*0.237631528 / 0.019802627 = 12.000000197.

A: Like this:
double logWithBase(double base, double x) {
    return log(x) / log(base);
}

A: Ray is right but here is a Obj-C method modification of it:
-(double) logWithBase:(double)base andNumber:(double)x {
    return log(x) / log(base);
}


text:
Q: Make PC always hibernate I want my pc to hibernate even when I press "shut down".
Either that, or simply remove the "shut down" button from the start menu.
Is there a way to do any of these?

A: To change the start button to something other than Shut Down
Click Start then right-click on Shut Down then click Properties
Under Power Button Action, change the dropdown to Hibernate


text:
Q: Serialize, unserialize, add elements and serialize again Can anyone please tell why this code doesn't work:
$ser = array('one','two','three','four');
$x = serialize($ser);
$x = unserialize($x);
$x = array_push($x, 'five');
$x = serialize($x);
echo $x;

I think it doesn't require any further explanation...
The result is only:

i:5;

A: That's because array_push() returns the number of items in the new array. The value is set by reference.
See the PHP documentation for the array_push function:
http://at.php.net/array_push

A: Dont assign the result of array_push to $x.
array_push($x, 'five');

This function returns the new number of elements, which you don't want to replace your array.
$ser = array('one','two','three','four');
$x = serialize($ser);
$x = unserialize($x);
array_push($x, 'five');
$x = serialize($x);
var_dump($x);


text:
Q: Neighbourhood of a point in Stiefel manifold
In Hatcher above, he claims that "This determines orthonormal bases for the $(k-m)$ planes orthogonal to all nearby $m$-frames", I feel confused about this claim (even after checking the preceding example): why is it orthonormal to all nearby $m$-frames, what are the nearby $m$-frames?
In particular, I am not clear what the nearby $m$-frames look like, so can anyone tell me, given an $m$-frame of a Stiefel manifold, what look like its neighbourhoods?


text:
Q: Classic ASP random date I have tried a long time to find help regarding a random date in classic ASP.
I want to create a random date between two dates.
For example: my random date must be between 2010-04-05 and 2012-04-05.
Thankful for any help!
Best Regards
Linus

A: Actually it's much easier in VBScript.
Randomize
Function RandomDate(dtmStart, dtmEnd)
    Dim dblDate
    dblDate = (CDbl(dtmStart) - CDbl(dtmEnd)) * Rnd + CDbl(dtmEnd)
    'dblDate = Int(dblDate) ' w/o time part, just date
    RandomDate = CDate(dblDate)
End Function

Response.Write RandomDate(#1985/06/10#, Now())

A: you could use DateDiff Function and Rnd function. The Rnd function to generate a random number and then datediff to diff the days

A: try this:
<%
Dim DDmax,DDmin,MMmax,MMmin,YYYYmax,YYYYmin

 MMmin=1
 MMmax=12

 DDmin=1
 DDmax=28

 YYYYmin=2010
 YYYYmax=2012

 Randomize

dim strTmpDate,strTmpDateYEAR,strTmpDateMONTH,strTmpDateDAY

 strTmpDateYEAR=Int((YYYYmax-YYYYmin+1)*Rnd+YYYYmin)
 strTmpDateMONTH=Int((MMmax-MMmin+1)*Rnd+MMmin)
 strTmpDateDAY=Int((DDmax-DDmin+1)*Rnd+DDmin)

 if Len(strTmpDateMONTH)=1 then
 strTmpDateMONTH="0" & strTmpDateMONTH
 end if

 if Len(strTmpDateDAY)=1 then
 strTmpDateDAY="0" & strTmpDateDAY
 end if

 strTmpDate=strTmpDateYEAR & strTmpDateMONTH & strTmpDateDAY

 if strTmpDate > "20100405" and strTmpDate < "20120405" then

 strTmpDateYEAR=Int((YYYYmax-YYYYmin+1)*Rnd+YYYYmin)
 strTmpDateMONTH=Int((MMmax-MMmin+1)*Rnd+MMmin)
 strTmpDateDAY=Int((DDmax-DDmin+1)*Rnd+DDmin)

 if Len(strTmpDateMONTH)=1 then
 strTmpDateMONTH="0" & strTmpDateMONTH
 end if

 if Len(strTmpDateDAY)=1 then
 strTmpDateDAY="0" & strTmpDateDAY
 end if

 strTmpDate=strTmpDateYEAR & strTmpDateMONTH & strTmpDateDAY

 end if
Response.write "Example A: " & strTmpDate & "<BR>"
Response.write "Example B: " & Left(strTmpDate,4) & "-" & Mid(strTmpDate,5,2) & "-" & Right(strTmpDate,2)
%>