问:
ViewModel concept still exists in ASP.NET MVC Core?
In previous versions of ASP.NET MVC you find some informations about ViewModels and how to use them in this version.

I'm wondering why I can't find any information about this topic in ASP.NET Core MVC? Does the concept still exist and if so where i need to put them?

The question comes up because i want to make a dashboard for projects. Projects are the main entry point in my web app. They have many relationships e.g with milestones.

Models:

    public class Project
    {
        public int ProjectId { get; set; }
        public string Name { get; set; }

        public ICollection<Milestone> Milestones { get; set; }
        ...
    }

    public class Milestone
    {
        public int MilestoneId { get; set; }
        public string Name { get; set; }
        public string Description { get; set; }
        public DateTime Deadline { get; set; }
        public int? ParentId { get; set; }
        public Milestone Parent { get; set; }

        public ICollection<Milestone> Childrens { get; set; }
        ...
    }
```

Before ASP.NET Core I created a ProjectDashboardViewModel for getting information to the view. Can I use the same approach?

答:
"Does the concept still exist?" "Can I use the same approach?"

Yes, the ViewModel concept is still applicable in .NET Core and you would still use them as before, i.e. to assemble a selection of data into a 'shape' that matches the needs of a particular view.

"I can't find any information about this topic in ASP.NET Core MVC"

The official documentation discusses view models extensively.  The Overview of ASP.NET Core MVC section has this to say:

Model Responsibilities

The Model in an MVC application represents the state of the
  application and any business logic or operations that should be
  performed by it. Business logic should be encapsulated in the model,
  along with any implementation logic for persisting the state of the
  application. Strongly-typed views will typically use ViewModel types
  specifically designed to contain the data to display on that view; the
  controller will create and populate these ViewModel instances from the
  model.

In the Rendering HTML with views section:

You can pass data to views using several mechanisms. The most robust
  approach is to specify a model type in the view (commonly referred to
  as a viewmodel, to distinguish it from business domain model types),
  and then pass an instance of this type to the view from the action. We
  recommend you use a model or view model to pass data to a view.

The MVC/Advanced/Application Parts section also discusses View Models, the sample code there shows how you can assemble a number of different objects together for consumption by the view with a view  model.

They also mention them in the section on Partial Views.  There is some sample code that goes along with that here, but those examples don't actually really highlight the difference between a model and a view model.

A search through the docs as follows highlights some more too: https://learn.microsoft.com/en-us/search/index?search=viewmodel&scope=ASP.NET+Core

"..i want to make a dashboard for projects"

In your case the data you've provided just shows a single domain object (the 'Project') which has some child objects.  If that's all the data you want to show then you probably don't need a view model as it would simply be a mirror of your Project model.

However, if you want to show other info on the Project dashboard, e.g. some data aggregated data about the number of projects in progress, a list of which projects are behind etc. then you might assemble a view model with properties for: Project, NumberInProgressPrjects, OverdueProjectsList etc.

```<code>public class ProjectDashboardViewModel
{
    public Project Project { get; set; }
    public int NumberInProgressProjects { get; set; }
    public ICollection<OverdueProjectInfo> OverdueProjectsList { get; set; }
}
</code>```

That's just an example, the point is you can use the view model to encapsulate all of the data needed by your view, rather than your controller returning a model object that matches a single domain object (often a table from your database) and then lots of additional data that's needed to make the rest of the page function in the ViewData collection (e.g. the data needed to populate the drop down lists).  There are many excellent articles on view models, this previous question covers them exhaustively for example, and is just as relevant in .NET MVC Core as other versions of MVC.

"..where i need to put them?"

You can put them where you choose, just make sure you use a using statement if needed. The typical convention in smaller projects is to put them in a folder called 'ViewModels'.

Body:
In previous versions of ASP.NET MVC you find some informations about ViewModels and how to use them in this version.

I'm wondering why I can't find any information about this topic in ASP.NET Core MVC? Does the concept still exist and if so where i need to put them?

The question comes up because i want to make a dashboard for projects. Projects are the main entry point in my web app. They have many relationships e.g with milestones.

Models:

    public class Project
    {
        public int ProjectId { get; set; }
        public string Name { get; set; }

        public ICollection<Milestone> Milestones { get; set; }
        ...
    }

    public class Milestone
    {
        public int MilestoneId { get; set; }
        public string Name { get; set; }
        public string Description { get; set; }
        public DateTime Deadline { get; set; }
        public int? ParentId { get; set; }
        public Milestone Parent { get; set; }

        public ICollection<Milestone> Childrens { get; set; }
        ...
    }

Before ASP.NET Core I created a ProjectDashboardViewModel for getting information to the view. Can I use the same approach?

Body:
"Does the concept still exist?" "Can I use the same approach?"

Yes, the ViewModel concept is still applicable in .NET Core and you would still use them as before, i.e. to assemble a selection of data into a 'shape' that matches the needs of a particular view.

"I can't find any information about this topic in ASP.NET Core MVC"

The official documentation discusses view models extensively.  The Overview of ASP.NET Core MVC section has this to say:

Model Responsibilities

The Model in an MVC application represents the state of the
  application and any business logic or operations that should be
  performed by it. Business logic should be encapsulated in the model,
  along with any implementation logic for persisting the state of the
  application. Strongly-typed views will typically use ViewModel types
  specifically designed to contain the data to display on that view; the
  controller will create and populate these ViewModel instances from the
  model.

In the Rendering HTML with views section:

You can pass data to views using several mechanisms. The most robust
  approach is to specify a model type in the view (commonly referred to
  as a viewmodel, to distinguish it from business domain model types),
  and then pass an instance of this type to the view from the action. We
  recommend you use a model or view model to pass data to a view.

The MVC/Advanced/Application Parts section also discusses View Models, the sample code there shows how you can assemble a number of different objects together for consumption by the view with a view  model.

They also mention them in the section on Partial Views.  There is some sample code that goes along with that here, but those examples don't actually really highlight the difference between a model and a view model.

A search through the docs as follows highlights some more too: https://learn.microsoft.com/en-us/search/index?search=viewmodel&scope=ASP.NET+Core

"..i want to make a dashboard for projects"

In your case the data you've provided just shows a single domain object (the 'Project') which has some child objects.  If that's all the data you want to show then you probably don't need a view model as it would simply be a mirror of your Project model.

However, if you want to show other info on the Project dashboard, e.g. some data aggregated data about the number of projects in progress, a list of which projects are behind etc. then you might assemble a view model with properties for: Project, NumberInProgressPrjects, OverdueProjectsList etc.

public class ProjectDashboardViewModel
{
    public Project Project { get; set; }
    public int NumberInProgressProjects { get; set; }
    public ICollection<OverdueProjectInfo> OverdueProjectsList { get; set; }
}

That's just an example, the point is you can use the view model to encapsulate all of the data needed by your view, rather than your controller returning a model object that matches a single domain object (often a table from your database) and then lots of additional data that's needed to make the rest of the page function in the ViewData collection (e.g. the data needed to populate the drop down lists).  There are many excellent articles on view models, this previous question covers them exhaustively for example, and is just as relevant in .NET MVC Core as other versions of MVC.

"..where i need to put them?"

You can put them where you choose, just make sure you use a using statement if needed. The typical convention in smaller projects is to put them in a folder called 'ViewModels'.


来源: stackexchange

问:
How to check if node is empty
I'm trying to make a variable, which tells me, whether node1 has something in it or not. node1 can be an empty element  or it may contain an attribute. But right now I would like to know how achieve answer "false" when the node1 is empty .</p>

```<code><xsl:variable name="elementHasData">
    <xsl:choose>
        <xsl:when test="node1 != ''">
            <xsl:value-of select="true()"/>
        </xsl:when>
        <xsl:otherwise>
            <xsl:value-of select="false()"/>
        </xsl:otherwise>
    </xsl:choose>
</xsl:variable>
</code>```

答:
Check whether node1 contains text or other child nodes:

```<code><xsl:variable name="elementHasData" select="node1/node()" />
</code>```

Check whether node1 contains child nodes or attributes:

```<code><xsl:variable name="elementHasData" select="node1/node() or node1/@*" />
</code>```

ContentLicense: CC BY-SA 3.0

Title: How to check if node is empty

Body:
I'm trying to make a variable, which tells me, whether node1 has something in it or not. node1 can be an empty element  or it may contain an attribute. But right now I would like to know how achieve answer "false" when the node1 is empty .

<xsl:variable name="elementHasData">
    <xsl:choose>
        <xsl:when test="node1 != ''">
            <xsl:value-of select="true()"/>
        </xsl:when>
        <xsl:otherwise>
            <xsl:value-of select="false()"/>
        </xsl:otherwise>
    </xsl:choose>
</xsl:variable>

Body:
Check whether node1 contains text or other child nodes:

<xsl:variable name="elementHasData" select="node1/node()" />

Check whether node1 contains child nodes or attributes:

<xsl:variable name="elementHasData" select="node1/node() or node1/@*" />


问:
C# Do I need TRY/CATCH in order to throw?
If all I want to do is throw the exception up a level when it occurs?

```<code>private void TryCatch()
{
   try
   {
       foo();
   }
   catch (Exception ex)
   {
       throw;
   }
}

private void NoTryCatch()
{
   foo();
}
</code>```

Aren't these two methods the same?

If an exception occurs in TryCatch it will be thrown up a level and if an exception occurs in NoTryCatch, the exception will also be thrown up a level.

This question came about after using ReSharper and noticing that it suggested to remove the try/catch block as it was redundant.

答:
Yes, those methods are pretty much (*) the same. The only difference is that it's easy to put a breakpoint in the first one. I'd always go with the second unless I really needed to break there and only there (as opposed to immediately any exceptions of that type were thrown, which would be easy). Even if I ever used the first, I'd put it back to the second form before committing the code.

(*) There may well be some differences in terms of how the JIT handles them. The first will end up with more IL, which will affect opportunities for inlining etc.

EDIT: I can't resist a bit of micro-benchmarking. It looks like try/catch/throw has nastier effects on performance than just disabling inlining:

```<code>using System;
using System.Diagnostics;
using System.Runtime.CompilerServices;

public class Test
{
    const int Iterations = 1000000000;

    static void Main()
    {
        Stopwatch sw;

        sw = Stopwatch.StartNew();
        for (int i=0; i < Iterations; i++)
        {
            SimpleMethod();
        }
        sw.Stop();
        Console.WriteLine("Simple method: {0}", sw.ElapsedMilliseconds);

        sw = Stopwatch.StartNew();
        for (int i=0; i < Iterations; i++)
        {
            NoInlining();
        }
        sw.Stop();
        Console.WriteLine("No inlining: {0}", sw.ElapsedMilliseconds);

        sw = Stopwatch.StartNew();
        for (int i=0; i < Iterations; i++)
        {
            TryCatchThrow();
        }
        sw.Stop();
        Console.WriteLine("try/catch/throw: {0}", sw.ElapsedMilliseconds);
    }

