text:
Q: "File not found" Excel VBA I have issue with my code. I did automatized form for a some requests in our company. I tested my code and everything goes well. My one colleague try use it but, excel showed msg "File not found".
Can you help me? I dont know what is a problem, because other colleague has no problem with this code.
Sub CommandButton1_Click()

id_request = Format(Now(), "yyyymmddHhNnSs")

date_year = Format(Now(), "yyyy")
date_month = Format(Now(), "mm")

Dim product As Variant
product = Range("H5").Value

Dim termin As Variant
termin = Range("H17").Value

Dim saveLocation As String

' Podmienka pre ukladania na zaklade mesiacov
If date_month = "01" Then
    saveLocation = "\\xx.xx.xxx.xxx\Skupiny\_INFO\NM-PRILOHY-HPDC\" & date_year & "\01-Január\NM_" & product & "_" & id_request & ".pdf"
    ElseIf date_month = "02" Then
    saveLocation = "\\xx.xx.xxx.xxx\Skupiny\_INFO\NM-PRILOHY-HPDC\" & date_year & "\02-Február\NM_" & product & "_" & id_request & ".pdf"
    ElseIf date_month = "03" Then
    saveLocation = "\\xx.xx.xxx.xxx\Skupiny\_INFO\NM-PRILOHY-HPDC\" & date_year & "\03-Marec\NM_" & product & "_" & id_request & ".pdf"
    ElseIf date_month = "04" Then
    saveLocation = "\\xx.xx.xxx.xxx\Skupiny\_INFO\NM-PRILOHY-HPDC\" & date_year & "\04-Apríl\NM_" & product & "_" & id_request & ".pdf"
    ElseIf date_month = "05" Then
    saveLocation = "\\xx.xx.xxx.xxx\Skupiny\_INFO\NM-PRILOHY-HPDC\" & date_year & "\05-Máj\NM_" & product & "_" & id_request & ".pdf"
    ElseIf date_month = "06" Then
    saveLocation = "\\xx.xx.xxx.xxx\Skupiny\_INFO\NM-PRILOHY-HPDC\" & date_year & "\06-Jún\NM_" & product & "_" & id_request & ".pdf"
    ElseIf date_month = "07" Then
    saveLocation = "\\xx.xx.xxx.xxx\Skupiny\_INFO\NM-PRILOHY-HPDC\" & date_year & "\07-Júl\NM_" & product & "_" & id_request & ".pdf"
    ElseIf date_month = "08" Then
    saveLocation = "\\xx.xx.xxx.xxx\Skupiny\_INFO\NM-PRILOHY-HPDC\" & date_year & "\08-August\NM_" & product & "_" & id_request & ".pdf"
    ElseIf date_month = "09" Then
    saveLocation = "\\xx.xx.xxx.xxx\Skupiny\_INFO\NM-PRILOHY-HPDC\" & date_year & "\09-September\NM_" & product & "_" & id_request & ".pdf"
    ElseIf date_month = "10" Then
    saveLocation = "\\xx.xx.xxx.xxx\Skupiny\_INFO\NM-PRILOHY-HPDC\" & date_year & "\10-Október\NM_" & product & "_" & id_request & ".pdf"
    ElseIf date_month = "11" Then
    saveLocation = "\\xx.xx.xxx.xxx\Skupiny\_INFO\NM-PRILOHY-HPDC\" & date_year & "\11-November\NM_" & product & "_" & id_request & ".pdf"
    ElseIf date_month = "12" Then
    saveLocation = "\\xx.xx.xxx.xxx\Skupiny\_INFO\NM-PRILOHY-HPDC\" & date_year & "\12-December\NM_" & product & "_" & id_request & ".pdf"
    Else
    saveLocation = "\\xx.xx.xxx.xxx\Skupiny\_INFO\NM-PRILOHY-HPDC\" & date_year & "\NM_" & product & "_" & id_request & ".pdf"
End If

  Dim IsCreated As Boolean
  Dim i As Long
  Dim PdfFile As String, Title As String
  Dim OutlApp As Object

  Title = Range("A1")

  ' Define PDF filename
  PdfFile = ActiveWorkbook.FullName
  i = InStrRev(PdfFile, ".")
  If i > 1 Then PdfFile = Left(PdfFile, i - 1)
  PdfFile = "NM_" & product & "_" & id_request & ".pdf"

  ' Export activesheet as PDF
  With ActiveSheet
    .ExportAsFixedFormat Type:=xlTypePDF, Filename:=PdfFile, From:=1, To:=1, Quality:=xlQualityStandard, IncludeDocProperties:=True, IgnorePrintAreas:=False, OpenAfterPublish:=False
  End With

  ' Use already open Outlook if possible
  On Error Resume Next
  Set OutlApp = GetObject(, "Outlook.Application")
  If Err Then
    Set OutlApp = CreateObject("Outlook.Application")
    IsCreated = True
  End If
  OutlApp.Visible = True
  On Error GoTo 0

  ' Prepare e-mail with PDF attachment
  With OutlApp.CreateItem(0)

    ' Prepare e-mail
    .Subject = "* Žiadosť o neplánované meranie - " & product
    .To = "xxx"
    .CC = "xxx"
    .Body = "Zdravím," & vbLf & vbLf _
          & "Poprosím vás o vykonanie neplánovaného merania." & vbLf _
          & "Termín: " & termin & vbLf _
          & "Číslo žiadosti: " & id_request & vbLf & vbLf _
          & "Cesta k NM: " & saveLocation & vbLf & vbLf _
          & "S pozdravom," & vbLf _
          & Application.UserName & vbLf & vbLf
    .Attachments.Add PdfFile

    ' Try to send
    On Error Resume Next
    .Send
    Application.Visible = True
    If Err Then
      MsgBox "POZOR ! Nastala chyba, žiadosť nebola odoslaná. Kontaktujte nás", vbExclamation
    Else
      MsgBox "Žiadosť bola odoslaná, dokument sa o chvíľu zatvorí", vbInformation
    End If
    On Error GoTo 0

  End With

  ' Delete PDF file
  Kill PdfFile

  ' Quit Outlook if it was created by this code
  If IsCreated Then OutlApp.Quit

  ' Release the memory of object variable
  Set OutlApp = Nothing

ActiveSheet.ExportAsFixedFormat Type:=xlTypePDF, From:=1, To:=1, _
    Filename:=saveLocation

ActiveWorkbook.Close SaveChanges:=False

End Sub

Private Sub Worksheet_SelectionChange(ByVal Target As Range)

End Sub

Many thanks in advance

A: Not sure which line is giving you the problem but in PdfFile = "NM_" & product & "_" & id_request & ".pdf", I see no path for the file? So .Attachments.Add PdfFile and Kill PdfFile may give you a problem.
Try this
Change
PdfFile = ActiveWorkbook.FullName
i = InStrRev(PdfFile, ".")
If i > 1 Then PdfFile = Left(PdfFile, i - 1)
PdfFile = "NM_" & Product & "_" & id_request & ".pdf"

to
Dim sFilePath As String
PdfFile = ActiveWorkbook.FullName
sFilePath = GetDirectoryFromPathFilename(PdfFile)
PdfFile = sFilePath & "NM_" & Product & "_" & id_request & ".pdf"

and paste this function right at the bottom. The below function extracts the directory part from the full Folder-File path. For example GetDirectoryFromPathFilename("C:\AAA\BB.Pdf") will give you C:\AAA\
Private Function GetDirectoryFromPathFilename(strPath As String) As String
    Dim pos As Integer
    pos = InStrRev(strPath, "\")
    If pos > 0 Then
        GetDirectoryFromPathFilename = Left$(strPath, pos)
    Else
        GetDirectoryFromPathFilename = ""
    End If
End Function


text:
Q: update python module while it is active Is it possible to update a python module while it is used in a running script?
The situation is the following:
1) I have a script running using pandas 0.15.2. It is a long data processing task and should continue running for at least another week.
2) I would like to run, on the same machine, another script, which requires pandas 0.16.
Is it possible for me to do 2) without interrupting 1)?

A: If the script is still running, it's likely that replacing the dependency  will not affect it at all - the code will already be in memory.
Still, it's better to be safe than sorry. I would install the other script inside a virtualenv, in which you can install whichever versions of modules you want without affecting anything else.

A: Install pandas 0.16 in an alternate location. For example on my system I made the directory /Users/kteague/pytest/ for installation. Then I used the --target option in pip to install into that location:
$ pip install --target /Users/kteague/pytest pandas
Collecting pandas
  Using cached pandas-0.17.0-cp35-cp35m-macosx_10_6_intel.macosx_10_9_intel.macosx_10_9_x86_64.macosx_10_10_intel.macosx_10_10_x86_64.whl
Collecting pytz>=2011k (from pandas)
  Using cached pytz-2015.6-py2.py3-none-any.whl
Collecting python-dateutil>=2 (from pandas)
  Using cached python_dateutil-2.4.2-py2.py3-none-any.whl
Collecting numpy>=1.7.0 (from pandas)
  Using cached numpy-1.10.1-cp35-cp35m-macosx_10_6_intel.macosx_10_9_intel.macosx_10_9_x86_64.macosx_10_10_intel.macosx_10_10_x86_64.whl
Collecting six>=1.5 (from python-dateutil>=2->pandas)
  Downloading six-1.10.0-py2.py3-none-any.whl
Installing collected packages: pytz, six, python-dateutil, numpy, pandas
Successfully installed numpy pandas python-dateutil pytz six-1.9.0

Now you can export your PYTHONPATH to point to that location first. Scripts run from a terminal where the PYTHONPATH=/Users/kteague/pytest will use pandas 0.1.7 over whatever version of pandas is installed in the default site-packages directory.
$ export PYTHONPATH=/Users/kteague/pytest/