    static void SimpleMethod()
    {
        Foo();
    }

    [MethodImpl(MethodImplOptions.NoInlining)]
    static void NoInlining()
    {
    }

    static void TryCatchThrow()
    {
        try
        {
            Foo();
        }
        catch (Exception)
        {
            throw;
        }
    }

    static void Foo() {}
}
</code>```

Compile with /o+ /debug-

Results (three runs):

Simple method: 504, 495, 489

No inlining: 2977, 3060, 3019

try/catch/throw: 5274, 4543, 5145

OwnerDisplayName: Petrolios

LastEditorDisplayName: Jon Skeet

ContentLicense: CC BY-SA 2.5

Body:
If all I want to do is throw the exception up a level when it occurs?

private void TryCatch()
{
   try
   {
       foo();
   }
   catch (Exception ex)
   {
       throw;
   }
}

private void NoTryCatch()
{
   foo();
}

Aren't these two methods the same?

If an exception occurs in TryCatch it will be thrown up a level and if an exception occurs in NoTryCatch, the exception will also be thrown up a level.

This question came about after using ReSharper and noticing that it suggested to remove the try/catch block as it was redundant.

Body:
Yes, those methods are pretty much (*) the same. The only difference is that it's easy to put a breakpoint in the first one. I'd always go with the second unless I really needed to break there and only there (as opposed to immediately any exceptions of that type were thrown, which would be easy). Even if I ever used the first, I'd put it back to the second form before committing the code.

(*) There may well be some differences in terms of how the JIT handles them. The first will end up with more IL, which will affect opportunities for inlining etc.

EDIT: I can't resist a bit of micro-benchmarking. It looks like try/catch/throw has nastier effects on performance than just disabling inlining:

using System;
using System.Diagnostics;
using System.Runtime.CompilerServices;

public class Test
{
    const int Iterations = 1000000000;

    static void Main()
    {
        Stopwatch sw;

        sw = Stopwatch.StartNew();
        for (int i=0; i < Iterations; i++)
        {
            SimpleMethod();
        }
        sw.Stop();
        Console.WriteLine("Simple method: {0}", sw.ElapsedMilliseconds);

        sw = Stopwatch.StartNew();
        for (int i=0; i < Iterations; i++)
        {
            NoInlining();
        }
        sw.Stop();
        Console.WriteLine("No inlining: {0}", sw.ElapsedMilliseconds);

        sw = Stopwatch.StartNew();
        for (int i=0; i < Iterations; i++)
        {
            TryCatchThrow();
        }
        sw.Stop();
        Console.WriteLine("try/catch/throw: {0}", sw.ElapsedMilliseconds);
    }

    static void SimpleMethod()
    {
        Foo();
    }

    [MethodImpl(MethodImplOptions.NoInlining)]
    static void NoInlining()
    {
    }

    static void TryCatchThrow()
    {
        try
        {
            Foo();
        }
        catch (Exception)
        {
            throw;
        }
    }

    static void Foo() {}
}

Compile with /o+ /debug-

Results (three runs):

Simple method: 504, 495, 489

No inlining: 2977, 3060, 3019

try/catch/throw: 5274, 4543, 5145

OwnerDisplayName: Jon Skeet


问:
selecting unique row from a table- ORACLE
I have a table employee that has employee’s benefit data.
I have a field in the table called isenrolled if field is 1 that means employee has enrolled for benefit and if field is 0 that means not enrolled.
My problem is i have multiple recs of a employee, that means Scott has two entries with isenrolled =1 and isenrolled =0.
I want to select only one rec of SCOTT where his isenrolled =1 and reject the one where isenrolled =0, that way i will get only unique recs for employees who has enrolled and who has not enrolled. How do i select those employees? I tried the qry below and it doesn't work</p>

```<code>select * FROM  employee e
WHERE e.empid not IN( SELECT empid FROM employee  e2
WHERE e2.isenrolled =1)
</code>```

答:
First I set up some test data using:

```<code>create table t4
as select * from scott.emp

alter table t4 add (isenrolled number(10))

update t4
set isenrolled = 0

insert into t4
(select emp.*, 1
from scott.emp)
</code>```

At this point the t4 table has now two records for each employee (one where isenrolled = 0 and one where isenrolled = 1)

so I change ALLEN's data so he has "opted" out

```<code>delete from t4
where ename = 'ALLEN'
and isenrolled = 1
</code>```

This query then shows the data for ALLEN (1 record) and SMITH (2 records)

```<code>select *
from t4
where ename IN ('ALLEN', 'SMITH')
order by ename
</code>```

Then to show just one record per employee (restricted to ALLEN and SMITH in this case) you could use:

```<code>select t.*
from t4 t
where isenrolled = (select MAX(isenrolled)
                    from t4
                    where t4.empno = t.empno)
and ename IN ('ALLEN', 'SMITH')
</code>```

Hope this helps

Body:
I have a table employee that has employee’s benefit data.
I have a field in the table called isenrolled if field is 1 that means employee has enrolled for benefit and if field is 0 that means not enrolled.
My problem is i have multiple recs of a employee, that means Scott has two entries with isenrolled =1 and isenrolled =0.
I want to select only one rec of SCOTT where his isenrolled =1 and reject the one where isenrolled =0, that way i will get only unique recs for employees who has enrolled and who has not enrolled. How do i select those employees? I tried the qry below and it doesn't work

select * FROM  employee e
WHERE e.empid not IN( SELECT empid FROM employee  e2
WHERE e2.isenrolled =1)

Body:
First I set up some test data using:

create table t4
as select * from scott.emp

alter table t4 add (isenrolled number(10))

update t4
set isenrolled = 0

insert into t4
(select emp.*, 1
from scott.emp)

At this point the t4 table has now two records for each employee (one where isenrolled = 0 and one where isenrolled = 1)

so I change ALLEN's data so he has "opted" out

delete from t4
where ename = 'ALLEN'
and isenrolled = 1

This query then shows the data for ALLEN (1 record) and SMITH (2 records)

select *
from t4
where ename IN ('ALLEN', 'SMITH')
order by ename

Then to show just one record per employee (restricted to ALLEN and SMITH in this case) you could use:

select t.*
from t4 t
where isenrolled = (select MAX(isenrolled)
                    from t4
                    where t4.empno = t.empno)
and ename IN ('ALLEN', 'SMITH')

Hope this helps


问:
Determine whether the trigger is created successfully or not using GAS
I want to determine programically whether the trigger is created successfully but even an unsuccessful trigger brings out a unique id and it seems to be created.

```<code>//this will show 0
var triggers = ScriptApp.getProjectTriggers();
showAlert(triggers.length); //define showAlert

var dt = new Date(2015,03,03,20,10) // create past date or feb 31
//Month index starts from 0 i.e. Jan =0,Feb=1... So on
 var ret = ScriptApp.newTrigger('myFunction').timeBased().at(dt).create()

showAlert(ret.getUniqueId()); //will display ID for sure

//this will show 1
var triggers = ScriptApp.getProjectTriggers();
showAlert(triggers.length); //define showAlert
</code>```

But actually the trigger isn't created

答:
Your best option is to check to see if the entered date has passed? And only set the trigger if it has not passed.

```<code>var dt = new Date(2015,03,03,20,10) // create past date or feb 31
//Month index starts from 0 i.e. Jan =0,Feb=1... So on
if( dt > new Date()){  //new Date() gives current date
 var ret = ScriptApp.newTrigger('myFunction').timeBased().at(dt).create()
}
</code>```

Hope that helps!

Body:
I want to determine programically whether the trigger is created successfully but even an unsuccessful trigger brings out a unique id and it seems to be created.

//this will show 0
var triggers = ScriptApp.getProjectTriggers();
showAlert(triggers.length); //define showAlert

var dt = new Date(2015,03,03,20,10) // create past date or feb 31
//Month index starts from 0 i.e. Jan =0,Feb=1... So on
 var ret = ScriptApp.newTrigger('myFunction').timeBased().at(dt).create()

showAlert(ret.getUniqueId()); //will display ID for sure

//this will show 1
var triggers = ScriptApp.getProjectTriggers();
showAlert(triggers.length); //define showAlert

But actually the trigger isn't created

Body:
Your best option is to check to see if the entered date has passed? And only set the trigger if it has not passed.

var dt = new Date(2015,03,03,20,10) // create past date or feb 31
//Month index starts from 0 i.e. Jan =0,Feb=1... So on
if( dt > new Date()){  //new Date() gives current date
 var ret = ScriptApp.newTrigger('myFunction').timeBased().at(dt).create()
}

Hope that helps!


问:
How can we make a TIMER with (RESET) functionality in bash
I am very new to shell scripting, I have googled many things for this problem. But cannot find a perfect solution to it.

Problem is: It's a log monitoring code with "ERROR", Pattern
How can we make a TIMER in unix scripting. Support I have a timer of 5 minutes, and time keep on decreasing every 1 second. So I want to reset again the timer to 5 minute on certain condition (say $FREQUENCY of ERROR occurrence is greater then say for ex2).

```<code>#!/usr/bin/env bash
PATTERN='ERROR'
TIMER=300
FREQUENCY=2

while true;
do grep -i $PATTERN logfile > tmp_log

while [ $TIMER -gt 0 ]
do
  sleep 1 &
  printf "  $TIMER \r" &
  TIMER=$[$TIMER-1];
  wait

done

if [[ $(wc -l <tmp_log) -ge $FREQUENCY ]]
        then
            TIMER=300
            echo $TIMER
fi

 sleep $TIMER
done
</code>```

答:
```<code>#!/bin/bash

PATTERN='ERROR'
TIMER=300
FREQUENCY=2

while true
do
        while [ $TIMER -gt 0 ]
        do
                sleep 1
                TIMER=$((TIMER - 1))
                grep -i $PATTERN logfile > tmp_log
                count=`wc -l tmp_log | awk '{ print $1 }'`
                if [ $count -gt $FREQUENCY ]
                then
                        TIMER=300
                fi
        done
        break
done
</code>```

This is good going for your case.

Body:
I am very new to shell scripting, I have googled many things for this problem. But cannot find a perfect solution to it.

Problem is: It's a log monitoring code with "ERROR", Pattern
How can we make a TIMER in unix scripting. Support I have a timer of 5 minutes, and time keep on decreasing every 1 second. So I want to reset again the timer to 5 minute on certain condition (say $FREQUENCY of ERROR occurrence is greater then say for ex2).

#!/usr/bin/env bash
PATTERN='ERROR'
TIMER=300
FREQUENCY=2

while true;
do grep -i $PATTERN logfile > tmp_log

while [ $TIMER -gt 0 ]
do
  sleep 1 &
  printf "  $TIMER \r" &
  TIMER=$[$TIMER-1];
  wait

done

if [[ $(wc -l <tmp_log) -ge $FREQUENCY ]]
        then
            TIMER=300
            echo $TIMER
fi

 sleep $TIMER
done

Body:
#!/bin/bash

PATTERN='ERROR'
TIMER=300
FREQUENCY=2

while true
do
        while [ $TIMER -gt 0 ]
        do
                sleep 1
                TIMER=$((TIMER - 1))
                grep -i $PATTERN logfile > tmp_log
                count=`wc -l tmp_log | awk '{ print $1 }'`
                if [ $count -gt $FREQUENCY ]
                then
                        TIMER=300
                fi
        done
        break
done

This is good going for your case.


问:
Excel IF formula with criteria based on structure of cell contents
I'm trying to figure out if it's possible to arrange to have an IF condition based off the arrangement of text in a cell..

Pretty much I have a bunch of raw data pasted in excel from a web page where the column with the data I need is mixed in with useless text from the webpage.

The data I need is all just unit codes in 8 character alpha numeric form (eg. ASSA2125 PHOS1801)

To extract just the right data I was hoping to write a formula that tested the cell for either characters in that alphanumeric arrangement or perhaps tested for only 8 characters in the cell. eg =IF(J52=AAAA2222,J52,"")

Not sure if such a thing is possible, or if I just need to write the formula some type of way for excel to go looking for that...

答:
Is using Google Spreadsheet an option for you? If yes you could use REGEXEXTRACT formula for that:

```<code>=REGEXEXTRACT("ASSA2125", "[A-Z]{4}[0-9]{4}")
</code>```

It would extract cells which content is 4 capital letters 4 digits.

Body:
Is using Google Spreadsheet an option for you? If yes you could use REGEXEXTRACT formula for that:

=REGEXEXTRACT("ASSA2125", "[A-Z]{4}[0-9]{4}")

It would extract cells which content is 4 capital letters 4 digits.


问:
Managing UIWindow height when on call
I am working in IOS application where all the work is done programmatically and we haven't used autolayout in complete application.

But I am facing one issue here from long time that when I got call or if my hotspot is on in that case my device status bar height changes.

So In this case how I can manage the application frame so that my UIView's will be managed.

Thank you in advance.

答:
Whenever the height of the status bar changes the following functions will be called. Just add these functions to your AppDelegate.m file. They will be called when the status bar changes its height. One of them is called before and the other after the change.

```<code>//Called before the change
- (void)application:(UIApplication *)application willChangeStatusBarFrame:(CGRect)newStatusBarFrame
{
//Change the size of Window
self.window.frame = CGRectMake(0.0f, 60.0f, 200.0f, 200.0f);
//In your case it will be
//self.window.frame = CGRectMake(0.0f, 40.0f, self.window.frame.size.width, self.window.frame.size.height - 40);
}

//Called after the change
//- (void)application:(UIApplication *)application didChangeStatusBarFrame:(CGRect)oldStatusBarFrame{
//Change the size of Window
//}
</code>```

Starting :

Changing statusBar Height by toggling in-Call Status Bar

Final Result with Changed Frame:

Hope this helps. Happy Coding.
Reference

Title: Managing UIWindow height when on call

Body:
Whenever the height of the status bar changes the following functions will be called. Just add these functions to your AppDelegate.m file. They will be called when the status bar changes its height. One of them is called before and the other after the change.

//Called before the change
- (void)application:(UIApplication *)application willChangeStatusBarFrame:(CGRect)newStatusBarFrame
{
//Change the size of Window
self.window.frame = CGRectMake(0.0f, 60.0f, 200.0f, 200.0f);
//In your case it will be
//self.window.frame = CGRectMake(0.0f, 40.0f, self.window.frame.size.width, self.window.frame.size.height - 40);
}

//Called after the change
//- (void)application:(UIApplication *)application didChangeStatusBarFrame:(CGRect)oldStatusBarFrame{
//Change the size of Window
//}

Starting :

Changing statusBar Height by toggling in-Call Status Bar

Final Result with Changed Frame:

Hope this helps. Happy Coding.
Reference


问:
Breaking a line every 46 characters using Javascript
Im trying to use the following code lines in order to check whether or not the string is larger than 46 characters. If it is longer, it'll break a new line every 46 characters, however, i'm failing to do so.

Can anyone tell me what's wrong?

function ContentFormat(content)
{
    var start = "";
    var end = "";
    var space = "
   ";
    var newcontent = "";
    var toadd = "";
    if (content.length > 46)
    {
        for (var i = 0, len = content.length; i < len; i++) {
            if(i/46 == 0)
            {
                start = content.slice(0, i);
                end = content.slice(i);
                toadd = start.concat(space, end);
            }
            newcontent = toadd;
            toadd = "";
        }
    }
    return newcontent;
}```

答:
This can also be achived with Regular Expressions and the String.replace method.

var str = 'Lorem ipsum dolor sit amet, consectetur adipiscing elit, 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.';

function breakEvery(str, interval, breaker) {
    if (str === void 0) { str = ""; }
    if (interval === void 0) { interval = 0; }
    if (breaker === void 0) { breaker = "\n"; }
    if (str.length < interval) {
        return str;
    }
    var re = new RegExp('.{' + interval + '}', "ig");
    return str.replace(re, function (part) { return part + breaker; });
}