Use setuptools from the python interpreter to ensure your terminal is importing the version of pandas that you want:
$ python
Python 3.5.0 (v3.5.0:374f501f4567, Sep 12 2015, 11:00:19)
[GCC 4.2.1 (Apple Inc. build 5666) (dot 3)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> import pkg_resources
>>> pkg_resources.require("pandas")[0].version
'0.17.0'

redpajama_set_name: RedPajamaStackExchange


text:
Q: keep periodicity when mapping a periodic strip onto another by mapping congruent parts Let $S$ be a vertical strip-like domain in $\mathbb{C}$ bounded by two simple curves. $S$ is periodic. That means that there is a real constant $c>0$, such that $S = S + ic$ and also $S = S + ic\cdot k$ for every $k \in \mathbb{Z}$. Lets cut $S$ with horizontal cuts into congruent parts which are exactly $c$ tall and are from now on called $S_k$. $S_k$ can be mapped one-to-one and holomorphic onto a rectangle with width $1$ and a specific height $r$. Lets call this function $f_k$. We map every $S_k$ onto such a rectangle $R_k$ in a way that $$R_k = \lbrace z \in \mathbb{C} | 0 < \Re(z) < 1 \text{ and } r\cdot k < \Im(z) < r\cdot (k+1) \rbrace$$ for every $k \in \mathbb{Z}$. To win a holomorphic map from $S$ onto the vertical strip $$T = \lbrace z \in \mathbb{C} | 0 < \Re(z) < 1 \rbrace$$
we need to complete the mapping by adding the missing cuts. Since each $S_k$ is bounded by two cuts - which are basically horizontal lines - the mapping has an analytic continuation. So $f_k$ can also be defined on one of the cuts.This should complete the mapping from $S$ onto $T$. The question is:
How can I am sure that I can assemble those continued mappings to a holomorphic map from $S$ onto $T$ such that $T$ is also periodic? It must come from the periodicity.


text:
Q: Requested View Couldn't be restored I made a web application using (JSF and JPA) and then deployed it to Glassfish Application Server.
It works fine, but when I leave the Application idle for a period of time, maybe one hour, and then trying to use the application, it throws exception said that (the requested view couldn't be restored).
And when reloading my application in Glassfish it works fine again, how can I solve this problem?

A: This is a ViewExpiredException and is fired when the state saving method is set to server(default) and you make a post request to the view which is not available in the session anymore.
One way to solve the problem is to redirect users to a particular page when this type of exception is thrown. You can configure an error page for this in web.xml.
<error-page>
<exception-type>javax.faces.application.ViewExpiredException</exception-type>
<location>/errorpage.xhtml</location>
</error-page>


text:
Q: Update : I get sum of products and total cost but it's not updating when quantity updated I get the  sum of products and over all cost but i want to update when item quantity changes
.filter('total', function () {
    return function (input, property) {
        var i = input instanceof Array ? input.length : 0;
        if (typeof property === 'undefined' || i === 0) {
            return i;
        } else if (isNaN(input[0][property])) {
            throw 'filter total can count only numeric values';
        } else {
            var total = 0;
            while (i--)
                total += input[i][property];
            return total;
        }
    };
})

And

{{ data|total }} items

{{ data|total:'price' }}

DEMO FOR UPDATED PLUNKER

A: And finally I got it using Filters in angularjs...
//code for getting total number of products
    .filter('total', function () {
        return function (input, property) {
            var i = input instanceof Array ? input.length : 0;
            if (typeof property === 'undefined' || i === 0) {
                return i;
            } else if (isNaN(input[0][property])) {
                throw 'filter total can count only numeric values';
            } else {
                var total = 0;
                while (i--)
                    total += input[i][property];
                return total;
            }
        };
    })

//to print the total

{{ data|total }} items

//to get the overall cost when you update item in quantity
 $scope.total = function () {
        var total = 0;
        angular.forEach($scope.data, function (item) {
            total += item.quan * item.price;
        })

        return total;
    }

// to print the overall total

new total{{total()}}

Updated Plunker Demo

A: Try using this
Change  total to total: {{ getTotal() }} in your template

Controller
$scope.getTotal = function () {
    var total = 0;
    for(var i = 0; i < $scope.cart.items.length; i++){
       var item = $scope.cart.items[i];
       total += (item.price * item.quantity);
    }
    return total;
}

.filter('total', ['$parse', function ($parse) {
    return function (input, property) {
    var i = input instanceof Array ? input.length : 0,
        p = $parse(property);

    if (typeof property === 'undefined' || i === 0) {
        return i;
    } else if (isNaN(p(input[0]))) {
        throw 'filter total can count only numeric values';
    } else {
        var total = 0;
        while (i--)
            total += p(input[i]);
        return total;
    }
};
}]);

A: Your products seem to be stored in $scope.todos, since that's what you're iterating on in the ng-repeat. But your loop to compute the total iterates on $scope.item.
It should be
angular.forEach($scope.todos, function (item) {


text:
Q: Is it possible for an HDMI cable to be "worn in"? I have an HDMI cable running thirty feet between my computer and a TV. I've had various problems with the screen flashing, stuttering, etcetera, due to the signal not being strong enough to carry a 4K HDR signal over that length. However with two separate cables now, after experiencing those issues initially, they've just gone away over time: initially the screen would go dark every ten to fifteen seconds, then less frequently, and now it doesn't seem to happen at all.
This is challenging my conception of how cables work in general. So, my question is... can a cable be "worn in" by use and carry a signal better over time? Or is there another likely explanation for this behavior?

A: Something else must have changed that causes the signal to reach TV better. Maybe TV firmware got updated and new input equalization settings updated with it. Maybe computer video card driver got updated and it uses more drive strength or pre-emphasis for the signal. Maybe some other devices are off so that there is less interference. And thirty feet is on the edge of being able to carry 18 GBPS 4K HDR signals reliably anyway, way more than many devices suggest in their manuals.


text:
Q: Unable set current navigation of web I want to change the current navigation to "Structural Navigation: Display only the navigation items below the current site" of sub site. I got this which shows how to set the current navigation and based on that I developed code as below:
static void Main(string[] args)
{
    using(SPSite site= new SPSite("http://............"))
    {
        string val = null;
        Console.WriteLine(site.Url);

        SPWeb web = site.AllWebs["Depts"];
        if (web != null)
        {
            Console.WriteLine(web.Url);
            PublishingWeb my = PublishingWeb.GetPublishingWeb(web);
            WebNavigationSettings navigationSettings = new WebNavigationSettings(web);
            navigationSettings.CurrentNavigation.Source = StandardNavigationSource.Unknown;
            my.Navigation.CurrentIncludePages = false;
            my.Navigation.CurrentIncludeSubSites = false;
            navigationSettings.Update();
            my.Update();
        }
        Console.WriteLine("Completed..");
        Console.ReadKey();
        web.Dispose();
    }
}

But when I run the code I am getting the error at line:navigationSettings.CurrentNavigation.Source = StandardNavigationSource.Unknown; that indicates "The value "Unknown" is not allowed for property type "StandardNavigationSource"."
What am I missing?

A: that is strange! when your writing your code and you enter StandardNavigationSource and then add  . (decimal) does it come out with a list of options? also i know more than likely you have but have you add the following references withinn the project and top of class?
web.Navigation (Namespace: Microsoft.SharePoint)
publishingWeb.Navigation (Namespace: Microsoft.SharePoint.Publishing)
WebNavigationSettings (Namespace: Microsoft.SharePoint.Publishing.Navigation)

also are you sure its ment to be that? and not:
        PublishingWeb my = PublishingWeb.GetPublishingWeb(web);
        WebNavigationSettings navigationSettings = new WebNavigationSettings(web);
        navigationSettings.GlobalNavigation.Source = StandardNavigationSource.Unknown;

There are two navigations. The Global navigation (also called Top
  navigation) and the Current navigation (also called left navigation or
  quicklaunch). Both of these can be set to different to use different
  sources. They can inherit from their parent (if a subsite only), use
  managed navigation, or structural navigation. All you need to do is
  select the webNavigationSettings object, choose which navigation to
  set, and select a source for that navigation.

so it is the quick launch that your trying to ammend ;), i know that you probably are, im just making sure!
more importantly I would also like to note from msdn on the error your getting:

This property determines whether the switchable site map provider will
  use the taxonomy site map provider or the portal site map provider in
  the standard configurations. If the settings are in an advanced
  configuration, then this property returns
  StandardNavigationSource.Unknown (section 3.1.5.11.1.1). If the
  protocol client attempts to assign the
  StandardNavigationSource.Unknown value to this property, the protocol
  server MUST return an InvalidOperationException error.

going to section 3.1.5.10.1.1 will show:

Indicates that the navigation scheme is in an advanced configuration
  that does not correspond to one of the standard configurations.


text:
Q: Golang json error convertering int from json I'm trying to do a simple unmarshall and extracting the int information from the code below. I found a link from another stackoverflow : link. Though, it doesn't help in my case. the program according to ideone think the data is a float.
package main
import "fmt"
import "encoding/json"

func main(){
    byt := []byte(`{"status": "USER_MOVED_LEFT", "id":1, "x":5, "y":3}`)
    var dat map[string]interface{}
    if err := json.Unmarshal(byt, &dat); err != nil {
        panic(err)
    }
    num := dat["id"].(int)
    fmt.Println(num)
}

A: If you are converting your byt to map[string]interfaec{} the default value of the number will be float64.
func main(){
    byt := []byte(`{"status": "USER_MOVED_LEFT", "id":1, "x":5, "y":3}`)
    var dat map[string]interface{}
    if err := json.Unmarshal(byt, &dat); err != nil {
        panic(err)
    }

    fmt.Println(reflect.TypeOf(dat["id"])) // print the type of value
    num := dat["id"].(float64)
    fmt.Println(num)
}

But you can also change this behavior by converting your byt which is your data to a struct like this :
type myStruct struct {
    Status string
    Id     int
    x      int
    y      int
}

func main() {
    byt := []byte(`{"status": "USER_MOVED_LEFT", "id":1, "x":5, "y":3}`)
    dat := myStruct{}
    if err := json.Unmarshal(byt, &dat); err != nil {
        panic(err)
    }

    fmt.Println(reflect.TypeOf(dat.Id))
    fmt.Printf("%+v\n", dat.Id)

}


text:
Q: Windows Files-OnDemand Context status column Files On-Demand
We must prepare the application similar to OneDrive on Windows - synchronization list of files stored in cloud and synchronization of selected files.
During the investigation we found a very nice library to manage On-Demand Files in Windows from C# - ShellBoost.
List files from the cloud as local files
Show list of on-demand files in a local folder

Show folder with files as Namespace extension

With ShellBoost we can synchronize files in a very cool way. We can show sync status, we can do all operations like on regular files, additionally, we can synchronize items or remove them from synchronization.
Unfortunately, we met some restrictions
File Status column problem
Problem is that with ShellBoost and Files On-Demand we can't set additional icons in the status column like OneDrive does it

Example
Here is a repo with the example
https://github.com/m4tchl0ck/ShellBoost-My-Samples


text:
Q: AtlasSpriteManager animation I am using AtlasSpriteManager and AltasSprite to create frame by fram animation with 1 one file. I wanna write something that at first show a simple picture, without any animation and for example when I touch it, it shows some animation and return to the first position and frame. I just can't show the first frame without animation using this code :
Sprite *checker = [Sprite spriteWithFile:@"test.png"];
float frameWidth = [checker boundingBox].size.width / frameNumber;
float frameHeight = [checker boundingBox].size.height;

AtlasSpriteManager *mgr = [AtlasSpriteManager spriteManagerWithFile:fileName];
AtlasSprite *sprite = [AtlasSprite spriteWithRect:CGRectMake(pos.x, pos.y, frameWidth, frameHeight) spriteManager:mgr];
sprite.position = ccp(pos.x, pos.y);
[mgr addChild:sprite];

[layer addChild:mgr];

AtlasAnimation* animation = [AtlasAnimation animationWithName:@"Animation" delay:delay];
assert( animation != nil );

for(int i = 0; i < frameNumber; i++){
    [animation addFrameWithRect:CGRectMake(i * frameWidth, 0, frameWidth, frameHeight)];
}

id action = [Animate actionWithAnimation:animation];
assert( action != nil );

id repeatAction;
if(repeatNumber == 0){
    repeatAction = [RepeatForever actionWithAction:action];
}else{
    repeatAction = [Repeat actionWithAction:action times:repeatNumber];
}

[sprite runAction:repeatAction];

any idea how to do that?
thanx in advance

A: Updated Answer
I don't think I understood your question as you intended it.
As I understand now, you have a sprite whih you have an animation for. But when the animation is finished, it doesn't return to the frame that you want the sprite to be set to when standing still.
In our code you use actionWithAnimation:, have you tried setting that to actionWithAnimation:restoreOrigionalFrame: and then set restoreOrigionalFrame part to YES?
That should render the animation, but then when it stops, return to the frame it was before the animation.
Alternatively, you can make the action run, then when it stops, return to a certain frame manually by calling setTextureRect: on the AtlasSprite.
[sprite setTextureRect:CGRectMake( x, y, width, height )];

below this marker is my old answer:

The code that you have now will animate it immediately.
If you want the animation to start on touch, you'll have to check for touches. Then add the code to start the animation in the method that receives the touch.
There is sample code on how to use touches in the cocos2d download.
Basically: make your sprite a TargetedTouchDelegate (or create a new object to do that, but that's a bit of a hassle) and implement -(BOOL)ccTouchBegan:(UITouch *)touch withEvent:(UIEvent *)event

A: I think that you need CallFunc action combined with Sequence action.
From your code:

}
    .....
    .....
    id action = [Animate actionWithAnimation:animation];
    assert( action != nil );

    id repeatAction;
    if(repeatNumber == 0){
            repeatAction = [RepeatForever actionWithAction:action];
    }else{
            repeatAction = [Repeat actionWithAction:action times:repeatNumber];
    }
    id actionCallFunc = [CallFunc actionWithTarget:self selector:@selector(resetSprite)];
    id actionSequence = [Sequence actions: repeatAction, actionCallFunc, nil];

    [sprite runAction:repeatAction];
    ....
}

-(void)resetSprite{
    [sprite runAction:repeatAction];
}

First will be executed your repeatAction and when it ends the actionCallFunc will be executed calling resetSprite method where you can do what you want with your sprite.


text:
Q: "Port 4200 is already in use. Use '--port' to specify a different port." Hey i am runnning an angular2 app with express as backend. Getting the following issue:
[3] Port 4200 is already in use. Use '--port' to specify a different port.
[3] [nodemon] app crashed - waiting for file changes before starting...
[1] [HPM] Error occurred while trying to proxy request /api/jobs from localhost:4200 to http://localhost:3000 (ECONNREFUSED) (https://nodejs.org/api/errors.html#errors_common_system_errors)

server.js:
import * as bodyParser from 'body-parser';
import * as dotenv from 'dotenv';
import * as express from 'express';
import * as morgan from 'morgan';
import * as mongoose from 'mongoose';
import * as path from 'path';

import setRoutes from './routes';

const app = express();
dotenv.load({path: '.env'});
app.set('port', (process.env.PORT || 3000));

app.use('/', express.static(path.join(__dirname, '../')));

app.use(bodyParser.json());
app.use(bodyParser.urlencoded({extended: false}));

app.use(morgan('dev'));

mongoose.connect(process.env.MONGODB_URI);
const db = mongoose.connection;
(<any>mongoose).Promise = global.Promise;

db.on('error', console.error.bind(console, 'connection error:'));
db.on('open', () => {
  console.log('Connected to MongoDB');
  setRoutes(app);

  app.get('/*', function (req, res) {
    res.sendFile(path.join(__dirname, '../index.html'));
  });

  app.listen(app.get('port'), () => {
    console.log('Angular 2 Full Stack listening on port ' +
  app.get('port'));
  });
});

export {app};

edit:
Here the hole code. I think i dont reach the line with db.on('open')
when i inspect the port:

I using concurrently: with this options
"dev": "concurrently \"mongod\" \"ng serve -pc proxy.conf.json --open\" \"tsc -w -p server\" \"nodemon dist/server/server.js\"",

A: Looks like there is some process running locally on 4200. Here is what I would do-

*

*Execute ps -ef | grep 4200 on your terminal to check which process is running locally

*Kill that process if thats not useful. kill -9 ${Process_Id} This will force kill the process.

*Try to run the app again.

A: webpack: Compiled successfully.
^C
[1]+ Killed: 9 ng serve
webpack: Compiled successfully.
^Z
[1]+ Stopped ng serve
If you use Ctrl+Z in Mac you will have ´Port 4200 is already in use. Use '--port' to specify a different port.´later.

A: That means the port have running some other process so you have two solution.
1 run the angular in different port by
ng serve --port '{new port}'

2 kill the same port and serve it in same port
sudo kill $(sudo lsof -t -i:4200)
ng serve

A: For Windows it might be poosible that the port is already running in that case go to cmd as administrator and look up PID for the running port.
For example my running port is 4200.
Then run this command on cmd
netstat -a -n -o

Find port with port number 4200 by lookingup in the list or you can
right click on terminal and click find here enter 4200 in "find what" and click "find next":
For example you found that port number 4200 is used by pid 17200 then type below command in cmd:
taskkill -f /pid 17200

and then you can link your port or start serve command as required

A: Use npx kill-port 4200 then use ng serve
Reference: "Port 4200 is already in use". Killing all the processes associated with 4200 did not work.


text:
Q: How to check the C++ version is being used in Linux OS? I have tried to print:
std::cout << __cplusplus;

And Getting 1 as output.
Also I have tried: g++ -version command. It produces the output:
g++ (GCC) 4.4.7 20120313 (Red Hat 4.4.7-17)
Copyright (C) 2010 Free Software Foundation, Inc.
This is free software; see the source for copying conditions.
There is NO warranty; not even for MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.

How to determine the version of the C++ standard with the above output ??
Or Is there any other way ??
Somewhere I found like, Boost.Config has a plethora of macros that can be used to test for support for specific C++11 features.

A:
I have tried to print:
std::cout << __cplusplus;

And Getting 1 as output

It sounds like __cplusplus is being coerced into a bool. You should probably show the full code, and not the abridged snippet.
Maybe you can cast __cplusplus to an unsigned type. Or maybe you need to include a c++ header like <iostream>. However, I cannot reproduce your results when doing so:
$ cat test.cxx
#include <iostream>
int main(int argc, char* argv[])
{
    std::cout << __cplusplus << std::endl;
    std::cout << (unsigned int)__cplusplus << std::endl;
    return 0;
}

$ ./test.exe
201402
201402

How to determine the version with the above output ?? Or Is there any other way ??

Usually you ask the compiler to give them to you. Also see the output of echo '#include <iostream>' | g++ -x c++ -dM -E - | sort. The one below is from Fedora 25 with GCC 6.3.
You can get even more macros tuned for the particular CPU you have by adding -march=native. Then you will see preprocessor definitions like __AES__, __PCLMUL__, __SHA__, etc.
You can also use different versions of the C++ standard with -std=c++03, -std=c++11, -std=c++14, etc.
$ echo '#include <iostream>' | g++ -x c++ -dM -E - | sort
#define ADJ_ESTERROR 0x0008
#define ADJ_FREQUENCY 0x0002
#define ADJ_MAXERROR 0x0004
#define ADJ_MICRO 0x1000
#define ADJ_NANO 0x2000
#define ADJ_OFFSET 0x0001
#define ADJ_OFFSET_SINGLESHOT 0x8001
#define ADJ_OFFSET_SS_READ 0xa001
#define ADJ_SETOFFSET 0x0100
#define ADJ_STATUS 0x0010
#define ADJ_TAI 0x0080
#define ADJ_TICK 0x4000
#define ADJ_TIMECONST 0x0020
#define _ALLOCA_H 1
#define alloca(size) __builtin_alloca (size)
#define _ALLOCATOR_H 1
#define _ALLOC_TRAITS_H 1
#define __always_inline __inline __attribute__ ((__always_inline__))
#define __amd64 1
#define __amd64__ 1
#define _ANSI_STDDEF_H
#define _ASM_GENERIC_ERRNO_BASE_H
#define _ASM_GENERIC_ERRNO_H
#define __ASMNAME2(prefix,cname) __STRING (prefix) cname
#define __ASMNAME(cname) __ASMNAME2 (__USER_LABEL_PREFIX__, cname)
#define _ATFILE_SOURCE 1
#define __ATOMIC_ACQ_REL 4
#define __ATOMIC_ACQUIRE 2
#define __ATOMIC_CONSUME 1
#define __ATOMIC_HLE_ACQUIRE 65536
#define __ATOMIC_HLE_RELEASE 131072
#define __ATOMIC_RELAXED 0
#define __ATOMIC_RELEASE 3
#define __ATOMIC_SEQ_CST 5
...
#define _T_PTRDIFF
#define _T_PTRDIFF_
#define __try try
#define _T_SIZE
#define _T_SIZE_
#define _T_WCHAR
#define _T_WCHAR_
#define _TYPEINFO
#define __U16_TYPE unsigned short int
#define __U32_TYPE unsigned int
#define __U64_TYPE unsigned long int
#define __u_char_defined
#define __uid_t_defined
#define __UID_T_TYPE __U32_TYPE
#define __UINT16_C(c) c
#define UINT16_C(c) c
#define __UINT16_MAX__ 0xffff
#define UINT16_MAX (65535)
#define __UINT16_TYPE__ short unsigned int
#define UINT16_WIDTH 16
#define __UINT32_C(c) c ## U
#define UINT32_C(c) c ## U
#define __UINT32_MAX__ 0xffffffffU
#define UINT32_MAX (4294967295U)
#define __uint32_t_defined
#define __UINT32_TYPE__ unsigned int
#define UINT32_WIDTH 32
#define __UINT64_C(c) c ## UL
#define UINT64_C(c) c ## UL
#define __UINT64_MAX__ 0xffffffffffffffffUL
#define UINT64_MAX (__UINT64_C(18446744073709551615))
#define __UINT64_TYPE__ long unsigned int
#define UINT64_WIDTH 64
#define __UINT8_C(c) c
#define UINT8_C(c) c
#define __UINT8_MAX__ 0xff
#define UINT8_MAX (255)
#define __UINT8_TYPE__ unsigned char
#define UINT8_WIDTH 8
#define __UINT_FAST16_MAX__ 0xffffffffffffffffUL
#define UINT_FAST16_MAX (18446744073709551615UL)
#define __UINT_FAST16_TYPE__ long unsigned int
#define UINT_FAST16_WIDTH __WORDSIZE
#define __UINT_FAST32_MAX__ 0xffffffffffffffffUL
#define UINT_FAST32_MAX (18446744073709551615UL)
#define __UINT_FAST32_TYPE__ long unsigned int
#define UINT_FAST32_WIDTH __WORDSIZE
#define __UINT_FAST64_MAX__ 0xffffffffffffffffUL
#define UINT_FAST64_MAX (__UINT64_C(18446744073709551615))
#define __UINT_FAST64_TYPE__ long unsigned int
#define UINT_FAST64_WIDTH 64
#define __UINT_FAST8_MAX__ 0xff
#define UINT_FAST8_MAX (255)
#define __UINT_FAST8_TYPE__ unsigned char
#define UINT_FAST8_WIDTH 8
#define __UINT_LEAST16_MAX__ 0xffff
#define UINT_LEAST16_MAX (65535)
#define __UINT_LEAST16_TYPE__ short unsigned int
#define UINT_LEAST16_WIDTH 16
#define __UINT_LEAST32_MAX__ 0xffffffffU
#define UINT_LEAST32_MAX (4294967295U)
#define __UINT_LEAST32_TYPE__ unsigned int
#define UINT_LEAST32_WIDTH 32
#define __UINT_LEAST64_MAX__ 0xffffffffffffffffUL
#define UINT_LEAST64_MAX (__UINT64_C(18446744073709551615))
#define __UINT_LEAST64_TYPE__ long unsigned int
#define UINT_LEAST64_WIDTH 64
#define __UINT_LEAST8_MAX__ 0xff
#define UINT_LEAST8_MAX (255)
#define __UINT_LEAST8_TYPE__ unsigned char
#define UINT_LEAST8_WIDTH 8
#define __UINTMAX_C(c) c ## UL
#define UINTMAX_C(c) c ## UL
#define __UINTMAX_MAX__ 0xffffffffffffffffUL
#define UINTMAX_MAX (__UINT64_C(18446744073709551615))
#define __UINTMAX_TYPE__ long unsigned int
#define UINTMAX_WIDTH 64
#define __u_intN_t(N,MODE) typedef unsigned int u_int ##N ##_t __attribute__ ((__mode__ (MODE)))
#define __UINTPTR_MAX__ 0xffffffffffffffffUL
#define UINTPTR_MAX (18446744073709551615UL)
#define __UINTPTR_TYPE__ long unsigned int
#define UINTPTR_WIDTH __WORDSIZE
#define __ULONG32_TYPE unsigned int
#define __ULONGWORD_TYPE unsigned long int
#define __unix 1
#define __unix__ 1
#define unix 1
#define __UQUAD_TYPE unsigned long int
#define __USE_ATFILE 1
#define __useconds_t_defined
#define __USECONDS_T_TYPE __U32_TYPE
#define __USE_FORTIFY_LEVEL 0
#define __USE_GNU 1
#define __USE_ISOC11 1
#define __USE_ISOC95 1
#define __USE_ISOC99 1
#define __USE_ISOCXX11 1
#define __USE_LARGEFILE 1
#define __USE_LARGEFILE64 1
#define __USE_MISC 1
#define __USE_POSIX 1
#define __USE_POSIX199309 1
#define __USE_POSIX199506 1
#define __USE_POSIX2 1
#define __USER_LABEL_PREFIX__
#define __USE_UNIX98 1
#define __USE_XOPEN 1
#define __USE_XOPEN2K 1
#define __USE_XOPEN2K8 1
#define __USE_XOPEN2K8XSI 1
#define __USE_XOPEN2KXSI 1
#define __USE_XOPEN_EXTENDED 1
#define __USING_NAMESPACE_C99(name)
#define __USING_NAMESPACE_STD(name)
#define __UWORD_TYPE unsigned long int
#define __va_arg_pack() __builtin_va_arg_pack ()
#define __va_arg_pack_len() __builtin_va_arg_pack_len ()
#define _VA_LIST_DEFINED
#define __VERSION__ "7.1.1 20170622 (Red Hat 7.1.1-3)"
#define __WALL 0x40000000
#define __warnattr(msg) __attribute__((__warning__ (msg)))
#define __warndecl(name,msg) extern void name (void) __attribute__((__warning__ (msg)))
#define _WCHAR_H 1
#define __WCHAR_MAX__ 0x7fffffff
#define __WCHAR_MAX __WCHAR_MAX__
#define WCHAR_MAX __WCHAR_MAX
#define __WCHAR_MIN__ (-__WCHAR_MAX__ - 1)
#define __WCHAR_MIN __WCHAR_MIN__
#define WCHAR_MIN __WCHAR_MIN
#define __wchar_t__
#define __WCHAR_T
#define __WCHAR_T__
#define _WCHAR_T
#define _WCHAR_T_
#define _WCHAR_T_DECLARED
#define _WCHAR_T_DEFINED
#define _WCHAR_T_DEFINED_
#define _WCHAR_T_H
#define __WCHAR_TYPE__ int
#define __WCHAR_WIDTH__ 32
#define WCHAR_WIDTH 32
#define __WCLONE 0x80000000
#define __W_CONTINUED 0xffff
#define WCONTINUED 8
#define __WCOREDUMP(status) ((status) & __WCOREFLAG)
#define __WCOREFLAG 0x80
#define _WCTYPE_H 1
#define WEOF (0xffffffffu)
#define __W_EXITCODE(ret,sig) ((ret) << 8 | (sig))
#define WEXITED 4
#define __WEXITSTATUS(status) (((status) & 0xff00) >> 8)
#define WEXITSTATUS(status) __WEXITSTATUS (status)
#define __WIFCONTINUED(status) ((status) == __W_CONTINUED)
#define WIFCONTINUED(status) __WIFCONTINUED (status)
#define WIFEXITED(status) __WIFEXITED (status)
#define __WIFEXITED(status) (__WTERMSIG(status) == 0)
#define __WIFSIGNALED(status) (((signed char) (((status) & 0x7f) + 1) >> 1) > 0)
#define WIFSIGNALED(status) __WIFSIGNALED (status)
#define __WIFSTOPPED(status) (((status) & 0xff) == 0x7f)
#define WIFSTOPPED(status) __WIFSTOPPED (status)
#define __WINT_MAX__ 0xffffffffU
#define WINT_MAX (4294967295u)
#define WINT_MIN (0u)
#define __WINT_MIN__ 0U
#define _WINT_T
#define __WINT_TYPE__ unsigned int
#define __WINT_WIDTH__ 32
#define WINT_WIDTH 32
#define WNOHANG 1
#define __WNOTHREAD 0x20000000
#define WNOWAIT 0x01000000
#define __WORDSIZE 64
#define __WORDSIZE_TIME64_COMPAT32 1
#define __W_STOPCODE(sig) ((sig) << 8 | 0x7f)
#define WSTOPPED 2
#define __WSTOPSIG(status) __WEXITSTATUS(status)
#define WSTOPSIG(status) __WSTOPSIG (status)
#define __WTERMSIG(status) ((status) & 0x7f)
#define WTERMSIG(status) __WTERMSIG (status)
#define WUNTRACED 2
#define __wur
#define __x86_64 1
#define __x86_64__ 1
#define _XLOCALE_H 1
#define _XOPEN_SOURCE 700
#define _XOPEN_SOURCE_EXTENDED 1

A: If you want specific features in c++, you can use the macros described here:
e.g. you want to know if lib chrono is available: __cpp_lib_chrono contains a value 201510
http://en.cppreference.com/w/User:D41D8CD98F/feature_testing_macros
The version of the used c++ standard can be checked by: __cplusplus. For c++17 the value is "201703", for c++14 it is "201402". But also if the compiler seems to have c++14 enabled, you should keep in mind that not all features must be present. For specific features you can check the macros above. This specific part of the question has already an answer here:
How to determine the version of the C++ standard used by the compiler?
gcc for example have also predefined macros to check e.g. :__GNUC__
https://gcc.gnu.org/onlinedocs/cpp/Common-Predefined-Macros.html
It is somewhat unclear if you want to check during compile time or before, like in configure step.
If you want to know something in configure step, you can write small test progs which test for the above described macros and write the result to stdout so you can check in gmake or autotools.
Also you can check things in Makefile and share that info with your compiler by defining macros with -D flag.

A:
I have tried to print:
std::cout << __cplusplus;

And Getting 1 as output

This is expected behavior for g++ 4.4.7, according to How to determine the version of the C++ standard used by the compiler?

gcc (apparently for nearly 10 years) had this value set to 1 ... until it was fixed when gcc 4.7.0 came out.

An alternative solution would be to keep your __cplusplus approach and upgrade to g++ 4.7.0 or higher.


text:
Q: Javascript Datetime Format I've been a programmer for only a few months, and I'm super new at Javascript, so help me out if there's a simpler way. I'm creating a drop down of months and a textbox of year.
Is there a better way to do my month select box?
And how can I format my date to yyyy-mm-dd?
Thanks!

            Month:
            <select id="month">
                <option value="0">January</option>
                <option value="1">February</option>
                <option value="2">March</option>
                <option value="3">April</option>
                <option value="4">May</option>
                <option value="5">June</option>
                <option value="6">July</option>
                <option value="7">August</option>
                <option value="8">September</option>
                <option value="9">October</option>
                <option value="10">November</option>
                <option value="11">December</option>
            </select>

            Year:
            <input type="text" id="year" value=""/>

A: Looks like you are trying to re-invent the wheel in this one, you are already using jQuery so you might as well use jQuery Date Picker, after you load the references you get a full functional calendar by doing $('#yourDateField').datepicker()
About the format part, you could use DataJS, then the format is simple as dt.toString('dd-MM-yyyy')

A: An implementation of the date formatting:
/**
 * Default format:yyyy-mm-dd hh:ii:ss
 * @param string stamp Time in milliseconds
 * @param string format Your desired format
 * @param boolean zero With zero-prefix or not
 */
function format(timestamp, format, zero){
    var stamp = Number(timestamp),
        date = new Date(stamp), formatDate,
        f = format ? format : "yyyy-mm-dd hh:ii:ss",
        _d = (zero === undefined) ? l.format.zero : function(s){return s;};

    var year = _d(date.getFullYear()),
        month = _d(date.getMonth() + 1),
        day = _d(date.getDate()),
        hour = _d(date.getHours()),
        minute = _d(date.getMinutes()),
        second = _d(date.getSeconds());

    formatDate = f.replace(/yyyy/i, year).replace(/mm/i, month).replace(/dd/i, day)
                .replace(/hh/i, hour).replace(/ii/i, minute).replace(/ss/i, second);
    return formatDate;
},


text:
Q: How to debug Flutter code in Xcode environment How can I debug Flutter code in Xcode?
I have to debug code in Xcode and can't debug it in
vs code and etc because first I need to config Xcode.
I try any way to do it


text:
Q: Auto Layout - Make UITextView, not UIImageView, stretch the container view I have 3 views:

*

*a UIImageView (blank, no image set)

*a UITextView with isScrollEnabled set to false

*a UIView container (gray background) that contains the UIImageView and UITextView
I'm trying to get the container to resize based on the UITextView's contents. It works well — but as soon as I set an image, the container seems to resize based on the UIImageView.

Shorter text
Longer text
After setting image

I do want the UIImageView to grow and fill the container view's height, though. I just don't want it to stretch the container view. That's the UITextView's job. Here's what my constraints look like:

And the storyboard code:
<?xml version="1.0" encoding="UTF-8"?>
<document type="com.apple.InterfaceBuilder3.CocoaTouch.Storyboard.XIB" version="3.0" toolsVersion="18122" targetRuntime="iOS.CocoaTouch" propertyAccessControl="none" useAutolayout="YES" useTraitCollections="YES" useSafeAreas="YES" colorMatched="YES" initialViewController="BYZ-38-t0r">
    <device id="retina6_1" orientation="portrait" appearance="light"/>
    <dependencies>
        <plugIn identifier="com.apple.InterfaceBuilder.IBCocoaTouchPlugin" version="18093"/>
        <capability name="System colors in document resources" minToolsVersion="11.0"/>
        <capability name="documents saved in the Xcode 8 format" minToolsVersion="8.0"/>
    </dependencies>
    <scenes>
        <!--View Controller-->
        <scene sceneID="tne-QT-ifu">
            <objects>
                <viewController id="BYZ-38-t0r" customClass="ViewController" customModule="AutoLayoutImage" customModuleProvider="target" sceneMemberID="viewController">
                    <view key="view" contentMode="scaleToFill" id="8bC-Xf-vdC">
                        <rect key="frame" x="0.0" y="0.0" width="414" height="896"/>
                        <autoresizingMask key="autoresizingMask" widthSizable="YES" heightSizable="YES"/>
                        <subviews>
                            <view contentMode="scaleToFill" translatesAutoresizingMaskIntoConstraints="NO" id="6rW-8U-sdf" userLabel="Container View">
                                <rect key="frame" x="0.0" y="197.5" width="414" height="501"/>
                                <subviews>
                                    <imageView clipsSubviews="YES" userInteractionEnabled="NO" contentMode="scaleAspectFill" horizontalHuggingPriority="251" translatesAutoresizingMaskIntoConstraints="NO" id="a4K-HY-RKq">
                                        <rect key="frame" x="0.0" y="0.0" width="150" height="501"/>
                                        <constraints>
                                            <constraint firstAttribute="width" constant="150" id="Pim-0S-hxs"/>
                                        </constraints>
                                    </imageView>
                                    <textView clipsSubviews="YES" multipleTouchEnabled="YES" contentMode="scaleToFill" scrollEnabled="NO" textAlignment="natural" translatesAutoresizingMaskIntoConstraints="NO" id="9HO-GD-av1">
                                        <rect key="frame" x="150" y="0.0" width="264" height="501"/>
                                        <color key="backgroundColor" white="0.0" alpha="0.0" colorSpace="custom" customColorSpace="genericGamma22GrayColorSpace"/>
                                        <mutableString key="text">Lorem ipsum dolor sit er elit lamet, consectetaur cillium adipisicing pecu, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum. Nam liber te conscient to factor tum poen legum odioque civiuda.Lorem ipsum dolor sit er elit lamet, consectetaur cillium adipisicing pecu, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum. Nam liber te conscient to factor tum poen legum odioque civiuda.</mutableString>
                                        <color key="textColor" systemColor="labelColor"/>
                                        <fontDescription key="fontDescription" type="system" pointSize="14"/>
                                        <textInputTraits key="textInputTraits" autocapitalizationType="sentences"/>
                                    </textView>
                                </subviews>
                                <color key="backgroundColor" systemColor="systemGrayColor"/>
                                <constraints>
                                    <constraint firstAttribute="bottom" secondItem="a4K-HY-RKq" secondAttribute="bottom" id="1sx-AM-Fqw"/>
                                    <constraint firstItem="9HO-GD-av1" firstAttribute="leading" secondItem="a4K-HY-RKq" secondAttribute="trailing" id="Jyx-tB-n4x"/>
                                    <constraint firstItem="9HO-GD-av1" firstAttribute="top" secondItem="6rW-8U-sdf" secondAttribute="top" id="QxL-cJ-Jed"/>
                                    <constraint firstAttribute="trailing" secondItem="9HO-GD-av1" secondAttribute="trailing" id="UGU-yx-lKn"/>
                                    <constraint firstItem="a4K-HY-RKq" firstAttribute="top" secondItem="6rW-8U-sdf" secondAttribute="top" id="WWU-dr-LHm"/>
                                    <constraint firstAttribute="bottom" secondItem="9HO-GD-av1" secondAttribute="bottom" id="fuH-5Z-rGP"/>
                                    <constraint firstItem="a4K-HY-RKq" firstAttribute="leading" secondItem="6rW-8U-sdf" secondAttribute="leading" id="wdj-Os-8pf"/>
                                </constraints>
                            </view>
                        </subviews>
                        <color key="backgroundColor" systemColor="systemBackgroundColor"/>
                        <constraints>
                            <constraint firstItem="6rW-8U-sdf" firstAttribute="centerY" secondItem="8bC-Xf-vdC" secondAttribute="centerY" id="Veu-vt-Hmb"/>
                            <constraint firstItem="6rW-8U-sdf" firstAttribute="leading" secondItem="8bC-Xf-vdC" secondAttribute="leading" id="hXI-pR-7IQ"/>
                            <constraint firstItem="6rW-8U-sdf" firstAttribute="trailing" secondItem="8bC-Xf-vdC" secondAttribute="trailing" id="zQE-bH-DL3"/>
                        </constraints>
                    </view>
                </viewController>
                <placeholder placeholderIdentifier="IBFirstResponder" id="dkx-z0-nzr" sceneMemberID="firstResponder"/>
            </objects>
            <point key="canvasLocation" x="131.8840579710145" y="114.50892857142857"/>
        </scene>
    </scenes>
    <resources>
        <systemColor name="labelColor">
            <color white="0.0" alpha="1" colorSpace="custom" customColorSpace="genericGamma22GrayColorSpace"/>
        </systemColor>
        <systemColor name="systemBackgroundColor">
            <color white="1" alpha="1" colorSpace="custom" customColorSpace="genericGamma22GrayColorSpace"/>
        </systemColor>
        <systemColor name="systemGrayColor">
            <color red="0.55686274509803924" green="0.55686274509803924" blue="0.57647058823529407" alpha="1" colorSpace="custom" customColorSpace="sRGB"/>
        </systemColor>
    </resources>
</document>

And here's the image that I used. How do I make the container resize based on the UITextView and not the UIImageView?

A: You should set the vertical content compression resistance priority of the image view to be lower than the vertical content hugging priority of the text view. For example, I've set the former to "low" and the latter to "high", and it works.
Image view:

Text View:

A: In my opinion, you should use constraints to resolve your problem!
set text view constraint height equal view (or set equal top and bottom) height constraint and set static image view constraint height (ex: imageView height constraints = 250)


text:
Q: Data Repeater items Does Not Displayed on another machine I have set the data source of Data Repeater in C# Windows Application to a collection of Images
,every thing is good on my machine and the Images Displayed successfully ,but when I try to Run my
Windows Application on another machine - The Images Are Not Displayed -
How can i fix this ?

A: I did it by installing this tool on the client machine VisualBasicPowerPacks3Setup.exe and it works good


text:
Q: Changing Style with click in jQuery i am trying to make a to do list app. When i click a span with class "check" then i want to apply a style. Then the class of the span will change to "uncheck". When click the uncheck then the previous style will restore. Here is the html and jquery what i have done so far.
Problem: Problem is when i first click the span it works The "uncheck" class get removed and "check" class get added. Then the second part not works. I suspect the second part don't working because the "check" class is not in the dom when document.ready() is runs.
Any help will be greatly appreciated! Thanks!
HTML:

M2u category shown. M2u category shown M2u category shown M2u category shown.

M2u category shown

M2u category shown

jQuery:
    $('.note-body ol li span.check').click(function(){
            $(this).addClass('uncheck').removeClass('check');

            $(this).parent().css({'text-decoration':'line-through', 'color':'#5b382e'});

    });

   $('.note-body ol li span.uncheck').click(function(){
            $(this).addClass('check').removeClass('uncheck');

            $(this).parent().css({'text-decoration':'none', 'color':'#5b382e'});

});

RESOLVED:
Had to use the live(); because i am adding dom dynamically. Here is the final code (placed the styles in classes):
$('.note-body ol li span.check').live('click', function(){
            $(this).addClass('uncheck').removeClass('check');
            $(this).parent().addClass('task-done').removeClass('task-notdone');
    });

   $('.note-body ol li span.uncheck').live('click', function(){
            $(this).addClass('check').removeClass('uncheck');
            $(this).parent().addClass('task-notdone').removeClass('task-done');
   });

A: You are correct. Since the 'uncheck' class is dynamically added to the DOM, you need to use the jQuery live API. Try this:
   $('.note-body ol li span.uncheck').live('click', function(){
            $(this).addClass('check').removeClass('uncheck');

            $(this).parent().css({'text-decoration':'none', 'color':'#5b382e'});

});

A: use jquery live or delegate as they are added runtime
http://api.jquery.com/live/
http://api.jquery.com/delegate/

A: Do you really need an uncheck class? Are there three states check, uncheck and 'nothing'? Getting rid of the uncheck class you could simplify your code.
I would do:
$('.note-body .some_other_identifier').live('click', function() {
    $(this).parent().toggleClass('check');
});

Adding
.some_other_identifier {'text-decoration':'line-through'; 'color':'#5b382e'; }
.check .some_other_identifier { 'text-decoration':'none'; 'color':'#5b382e'; }

to your css.


text:
Q: C# application with random questions can't add answers I have a project where I want to make a random quiz with random questions and answers. I used a dictionary to do this and I succeeded in making the questions and answers and in displaying a random one.
Now I want to add specific answers per question asked. I figured this should be done by a dictionary also but I don't know how to make this work.
I already made the random generator, the questions and answers (tkey and tvalue)
So now I only need to add a part where you have specific answers per questions and a way to detect if the questions are wrong or right, this can be done by a if and a else statement but I'm not experienced enough to know how to implement all these functions.
This is what I have right now
class Program
{
    static public void Main()
    {
        //maak een dictionary aan
        Console.WriteLine("Quiz");

        Dictionary<int, string> Questions = new Dictionary<int, string>();

        //voeg vragen toe
        //key koppelen aan vraag
        Questions.Add(11, "Vraag1?");
        Questions.Add(12, "Vraag2?");
        Questions.Add(13, "Vraag3?");
        Questions.Add(14, "Vraag4?");
        Questions.Add(15, "Vraag5?");

        Dictionary<int, string> answers = new Dictionary<int, string>();

        List<int> keylist = new List<int>(); // string naar int converten
        keylist = Questions.Keys.ToList();

        Random rand = new Random(); //maak random aan
        int countKeys = Questions.Keys.Count();
        int randomIndex = rand.Next(0, countKeys);

        Console.WriteLine(Questions.ElementAt(randomIndex).Key); //geef een random index en de gekoppelde key daaraan

        string input = Console.ReadLine();

        Console.WriteLine("You answered: " + input);

        Console.ReadKey();
    }
}

Can someone help me by telling me / helping me make a way to add specific answers to these questions?

A: You can use a Dictionary<string, string> to store the questions as key and the answer as value
Then, get the list of keys and shuffle it, to finally iterate through that list.
In example (fiddle to the below code) :
private static Random rng = new Random();

public static void Shuffle<T>(this IList<T> list)
{
    int n = list.Count;
    while (n > 1)
    {
        n--;
        int k = rng.Next(n + 1);
        T value = list[k];
        list[k] = list[n];
        list[n] = value;
    }
}

public static void Main(string[] args)
{
    var quizz = new Dictionary<string, string>
    {
        { "What is the answer to the Ultimate Question of Life, the Universe, and Everything ?", "42" },
        { "What is your name ?", "Sir Arthur, king of the Britons" },
        { "What is your quest ?", "To seek the Holy Grail" },
        { "What is the air-speed velocity of an unladen swallow?", "What do you mean ? An African or European swallow ?" }
    };
    var questions = quizz.Keys.ToList();
    questions.Shuffle();

    foreach (var question in questions)
    {
        Console.WriteLine(question);
        if (Console.ReadLine() != quizz[question])
        {
            Console.WriteLine("You failed");
            Console.ReadLine();
            break;
        }
        else
        {
            Console.WriteLine("Nice !");
        }
    }
}

A: Put answer for each key from Questions.
foreach(var item in Questions) {
    answers.Add(item.Key, "answer")
}

store the specific answer by same random index of question into another variable
var askingQuestion = Questions.ElementAt(randomIndex);
var answerOfAskingQuestion = answers.ElementAt(randomIndex);

Display the question to read answer from console
Console.WriteLine(answerOfAskingQuestion.value);
string input = Console.ReadLine();

Now compare the input with value of answerOfAskingQuestion
if (input.ToLower().Equals(answerOfAskingQuestion.Value.ToLower()) {
    // given answer is correct
    // display "your answer is correct"
    Console.WriteLine("Your answer is correct");
} else {
    // answer is wrong
    // display "incorrect"
    Console.WriteLine("Your answer is wrong");
}

A: You should create a "Question" class containing the question text, a list of answers and the correct answer. So your Questions dictionary should be:
Dictionary<int, Question> Questions = new Dictionary<int, Question>();


text:
Q: Assign default excel format to cell I'm using XlsxWriter to format cells containing currency formatted strings as follows:
currency_cell_format = self.workbook.add_format()
currency_cell_format.set_num_format('_($* #,##0.00_);_($* (#,##0.00);_($* "-"??_);_(@_)')
self.worksheet.write_string(row=r, col=c, string=value, cell_format=currency_cell_format)

The expected outcome is that the format type when viewing the worksheet in excel should be a Number (specifically $).  There appears to be no visual formatting (however the type is Custom) and the values are left justified (instead of the typical right justified when the cell is Numeric formatted.
How can I assign the default Excel format types to cells using Xslxwriter so that the columns are Numeric formatted (instead of Custom) thus enabling functionality like calculations?
Note: Applying bold or font formatting works correctly.  I tried the hex index values but the cells remained unformatted.

A: In Excel assigning a number format to a string has no effect. The same applies when using XlsxWriter, particularly if you are using write_string().
You should convert your data to a number, if it is numeric, and then apply the format using write_number() or write().


text:
Q: Posts with Tag on Bottom of Page I have a plugin request that I cannot find by a Google search because I can't think of what it would be called:
I need a plugin that will, on a page-by-page basis, allow me to define a list of tags (probably via a Custom Field), and should show the most recent 5 (or any number) posts that have that tag on the bottom of the page.
Thanks!

A: Here's a quick shortcode I put together for your functions.php file if you want to use it as a starting point. or it can be converted to a plugin if you prefer.
function wpse27961_show_tagged_posts( $atts ) {
    extract( shortcode_atts( array(
        'tags' => '',
        'number' => 5,
    ), $atts ) );

    $args = array(
        'posts_per_page' => $number,
        'tag' => $tags
    );

    $wpse_tagged_posts = new WP_Query( $args );

    $output = "";

    if($wpse_tagged_posts):
        $output .= "
";
        while($wpse_tagged_posts->have_posts()):
            $wpse_tagged_posts->the_post();
            $output .= '
';
            $output .= the_title( '', '', false );
            $output .= '
';
        endwhile;
        $output .= "
";
    endif;

    wp_reset_query();

    return $output;
}
add_shortcode( 'wpse_tagged_posts', 'wpse27961_show_tagged_posts' );

yeah, it's not pretty, but someone can tweak it if they have the time. add the shortcode to your page like this:
[wpse_tagged_posts tags="foo,bar"]

it'll default to showing 5 posts. or if you want a specific number of posts:
[wpse_tagged_posts tags="foo,bar" number="6"]


text:
Q: Using probability distributions and variances to modify a formula We have a lamp and it is in 2m distance. Its light intensity is 5. We want to know what amount of light is reaching to us. We can simply use a formula like:
$
\mathrm{light} = \frac{\mathrm{intensity}}{\mathrm{distance}}
$.
Now suppose that the distance is a random variable (i.e. it is in $ 2m \pm 1m $ distance, and the intensity is $ 5 \pm 4.7 $).
How we can change the formula in order to be able to use it in case we have random variables too?
P.S. Actually the question is how we can make use of probability distributions, variance, etc. to change the formula?

A: Your question seems to be when a variable is a ratio of two measurements each having uncertainty associated with it shouldn't we deal with the ratio like any other random variable?  The answer is yes and this is often done.  The delta method is one way to approximate the variance of a function of random variables when the variance(s) of the variable(s) that are inputs to the function are known.
In the case of ratios there are special issues.  For example if X and Y are independent standard normal random variables X/Y is distributed as a Cauchy random variable which has an infinite variance and also an infinite mean. When the denominator has positive probability density around 0 the heavy tail can mean that the variance is infinite.
When you know the density functions for X and Y and they are independent you can write down the joint density of X and Y apply a change of variables mapping (X,Y) into (X/Y, Y) and integrating out Y.
Also by Jensen's inequality E(X/Y)>=E(X)/E(Y).  The inequality is strict unless X/Y or Y have degenerate distributions.  So there is a lot that can be done to deal with ratios of random variables.


text:
Q: Finding base points of a polynomial considered in projective space I am given the following polynomial
$$f(x,y)=y^2-4x^3-g_2 x, $$
for a fixed constant $g_2$. A base point of $f$ is a point $(x_0,y_0)$ which is a member of all level curves $\{ (x,y): f(x,y)=c \},c \in \mathbb R$. Obviously the polynomial has no base points when considered in $\mathbb R^2$. Thus I was told to consider it in the projective space $\mathbb{CP}^2$. I'm not entirely sure what it means. I guess I should embed the point $(x,y) \in \mathbb{R}^2$ as $[1:x:y] \in \mathbb{CP}^2$, but I'm not really sure how to take it from there.
Thanks.

A: Yes, you're on the right track.
The projective closure of the zero set of the polynomial $f(x,y)-c$ is the zero set of the "homogenized" version of $f(x,y)-c$, that is the homogeneous polynomial
$$F_c(X,Y,Z)=Y^2Z-4X^3+g_2XZ^2+cZ^3$$
where $X,Y,Z$ are homogeneous coordinates on $\mathbf P^2$. Now you are trying to find points $[a,b,c] \in \mathbf P^2$ which lie in the set $F_c=0$ for all $c$.
As you have already observed, there are no such points in the "usual" $(x,y)$-plane; in projective terms this translates to the statement that no point $[\alpha,\beta,1]$ lies in $F_c=0$ for all $c$. So you can restrict attention to points $[\alpha,\beta,0]$. (Remember that in projective space, we can rescale coordinates by nonzero scalars, so that every point is represented by a triple of homogeneous coordinates in which either $Z=1$ or $Z=0$.)
But now setting $Z=0$ in the formula for $F_c$, we see that if $[\alpha,\beta,0] \in \{ F_c=0\}$ then we must have $\alpha=0$ too; rescaling $\beta$ (which must be nonzero) we get just one point, namely $[0,1,0]$. Conversely, it's a straightforward check to see that $[0,1,0] \in \{F_c=0\}$ for all $c$.
So there's exactly one base point in $\mathbf P^2$, namely the point $[0,1,0]$. (From a fancier point of view, we might view this as 9 "coincident" basepoints, or one point "with multiplicity 9", but that's a story for another day.)


text:
Q: how to keep both activities on the screen in android? Hi In my app i have two activities. one is the main activity. so when i launch the app it invokes the main activity.  the main activity displays on the top left corner of the screen with some width and height. on the main activity there is a button. when i press the button it launches the second activity. when the second activity is launched it displays itself in the center of the screen. When second activity got the focus, the first activity goes to the pause state but it is still displayed on the screen. But when i move from the second activity to the first activity, the first activity gains focus. The problem is when the first activity gains focus, the second activity disappears from the screen. What i want is it should not disappear. It has to be on the screen in pause state. Then I need to switch between these activities.
The following is my manifest file:-
    <application
    android:allowBackup="true"
    android:icon="@drawable/ic_launcher"
    android:label="@string/app_name"
    android:theme="@style/AppTheme" >
    <activity
        android:theme="@android:style/Theme.Dialog"
        android:name="com.example.firstapp.MainActivity"
        android:label="@string/app_name" >
        <intent-filter>
            <action android:name="android.intent.action.MAIN" />

            <category android:name="android.intent.category.LAUNCHER" />
        </intent-filter>
    </activity>
    <activity
        android:theme="@android:style/Theme.Dialog"
        android:name="com.example.firstapp.DisplayMessageActivity"
        android:label="@string/title_activity_display_message"
        android:parentActivityName="com.example.firstapp.MainActivity" >
        <meta-data
            android:name="android.support.PARENT_ACTIVITY"
            android:value="com.example.firstapp.MainActivity" />
    </activity>
    </application>

The two actions uses Linear layout as their root layout and contains some gui elemnts.

A: You need to use Fragments.  Vogella has a fantastic tutorial.
http://www.vogella.com/articles/AndroidFragments/article.html

A: Use fragments.
http://developer.android.com/guide/components/fragments.html
Example at the developer site.
http://developer.android.com/guide/components/fragments.html#Example
EDIT:
When you h navigate to second Activity from first activity, first activity will be paused (will be there on back stack).Your second activity is put on stack and takes focus. When you return to first activity second activity is popped form the stack and destroyed. Now first activity takes focus. This is how it works. Stack works like last in, first out. (LIFO).
For more detail regarding activity back stack read the topic in the link below.
http://developer.android.com/guide/components/tasks-and-back-stack.html


text:
Q: Are there any Dart resources that would split a command-line String into a List of arguments? Are there any Dart resources that would split a command-line String into a List<String> of arguments?
ArgsParser takes a List<String> of already split arguments usually from main(List<String>).

A: To answer my own question,
I've converted a Java function I liked into a Dart Converter<String, List<String>) class:
import 'dart:convert';

/// Splits a `String` into a list of command-line argument parts.
/// e.g. "command -p param" -> ["command", "-p", "param"]
///
class CommandlineConverter extends Converter<String, List<String>>
{
  @override
  List<String> convert(String input)
  {
    if (input == null || input.isEmpty)
    {
        //no command? no string
        return [];
    }

    final List<String> result = new List<String>();

    var current = "";

    String inQuote;
    bool   lastTokenHasBeenQuoted = false;

    for (int index = 0; index < input.length; index++)
    {
        final token = input[index];

        if (inQuote != null)
        {
          if   (token == inQuote)
          {
              lastTokenHasBeenQuoted = true;
              inQuote                = null;
          }
          else
          {
              current += token;
          }
        }
        else
        {
          switch (token)
          {
            case "'": // '
            case '"': // ""

              inQuote = token;
              continue;

            case " ": // space

              if (lastTokenHasBeenQuoted || current.isNotEmpty)
              {
                  result.add(current);
                  current = "";
              }
              break;

            default:

              current               += token;
              lastTokenHasBeenQuoted = false;
          }
        }
    }

    if (lastTokenHasBeenQuoted || current.isNotEmpty)
    {
        result.add(current);
    }

    if (inQuote != null)
    {
        throw new Exception("Unbalanced quote $inQuote in input:\n$input");
    }

    return result;
  }
}


text:
Q: Unity performance considerations with container controlled lifetime - Is there any reflection lag with multiple Resolve() calls? Is there any reflection performance considerations when repeatedly calling container.Resolve<T>() when a resolution has already been established?
I'm using it in an MVC controller to resolve my data service, so it will be called on every HTTP request. I'm storing the container instance in Application state, and I'm using container controlled lifetime so it maintains a singleton instance of my resolved class. My assumption is that while the container is alive and has created a new instance of the service, it will not need to use reflection on subsequent calls to resolve it.
I'm considering keeping a reference to the resolved class instead if performance of Resolve<T>() is an issue. But with the singleton lifetime setup, it seems like I would be duplicating something that's already built-in.

A: While not directly answering your question, Torkel Ödegaard's IoC container benchmarks suggest that you'll not be seeing a major performance hit related to resolving dependecies.


text:
Q: Is it possible to define (pure virtual) test cases in a base class using googletest is it possible to define a base test-fixture with (abstract) test cases and derive classes from them?
There are two szenarios I'd like to support (Taken from Roy Overshores "The art of Unit Testing"):

*

*Template test class pattern Define abstract test cases in the base test-fixture and thus force derived classes to implement them.

*Abstract test driver class pattern Implement tests in the base class that all derived class inherit automatically

I cannot figure out how this works with googletest. If I have a base class
#pragma once

class BaseClass : public ::testing::Test
{
};

TEST_F(BaseClass, T1)
{

}

and two derived classes (in different files)
#include "stdafx.h"

#include "BaseClass.h"

class DerivedClass1 : public BaseClass
{

};

and
#include "stdafx.h"

#include "BaseClass.h"

class DerivedClass2 : public BaseClass
{

};

I get the compiler error
virtual void __thiscall BaseClass_T1_Test::TestBody(void)" (?TestBody@BaseClass_T1_Test@@EAEXXZ) already defined in DerivedClass1.obj

Is it somehow possible to define concrete and pure virtual tests in a test base class?

A: Try move TEST_F(BaseClass, T1){} out of the BaseClass.h into its own .cpp file.
The BaseClass.h is included into 2 .cpp files of DerivedClass1  and DerivedClass2, and during compilation the TEST_F will be expanded to a bunch of executable functions that would be included into both of these .cpp files. And that is why the linker is unhappy and complain about the duplication of symbol TestBody@BaseClass_T1_Test@@EAEXXZ).


text:
Q: Changing lower letter to upper letter in SVG Svg File
I am working on a graphics application where I can only use Arc, Line, cubic and Quadratic bézier. I have an SVG file, which is a bit long but I just took first few path elements to build to see the output. I wrote a small application which replaces lower letters to upper letters and produced a simple SVG file which consists upper causes and consists only four SVG commands. I have created two paths with original for and the second path with a modified version to confirm my output. Everything seems work fine excluding lower letter 'm'. The result is not correct. I am not sure way. Any help should be very much appreciated. What mistake I am making? To see the converted version you have to uncomment the send path

A: There are several things wrong with your SVG.

*

*Your path consists of eleven subpaths. Each of the subpaths form a very thin horizontal rectangle. For example, look at the first subpath:
M 21.52,184.48, H 91.11, v-.07, H21.54, l 0,.07 Z
That's a rectangle that is 91px wide and 0.07 pixels high.  A rectangle that is 7/100 of a pixel high is going to be very faint at best. It is visible in Firefox, but Chrome seems to be culling it completely for some reason.

*Your fill is invalid.
fill="New_Gradient_35"

should be:
fill="url(#New_Gradient_35)"

*Your path definition is invalid.  There should not be commas before a path command letter.
M21.52,184.48,H91.11,v-.07,H21.54,l0,.07Z,

should be
M21.52,184.48H91.11v-.07H21.54l0,.07Z

Chrome is a little forgiving. It will allow commas after a coordinate value, but not after a path command.  So it doesn't mind:
M21.52,184.48,H91.11,v-.07,H21.54,l0,.07Z

but it doesn't like the comma between the Z and the M:
M21.52,184.48,H91.11,v-.07,H21.54,l0,.07Z,
M ...etc...

Firefox doesn't accept either comma.

*You are specifying a stroke colour, but your stroke-width is "0", so your stroke will not be drawn.  But perhaps that was intentional.
If you fix these issues, you get a more successful result. I'm not sure if it was what you are expecting though. It doesn't look much like a letter "m" to me.

<svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" viewBox="0 0 498.9 498.9" width="100%" height="100%">

    <linearGradient id="New_Gradient_35" x1="369.44" y1="1293.18" x2="137.44" y2="718.97" gradientTransform="translate(15.85 -609.22)" gradientUnits="userSpaceOnUse">
      <stop offset="0.07"/>
      <stop offset="0.93" stop-color="#454d51"/>
    </linearGradient>

  <title>Test One</title>
  <g id="Case">
    <path fill="url(#New_Gradient_35)" stroke-width="0" stroke="red" d="M21.52,184.48H91.11v-.07H21.54l0,.07Z
    M469,147.4q1.62,0,3.21,.12l-406.4,0c.67,-.05,1.35,-.09,2,-.12l401.16,0Z
    m8.55,.76,.22,0H60.82l.56,-.1h6l-5.47,.06Z
    m1,.2,.7,.15,-419.89,0,.4,-.09,418.79,0Z
    m2.21,.5,.31,.08H185.41v-.07Z
    m1.88,.5,.37,.11H55.54l.23,-.07,426.9,0Z
    m.74,.22,.16,0,-428.69,0,.43,-.13,428.11,0Z
    m.85,.27,.47,.15H227.91l-63.75,0v0l58.44,-.08Z
    m.8,.27,.23,.08,-432.07,0,.35,-.12,431.49,0Z
    m.55,.19,.33,.12,-433.37,0,.39,-.14Z
    m.83,.31,.2,.08H51.93l.2,-.08Z" />

  </g>

</svg>


text:
Q: Aurelia: notification when ANY property is modified Do you see any way to know when ANY model's property has been modified through a binding?
I would need something generic because it would be applied to all the forms of the application. This means I cannot just have a 'property'Changed() observable callback for every properties of the models. I'm thinking along the ways of overriding the properties setters created by the binding engine so they can call a single defined callback but I feel like there could be a better way.

A: I created a aurelia-plugin for this kind of scenario (and more).
Its not exactly what your asking for, but can help you a lot.
because the plugin will create a single property called isDirty that you can observe and fire your code accordingly.
https://github.com/avrahamcool/aleph1-aurelia-utilities
look at the Dirty Tracking a model: section

your model class need to extends the baseClass provided by the plugin.
  now you can decorate any properties of your model with the
  @dirtyTrack() decorator.
for babel users: the assignment in the declaration will set the
  default value for the property. for TS users: you should call the
  decorator with a parameter @dirtyTrack(7) someInt: number;
this will set up a isDirty variable in your model. this property will
  be automatically updated to with every change to your tracked
  properties.
at any point, you can call saveChanges() on your model, to commit the
  current changes. or discardChanges() to revert back to the last saved
  point. you can call serialize() to get a pojo object from your model,
  or deserialize(pojo) to populate your model from a pojo object.

A: Ok, I ended up just using the binding engine to watch all properties changes. This allowed me to implement my isDirty checks without modifying the existing models...
So the final code looks like this:
Object.getOwnPropertyNames(obj).forEach(p => {
        this.subscriptions.push(this.binding.propertyObserver(obj, p)
           .subscribe(() => this.updateDirty()));
    });

my updateDirty() method is called after every property change and no change was necessary to the model.
If anyone can come up with a better solution, I'm still interested but this fits my needs for the time being.


text:
Q: MongoDB uses wrong index, even after clearing the query plan cache I have the following command:
db.mycol.find({sourceId:ObjectId("596bac5a6f473e1a042bFFFF"),myFlag:false}).count()

It was taking a lot of time.
So I decided to add an index { "sourceId" : -1, "myFlag" : -1 }
MongoDB still kept taking the same time.
When I ran explain() on the find command, I noticed that mongoDB still kept using my old indexes.
db.mycol.find({sourceId:ObjectId("596bac5a6f473e1a042bFFFF"),myFlag:false}).explain(true)
{
    "queryPlanner" : {
        "plannerVersion" : 1,
        "namespace" : "mydb.mycol",
        "indexFilterSet" : false,
        "parsedQuery" : {
            "$and" : [
                {
                    "sourceId" : {
                        "$eq" : ObjectId("596bac5a6f473e1a042bFFFF")
                    }
                },
                {
                    "myFlag" : {
                        "$eq" : false
                    }
                }
            ]
        },
        "winningPlan" : {
            "stage" : "FETCH",
            "filter" : {
                "myFlag" : {
                    "$eq" : false
                }
            },
            "inputStage" : {
                "stage" : "IXSCAN",
                "keyPattern" : {
                    "sourceId" : 1
                },
                "indexName" : "sourceId_1",
                "isMultiKey" : false,
                "isUnique" : false,
                "isSparse" : false,
                "isPartial" : false,
                "indexVersion" : 1,
                "direction" : "forward",
                "indexBounds" : {
                    "sourceId" : [
                        "[ObjectId('596bac5a6f473e1a042bFFFF'), ObjectId('596bac5a6f473e1a042bFFFF')]"
                    ]
                }
            }
        },
        "rejectedPlans" : [
            {
                "stage" : "FETCH",
                "filter" : {
                    "sourceId" : {
                        "$eq" : ObjectId("596bac5a6f473e1a042bFFFF")
                    }
                },
                "inputStage" : {
                    "stage" : "IXSCAN",
                    "keyPattern" : {
                        "myFlag" : -1
                    },
                    "indexName" : "myFlag_-1",
                    "isMultiKey" : false,
                    "isUnique" : false,
                    "isSparse" : false,
                    "isPartial" : false,
                    "indexVersion" : 1,
                    "direction" : "forward",
                    "indexBounds" : {
                        "myFlag" : [
                            "[false, false]"
                        ]
                    }
                }
            },
            {
                "stage" : "FETCH",
                "filter" : {
                    "myFlag" : {
                        "$eq" : false
                    }
                },
                "inputStage" : {
                    "stage" : "IXSCAN",
                    "keyPattern" : {
                        "sourceId" : -1,
                        "timestamp" : -1
                    },
                    "indexName" : "sourceId_-1_timestamp_-1",
                    "isMultiKey" : false,
                    "isUnique" : false,
                    "isSparse" : false,
                    "isPartial" : false,
                    "indexVersion" : 1,
                    "direction" : "forward",
                    "indexBounds" : {
                        "sourceId" : [
                            "[ObjectId('596bac5a6f473e1a042bFFFF'), ObjectId('596bac5a6f473e1a042bFFFF')]"
                        ],
                        "timestamp" : [
                            "[MaxKey, MinKey]"
                        ]
                    }
                }
            },
            {
                "stage" : "FETCH",
                "filter" : {
                    "myFlag" : {
                        "$eq" : false
                    }
                },
                "inputStage" : {
                    "stage" : "IXSCAN",
                    "keyPattern" : {
                        "sourceId" : -1,
                        "timestamp" : 1
                    },
                    "indexName" : "sourceId_-1_timestamp_1",
                    "isMultiKey" : false,
                    "isUnique" : false,
                    "isSparse" : false,
                    "isPartial" : false,
                    "indexVersion" : 1,
                    "direction" : "forward",
                    "indexBounds" : {
                        "sourceId" : [
                            "[ObjectId('596bac5a6f473e1a042bFFFF'), ObjectId('596bac5a6f473e1a042bFFFF')]"
                        ],
                        "timestamp" : [
                            "[MinKey, MaxKey]"
                        ]
                    }
                }
            },
            {
                "stage" : "FETCH",
                "inputStage" : {
                    "stage" : "IXSCAN",
                    "keyPattern" : {
                        "sourceId" : -1,
                        "myFlag" : -1
                    },
                    "indexName" : "sourceId_-1_myFlag_-1",
                    "isMultiKey" : false,
                    "isUnique" : false,
                    "isSparse" : false,
                    "isPartial" : false,
                    "indexVersion" : 1,
                    "direction" : "forward",
                    "indexBounds" : {
                        "sourceId" : [
                            "[ObjectId('596bac5a6f473e1a042bFFFF'), ObjectId('596bac5a6f473e1a042bFFFF')]"
                        ],
                        "myFlag" : [
                            "[false, false]"
                        ]
                    }
                }
            }
        ]
    },
    "executionStats" : {
        "executionSuccess" : true,
        "nReturned" : 2074,
        "executionTimeMillis" : 33936,
        "totalKeysExamined" : 2074,
        "totalDocsExamined" : 2074,
        "executionStages" : {
            "stage" : "FETCH",
            "filter" : {
                "myFlag" : {
                    "$eq" : false
                }
            },
            "nReturned" : 2074,
            "executionTimeMillisEstimate" : 31710,
            "works" : 2075,
            "advanced" : 2074,
            "needTime" : 0,
            "needYield" : 0,
            "saveState" : 1554,
            "restoreState" : 1554,
            "isEOF" : 1,
            "invalidates" : 0,
            "docsExamined" : 2074,
            "alreadyHasObj" : 0,
            "inputStage" : {
                "stage" : "IXSCAN",
                "nReturned" : 2074,
                "executionTimeMillisEstimate" : 0,
                "works" : 2075,
                "advanced" : 2074,
                "needTime" : 0,
                "needYield" : 0,
                "saveState" : 1554,
                "restoreState" : 1554,
                "isEOF" : 1,
                "invalidates" : 0,
                "keyPattern" : {
                    "sourceId" : 1
                },
                "indexName" : "sourceId_1",
                "isMultiKey" : false,
                "isUnique" : false,
                "isSparse" : false,
                "isPartial" : false,
                "indexVersion" : 1,
                "direction" : "forward",
                "indexBounds" : {
                    "sourceId" : [
                        "[ObjectId('596bac5a6f473e1a042bFFFF'), ObjectId('596bac5a6f473e1a042bFFFF')]"
                    ]
                },
                "keysExamined" : 2074,
                "dupsTested" : 0,
                "dupsDropped" : 0,
                "seenInvalidated" : 0
            }
        },
        "allPlansExecution" : [
            {
                "nReturned" : 0,
                "executionTimeMillisEstimate" : 1630,
                "totalKeysExamined" : 101,
                "totalDocsExamined" : 101,
                "executionStages" : {
                    "stage" : "FETCH",
                    "filter" : {
                        "sourceId" : {
                            "$eq" : ObjectId("596bac5a6f473e1a042bFFFF")
                        }
                    },
                    "nReturned" : 0,
                    "executionTimeMillisEstimate" : 1630,
                    "works" : 101,
                    "advanced" : 0,
                    "needTime" : 101,
                    "needYield" : 0,
                    "saveState" : 1554,
                    "restoreState" : 1554,
                    "isEOF" : 0,
                    "invalidates" : 0,
                    "docsExamined" : 101,
                    "alreadyHasObj" : 0,
                    "inputStage" : {
                        "stage" : "IXSCAN",
                        "nReturned" : 101,
                        "executionTimeMillisEstimate" : 0,
                        "works" : 101,
                        "advanced" : 101,
                        "needTime" : 0,
                        "needYield" : 0,
                        "saveState" : 1554,
                        "restoreState" : 1554,
                        "isEOF" : 0,
                        "invalidates" : 0,
                        "keyPattern" : {
                            "myFlag" : -1
                        },
                        "indexName" : "myFlag_-1",
                        "isMultiKey" : false,
                        "isUnique" : false,
                        "isSparse" : false,
                        "isPartial" : false,
                        "indexVersion" : 1,
                        "direction" : "forward",
                        "indexBounds" : {
                            "myFlag" : [
                                "[false, false]"
                            ]
                        },
                        "keysExamined" : 101,
                        "dupsTested" : 0,
                        "dupsDropped" : 0,
                        "seenInvalidated" : 0
                    }
                }
            },
            {
                "nReturned" : 101,
                "executionTimeMillisEstimate" : 0,
                "totalKeysExamined" : 101,
                "totalDocsExamined" : 101,
                "executionStages" : {
                    "stage" : "FETCH",
                    "filter" : {
                        "myFlag" : {
                            "$eq" : false
                        }
                    },
                    "nReturned" : 101,
                    "executionTimeMillisEstimate" : 0,
                    "works" : 101,
                    "advanced" : 101,
                    "needTime" : 0,
                    "needYield" : 0,
                    "saveState" : 1554,
                    "restoreState" : 1554,
                    "isEOF" : 0,
                    "invalidates" : 0,
                    "docsExamined" : 101,
                    "alreadyHasObj" : 0,
                    "inputStage" : {
                        "stage" : "IXSCAN",
                        "nReturned" : 101,
                        "executionTimeMillisEstimate" : 0,
                        "works" : 101,
                        "advanced" : 101,
                        "needTime" : 0,
                        "needYield" : 0,
                        "saveState" : 1554,
                        "restoreState" : 1554,
                        "isEOF" : 0,
                        "invalidates" : 0,
                        "keyPattern" : {
                            "sourceId" : -1,
                            "timestamp" : -1
                        },
                        "indexName" : "sourceId_-1_timestamp_-1",
                        "isMultiKey" : false,
                        "isUnique" : false,
                        "isSparse" : false,
                        "isPartial" : false,
                        "indexVersion" : 1,
                        "direction" : "forward",
                        "indexBounds" : {
                            "sourceId" : [
                                "[ObjectId('596bac5a6f473e1a042bFFFF'), ObjectId('596bac5a6f473e1a042bFFFF')]"
                            ],
                            "timestamp" : [
                                "[MaxKey, MinKey]"
                            ]
                        },
                        "keysExamined" : 101,
                        "dupsTested" : 0,
                        "dupsDropped" : 0,
                        "seenInvalidated" : 0
                    }
                }
            },
            {
                "nReturned" : 101,
                "executionTimeMillisEstimate" : 10,
                "totalKeysExamined" : 101,
                "totalDocsExamined" : 101,
                "executionStages" : {
                    "stage" : "FETCH",
                    "filter" : {
                        "myFlag" : {
                            "$eq" : false
                        }
                    },
                    "nReturned" : 101,
                    "executionTimeMillisEstimate" : 10,
                    "works" : 101,
                    "advanced" : 101,
                    "needTime" : 0,
                    "needYield" : 0,
                    "saveState" : 1554,
                    "restoreState" : 1554,
                    "isEOF" : 0,
                    "invalidates" : 0,
                    "docsExamined" : 101,
                    "alreadyHasObj" : 0,
                    "inputStage" : {
                        "stage" : "IXSCAN",
                        "nReturned" : 101,
                        "executionTimeMillisEstimate" : 0,
                        "works" : 101,
                        "advanced" : 101,
                        "needTime" : 0,
                        "needYield" : 0,
                        "saveState" : 1554,
                        "restoreState" : 1554,
                        "isEOF" : 0,
                        "invalidates" : 0,
                        "keyPattern" : {
                            "sourceId" : -1,
                            "timestamp" : 1
                        },
                        "indexName" : "sourceId_-1_timestamp_1",
                        "isMultiKey" : false,
                        "isUnique" : false,
                        "isSparse" : false,
                        "isPartial" : false,
                        "indexVersion" : 1,
                        "direction" : "forward",
                        "indexBounds" : {
                            "sourceId" : [
                                "[ObjectId('596bac5a6f473e1a042bFFFF'), ObjectId('596bac5a6f473e1a042bFFFF')]"
                            ],
                            "timestamp" : [
                                "[MinKey, MaxKey]"
                            ]
                        },
                        "keysExamined" : 101,
                        "dupsTested" : 0,
                        "dupsDropped" : 0,
                        "seenInvalidated" : 0
                    }
                }
            },
            {
                "nReturned" : 101,
                "executionTimeMillisEstimate" : 0,
                "totalKeysExamined" : 101,
                "totalDocsExamined" : 101,
                "executionStages" : {
                    "stage" : "FETCH",
                    "nReturned" : 101,
                    "executionTimeMillisEstimate" : 0,
                    "works" : 101,
                    "advanced" : 101,
                    "needTime" : 0,
                    "needYield" : 0,
                    "saveState" : 1554,
                    "restoreState" : 1554,
                    "isEOF" : 0,
                    "invalidates" : 0,
                    "docsExamined" : 101,
                    "alreadyHasObj" : 0,
                    "inputStage" : {
                        "stage" : "IXSCAN",
                        "nReturned" : 101,
                        "executionTimeMillisEstimate" : 0,
                        "works" : 101,
                        "advanced" : 101,
                        "needTime" : 0,
                        "needYield" : 0,
                        "saveState" : 1554,
                        "restoreState" : 1554,
                        "isEOF" : 0,
                        "invalidates" : 0,
                        "keyPattern" : {
                            "sourceId" : -1,
                            "myFlag" : -1
                        },
                        "indexName" : "sourceId_-1_myFlag_-1",
                        "isMultiKey" : false,
                        "isUnique" : false,
                        "isSparse" : false,
                        "isPartial" : false,
                        "indexVersion" : 1,
                        "direction" : "forward",
                        "indexBounds" : {
                            "sourceId" : [
                                "[ObjectId('596bac5a6f473e1a042bFFFF'), ObjectId('596bac5a6f473e1a042bFFFF')]"
                            ],
                            "myFlag" : [
                                "[false, false]"
                            ]
                        },
                        "keysExamined" : 101,
                        "dupsTested" : 0,
                        "dupsDropped" : 0,
                        "seenInvalidated" : 0
                    }
                }
            },
            {
                "nReturned" : 101,
                "executionTimeMillisEstimate" : 0,
                "totalKeysExamined" : 101,
                "totalDocsExamined" : 101,
                "executionStages" : {
                    "stage" : "FETCH",
                    "filter" : {
                        "myFlag" : {
                            "$eq" : false
                        }
                    },
                    "nReturned" : 101,
                    "executionTimeMillisEstimate" : 0,
                    "works" : 101,
                    "advanced" : 101,
                    "needTime" : 0,
                    "needYield" : 0,
                    "saveState" : 88,
                    "restoreState" : 88,
                    "isEOF" : 0,
                    "invalidates" : 0,
                    "docsExamined" : 101,
                    "alreadyHasObj" : 0,
                    "inputStage" : {
                        "stage" : "IXSCAN",
                        "nReturned" : 101,
                        "executionTimeMillisEstimate" : 0,
                        "works" : 101,
                        "advanced" : 101,
                        "needTime" : 0,
                        "needYield" : 0,
                        "saveState" : 88,
                        "restoreState" : 88,
                        "isEOF" : 0,
                        "invalidates" : 0,
                        "keyPattern" : {
                            "sourceId" : 1
                        },
                        "indexName" : "sourceId_1",
                        "isMultiKey" : false,
                        "isUnique" : false,
                        "isSparse" : false,
                        "isPartial" : false,
                        "indexVersion" : 1,
                        "direction" : "forward",
                        "indexBounds" : {
                            "sourceId" : [
                                "[ObjectId('596bac5a6f473e1a042bFFFF'), ObjectId('596bac5a6f473e1a042bFFFF')]"
                            ]
                        },
                        "keysExamined" : 101,
                        "dupsTested" : 0,
                        "dupsDropped" : 0,
                        "seenInvalidated" : 0
                    }
                }
            }
        ]
    },
    "serverInfo" : {
        "host" : "gdm3d",
        "port" : 27017,
        "version" : "3.2.15",
        "gitVersion" : "e11e3c1b9c9ce3f7b4a79493e16f5e4504e01140"
    },
    "ok" : 1
}

For some reason, it rejects the plan to use sourceId_-1_myFlag_-1 and goes with sourceId_1 and then filters myFlag document by document.
When I forced it to use the index, it returned the result immediately!
db.mycol.find({sourceId:ObjectId("596bac5a6f473e1a042bFFFF"),myFlag:false}).hint("sourceId_-1_myFlag_-1").count()

I read that periodically mongoDB runs all the plans and checks which one is faster, then uses that one in future.
I even tried restarting the mongodb, clearing query plan cache, restarting the computer. For some sourceIds with very less data, it did use the correct index automatically (I checked the index usage) but then it again started using the old ones.
I don't want to force it to use the index. How do I make sure it automatically does that?
Update:
It started using the correct one after some time. Atleast thats what the indexStats says.
However, the command still takes time, and when i give it hint, it gives output immediately.


text:
Q: Creating directory in android able to view in windows explorer I am developing an android application using Android Studio and Java.
I need to create a directory and manipulate some files. But above all, I need this directory to be visible to the user when they connect the phone with a USB cable.
I am using the "external" memory of the phone. Not the internal one. Not even removable.
I am using Bookan code (Can't create folder on external storage on android) to create the directory.
private void createFolder () {
    if (isStoragePermissionGranted ()) {
        File folder = new File (Environment.getExternalStorageDirectory () + File.separator + "NewFolderCreated");

        if (! folder.exists ()) {
            folder.mkdir ();
        }
    }

public boolean isStoragePermissionGranted () {
    if (Build.VERSION.SDK_INT> = 23) {
        if (checkSelfPermission (android.Manifest.permission.WRITE_EXTERNAL_STORAGE)
                == PackageManager.PERMISSION_GRANTED) {
            return true;
        } else {
            ActivityCompat.requestPermissions (this,
                    new String [] {Manifest.permission.WRITE_EXTERNAL_STORAGE}, 1);
            return false;
        }
    }
    else {// permission is automatically granted on sdk <23 upon installation
        return true;
    }
}

In the manifest file, permissions are present.
<uses-permission android: name = "android.permission.WRITE_EXTERNAL_STORAGE" />

Although WRITE's permission implies reading and writing, I have made both explicit.
When I have console output displayed for the path created, I have the answer:
/storage/emulated/0/NewFolderCreated

However, when accessing the directory through Windows Explorer, "NewFolderCreated" is neither a folder nor a file. Get that unassociated item icon in windows. You can see that windows does not know that it is a directory.
What am I doing wrong?
If I try to access the directory through android studio's file explorer, I have the permission error, which I can't solve either.
ls: /storage/emulated/: Perm

EDIT1: Added a screenshot