console.log(breakEvery(str, 46, "\n
   "));```

Body:
This can also be achived with Regular Expressions and the String.replace method.

var str = 'Lorem ipsum dolor sit amet, consectetur adipiscing elit, 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.';

function breakEvery(str, interval, breaker) {
    if (str === void 0) { str = ""; }
    if (interval === void 0) { interval = 0; }
    if (breaker === void 0) { breaker = "\n"; }
    if (str.length < interval) {
        return str;
    }
    var re = new RegExp('.{' + interval + '}', "ig");
    return str.replace(re, function (part) { return part + breaker; });
}

console.log(breakEvery(str, 46, "\n<br/>&nbsp; &nbsp;"));


问:
discoverAllIdentities & discoverUserIdentity returning nil for CKUserIdentity.lookupInfo as of iOS 10.3
CKContainer.discoverAllIdentities(completionHandler:), discoverUserIdentity(recordID: - completion handler returns CKUserIdentity but .lookupInfo is always nil even when contacts contain email, phone, etc. Other properties such as hasiCloudAccount, userRecordID, nameComponents are fine. This issue just started happening with recent Swift 3.1 release. Does anyone know if this is intended behavior as I have not been able to find any reference to CloudKit changes in release notes but this is looking like a privacy thing.

After further investigation, it appears that this issue might be due to the recent iOS 10.3 update. When running the app on an iPhone 5 with 10.2.1 the problem does not occur and lookupInfo properly contains emailAddress

Submitted Apple bug: 31377433

NEW: In addition, if I try to access information via CKDiscoverAllUserIdentitiesOperation, in particular userIdentityDiscoveredBlock -> user.nameComponents the result is "empty string" for apple id's associated with users who are under 12 years old (and potentially on the "Family Sharing" plan). I've found no information about this and apple dev support offered no help either.

答:
Since I can´t put a comment because of missing reputation, I have to do it this way...

I also submitted the same bug (31397767) and hope they will fix it.

For CKFetchShareParticipantsOperation it is necessary to have CKUserIdentityLookupInfo. Since there is no workaround we need to wait for them to fix it.

I'm just curious about this bug because if you already submitted your app to the app store the whole sharing part would not work for the users.

Update

iOS 10.3.1 update didn't solve the issue.

Update: Solution

I got a response from Apple about this "issue". Here is the answer c&p:

This is the expected behavior, since
  CKDiscoverAllUserIdentitiesOperation doesn't require prompting the
  user for Contacts access. If you'd like to turn these results into
  participants you'll need to request contacts access and get the lookup
  info off the contacts yourself via the contactIdentifiers property.

// Identities discovered via CKDiscoverAllUserIdentitiesOperation
  correspond to entries in the local Contacts database.  These
  identities will have contactIdentifiers filled out, which your app may
  use to get additional information about the contacts that were
  discovered.  Multiple contactIdentifiers may exist for a single
  discovered user, as multiple contacts may contain the same email
  addresses or phone numbers.

Note that discovering users and looking up participants are two
  logically different things- you can only discover users that have made
  themselves discoverable via -[CKContainer
  requestApplicationPermission:CKApplicationPermissionUserDiscoverability
  ...], but you can get a participant for any email address or phone
  number even if it doesn't correspond to an iCloud account. You don't
  need to discover users and then turn them into participants- you can
  just have the user of your app enter addresses for participants to add
  to a share.


问:
Is there a good HTML template engine in cocoa touch?
In my iphone app, I want to populate UIWebView with some html generated from a templates.
Is there a good opensource template engine library for cocoa touch like jinja or smarty?</p>

答: https://github.com/groue/GRMustache is a full implementation of the {{ mustache }} template engine.</p>


问:
Postman App on windows: Unable to see application menu and update tab on settings dialog
I am using the free postman app on win 7.
I am unable to see application menu and update tab on settings dialog.
I have enabled debugging for packed apps as shown below.

Debugging for packed apps Mac, Windows, Linux, Chrome OS Enables
  debugging context menu options such as Inspect Element for packed
  applications. #debug-packed-apps Disable

Is there any way to get these items?

答:
So there is a native app and there is a chrome app i.e. Postman for windows and Postman for Chrome.
The Postman for Windows app has the options Certificates and Update but i didn't see the same on Chrome App.

Also, the interceptor is an add-on on the chrome app whereas the windows native app provides a proxy settings option.


问:
Android: EditText in ListView issue
I have a listview in my application that is basically a questionaire so there are some EditTexts that the user needs to fill. I've encountered the following issues:

Some of the EditText require numeric input, so I set the inputType in the corresponding xml type as numeric, however, as when I click on the EditText the numeric keyboard is shown but almost immediately it disappears and the regular keyboard is shown.

As you can imagine, I need to store the values that the user inputs in these EditTexts. The problem I have with this is that after I input some text in SOME EditTexts and I scroll down, the text is gone when I go back. You can see in my code that I made an attempt to prevent this and I should mention that it works perfectly fine with checkboxes.

At the beginning I was having problems with losing the focus but I solved it looking at other questions (added descendantFocusablity="beforeDescendants" to the ListView and windowSoftInputMode="adjustPan"). Works fine except that when an EditText is below the half of the screen it loses focus as soon as I start typing into it.
getView method for list adapter:

```<code>public View getView(final int position,View result,ViewGroup parent)
{
final ViewHolder vh;
final Question question = values.get(position);
if(holders[position]==null)
    vh = new ViewHolder();
else
    vh = holders[position];

LayoutInflater inflater = (LayoutInflater)context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
if(question.getQuestionType().equals(Question.TYPE_CLOSED))
{
    result = inflater.inflate(R.layout.closed_question_list_item, null);
    vh.cb  = (CheckBox)result.findViewById(R.id.checkbox);
    vh.cb.setOnCheckedChangeListener(new OnCheckedChangeListener()
    {

        @Override
        public void onCheckedChanged(CompoundButton buttonView, boolean isChecked)
        {
            vh.isChecked      = isChecked;
            holders[position] = vh;
        }
    });
    vh.cb.setChecked(vh.isChecked);
}

else
{
    result = inflater.inflate(R.layout.numeric_question_list_item, null);
    vh.et  = (EditText)result.findViewById(R.id.question_et);
    vh.et.addTextChangedListener(new TextWatcher()
    {
        @Override
        public void afterTextChanged(Editable s)
        {
            vh.tvValue = s.toString();
            holders[position] = vh;
            Log.i(TAG,"Entered afterTextChanged for "+ question.getText());
        }

        @Override
        public void beforeTextChanged(CharSequence s, int start,int count, int after)
        {
        }

        @Override
        public void onTextChanged(CharSequence s, int start,int before, int count)
        {
        }
    });
    vh.et.setText(vh.tvValue);
}
vh.tv = (TextView)result.findViewById(R.id.question_text);

vh.tv.setText(question.getText());

holders[position] = vh;
result.setTag(vh);
return result;
}
</code>```

答:
Its working for me.... Please check this </p>

```<code>listview.setItemsCanFocus(true);
</code>```

Title: Android: EditText in ListView issue

Body:
I have a listview in my application that is basically a questionaire so there are some EditTexts that the user needs to fill. I've encountered the following issues:

Some of the EditText require numeric input, so I set the inputType in the corresponding xml type as numeric, however, as when I click on the EditText the numeric keyboard is shown but almost immediately it disappears and the regular keyboard is shown.

As you can imagine, I need to store the values that the user inputs in these EditTexts. The problem I have with this is that after I input some text in SOME EditTexts and I scroll down, the text is gone when I go back. You can see in my code that I made an attempt to prevent this and I should mention that it works perfectly fine with checkboxes.

At the beginning I was having problems with losing the focus but I solved it looking at other questions (added descendantFocusablity="beforeDescendants" to the ListView and windowSoftInputMode="adjustPan"). Works fine except that when an EditText is below the half of the screen it loses focus as soon as I start typing into it.
getView method for list adapter:

public View getView(final int position,View result,ViewGroup parent)
{
final ViewHolder vh;
final Question question = values.get(position);
if(holders[position]==null)
    vh = new ViewHolder();
else
    vh = holders[position];

LayoutInflater inflater = (LayoutInflater)context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
if(question.getQuestionType().equals(Question.TYPE_CLOSED))
{
    result = inflater.inflate(R.layout.closed_question_list_item, null);
    vh.cb  = (CheckBox)result.findViewById(R.id.checkbox);
    vh.cb.setOnCheckedChangeListener(new OnCheckedChangeListener()
    {

        @Override
        public void onCheckedChanged(CompoundButton buttonView, boolean isChecked)
        {
            vh.isChecked      = isChecked;
            holders[position] = vh;
        }
    });
    vh.cb.setChecked(vh.isChecked);
}

else
{
    result = inflater.inflate(R.layout.numeric_question_list_item, null);
    vh.et  = (EditText)result.findViewById(R.id.question_et);
    vh.et.addTextChangedListener(new TextWatcher()
    {
        @Override
        public void afterTextChanged(Editable s)
        {
            vh.tvValue = s.toString();
            holders[position] = vh;
            Log.i(TAG,"Entered afterTextChanged for "+ question.getText());
        }

        @Override
        public void beforeTextChanged(CharSequence s, int start,int count, int after)
        {
        }

        @Override
        public void onTextChanged(CharSequence s, int start,int before, int count)
        {
        }
    });
    vh.et.setText(vh.tvValue);
}
vh.tv = (TextView)result.findViewById(R.id.question_text);

vh.tv.setText(question.getText());

holders[position] = vh;
result.setTag(vh);
return result;
}

Body:
Its working for me.... Please check this

listview.setItemsCanFocus(true);


问:
Convert String Date to Time using Moment
I am using moment.js and I want to convert my string date into time.

I am getting the date in this format: Apr 01 and I want the output like 2017-01-01T00:00:00+05:00.

How can I achieve this?

答:
Simply use moment(String, String) and format() method.

Here a working sample:

console.log(moment('Apr 01', 'MMM DD').format());```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.18.1/moment.min.js"></script></code>```

Body:
Simply use moment(String, String) and format() method.

Here a working sample:

console.log(moment('Apr 01', 'MMM DD').format());

<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.18.1/moment.min.js"></script>


问:
How to limit the number of threads excecuted by ManagedExecutorService
The class javax.enterprise.concurrent.ManagedExecutorService manages threads within Enterprise Java Bean. As threads in EJBs should not be started in the classical Java SE way, I use the ManagedExecutorService to handle threads.

"Obligatory warning: Creating your own threads in a Java EE app server (even Tomcat) is discouraged as it can be a huge performance issue and in most cases will prevent container functionality, such as JNDI, from working. The new threads won't know which application they belong to, the Thread context classloader will not be set and many other hidden issues."

In Java SE you can define the maximum number of threads, as shown in the following code.

```<code>java.util.concurrent.Executors.newFixedThreadPool(numberOfThreadsInThePool);
</code>```

Do you know how to limit the number of threads excecuted by the ManagedExecutorService?

答:
The maximum thread pool size can be determined when the ManagedExcecutorService is created in the Glassfish Application Server. According to the this article https://blogs.oracle.com/arungupta/entry/create_managedexecutorservice_managedscheduledexecutorservice_managedthreadfactory_contextservice glassfish's asadmin command has a parameter "maximumpoolsize" which defines the maximum number of threads used by the ManagedExcecutorService.

```<code>asadmin create-managed-executor-service concurrent/myExecutor --maximumpoolsize=20
</code>```

Body:
The class javax.enterprise.concurrent.ManagedExecutorService manages threads within Enterprise Java Bean. As threads in EJBs should not be started in the classical Java SE way, I use the ManagedExecutorService to handle threads.

"Obligatory warning: Creating your own threads in a Java EE app server (even Tomcat) is discouraged as it can be a huge performance issue and in most cases will prevent container functionality, such as JNDI, from working. The new threads won't know which application they belong to, the Thread context classloader will not be set and many other hidden issues."

In Java SE you can define the maximum number of threads, as shown in the following code.

java.util.concurrent.Executors.newFixedThreadPool(numberOfThreadsInThePool);

Do you know how to limit the number of threads excecuted by the ManagedExecutorService?

Body:
The maximum thread pool size can be determined when the ManagedExcecutorService is created in the Glassfish Application Server. According to the this article https://blogs.oracle.com/arungupta/entry/create_managedexecutorservice_managedscheduledexecutorservice_managedthreadfactory_contextservice glassfish's asadmin command has a parameter "maximumpoolsize" which defines the maximum number of threads used by the ManagedExcecutorService.

asadmin create-managed-executor-service concurrent/myExecutor --maximumpoolsize=20


问:
Sort Multidimensional Array in VB.NET
I have a 2X50 array like this-

```<code>R-125212,11
C-254645,25
R-456598,96
M-456878,35
O-980857,89
And so on...
</code>```

Now I want to sort this array with the values of the 2nd Column. So the output should look like-

```<code>R-125212,11
C-254645,25
M-456878,35
O-980857,89
R-456598,96
And so on...
</code>```

How to do this with VB.NET easily? If there is other better way to have the similar result without using array, that also will help me.

答:
I would recommend the use of a List(Of Tuple) instead of an array. It is more dynamic. Please check this code:

```<code>Sub SortList()
    'Declare the List Of Tuple with a Tuple of Char, Integer, Integer
    Dim lstToSort As New List(Of Tuple(Of Char, Integer, Integer))
    'Example to Add items
    lstToSort.Add(Tuple.Create("R"c, 250645, 11))
    lstToSort.Add(Tuple.Create("C"c, 125212, 25))
    'Sort is just 1 line
    lstToSort = lstToSort.OrderBy(Function(i) i.Item2).ToList
    'Loop through the elements to print them
    For Each tpl As Tuple(Of Char, Integer, Integer) In lstToSort
        Console.WriteLine(tpl.Item1 & "-" & tpl.Item2 & "," & tpl.Item3)
    Next
End Sub
</code>```

Edit: Given your edit on the question here is the code fixed:

```<code>Sub SortList()
    'Declare the List Of Tuple with a tuple of String, Integer
    Dim lstToSort As New List(Of Tuple(Of String, Integer))
    'Example to add items
    lstToSort.Add(Tuple.Create("R-250645", 11))
    lstToSort.Add(Tuple.Create("C-125212", 25))
    'Sort is just 1 line
    lstToSort = lstToSort.OrderBy(Function(i) i.Item2).ToList
    'Loop through the elements to print them
    For Each tpl As Tuple(Of String, Integer) In lstToSort
        Console.WriteLine(tpl.Item1 & "," & tpl.Item2)
    Next
End Sub
</code>```

Give it a try and let me know your comments

Title: Sort Multidimensional Array in VB.NET

Body:
I have a 2X50 array like this-

R-125212,11
C-254645,25
R-456598,96
M-456878,35
O-980857,89
And so on...

Now I want to sort this array with the values of the 2nd Column. So the output should look like-

R-125212,11
C-254645,25
M-456878,35
O-980857,89
R-456598,96
And so on...

How to do this with VB.NET easily? If there is other better way to have the similar result without using array, that also will help me.

Body:
I would recommend the use of a List(Of Tuple) instead of an array. It is more dynamic. Please check this code:

Sub SortList()
    'Declare the List Of Tuple with a Tuple of Char, Integer, Integer
    Dim lstToSort As New List(Of Tuple(Of Char, Integer, Integer))
    'Example to Add items
    lstToSort.Add(Tuple.Create("R"c, 250645, 11))
    lstToSort.Add(Tuple.Create("C"c, 125212, 25))
    'Sort is just 1 line
    lstToSort = lstToSort.OrderBy(Function(i) i.Item2).ToList
    'Loop through the elements to print them
    For Each tpl As Tuple(Of Char, Integer, Integer) In lstToSort
        Console.WriteLine(tpl.Item1 & "-" & tpl.Item2 & "," & tpl.Item3)
    Next
End Sub

Edit: Given your edit on the question here is the code fixed:

Sub SortList()
    'Declare the List Of Tuple with a tuple of String, Integer
    Dim lstToSort As New List(Of Tuple(Of String, Integer))
    'Example to add items
    lstToSort.Add(Tuple.Create("R-250645", 11))
    lstToSort.Add(Tuple.Create("C-125212", 25))
    'Sort is just 1 line
    lstToSort = lstToSort.OrderBy(Function(i) i.Item2).ToList
    'Loop through the elements to print them
    For Each tpl As Tuple(Of String, Integer) In lstToSort
        Console.WriteLine(tpl.Item1 & "," & tpl.Item2)
    Next
End Sub

Give it a try and let me know your comments


问:
how to encode 27 vector3's into a 0-256 value?
I have 27 combinations of 3 values from -1 to 1 of type:

```<code> Vector3(0,0,0);
 Vector3(-1,0,0);
 Vector3(0,-1,0);
 Vector3(0,0,-1);
 Vector3(-1,-1,0);
 ... up to
 Vector3(0,1,1);
 Vector3(1,1,1);
</code>```

I need to convert them to and from a 8-bit sbyte / byte array.

One solution is to say the first digit, of the 256 = X the second digit is Y and the third is Z...

so

```<code>  Vector3(-1,1,1) becomes 022,
  Vector3(1,-1,-1) becomes 200,
  Vector3(1,0,1) becomes 212...
</code>```

I'd prefer to encode it in a more compact way, perhaps using bytes (which I am clueless about), because the above solution uses a lot of multiplications and round functions to decode, do you have some suggestions please? the other option is to write 27 if conditions to write the Vector3 combination to an array, it seems inefficient.

Thanks to Evil Tak for the guidance, i changed the code a bit to add 0-1 values to the first bit, and to adapt it for unity3d:

```<code>function Pack4(x:int,y:int,z:int,w:int):sbyte {
var b: sbyte = 0;

b |= (x + 1) << 6;
b |= (y + 1) << 4;
b |= (z + 1) << 2;
b |= (w + 1);
return b;
}

function unPack4(b:sbyte):Vector4 {
var v : Vector4;
v.x = ((b & 0xC0) >> 6) - 1;      //0xC0 == 1100 0000
v.y = ((b & 0x30) >> 4) - 1;    // 0x30 == 0011 0000
v.z = ((b & 0xC) >> 2) - 1;     // 0xC  == 0000 1100
v.w = (b  & 0x3) - 1;            // 0x3  == 0000 0011
return v;
}
</code>```

答:
I assume your values are float not integer

so bit operations will not improve speed too much in comparison to conversion to integer type. So my bet using full range will be better. I would do this for 3D case:

```<code>8 bit -> 256 values
3D -> pow(256,1/3) = ~ 6.349 values per dimension
6^3 = 216 < 256
</code>```

So packing of (x,y,z) looks like this:

BYTE p;
p =floor((x+1.0)*3.0);
p+=floor((y+1.0)*3.0*6.0);
p+=floor((y+1.0)*3.0*6.0*6.0);
```

<p>The idea is convert <code><-1,+1></code> to range <code><0,1></code> hence the <code>+1.0</code> and <code>*3.0</code> instead of <code>*6.0</code> and then just multiply to the correct place in final <strong>BYTE</strong>.</p>

<p><strong>and unpacking of <code>p</code> looks like this:</strong></p>

<pre class="lang-cpp prettyprint-override"><code>x=p%6; x=(x/3.0)-1.0; p/=6;
y=p%6; y=(y/3.0)-1.0; p/=6;
z=p%6; z=(z/3.0)-1.0;
</code>```

This way you use 216 from 256 values which is much better then just 2 bits (4 values). Your 4D case would look similar just use instead 3.0,6.0 different constant floor(pow(256,1/4))=4 so use 2.0,4.0 but beware case when p=256 or use 2 bits per dimension and bit approach like the accepted answer does.

If you need real speed you can optimize this to force float representation holding result of packet BYTE to specific exponent and extract mantissa bits as your packed BYTE directly. As the result will be <0,216>  you can add any bigger number to it. see IEEE 754-1985 for details but you want the mantissa to align with your BYTE so if you add to p number like 2^23 then the lowest 8 bit of float should be your packed value directly (as MSB 1 is not present in mantissa) so no expensive conversion is needed.

In case you got just {-1,0,+1} instead of <-1,+1>

then of coarse you should use integer approach like bit packing with 2 bits per dimension or use LUT table of all 3^3 = 27 possibilities and pack entire vector in 5 bits.

The encoding would look like this:

int enc[3][3][3] = { 0,1,2, ... 24,25,26 };
p=enc[x+1][y+1][z+1];
```

<p><strong>And decoding:</strong></p>

<pre class="lang-cpp prettyprint-override"><code>int dec[27][3] = { {-1,-1,-1},.....,{+1,+1,+1} };
x=dec[p][0];
y=dec[p][1];
z=dec[p][2];
</code>```

Which should be fast enough and if you got many vectors you can pack the p into each 5 bits ... to save even more memory space

Body:
I have 27 combinations of 3 values from -1 to 1 of type:

 Vector3(0,0,0);
 Vector3(-1,0,0);
 Vector3(0,-1,0);
 Vector3(0,0,-1);
 Vector3(-1,-1,0);
 ... up to
 Vector3(0,1,1);
 Vector3(1,1,1);

I need to convert them to and from a 8-bit sbyte / byte array.

One solution is to say the first digit, of the 256 = X the second digit is Y and the third is Z...

so

  Vector3(-1,1,1) becomes 022,
  Vector3(1,-1,-1) becomes 200,
  Vector3(1,0,1) becomes 212...

I'd prefer to encode it in a more compact way, perhaps using bytes (which I am clueless about), because the above solution uses a lot of multiplications and round functions to decode, do you have some suggestions please? the other option is to write 27 if conditions to write the Vector3 combination to an array, it seems inefficient.

Thanks to Evil Tak for the guidance, i changed the code a bit to add 0-1 values to the first bit, and to adapt it for unity3d:

function Pack4(x:int,y:int,z:int,w:int):sbyte {
var b: sbyte = 0;

b |= (x + 1) << 6;
b |= (y + 1) << 4;
b |= (z + 1) << 2;
b |= (w + 1);
return b;
}

function unPack4(b:sbyte):Vector4 {
var v : Vector4;
v.x = ((b & 0xC0) >> 6) - 1;      //0xC0 == 1100 0000
v.y = ((b & 0x30) >> 4) - 1;    // 0x30 == 0011 0000
v.z = ((b & 0xC) >> 2) - 1;     // 0xC  == 0000 1100
v.w = (b  & 0x3) - 1;            // 0x3  == 0000 0011
return v;
}

Body:
I assume your values are float not integer

so bit operations will not improve speed too much in comparison to conversion to integer type. So my bet using full range will be better. I would do this for 3D case:

8 bit -> 256 values
3D -> pow(256,1/3) = ~ 6.349 values per dimension
6^3 = 216 < 256

So packing of (x,y,z) looks like this:

BYTE p;
p =floor((x+1.0)*3.0);
p+=floor((y+1.0)*3.0*6.0);
p+=floor((y+1.0)*3.0*6.0*6.0);

The idea is convert <-1,+1> to range <0,1> hence the +1.0 and *3.0 instead of *6.0 and then just multiply to the correct place in final BYTE.

and unpacking of p looks like this:

x=p%6; x=(x/3.0)-1.0; p/=6;
y=p%6; y=(y/3.0)-1.0; p/=6;
z=p%6; z=(z/3.0)-1.0;

This way you use 216 from 256 values which is much better then just 2 bits (4 values). Your 4D case would look similar just use instead 3.0,6.0 different constant floor(pow(256,1/4))=4 so use 2.0,4.0 but beware case when p=256 or use 2 bits per dimension and bit approach like the accepted answer does.

If you need real speed you can optimize this to force float representation holding result of packet BYTE to specific exponent and extract mantissa bits as your packed BYTE directly. As the result will be <0,216>  you can add any bigger number to it. see IEEE 754-1985 for details but you want the mantissa to align with your BYTE so if you add to p number like 2^23 then the lowest 8 bit of float should be your packed value directly (as MSB 1 is not present in mantissa) so no expensive conversion is needed.

In case you got just {-1,0,+1} instead of <-1,+1>

then of coarse you should use integer approach like bit packing with 2 bits per dimension or use LUT table of all 3^3 = 27 possibilities and pack entire vector in 5 bits.

The encoding would look like this:

int enc[3][3][3] = { 0,1,2, ... 24,25,26 };
p=enc[x+1][y+1][z+1];

And decoding:

int dec[27][3] = { {-1,-1,-1},.....,{+1,+1,+1} };
x=dec[p][0];
y=dec[p][1];
z=dec[p][2];

Which should be fast enough and if you got many vectors you can pack the p into each 5 bits ... to save even more memory space


问:
pandas join string and number columns from same dataframe
I want to merge a Two columns in a database:

The two columns are

```<code>A
1
2
Na
Na

B
Na
Na
C
Na
</code>```

Output

```<code>D
1
2
C
Na
</code>```

答:
You can use combine_first or fillna:

```<code>df['D'] = df['A'].combine_first(df['B'])
</code>```

Or:

```<code>df['D'] = df['A'].fillna(df['B'])
</code>```

Notice:

If one column is numeric and another not, get mixed types and some functions can be broken.

Body:
I want to merge a Two columns in a database:

The two columns are

A
1
2
Na
Na

B
Na
Na
C
Na

Output

D
1
2
C
Na

Body:
You can use combine_first or fillna:

df['D'] = df['A'].combine_first(df['B'])

Or:

df['D'] = df['A'].fillna(df['B'])

Notice:

If one column is numeric and another not, get mixed types and some functions can be broken.


问:
Firebase SyntaxError when deploying functions
I started a firebase functions project last week and it all worked like a charm for the first couple of days. This morning however I started having this error whenever I run the firebase deploy --only functions command:

```<code>Error: Error occurred while parsing your function triggers.

SyntaxError: Unexpected token {
    at exports.runInThisContext (vm.js:53:16)
    at Module._compile (module.js:387:25)
    at Object.Module._extensions..js (module.js:422:10)
    at Module.load (module.js:357:32)
    at Function.Module._load (module.js:314:12)
    at Module.require (module.js:367:17)
    at require (internal/module.js:16:19)
    at Object.<anonymous> (/usr/local/lib/node_modules/firebase-tools/lib/triggerParser.js:16:9)
    at Module._compile (module.js:413:34)
    at Object.Module._extensions..js (module.js:422:10)
</code>```

I am now running the Firebase cli tools version 3.5.0 and Node 5.5.0

Anyone knows what's happening?

答: Ok the problem was with the Node installation but in order to solve that I had to first update homebrew. Once I did that I could actually upgrade Node and the problem disappeared.</p>

Body:
I started a firebase functions project last week and it all worked like a charm for the first couple of days. This morning however I started having this error whenever I run the firebase deploy --only functions command:

Error: Error occurred while parsing your function triggers.

SyntaxError: Unexpected token {
    at exports.runInThisContext (vm.js:53:16)
    at Module._compile (module.js:387:25)
    at Object.Module._extensions..js (module.js:422:10)
    at Module.load (module.js:357:32)
    at Function.Module._load (module.js:314:12)
    at Module.require (module.js:367:17)
    at require (internal/module.js:16:19)
    at Object.<anonymous> (/usr/local/lib/node_modules/firebase-tools/lib/triggerParser.js:16:9)
    at Module._compile (module.js:413:34)
    at Object.Module._extensions..js (module.js:422:10)

I am now running the Firebase cli tools version 3.5.0 and Node 5.5.0

Anyone knows what's happening?


答:
Use combine_first

```<code>df.A.combine_first(df.B)
</code>```

Consider the dataframe df

```<code>df = pd.DataFrame(dict(A=[1, 2, np.nan, np.nan], B=[np.nan, np.nan, 'C', np.nan]))
</code>```

Then

```<code>df.A.combine_first(df.B)

0      1
1      2
2      C
3    NaN
Name: A, dtype: object
</code>```

You can assign it to a new column 'C'

```<code>df.assign(C=df.A.combine_first(df.B))

     A    B    C
0  1.0  NaN    1
1  2.0  NaN    2
2  NaN    C    C
3  NaN  NaN  NaN
</code>```

Title: pandas join string and number columns from same dataframe

Body:
Use combine_first

df.A.combine_first(df.B)

Consider the dataframe df

df = pd.DataFrame(dict(A=[1, 2, np.nan, np.nan], B=[np.nan, np.nan, 'C', np.nan]))

Then

df.A.combine_first(df.B)

0      1
1      2
2      C
3    NaN
Name: A, dtype: object

You can assign it to a new column 'C'

df.assign(C=df.A.combine_first(df.B))

     A    B    C
0  1.0  NaN    1
1  2.0  NaN    2
2  NaN    C    C
3  NaN  NaN  NaN


问:
How to load 2 controllers one by one or at a time in angularjs?
Is it possible to load multiple controllers one by one or at a time. If yes  then Can anyone tell me how to load two different controllers at the time of loading page in AngularJs. I'm using routing.

Thank you.

答:
You can just refer them in the index.html in the order you want </p>

```<code>  <script type="text/javascript" src="controller1.js"></script>
  <script type="text/javascript" src="controller2.js"></script>
</code>```

Body:
You can just refer them in the index.html in the order you want

  <script type="text/javascript" src="controller1.js"></script>
  <script type="text/javascript" src="controller2.js"></script>


问:
How to convert txt files to FoxPro frx files
Plain text files contain lot of static text divided into paragraphs.

Those texts should convertert into reports (frx,frt) files.

After than those report will be modifined manually to add fields
to them and some formatting shoud applied.

Creating reports manually is huge work: Report field maximum  size is 255
characters. Thus every sentence in txt file should copied and pasted
manually.

How to convert txt files to frx files automatically.
E.q. every row in txt file should appear as label element in report.

Is it possible to insert this information to frx file manually ? If yes, how to calculate vpos values?
Or is there better solution ?

答:
Like most things in FoxPro metadata, FRX files are just DBF files with a different extension. So you can browse and manipulate them like any other DBF.

So I can create a simple report:

```<code>create report e:\temp\report1
</code>```

and then add a text expression to it in the normal way in the report designer.

I can then open it as a DBF:

```<code>use e:\temp\report1.frx
</code>```

And then view the relevant type of object:

```<code>brow for objtype = 8
</code>```

So you see you can add records to it programmatically but you would have to calculate the vertical position based on the font size, handle page breaks and so forth. Big pain.

So why not create a table with a memo-type field, create some records and put your source text each. Then have one report layout with one text field in the detail band, set to 'stretch with overflow' and the data source as your memo field? Or automate MS Word to do it. Anything would be easier than building the FRX programmatically.

Body:
Like most things in FoxPro metadata, FRX files are just DBF files with a different extension. So you can browse and manipulate them like any other DBF.

So I can create a simple report:

create report e:\temp\report1

and then add a text expression to it in the normal way in the report designer.

I can then open it as a DBF:

use e:\temp\report1.frx

And then view the relevant type of object:

brow for objtype = 8

So you see you can add records to it programmatically but you would have to calculate the vertical position based on the font size, handle page breaks and so forth. Big pain.

So why not create a table with a memo-type field, create some records and put your source text each. Then have one report layout with one text field in the detail band, set to 'stretch with overflow' and the data source as your memo field? Or automate MS Word to do it. Anything would be easier than building the FRX programmatically.


问:
angular filter - group by object (or multiple fields)
I extended the Angular filter group by example to the following by transforming the team to an object.

     var app = angular.module('myApp',['angular.filter']);

app.controller('MainController', ['$scope', function($scope){
  $scope.players = [
  {
    name: 'Gene',
    team: {
      'id' : '1',
      'name' : 'alpha'

    }
  },
  {
    name: 'George',
    team: {
      'id' : '2',
      'name' : 'beta'
    }
  },
  {
    name: 'Steve',
    team: {
      'id' : '3',
      'name' : 'gamma'
    }
  },
  {
    name: 'Paula',
    team: {
      'id' : '2',
      'name' : 'beta'
    }
  },
  {
    name: 'Scruath',
    team: {
      'id' : '3',
      'name' : 'gamma'
    }
  }
];
}]);

  ```
<pre class="snippet-code-html lang-html prettyprint-override"><code><!DOCTYPE html>
<html>

  <head>
    <script data-require="angularjs@1.6.2" data-semver="1.6.2" src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.2/angular.js"></script>
    <script data-require="angular-filter@*" data-semver="0.5.7" src="//cdnjs.cloudflare.com/ajax/libs/angular-filter/0.5.7/angular-filter.js"></script>
    <link rel="stylesheet" href="style.css" />
    <script src="script.js"></script>
  </head>

  <body ng-app="myApp">
    <div ng-controller="MainController">
      <ul>
        <li ng-repeat="(team, players) in players | groupBy: 'team.name'">
          Group name: {{ team }}
          <ul>
            <li ng-repeat="player in players">
              player: {{ player.name }}
            </li>
          </ul>
        </li>
      </ul>
    </div>
  </body>

</html></code>```

But, what if I need the team id in the group by? What can I do?

```<code><a href="#I need the team ID">Group name: {{ team }}</a>
</code>```

I tried to group by the team object and use team.name and team.id but it didn't work. Also, I didn't know how to create a group by with multiple fields (team.id, team.name)

Here's a working plnkr

答:
You should group by team.id because a team name is not unique. In that way you avoid a wrong data output. Ok, well. I was able to solve your problem by pre-collecting your team in the controller and normalize them by team.idin a seperate object - demo fiddle:

View

```<code><body ng-app="myApp">
<div ng-controller="MainController">
    <ul>
        <li ng-repeat="(team, players) in players | groupBy: 'team.id'">
            <a href="{{ team }} ">Group name: {{ teams[team].name }}</a>
            <ul>
                <li ng-repeat="player in players">
                    player: {{ player.name }}
                </li>
            </ul>
        </li>
    </ul>
</div>
</body>
</code>```

AngularJS Application

```<code>var app = angular.module('myApp',['angular.filter']);

app.controller('MainController', ['$scope', function($scope){

    $scope.players = [
        {
            name: 'Gene',
            team: {
                'id' : '1',
                'name' : 'alpha'

            }
        }, {
            name: 'George',
            team: {
                'id' : '2',
                'name' : 'beta'
            }
        }, {
            name: 'Steve',
            team: {
                'id' : '3',
                'name' : 'gamma'
            }
        }, {
            name: 'Paula',
            team: {
                'id' : '4',
                'name' : 'beta'
            }
        }, {
            name: 'Scruath',
            team: {
                'id' : '5',
                'name' : 'gamma'
            }
        }];

    $scope.teams = {};

    $scope.players.forEach(function (player) {
        if (angular.isUndefined($scope.teams[player.team.id])) {
            $scope.teams[player.team.id] = player.team;
        }
    });
}]);
</code>```

Body:
I extended the Angular filter group by example to the following by transforming the team to an object.

     var app = angular.module('myApp',['angular.filter']);

app.controller('MainController', ['$scope', function($scope){
  $scope.players = [
  {
    name: 'Gene',
    team: {
      'id' : '1',
      'name' : 'alpha'

    }
  },
  {
    name: 'George',
    team: {
      'id' : '2',
      'name' : 'beta'
    }
  },
  {
    name: 'Steve',
    team: {
      'id' : '3',
      'name' : 'gamma'
    }
  },
  {
    name: 'Paula',
    team: {
      'id' : '2',
      'name' : 'beta'
    }
  },
  {
    name: 'Scruath',
    team: {
      'id' : '3',
      'name' : 'gamma'
    }
  }
];
}]);

<!DOCTYPE html>

    <link rel="stylesheet" href="style.css" />

          Group name: {{ team }}

              player: {{ player.name }}

But, what if I need the team id in the group by? What can I do?

Group name: {{ team }}

I tried to group by the team object and use team.name and team.id but it didn't work. Also, I didn't know how to create a group by with multiple fields (team.id, team.name)

Here's a working plnkr

Body:
You should group by team.id because a team name is not unique. In that way you avoid a wrong data output. Ok, well. I was able to solve your problem by pre-collecting your team in the controller and normalize them by team.idin a seperate object - demo fiddle:

View

<body ng-app="myApp">
<div ng-controller="MainController">
    <ul>
        <li ng-repeat="(team, players) in players | groupBy: 'team.id'">
            <a href="{{ team }} ">Group name: {{ teams[team].name }}</a>
            <ul>
                <li ng-repeat="player in players">
                    player: {{ player.name }}
                </li>
            </ul>
        </li>
    </ul>
</div>
</body>

AngularJS Application

var app = angular.module('myApp',['angular.filter']);

app.controller('MainController', ['$scope', function($scope){

    $scope.players = [
        {
            name: 'Gene',
            team: {
                'id' : '1',
                'name' : 'alpha'

            }
        }, {
            name: 'George',
            team: {
                'id' : '2',
                'name' : 'beta'
            }
        }, {
            name: 'Steve',
            team: {
                'id' : '3',
                'name' : 'gamma'
            }
        }, {
            name: 'Paula',
            team: {
                'id' : '4',
                'name' : 'beta'
            }
        }, {
            name: 'Scruath',
            team: {
                'id' : '5',
                'name' : 'gamma'
            }
        }];

    $scope.teams = {};

    $scope.players.forEach(function (player) {
        if (angular.isUndefined($scope.teams[player.team.id])) {
            $scope.teams[player.team.id] = player.team;
        }
    });
}]);


问:
Route not found on refresh using react router and express on heroku
When serving my app locally everything is loading and working as normal on refresh. When I deploy to Heroku, everything is working normal when clicking around to different links.

The issue I keep running into is when I get to a route. IE: /aboutus and refresh I get a "not found". When I navigate there it all checks out fine. Any thoughts?

I am using react router redux also.

package.json

```<code>....
"express": "^4.14.1",
"react-redux": "^5.0.3",
"react-router": "^3.0.2",
"react-router-redux": "^4.0.8",
</code>```

server.js

```<code>app.use(express.static(path.join(__dirname, '/../dist')));
app.use('/data', express.static(__dirname + '/data'));
app.use(express.static(__dirname))
app.get('*', (req, res) => {
    res.sendFile(path.join(__dirname, 'index.html'));
});
</code>```

Index.js

```<code>...
const router = (
  <Provider store={store}>
    <Router history={history}>
      <Route path="/" component={App}>
        <IndexRoute component={Home} />
        <Route path="/aboutus" component={About} />
        <Route path="/list" component={List}  />
      </Route>
    </Router>
  </Provider>
)

render(router, document.getElementById('main'));
</code>```

答:
I ended up solving this by adjusting my Express config to the following if anyone else runs into this problem:</p>

```<code>//res.sendFile(path.join(__dirname, 'index.html'));
res.sendFile(path.resolve(__dirname + '/../dist/index.html'));
</code>```

Body:
When serving my app locally everything is loading and working as normal on refresh. When I deploy to Heroku, everything is working normal when clicking around to different links.

The issue I keep running into is when I get to a route. IE: /aboutus and refresh I get a "not found". When I navigate there it all checks out fine. Any thoughts?

I am using react router redux also.

package.json

....
"express": "^4.14.1",
"react-redux": "^5.0.3",
"react-router": "^3.0.2",
"react-router-redux": "^4.0.8",

server.js

app.use(express.static(path.join(__dirname, '/../dist')));
app.use('/data', express.static(__dirname + '/data'));
app.use(express.static(__dirname))
app.get('*', (req, res) => {
    res.sendFile(path.join(__dirname, 'index.html'));
});

Index.js

...
const router = (
  <Provider store={store}>
    <Router history={history}>
      <Route path="/" component={App}>
        <IndexRoute component={Home} />
        <Route path="/aboutus" component={About} />
        <Route path="/list" component={List}  />
      </Route>
    </Router>
  </Provider>
)

render(router, document.getElementById('main'));

Body:
I ended up solving this by adjusting my Express config to the following if anyone else runs into this problem:

//res.sendFile(path.join(__dirname, 'index.html'));
res.sendFile(path.resolve(__dirname + '/../dist/index.html'));


问:
How to judge long variable is null, or can if() contain an exception judgment in Java?
In my case, results[i] might not exist in HBase table, so using getTimestamp() to get results[i]'s timestamp might cause an exception. Timestamp in HBase is a long variable, so following two ways I tried do not works.

```<code>if((results[i].listCells().get(0).getTimestamp()) != null){
    rowkeytime = results[i].listCells().get(0).getTimestamp();
}

if(((Long)(results[i].listCells().get(0).getTimestamp())) != null){
    rowkeytime = results[i].listCells().get(0).getTimestamp();
}
</code>```

I want to know whether there is an usage like below in Java?

```<code>if ((results[i].listCells().get(0).getTimestamp()) throws an exception){
    rowkeytime = results[i].listCells().get(0).getTimestamp();
}
</code>```

答:
Use try-catch to handle exceptions:

```<code>try {
    results[i].listCells().get(0).getTimestamp();
} catch (NullPointerException e) {
    // Do something if an exception is thrown
}
</code>```

In your scenario it would be better to check you input beforehand.

```<code>if (results != null && results.length >= i - 1) {
    results[i].listCells().get(0).getTimestamp();
    // You may want to add additional checks for
    // the return values of listCells() and get(0)
} else {
    // Do something else
}
</code>```

Body:
In my case, results[i] might not exist in HBase table, so using getTimestamp() to get results[i]'s timestamp might cause an exception. Timestamp in HBase is a long variable, so following two ways I tried do not works.

if((results[i].listCells().get(0).getTimestamp()) != null){
    rowkeytime = results[i].listCells().get(0).getTimestamp();
}

if(((Long)(results[i].listCells().get(0).getTimestamp())) != null){
    rowkeytime = results[i].listCells().get(0).getTimestamp();
}

I want to know whether there is an usage like below in Java?

if ((results[i].listCells().get(0).getTimestamp()) throws an exception){
    rowkeytime = results[i].listCells().get(0).getTimestamp();
}

Body:
Use try-catch to handle exceptions:

try {
    results[i].listCells().get(0).getTimestamp();
} catch (NullPointerException e) {
    // Do something if an exception is thrown
}

In your scenario it would be better to check you input beforehand.

if (results != null && results.length >= i - 1) {
    results[i].listCells().get(0).getTimestamp();
    // You may want to add additional checks for
    // the return values of listCells() and get(0)
} else {
    // Do something else
}


问:
ASP.Net Log Response to Output File
Occaisionally our office printer craps out on us in the middle of a print job, or someone just forgets to print because they get interrupted. In the good 'ole days, I built up my response using a StringBuilder and output the contents to the screen and to a log file in case we ever needed to go back and re-print.

Now I'm working with a system that makes use of all the .Net yumminess (Repeaters, page events, etc) rather than building up the HTML in code. Is there a way for me to log/archive the entire HTML response generated by the server for a particular page (e.g. hook into the Page_Render event and dump the output to a file)?

Thanks,
Sam

答:
You can write an Http Module that plugs in at the end of the request pipeline and records the complete output.

See this example that should get you most of the way there.

Title: ASP.Net Log Response to Output File


问:
Where to set maximumImageFileSize of angular-summernote?
I need to limit the file size of uploaded image through angular-summernote. This github issue says we need to specify size in bytes for 'maximumImageFileSize' in its settings.js. Though even after specifying the size, summernote is not limiting upload size. There is no documentation regarding image size limit, hence if anyone has implemented this successfully, please point out what am I missing here?</p>

答:
I implemented this in an Angular 1 project. In our html file we added summernote with the config attribute containing the maximum size value in bytes (ex: 5242880 for 5Mo).

```<code><summernote config="options" lang="fr-FR"></summernote>
</code>```

In our controller we define a scope variable $scope.options

```<code>$scope.options = {
  maximumImageFileSize: <Your limit size>,
  callbacks: {
     onImageUploadError: function () {
     alert('Size too big');
    }
   }
};
</code>```

Body:
I implemented this in an Angular 1 project. In our html file we added summernote with the config attribute containing the maximum size value in bytes (ex: 5242880 for 5Mo).

<summernote config="options" lang="fr-FR"></summernote>

In our controller we define a scope variable $scope.options

$scope.options = {
  maximumImageFileSize: <Your limit size>,
  callbacks: {
     onImageUploadError: function () {
     alert('Size too big');
    }
   }
};


问:
Android Custom Spinner unable to select an option and show it
I have a problem with spinner it do not let me select one item. I tried a lot of things and that still not working.

The picture shows that the spinner is in blank when the activity load

When I clicked the arrow it shows the items

but when I choose one, nothing happends.

```<code>   <?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"

    tools:context=".Activities.Inspeccion.DatosGeneralesActivity">

    <ScrollView
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:id="@+id/scrollView"
        >
        <RelativeLayout
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:layout_marginLeft="15dp"
            android:layout_marginRight="15dp"
            android:layout_marginTop="15dp"
            >
            <TextView
                android:id="@+id/tvSubestacionTitulo"
                android:layout_below="@+id/imgLogo"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:text="@string/strSubestacion"
                android:textSize="18sp"
                android:textColor="@color/colorPrimaryDark"
                android:textStyle="bold"
                />
            <TextView
                android:id="@+id/tvSubestacionDato"
                android:layout_below="@+id/tvSubestacionTitulo"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:textSize="12sp"
                android:text="Prueba"
                />
            <Spinner
                android:id="@+id/spinnerSubEstacion"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:layout_below="@+id/tvSubestacionDato"
                >
            </Spinner>
        </RelativeLayout>
    </ScrollView>
</RelativeLayout>
</code>```

This is the Layout of the activity.

```<code>    <?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:orientation="horizontal">

    <TextView
        android:id="@+id/tvNumeroOpcion"
        android:layout_width="wrap_content"
        android:layout_height="match_parent"
        android:layout_marginLeft="15dp"
        android:layout_marginTop="5dp"
        android:text="1"
        android:textColor="@color/black"
        android:textSize="14sp" />

    <TextView
        android:id="@+id/tvDescriptionOption"
        android:layout_width="wrap_content"
        android:layout_height="match_parent"
        android:layout_marginLeft="15dp"
        android:layout_marginTop="5dp"
        android:text="Guatemala"
        android:textColor="@color/black"
        android:textSize="14sp" />
</LinearLayout>
</code>```

That is the custom layout for the spinner

```<code>Public class ComboAdapter extends BaseAdapter{

    private List<Combo> combos;
    private Activity activity;
    private LayoutInflater inflater;

    public ComboAdapter(List<Combo> combos, Activity activity) {

        this.combos = combos;
        this.inflater = (LayoutInflater) activity.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
    }

    @Override
    public int getCount() {
        return combos.size();
    }

    @Override
    public Object getItem(int position) {
        return position;
    }

    @Override
    public long getItemId(int position) {
        return position;
    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        View view = convertView;

        if (convertView == null){
            view = inflater.inflate(R.layout.combo_list_item, null);

            TextView tvId = (TextView) view.findViewById(R.id.tvNumeroOpcion);
            TextView tvDescripcion = (TextView) view.findViewById(R.id.tvDescriptionOption);

            tvId.setText(combos.get(position).getId());
            tvDescripcion.setText(combos.get(position).getDescripcion());
        }
               return view;
    }

    @Override
    public View getDropDownView(int position, View convertView,
                                ViewGroup parent) {
        return getView(position, convertView,parent);
    }
}
</code>```

That is my Adapter

And below is my activity.

```<code>public class DatosGeneralesActivity extends AppCompatActivity {

    private TextView tvSubestacionDato;

    private List<Combo>  listaCombo;

    private Spinner spinnerSubestacion;

    private ArrayAdapter<Combo> adapterSubestacion;

    String seleccion;

    @Override
    protected void onCreate(final Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_datos_generales);
        //Inicializando textos
        tvSubestacionDato = (TextView) findViewById(R.id.tvSubestacionDato);

        //Inicializanco listas
        listaCombo = new ArrayList<>();

        //Inivializando spinners
        spinnerSubestacion = (Spinner) findViewById(R.id.spinnerSubEstacion);

        AppService service = API.getCombos().create(AppService.class);
        Call<List<Combo>> subestacionCall = service.getSubestacion();

        subestacionCall.enqueue(new Callback<List<Combo>>() {
            @Override
            public void onResponse(Call<List<Combo>> call, Response<List<Combo>> response) {
                listaCombo.clear();
                listaCombo.addAll(response.body());
            }

            @Override
            public void onFailure(Call<List<Combo>> call, Throwable t) {

            }
        });

        //final ComboAdapter adapter = new ComboAdapter(listaCombo, DatosGeneralesActivity.this);
        final ArrayAdapter<Combo> adapter = new ArrayAdapter<Combo>(this, R.layout.support_simple_spinner_dropdown_item, listaCombo);
        spinnerSubestacion.setAdapter(adapter);

        spinnerSubestacion.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
                adapter.notifyDataSetChanged();
                Toast.makeText(DatosGeneralesActivity.this, ""+position, Toast.LENGTH_SHORT).show();
                tvSubestacionDato.setText(listaCombo.get(position).getDescripcion());
            }

            @Override
            public void onNothingSelected(AdapterView<?> parent) {

            }
        });
    }
</code>```

答:
Try this changes:

Call adapter like:

```<code>ComboAdapter adapter = new ComboAdapter(DatosGeneralesActivity.this,
            R.layout.combo_list_item, R.id.tvDescriptionOption, listaCombo);
</code>```

now in adapter class:

```<code> public ComboAdapter(Activity context,int resouceId, int textviewId, List<Combo> list){

        super(context,resouceId,textviewId, list);
        this.combos = list;
        this.inflater = (LayoutInflater) activity.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
    }
</code>```

Also inside your getView() method inflate layout like:

```<code>if (convertView == null){
     view = inflater.inflate(R.layout.combo_list_item, parent , false);
</code>```

Body:
I have a problem with spinner it do not let me select one item. I tried a lot of things and that still not working.

The picture shows that the spinner is in blank when the activity load

When I clicked the arrow it shows the items

but when I choose one, nothing happends.

   <?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"

    tools:context=".Activities.Inspeccion.DatosGeneralesActivity">

    <ScrollView
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:id="@+id/scrollView"
        >
        <RelativeLayout
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:layout_marginLeft="15dp"
            android:layout_marginRight="15dp"
            android:layout_marginTop="15dp"
            >
            <TextView
                android:id="@+id/tvSubestacionTitulo"
                android:layout_below="@+id/imgLogo"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:text="@string/strSubestacion"
                android:textSize="18sp"
                android:textColor="@color/colorPrimaryDark"
                android:textStyle="bold"
                />
            <TextView
                android:id="@+id/tvSubestacionDato"
                android:layout_below="@+id/tvSubestacionTitulo"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:textSize="12sp"
                android:text="Prueba"
                />
            <Spinner
                android:id="@+id/spinnerSubEstacion"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:layout_below="@+id/tvSubestacionDato"
                >
            </Spinner>
        </RelativeLayout>
    </ScrollView>
</RelativeLayout>

This is the Layout of the activity.

    <?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:orientation="horizontal">

    <TextView
        android:id="@+id/tvNumeroOpcion"
        android:layout_width="wrap_content"
        android:layout_height="match_parent"
        android:layout_marginLeft="15dp"
        android:layout_marginTop="5dp"
        android:text="1"
        android:textColor="@color/black"
        android:textSize="14sp" />

    <TextView
        android:id="@+id/tvDescriptionOption"
        android:layout_width="wrap_content"
        android:layout_height="match_parent"
        android:layout_marginLeft="15dp"
        android:layout_marginTop="5dp"
        android:text="Guatemala"
        android:textColor="@color/black"
        android:textSize="14sp" />
</LinearLayout>

That is the custom layout for the spinner

Public class ComboAdapter extends BaseAdapter{

    private List<Combo> combos;
    private Activity activity;
    private LayoutInflater inflater;

    public ComboAdapter(List<Combo> combos, Activity activity) {

        this.combos = combos;
        this.inflater = (LayoutInflater) activity.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
    }

    @Override
    public int getCount() {
        return combos.size();
    }

    @Override
    public Object getItem(int position) {
        return position;
    }

    @Override
    public long getItemId(int position) {
        return position;
    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        View view = convertView;

        if (convertView == null){
            view = inflater.inflate(R.layout.combo_list_item, null);

            TextView tvId = (TextView) view.findViewById(R.id.tvNumeroOpcion);
            TextView tvDescripcion = (TextView) view.findViewById(R.id.tvDescriptionOption);

            tvId.setText(combos.get(position).getId());
            tvDescripcion.setText(combos.get(position).getDescripcion());
        }
               return view;
    }

    @Override
    public View getDropDownView(int position, View convertView,
                                ViewGroup parent) {
        return getView(position, convertView,parent);
    }
}

That is my Adapter

And below is my activity.

public class DatosGeneralesActivity extends AppCompatActivity {

    private TextView tvSubestacionDato;

    private List<Combo>  listaCombo;

    private Spinner spinnerSubestacion;

    private ArrayAdapter<Combo> adapterSubestacion;

    String seleccion;

    @Override
    protected void onCreate(final Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_datos_generales);
        //Inicializando textos
        tvSubestacionDato = (TextView) findViewById(R.id.tvSubestacionDato);

        //Inicializanco listas
        listaCombo = new ArrayList<>();

        //Inivializando spinners
        spinnerSubestacion = (Spinner) findViewById(R.id.spinnerSubEstacion);

        AppService service = API.getCombos().create(AppService.class);
        Call<List<Combo>> subestacionCall = service.getSubestacion();

        subestacionCall.enqueue(new Callback<List<Combo>>() {
            @Override
            public void onResponse(Call<List<Combo>> call, Response<List<Combo>> response) {
                listaCombo.clear();
                listaCombo.addAll(response.body());
            }

            @Override
            public void onFailure(Call<List<Combo>> call, Throwable t) {

            }
        });

        //final ComboAdapter adapter = new ComboAdapter(listaCombo, DatosGeneralesActivity.this);
        final ArrayAdapter<Combo> adapter = new ArrayAdapter<Combo>(this, R.layout.support_simple_spinner_dropdown_item, listaCombo);
        spinnerSubestacion.setAdapter(adapter);

        spinnerSubestacion.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
                adapter.notifyDataSetChanged();
                Toast.makeText(DatosGeneralesActivity.this, ""+position, Toast.LENGTH_SHORT).show();
                tvSubestacionDato.setText(listaCombo.get(position).getDescripcion());
            }

            @Override
            public void onNothingSelected(AdapterView<?> parent) {

            }
        });
    }

Body:
Try this changes:

Call adapter like:

ComboAdapter adapter = new ComboAdapter(DatosGeneralesActivity.this,
            R.layout.combo_list_item, R.id.tvDescriptionOption, listaCombo);

now in adapter class:

 public ComboAdapter(Activity context,int resouceId, int textviewId, List<Combo> list){

        super(context,resouceId,textviewId, list);
        this.combos = list;
        this.inflater = (LayoutInflater) activity.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
    }

Also inside your getView() method inflate layout like:

if (convertView == null){
     view = inflater.inflate(R.layout.combo_list_item, parent , false);


问:
IllegalStateException when using the Tray Notification in java Fx?
I am trying to implement a pop upp notification in JavaFx I am using this lib
and according to that tutorial wrote this code:

```<code>    String title = "Well done boy!!";
    String message = "You've successfully created your first Tray Notification";

    TrayNotification tray = new TrayNotification();
    tray.setTitle(title);
    tray.setMessage(message);
    tray.setNotificationType(NotificationType.SUCCESS);
    tray.showAndWait();
</code>```

but the code is throwing an Exception:

Caused by: java.lang.IllegalStateException: Toolkit not initialized
    at com.sun.javafx.application.PlatformImpl.runLater(Unknown Source)
    at com.sun.javafx.application.PlatformImpl.runLater(Unknown Source)
    at
  com.sun.javafx.application.PlatformImpl.setPlatformUserAgentStylesheet(Unknown
  Source)   at
  com.sun.javafx.application.PlatformImpl.setDefaultPlatformUserAgentStylesheet(Unknown
  Source)   at javafx.scene.control.Control.(Unknown Source)    ...
  15 more

Any suggetion why?

please note, the original code example is implemented like:

```<code>tray.setNotification(notification);
</code>```

where notification is

but some how I can not import the class

```<code> Notification notification = Notifications.SUCCESS;
</code>```

答:
try to use constructor for creating.ıt works for me that way.
Did you add the library from the module settings?

Ex:

```<code> TrayNotification tray = new TrayNotification("Test", "mesaj", NotificationType.SUCCESS);
    tray.showAndWait();
</code>```

Body:
I am trying to implement a pop upp notification in JavaFx I am using this lib
and according to that tutorial wrote this code:

    String title = "Well done boy!!";
    String message = "You've successfully created your first Tray Notification";

    TrayNotification tray = new TrayNotification();
    tray.setTitle(title);
    tray.setMessage(message);
    tray.setNotificationType(NotificationType.SUCCESS);
    tray.showAndWait();

but the code is throwing an Exception:

Caused by: java.lang.IllegalStateException: Toolkit not initialized
    at com.sun.javafx.application.PlatformImpl.runLater(Unknown Source)
    at com.sun.javafx.application.PlatformImpl.runLater(Unknown Source)
    at
  com.sun.javafx.application.PlatformImpl.setPlatformUserAgentStylesheet(Unknown
  Source)   at
  com.sun.javafx.application.PlatformImpl.setDefaultPlatformUserAgentStylesheet(Unknown
  Source)   at javafx.scene.control.Control.(Unknown Source)    ...
  15 more

Any suggetion why?

please note, the original code example is implemented like:

tray.setNotification(notification);

where notification is

but some how I can not import the class

 Notification notification = Notifications.SUCCESS;

Body:
try to use constructor for creating.ıt works for me that way.
Did you add the library from the module settings?

Ex:

 TrayNotification tray = new TrayNotification("Test", "mesaj", NotificationType.SUCCESS);
    tray.showAndWait();