问:
Skip Item Android Grid View in condition
I'm trying to build an android application,I have a 3 columns gridview that show a list of points,I want to jump to next line in a condition even when some of the  columns are empty

Example I want to do something like this:

```<code> ARX ARH
 BRH BRX BRY
 CRH
 DRH DRY
</code>```

答:
Try this One

  your List item Row XML would be like this
  Abc.xml

```<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="vertical"
    android:background="@android:color/darker_gray">

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="horizontal"
        android:layout_margin="5dp">

        <TextView
            android:id="@+id/textView1"
            android:layout_width="match_parent"
            android:layout_height="80dp"
            android:layout_weight="1"
            android:gravity="center"
            android:text="Name1"
            android:textSize="18sp"
            android:background="@android:color/white"
            android:layout_margin="5dp"/>

        <TextView
            android:id="@+id/textView2"
            android:layout_width="match_parent"
            android:layout_height="80dp"
            android:layout_weight="1"
            android:gravity="center"
            android:text="Name2"
            android:textSize="18sp"
            android:layout_margin="5dp"
            android:background="@android:color/white"/>

        <TextView
            android:id="@+id/textView3"
            android:layout_width="match_parent"
            android:layout_height="80dp"
            android:layout_weight="1"
            android:gravity="center"
            android:text="Name3"
            android:textSize="18sp"
            android:layout_margin="5dp"
            android:background="@android:color/white"/>

    </LinearLayout>

</LinearLayout>
</code>```

And CustomAdapter for List Would be like this

```<code>public class Custom_Adapter_Products extends BaseAdapter {
    Context context;
    String[] list = {"AAA","AAA","AAA","AAA","AAA","","AAA", "AAA","AAA"};

    public Custom_Adapter_Products(Context context){
        this.context = context;
    }

    @Override
    public int getCount() {
        return (list.length/3);
    }

    @Override
    public Object getItem(int position) {

        return null;
    }

    @Override
    public long getItemId(int position) {

        return position;
    }

    @Override
    public View getView(int pos, View convertView, ViewGroup parent) {
        try{
            int position = (pos*3);
            ViewHolder holder;
            LayoutInflater vi = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
            if (convertView == null)
            {
                convertView = vi.inflate(R.layout.abc, null);
                holder = createViewHolder(convertView);
                convertView.setTag(holder);
            }
            else
            {
                holder = (ViewHolder) convertView.getTag();
            }

            if(!list[position].equals("")){
                holder.textView1.setText(list[position]);
                holder.textView1.setVisibility(View.VISIBLE);
            }
            else{
                holder.textView1.setVisibility(View.GONE);
            }

            if(!list[position+1].equals("")){
                holder.textView2.setText(list[position]);
                holder.textView2.setVisibility(View.VISIBLE);
            }
            else{
                holder.textView2.setVisibility(View.GONE);
            }

            if(!list[position+2].equals("")){
                holder.textView3.setText(list[position]);
                holder.textView3.setVisibility(View.VISIBLE);
            }
            else{
                holder.textView3.setVisibility(View.GONE);
            }

        }catch (Exception e){
            e.printStackTrace();
        }
        return convertView;
    }

    private static class ViewHolder
    {
        public TextView textView1;
        public TextView textView2;
        public TextView textView3;
    }

    private ViewHolder createViewHolder(View v) {
        ViewHolder holder = new ViewHolder();
        try{
            holder.textView1 = (TextView) v.findViewById(R.id.textView1);
            holder.textView2 = (TextView) v.findViewById(R.id.textView2);
            holder.textView3 = (TextView) v.findViewById(R.id.textView3);
        }catch (Exception e) {
            // TODO: handle exception
            e.printStackTrace();
        }
        return holder;
    }
}
</code>```

Body:
I'm trying to build an android application,I have a 3 columns gridview that show a list of points,I want to jump to next line in a condition even when some of the  columns are empty

Example I want to do something like this:

 ARX ARH
 BRH BRX BRY
 CRH
 DRH DRY

Body:
Try this One

  your List item Row XML would be like this
  Abc.xml

<?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="vertical"
    android:background="@android:color/darker_gray">

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="horizontal"
        android:layout_margin="5dp">

        <TextView
            android:id="@+id/textView1"
            android:layout_width="match_parent"
            android:layout_height="80dp"
            android:layout_weight="1"
            android:gravity="center"
            android:text="Name1"
            android:textSize="18sp"
            android:background="@android:color/white"
            android:layout_margin="5dp"/>

        <TextView
            android:id="@+id/textView2"
            android:layout_width="match_parent"
            android:layout_height="80dp"
            android:layout_weight="1"
            android:gravity="center"
            android:text="Name2"
            android:textSize="18sp"
            android:layout_margin="5dp"
            android:background="@android:color/white"/>

        <TextView
            android:id="@+id/textView3"
            android:layout_width="match_parent"
            android:layout_height="80dp"
            android:layout_weight="1"
            android:gravity="center"
            android:text="Name3"
            android:textSize="18sp"
            android:layout_margin="5dp"
            android:background="@android:color/white"/>

    </LinearLayout>

</LinearLayout>

And CustomAdapter for List Would be like this

public class Custom_Adapter_Products extends BaseAdapter {
    Context context;
    String[] list = {"AAA","AAA","AAA","AAA","AAA","","AAA", "AAA","AAA"};

    public Custom_Adapter_Products(Context context){
        this.context = context;
    }

    @Override
    public int getCount() {
        return (list.length/3);
    }

    @Override
    public Object getItem(int position) {

        return null;
    }

    @Override
    public long getItemId(int position) {

        return position;
    }

    @Override
    public View getView(int pos, View convertView, ViewGroup parent) {
        try{
            int position = (pos*3);
            ViewHolder holder;
            LayoutInflater vi = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
            if (convertView == null)
            {
                convertView = vi.inflate(R.layout.abc, null);
                holder = createViewHolder(convertView);
                convertView.setTag(holder);
            }
            else
            {
                holder = (ViewHolder) convertView.getTag();
            }

            if(!list[position].equals("")){
                holder.textView1.setText(list[position]);
                holder.textView1.setVisibility(View.VISIBLE);
            }
            else{
                holder.textView1.setVisibility(View.GONE);
            }

            if(!list[position+1].equals("")){
                holder.textView2.setText(list[position]);
                holder.textView2.setVisibility(View.VISIBLE);
            }
            else{
                holder.textView2.setVisibility(View.GONE);
            }

            if(!list[position+2].equals("")){
                holder.textView3.setText(list[position]);
                holder.textView3.setVisibility(View.VISIBLE);
            }
            else{
                holder.textView3.setVisibility(View.GONE);
            }

        }catch (Exception e){
            e.printStackTrace();
        }
        return convertView;
    }

    private static class ViewHolder
    {
        public TextView textView1;
        public TextView textView2;
        public TextView textView3;
    }

    private ViewHolder createViewHolder(View v) {
        ViewHolder holder = new ViewHolder();
        try{
            holder.textView1 = (TextView) v.findViewById(R.id.textView1);
            holder.textView2 = (TextView) v.findViewById(R.id.textView2);
            holder.textView3 = (TextView) v.findViewById(R.id.textView3);
        }catch (Exception e) {
            // TODO: handle exception
            e.printStackTrace();
        }
        return holder;
    }
}


来源: stackexchange

问:
Overriding keypress
I know this may be an easy answer to some of you but i dont know how to properly do this. Ive created a text editor, that also has a docking window that will display functions. I have it set up in the menu that F8 is the shortcut key for showing the function window. I would also like to catch the F8 keypress event to parse the current data for the functions in the program but I cant get this to happen.. </p>

答: Set up an event handler for the OnKeyPress (or OnKeyDown or OnKeyUp) event, and check which key was pressed (it will be in the event arguments). Then, you can do whatever you want.

ContentLicense: CC BY-SA 2.5

Title: Overriding keypress


问:
Bootstrap - reversing my navbar to Right-to-Left
Im trying to make a navbar but I need it to be from Right to Left cause its in Hebrew.

I tried making a responsive Navbar Where all the linked buttons are on the Left and Going Right.
And a Brand on the Right side.
And they collapse on Small devices.

Well I cant get it to reverse and I also sometimes get an issue where on small devices the Brand and the Collapse button collide in the middle of the navbar.

答:
```<code>Maybe you can use media query with the smallest query eg media query
example:

<nav class="navbar navbar-default" role="navigation">
  <div class="navbar-header">
    <button type="button" class="navbar-toggle" data-toggle="collapse" data-target=".navbar-collapse">
      <span class="icon-bar"></span>
      <span class="icon-bar"></span>
      <span class="icon-bar"></span>
    </button>
  </div>
  <div class="navbar-collapse collapse">
    <ul class="nav navbar-nav">
        <li><a href="#">Left</a></li>
    </ul>
    <ul class="nav navbar-nav navbar-center">
        <li><a href="#">Center</a></li>
        <li><a href="#">Center</a></li>
      <li><a href="#">Center</a></li>
    </ul>
    <ul class="nav navbar-nav navbar-right">
        <li><a href="#">Right</a></li>
    </ul>
  </div>
</nav>

@media (min-width: 240px) {
  .navbar-nav.navbar-center {
    position: absolute;
    left: 50%;
    transform: translatex(-50%);
  }
</code>```

ContentLicense: CC BY-SA 3.0


问:
Logger for Unity3d that hooks up nicely with MonoDevelop
I want to write a central logger class for Unity3d project. Its pretty straight-forward if I were to print the console logs only. I would want it to look something like the following :

```<code>using System.Collections;
using System.Collections.Generic;
using UnityEngine;

//Consider this class is a Singleton, and is available to all other classes.
//I'm leaving the generic inheritance from something like Singleton<Logger> for simplicity

public class Logger : MonoBehaviour
{
    public enum LogLevel
    {
        Verbose,
        Debug,
        Warn,
        Error
    }

    public bool _enableLogs;

    public LogLevel _logLevel;

    public void Log(LogLevel logType, string msg)
    {
        if (!_enableLogs)
            return;

        // some logic to filter out messages below this "_logLevel".

        // Log the msg to console.
        Debug.Log (msg);
    }
}
</code>```

Normally when you double click a log message, it takes you to that line of code in the MonoDevelop file. How can I modify my code so that it links with the line of code producing it, like in a normal logger? Any help is greatly appreciated.

答:
There's a simple solution to what you want: compile your logger into a .DLL and include that .DLL in your project. Now, clicking on log messages should take you to the location you want.

I'm not sure why this works, but it's been known to work like that for a long time (we also have a custom logger that works like that).

Body:
I want to write a central logger class for Unity3d project. Its pretty straight-forward if I were to print the console logs only. I would want it to look something like the following :

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

//Consider this class is a Singleton, and is available to all other classes.
//I'm leaving the generic inheritance from something like Singleton<Logger> for simplicity

public class Logger : MonoBehaviour
{
    public enum LogLevel
    {
        Verbose,
        Debug,
        Warn,
        Error
    }

    public bool _enableLogs;

    public LogLevel _logLevel;

    public void Log(LogLevel logType, string msg)
    {
        if (!_enableLogs)
            return;

        // some logic to filter out messages below this "_logLevel".

        // Log the msg to console.
        Debug.Log (msg);
    }
}

Normally when you double click a log message, it takes you to that line of code in the MonoDevelop file. How can I modify my code so that it links with the line of code producing it, like in a normal logger? Any help is greatly appreciated.


问:
Passing object containing object from model to view in ASP.NET
Usin ASP.NET I am trying to add a list of profiles to a object in a model and then enumerate over this list in the view.

```<code>     public ActionResult Index(BlogPage currentPage)
    {
        var model = new BlogPageModel(currentPage);

        var pages = new List<BlogPage>();

        var profilePages = new List<ProfilePage>();
        if (currentPage.ProfileArea != null)
        {
            foreach (LinkItem linkItem in currentPage.ProfileArea)
            {
                var page = _pageDataHelper.GetPageData(linkItem);
                var profilePage = page as ProfilePage;
                if (profilePage != null)
                {
                    profilePages.Add(profilePage);
                }
            }
            model.Profiles = profilePages;
        }
        return View(model);
    }
</code>```

Using this code in the view:

```<code>   @foreach (ProfilePage profile in Model.BlogPages)
            {
            @Html.Partial("../ProfilePage/Index", new PageViewModel<ProfilePage>(profile))
            }
</code>```

However above code returns the error:

CS0030: Cannot convert type 'Models.Pages.BlogPage' to 'Models.Pages.ProfilePage'

Can someone point me the correct way to store a list inside a model and render this nested object in a view?

Thanks!

答:
You have a typo in your foreach loop:

```<code>@foreach (ProfilePage profile in Model.BlogPages)
{
    @Html.Partial("../ProfilePage/Index", new PageViewModel<ProfilePage>(profile))
}
</code>```

You are looping over the property BlogPages not the property Profiles that you set with a ProfilePage collection in your controller:

```<code>var pages = new List<BlogPage>();

var profilePages = new List<ProfilePage>();
if (currentPage.ProfileArea != null)
{
    ...shortened for length...
    model.Profiles = profilePages; // Right here is what you intended to loop over
}
</code>```

Body:
Usin ASP.NET I am trying to add a list of profiles to a object in a model and then enumerate over this list in the view.

     public ActionResult Index(BlogPage currentPage)
    {
        var model = new BlogPageModel(currentPage);

        var pages = new List<BlogPage>();

        var profilePages = new List<ProfilePage>();
        if (currentPage.ProfileArea != null)
        {
            foreach (LinkItem linkItem in currentPage.ProfileArea)
            {
                var page = _pageDataHelper.GetPageData(linkItem);
                var profilePage = page as ProfilePage;
                if (profilePage != null)
                {
                    profilePages.Add(profilePage);
                }
            }
            model.Profiles = profilePages;
        }
        return View(model);
    }

Using this code in the view:

   @foreach (ProfilePage profile in Model.BlogPages)
            {
            @Html.Partial("../ProfilePage/Index", new PageViewModel<ProfilePage>(profile))
            }

However above code returns the error:

CS0030: Cannot convert type 'Models.Pages.BlogPage' to 'Models.Pages.ProfilePage'

Can someone point me the correct way to store a list inside a model and render this nested object in a view?

Thanks!

Body:
You have a typo in your foreach loop:

@foreach (ProfilePage profile in Model.BlogPages)
{
    @Html.Partial("../ProfilePage/Index", new PageViewModel<ProfilePage>(profile))
}

You are looping over the property BlogPages not the property Profiles that you set with a ProfilePage collection in your controller:

var pages = new List<BlogPage>();

var profilePages = new List<ProfilePage>();
if (currentPage.ProfileArea != null)
{
    ...shortened for length...
    model.Profiles = profilePages; // Right here is what you intended to loop over
}


问:
Powershell force 5 digit format in a string pattern
So what I have now will (below) will search for XX-##-# and force it to XX-##-#0000.

How can I do this to return XX-##-0000#?

Is there a way to force 5 digits at the end, filling preceding 0s, to cover the other possibilities (XX-##-##, XX-##-###, XX-##-####)? As opposed to copying this 4 times, slightly adjusting for each.

```<code>$Pattern1 = '[a-zA-Z][a-zA-Z]-[0-9][0-9]-[0-9]'
Get-ChildItem 'C:\path\to\file\*.txt' -Recurse | ForEach {
     (Get-Content $_ |
     ForEach  { $_ -replace $Pattern1, ('$1'+'0000')}) |
     Set-Content $_
}
</code>```

Thanks.

EDIT: I would like to do the following

```<code>Search           Replacement
XX-##-#          XX-##-0000#
XX-##-##         XX-##-000##
XX-##-###        XX-##-00###
XX-##-####       XX-##-0####
</code>```

答:
This is ancillary information that should help you fix your current
  code and come to the correct conclusion.

https://technet.microsoft.com/en-us/library/ee692795.aspx

I recommend utilizing a combination of the techniques listed in this documentation.  The example provided is very helpful in numeric formatting:

```<code>$a = 348
"{0:N2}" -f $a
"{0:D8}" -f $a
"{0:C2}" -f $a
"{0:P0}" -f $a
"{0:X0}" -f $a

Output
348.00
00000348
$348.00
34,800 %
15C
</code>```

You can also utilize [String]::Format and add in some assertions to insure the item is formatted properly; If a specific value is not specified for example you could simply default it to 0.

https://blogs.technet.microsoft.com/heyscriptingguy/2013/03/11/understanding-powershell-and-basic-string-formatting/

Hope this helped.

Body:
So what I have now will (below) will search for XX-##-# and force it to XX-##-#0000.

How can I do this to return XX-##-0000#?

Is there a way to force 5 digits at the end, filling preceding 0s, to cover the other possibilities (XX-##-##, XX-##-###, XX-##-####)? As opposed to copying this 4 times, slightly adjusting for each.

$Pattern1 = '[a-zA-Z][a-zA-Z]-[0-9][0-9]-[0-9]'
Get-ChildItem 'C:\path\to\file\*.txt' -Recurse | ForEach {
     (Get-Content $_ |
     ForEach  { $_ -replace $Pattern1, ('$1'+'0000')}) |
     Set-Content $_
}

Thanks.

EDIT: I would like to do the following

Search           Replacement
XX-##-#          XX-##-0000#
XX-##-##         XX-##-000##
XX-##-###        XX-##-00###
XX-##-####       XX-##-0####

Body:
This is ancillary information that should help you fix your current
  code and come to the correct conclusion.

https://technet.microsoft.com/en-us/library/ee692795.aspx

I recommend utilizing a combination of the techniques listed in this documentation.  The example provided is very helpful in numeric formatting:

$a = 348
"{0:N2}" -f $a
"{0:D8}" -f $a
"{0:C2}" -f $a
"{0:P0}" -f $a
"{0:X0}" -f $a

Output
348.00
00000348
$348.00
34,800 %
15C

You can also utilize [String]::Format and add in some assertions to insure the item is formatted properly; If a specific value is not specified for example you could simply default it to 0.

https://blogs.technet.microsoft.com/heyscriptingguy/2013/03/11/understanding-powershell-and-basic-string-formatting/

Hope this helped.


问:
List of dates for given day of the week Swift
I need to get the List of dates for the given date of the week.

As an example :
If user select the random date from picker Like 2017-6-7,
I needs to get and display the dates of the week.
[2017-6-4, 2017-6-5, 2017-6-6, 2017-6-7, 2017-6-8, 2017-6-9, 2017-6-10]

I couldn't find any solution on the internet.

Thank you

答:
You can use this.

```<code> let today = Date()
  let  weekStartDate = today.getWeekStartDate(fromDate: today)
   for i in 0..<5 {
    let nextDate = weekStartDate?.getNextDay(value: i, currentDate:weekStartDate)
}

func getWeekStartDate(fromDate : Date?) -> Date? {

        let dateFormatter = DateFormatter()
        dateFormatter.dateFormat = "yyyy-MM-dd"

        if let date = fromDate {
            var calendar = Calendar(identifier: .gregorian)
            calendar.firstWeekday = 3
            var startDate : Date = Date()
            var interval : TimeInterval = 0

            if calendar.dateInterval(of: .weekOfYear, start: &startDate, interval: &interval, for: date) {
                print("Start of week is \(startDate)")
                // prints "Start of week is 2017-01-01 06:00:00 +0000"
                return startDate
            }
        }
        return nil
    }

     func getNextDay(value : Int, currentDate : Date?) -> Date? {

            let dayComponenet = NSDateComponents()
            dayComponenet.day = value

            let theCalendar = NSCalendar.current
            let nextDate = theCalendar.date(byAdding: dayComponenet as DateComponents, to: currentDate!)
            return nextDate

        }
</code>```

Hope this will help!.

Body:
You can use this.

 let today = Date()
  let  weekStartDate = today.getWeekStartDate(fromDate: today)
   for i in 0..<5 {
    let nextDate = weekStartDate?.getNextDay(value: i, currentDate:weekStartDate)
}

func getWeekStartDate(fromDate : Date?) -> Date? {

        let dateFormatter = DateFormatter()
        dateFormatter.dateFormat = "yyyy-MM-dd"

        if let date = fromDate {
            var calendar = Calendar(identifier: .gregorian)
            calendar.firstWeekday = 3
            var startDate : Date = Date()
            var interval : TimeInterval = 0

            if calendar.dateInterval(of: .weekOfYear, start: &startDate, interval: &interval, for: date) {
                print("Start of week is \(startDate)")
                // prints "Start of week is 2017-01-01 06:00:00 +0000"
                return startDate
            }
        }
        return nil
    }

     func getNextDay(value : Int, currentDate : Date?) -> Date? {

            let dayComponenet = NSDateComponents()
            dayComponenet.day = value

            let theCalendar = NSCalendar.current
            let nextDate = theCalendar.date(byAdding: dayComponenet as DateComponents, to: currentDate!)
            return nextDate

        }

Hope this will help!.


问:
In ns-3 simulator when to use p2p nodes, wifistanodes and csmanodes
I'm trying to use NS-3 simulator to do some tests between random waypoint model and some other models. While during the simulation I found that when need to run the simulation we need to initiate the model by using a class called

MobilityHelper

Code below is the part of the code that I am using. During the initialization, there are some nodes need to be created beforehand such as

p2pNodes

csmaNodes

So what do these nodes mean, and in which situation need to use them? Are they specify to some specific mobility models? If so please give some details, many thanks!

```<code>  NodeContainer p2pNodes;
  p2pNodes.Create (3);

  PointToPointHelper pointToPoint;
  pointToPoint.SetDeviceAttribute ("DataRate", StringValue ("5Mbps"));
  pointToPoint.SetChannelAttribute ("Delay", StringValue ("2ms"));

  NetDeviceContainer p2pDevices;
  p2pDevices = pointToPoint.Install (p2pNodes);

  NodeContainer csmaNodes;
  csmaNodes.Add (p2pNodes.Get (1));
  csmaNodes.Create (nCsma);

  CsmaHelper csma;
  csma.SetChannelAttribute ("DataRate", StringValue ("100Mbps"));
  csma.SetChannelAttribute ("Delay", TimeValue (NanoSeconds (6560)));

  NetDeviceContainer csmaDevices;
  csmaDevices = csma.Install (csmaNodes);
</code>```

答:
p2pNodes and csmaNodes are simply variable names for the NodeContainer used in this particular example in order to keep track of nodes for the two networks (the Point-to-Point and the CSMA). The fact that you named them p2pNodes and csmaNodes is only for your own convenience. What matters are the types of NetDevices that end up being installed on these nodes.

In any case, that has nothing to do with the MobilityModel that you install.
Both P2P and CSMA are wired networks and I wouldn't think of adding a random mobility on those. It wouldn't make sense to move around with a wire attached to you..!

Note that the above example code will crash, as you have created 3 p2pNodes, and a point-to-point link can only be instantiated between two nodes.

I would recommend studying the ns-3 tutorial to get an understanding of the concepts of Node, NodeContainer (ie. vectors of Nodes), NetDevice (ie. the network card/type), MobilityModel etc.

Body:
I'm trying to use NS-3 simulator to do some tests between random waypoint model and some other models. While during the simulation I found that when need to run the simulation we need to initiate the model by using a class called

MobilityHelper

Code below is the part of the code that I am using. During the initialization, there are some nodes need to be created beforehand such as

p2pNodes

csmaNodes

So what do these nodes mean, and in which situation need to use them? Are they specify to some specific mobility models? If so please give some details, many thanks!

  NodeContainer p2pNodes;
  p2pNodes.Create (3);

  PointToPointHelper pointToPoint;
  pointToPoint.SetDeviceAttribute ("DataRate", StringValue ("5Mbps"));
  pointToPoint.SetChannelAttribute ("Delay", StringValue ("2ms"));

  NetDeviceContainer p2pDevices;
  p2pDevices = pointToPoint.Install (p2pNodes);

  NodeContainer csmaNodes;
  csmaNodes.Add (p2pNodes.Get (1));
  csmaNodes.Create (nCsma);

  CsmaHelper csma;
  csma.SetChannelAttribute ("DataRate", StringValue ("100Mbps"));
  csma.SetChannelAttribute ("Delay", TimeValue (NanoSeconds (6560)));

  NetDeviceContainer csmaDevices;
  csmaDevices = csma.Install (csmaNodes);

ContentLicense: CC BY-SA 4.0


问:
C unsigned int x = 1; smaller than int y = -1;
i do know the differences of signed unsigened etc.
But i don´t understand the following code:

```<code>unsigned int x = 1;
int y = -1;
    if(y < x)
        printf("of course it is");
    else
        printf("strange stuff");
</code>```

1 should be a greater number than -1, no matter which representation is used. Because "strange stuff" will be displayed on the console.

答:
You're comparing an unsigned int with a signed int. You shouldn't do that. C fixes this by converting one of them to the type of the other. In this case it probably converts y to an unsigned int making it positive so x should be the same as y.

You sould make them both an int, or if it's really necessary you can cast the unsigned int to an int when comparing.

if(y<(int)x)

Body:
i do know the differences of signed unsigened etc.
But i don´t understand the following code:

unsigned int x = 1;
int y = -1;
    if(y < x)
        printf("of course it is");
    else
        printf("strange stuff");

1 should be a greater number than -1, no matter which representation is used. Because "strange stuff" will be displayed on the console.


问:
php Get the original key value in in_array multidimensional
I have a multidimensional array with some duplicate sub-arrays:

```<code> $data = array(
    2 => array  (
            'User'      => 'cat',
            'File_name' => 'cat.docx',
            'Document'  => 'Document1',
            'Date'      => '2017-03-02',
            'Pages'     => 1
        ),
    3 => array  (
            'User'      => 'dog',
            'File_name' => 'dog.docx',
            'Document'  => 'Document2',
            'Date'      => '2017-03-02',
            'Pages'     => 3
        ),
    4 => array  (
            'User'      => 'shark',
            'File_name' => 'shark.docx',
            'Document'  => 'Document3',
            'Date'      => '2017-03-01',
            'Pages'     => 5
        ),
    5 => array  (
            'User'      => 'dog',
            'File_name' => 'dog.docx',
            'Document'  => 'Document2',
            'Date'      => '2017-03-02',
            'Pages'     => 3
    ),
    6 => array  (
            'User'      => 'dog',
            'File_name' => 'dog.docx',
            'Document'  => 'Document2',
            'Date'      => '2017-03-02',
            'Pages'     => 3
    ),
    //...
);
</code>```

I could recognize which items are duplicated with:

```<code>$final = $dupli = array();
foreach ($data as $key => $array ) {
    if(!in_array($array, $final)){
        $final[$key] = $array;
    }
    else
    {
        $dupli[$key] = $array;
    }
}
print_r($dupli);
</code>```

But I would like to know what index was the first subarray (the key of this) found, as a message, for example:

```<code> $final = $dupli = array();
    foreach ($data as $key => $array ) {
        if(!in_array($array, $final)){
            $final[$key] = $array;
        }
        else
        {
            $dupli[$key] = $array;
            echo "Line " . $key . " duplicated row, the original row is: " . $originalkey;
        }
    }
</code>```

Output:

```<code>Line 5 duplicated row, the original row is: 3
Line 6 duplicated row, the original row is: 3
</code>```

答:
Using  array_search() along with loop you can simplify your code like below :

```<code>foreach($data as $index => $value)
{
    $key = array_search($value, $data);
    if($key!==false && $key != $index){
        printf("Line %d duplicated row, the original row is: %d\n",$index, $key);
    }
}
</code>```

Test results on CLI

Script

```<code>akshay@db-3325:/tmp$ cat test.php
<?php
$data = array(
    2 => array  (
            'User'      => 'cat',
            'File_name' => 'cat.docx',
            'Document'  => 'Document1',
            'Date'      => '2017-03-02',
            'Pages'     => 1
        ),
    3 => array  (
            'User'      => 'dog',
            'File_name' => 'dog.docx',
            'Document'  => 'Document2',
            'Date'      => '2017-03-02',
            'Pages'     => 3
        ),
    4 => array  (
            'User'      => 'shark',
            'File_name' => 'shark.docx',
            'Document'  => 'Document3',
            'Date'      => '2017-03-01',
            'Pages'     => 5
        ),
    5 => array  (
            'User'      => 'dog',
            'File_name' => 'dog.docx',
            'Document'  => 'Document2',
            'Date'      => '2017-03-02',
            'Pages'     => 3
    ),
    6 => array  (
            'User'      => 'dog',
            'File_name' => 'dog.docx',
            'Document'  => 'Document2',
            'Date'      => '2017-03-02',
            'Pages'     => 3
    ),
    //...
);

foreach($data as $index => $value)
{
    $key = array_search($value, $data);
    if($key!==false && $key != $index){
        printf("Line %d duplicated row, the original row is: %d\n",$index, $key);
    }
}

?>
</code>```

Output

```<code>akshay@db-3325:/tmp$ php test.php
Line 5 duplicated row, the original row is: 3
Line 6 duplicated row, the original row is: 3
</code>```

Body:
I have a multidimensional array with some duplicate sub-arrays:

 $data = array(
    2 => array  (
            'User'      => 'cat',
            'File_name' => 'cat.docx',
            'Document'  => 'Document1',
            'Date'      => '2017-03-02',
            'Pages'     => 1
        ),
    3 => array  (
            'User'      => 'dog',
            'File_name' => 'dog.docx',
            'Document'  => 'Document2',
            'Date'      => '2017-03-02',
            'Pages'     => 3
        ),
    4 => array  (
            'User'      => 'shark',
            'File_name' => 'shark.docx',
            'Document'  => 'Document3',
            'Date'      => '2017-03-01',
            'Pages'     => 5
        ),
    5 => array  (
            'User'      => 'dog',
            'File_name' => 'dog.docx',
            'Document'  => 'Document2',
            'Date'      => '2017-03-02',
            'Pages'     => 3
    ),
    6 => array  (
            'User'      => 'dog',
            'File_name' => 'dog.docx',
            'Document'  => 'Document2',
            'Date'      => '2017-03-02',
            'Pages'     => 3
    ),
    //...
);

I could recognize which items are duplicated with:

$final = $dupli = array();
foreach ($data as $key => $array ) {
    if(!in_array($array, $final)){
        $final[$key] = $array;
    }
    else
    {
        $dupli[$key] = $array;
    }
}
print_r($dupli);

But I would like to know what index was the first subarray (the key of this) found, as a message, for example:

 $final = $dupli = array();
    foreach ($data as $key => $array ) {
        if(!in_array($array, $final)){
            $final[$key] = $array;
        }
        else
        {
            $dupli[$key] = $array;
            echo "Line " . $key . " duplicated row, the original row is: " . $originalkey;
        }
    }

Output:

Line 5 duplicated row, the original row is: 3
Line 6 duplicated row, the original row is: 3

Body:
Using  array_search() along with loop you can simplify your code like below :

foreach($data as $index => $value)
{
    $key = array_search($value, $data);
    if($key!==false && $key != $index){
        printf("Line %d duplicated row, the original row is: %d\n",$index, $key);
    }
}

Test results on CLI

Script

akshay@db-3325:/tmp$ cat test.php
<?php
$data = array(
    2 => array  (
            'User'      => 'cat',
            'File_name' => 'cat.docx',
            'Document'  => 'Document1',
            'Date'      => '2017-03-02',
            'Pages'     => 1
        ),
    3 => array  (
            'User'      => 'dog',
            'File_name' => 'dog.docx',
            'Document'  => 'Document2',
            'Date'      => '2017-03-02',
            'Pages'     => 3
        ),
    4 => array  (
            'User'      => 'shark',
            'File_name' => 'shark.docx',
            'Document'  => 'Document3',
            'Date'      => '2017-03-01',
            'Pages'     => 5
        ),
    5 => array  (
            'User'      => 'dog',
            'File_name' => 'dog.docx',
            'Document'  => 'Document2',
            'Date'      => '2017-03-02',
            'Pages'     => 3
    ),
    6 => array  (
            'User'      => 'dog',
            'File_name' => 'dog.docx',
            'Document'  => 'Document2',
            'Date'      => '2017-03-02',
            'Pages'     => 3
    ),
    //...
);

foreach($data as $index => $value)
{
    $key = array_search($value, $data);
    if($key!==false && $key != $index){
        printf("Line %d duplicated row, the original row is: %d\n",$index, $key);
    }
}

?>

Output

akshay@db-3325:/tmp$ php test.php
Line 5 duplicated row, the original row is: 3
Line 6 duplicated row, the original row is: 3


问:
Double check my IF AND OR statement
is this logical... If $dirchk1 and $dirchk2 exist or if just $dirchk1 exist continue processing. But if only $dirchk2 exist then process else statement. Thanks in advance

```<code>$dirchk1 = "/temp/files/" . $data[0] . ".doc";
$dirchk2 = "/temp/files/" . $data[1] . ".doc";
    if (is_file($dirchk1) && is_file($dirchk2)) || (is_file($dirchk1)) {
//.. do code
    } else {
    ...// only $dirchk2 exist
    }
</code>```

EDIT: sorry I failed to mention that if $dirchk1 and $dirchk2 DO NOT exist then the else statement should process.

答:
No, I don't think that's right. There's no check for dirchk2 on the else case, and your if case is ($1 && $2) || $1 would reorder into $1 && ($2 || true) == $1 with no $2 check. You probably want

```<code>if (is_file($dirchk1)) {
    //.. do code
} elseif (is_file($dirchk2)) {
    // only $dirchk2 exist
}
</code>```

Title: Double check my IF AND OR statement

Body:
is this logical... If $dirchk1 and $dirchk2 exist or if just $dirchk1 exist continue processing. But if only $dirchk2 exist then process else statement. Thanks in advance

$dirchk1 = "/temp/files/" . $data[0] . ".doc";
$dirchk2 = "/temp/files/" . $data[1] . ".doc";
    if (is_file($dirchk1) && is_file($dirchk2)) || (is_file($dirchk1)) {
//.. do code
    } else {
    ...// only $dirchk2 exist
    }

EDIT: sorry I failed to mention that if $dirchk1 and $dirchk2 DO NOT exist then the else statement should process.

Body:
No, I don't think that's right. There's no check for dirchk2 on the else case, and your if case is ($1 && $2) || $1 would reorder into $1 && ($2 || true) == $1 with no $2 check. You probably want

if (is_file($dirchk1)) {
    //.. do code
} elseif (is_file($dirchk2)) {
    // only $dirchk2 exist
}


问:
JavaFx: How to update text of dynimically created TextFields inside GridPane?
I'm developing an app in JavaFx, in which which I'm dynamically creating TextFeids and CheckBoxes inside GridPane like this:

I'm adding numbers which user will enter in TextField 1 and TextField 2 and displaying in TextField 3 like this using listener:

Problem: What I want is when user will check the CheckBox it should add 10 to the value already present in the TextField 3 of (same row as of triggered CheckBox) and update the text of TextField 3, and when user will uncheck the CheckBox it should subtract 10 from the value present in the TextField 3 of (same row as of triggered CheckBox) and update the text of TextField 3. I tried to do it but it's not working (not adding and removing):

This is how I'm creating GridPane:

```<code> public static GridPane table(int rows){
        GridPane table = new GridPane();

        for(int i=0; i<rows; i++){
            TextField textField = new TextField();
            textField.setAlignment(Pos.CENTER);
            TextField textField2 = new TextField();
            textField2.setAlignment(Pos.CENTER);
            CheckBox checkBox = new CheckBox("Check Box");
            checkBox.setTextFill(Color.WHITE);
            checkBox.setAlignment(Pos.CENTER);
            TextField textField3 = new TextField();
            textField3.setAlignment(Pos.CENTER);

            table.add(textField, 0, i);
            table.add(textField2, 1, i);
            table.add(checkBox , 2, i);
            table.add(textField3,3, i);

            GridPane.setMargin(textField, new Insets(5));
            GridPane.setMargin(textField2, new Insets(5));
            GridPane.setMargin(checkBox, new Insets(5));
            GridPane.setMargin(textField3, new Insets(5));
         }
        table.setAlignment(Pos.CENTER);

        return table;
    }
</code>```

A method to return a component from Table at specific row and column

```<code>public static Node getComponent (int row, int column, GridPane table) {
     for (Node component : table.getChildren()) {
         if(GridPane.getRowIndex(component) == row &&
                         GridPane.getColumnIndex(component) == column) {
             return component;
         }
     }

     return null;
 }
</code>```

This is how I'm adding:

```<code>    public void add(GridPane table, int numRows){

       for(int i=0; i<numRows; i++){
           try {

                int valueA = Integer.parseInt(((TextField)(getComponent (i, 0, table))).getText());
                System.out.println(valueA);
                int valueB = Integer.parseInt(((TextField)(getComponent (i, 1, table))).getText());
                System.out.println(valueB);

                int add = valueA+valueB;

                String addToString = Integer.toString(add);

                ((TextField)(getComponent (i, 3, table))).setText(addToString);

                } catch (NullPointerException e) {
                  System.out.print("Caught the NullPointerException");
                    }
       }

    }
</code>```

Problem: Addition and subtraction using CheckBox:

```<code>     public void addPause(GridPane table, int numRows){

                for(int i=0; i<numRows; i++){

                boolean pause = ((CheckBox)(getComponent (i, 2, table))).isSelected();
                int getTextValue = Integer.parseInt(((TextField)(getComponent (i, 3, table))).getText());

                int addPause = getTextValue+10;
                int removePause = addPause-10;

                String addPToString = Integer.toString(addPause);
                String removePToString = Integer.toString(removePause);

                if (pause) {
                    ((TextField)(getComponent (i, 3, table))).setText(addPToString);
                } else {
                    ((TextField)(getComponent (i, 3, table))).setText(removePToString);
                }
       }
    }
</code>```

This is how I'm triggering using listeners:

```<code>        for(Node node : table.getChildren()){
          if(node instanceof TextField){
             ((TextField)node).textProperty().addListener((obs, old, newV)->{
               add(table, numRows);
           });
         }
          else if(node instanceof CheckBox){
              ((CheckBox)node).selectedProperty().addListener((obs, old, newV)->{
                addPause(table, numRows);
             });
           }
       }
</code>```

答:
One way to achieve that is by adding a ChangeListener to every CheckBox in the Table(GridPane), something like this:

```<code>/**
* This method to change the current value of the TextField at
* column 3 in the Table(GridPane) by ten
* @param table
*/
private static void changeByTen(GridPane table){
   // loop through every node in the GridPane
   for(Node node : table.getChildren()){
       // and for every CheckBox
       if(node instanceof CheckBox){
          // add change listener to the Selected Property
          ((CheckBox)node).selectedProperty().addListener((obs, unSelected, selected)->{
              // get the TextField at third column that corresponds to this CehckBox
              TextField targetTextFeild =
                      ((TextField)getComponent(GridPane.getRowIndex(node), 3, table));
              try{// then try to add/subtract
                  if(selected){// if checked add 10
                     targetTextFeild.setText(String.valueOf(
                         Integer.parseInt(targetTextFeild.getText())+10));
                  }
                  else if(!selected){ // if unchecked subtract 10
                          targetTextFeild.setText(String.valueOf(
                           Integer.parseInt(targetTextFeild.getText())-10));
                  }
               }catch(Exception e){// do nothing}
           });
        }
    }
}
</code>```

Then add this method in the tabPane ChangeListener:

```<code>tabPane.getSelectionModel().selectedItemProperty().addListener(new ChangeListener<Tab>(){
    ......
    ......
    // I think you have here anchorPane not containerB in the original code
    changeByTen((GridPane) containerB.getChildren().get(0));
}
</code>```

Test

Body:
I'm developing an app in JavaFx, in which which I'm dynamically creating TextFeids and CheckBoxes inside GridPane like this:

I'm adding numbers which user will enter in TextField 1 and TextField 2 and displaying in TextField 3 like this using listener:

Problem: What I want is when user will check the CheckBox it should add 10 to the value already present in the TextField 3 of (same row as of triggered CheckBox) and update the text of TextField 3, and when user will uncheck the CheckBox it should subtract 10 from the value present in the TextField 3 of (same row as of triggered CheckBox) and update the text of TextField 3. I tried to do it but it's not working (not adding and removing):

This is how I'm creating GridPane:

 public static GridPane table(int rows){
        GridPane table = new GridPane();

        for(int i=0; i<rows; i++){
            TextField textField = new TextField();
            textField.setAlignment(Pos.CENTER);
            TextField textField2 = new TextField();
            textField2.setAlignment(Pos.CENTER);
            CheckBox checkBox = new CheckBox("Check Box");
            checkBox.setTextFill(Color.WHITE);
            checkBox.setAlignment(Pos.CENTER);
            TextField textField3 = new TextField();
            textField3.setAlignment(Pos.CENTER);

            table.add(textField, 0, i);
            table.add(textField2, 1, i);
            table.add(checkBox , 2, i);
            table.add(textField3,3, i);

            GridPane.setMargin(textField, new Insets(5));
            GridPane.setMargin(textField2, new Insets(5));
            GridPane.setMargin(checkBox, new Insets(5));
            GridPane.setMargin(textField3, new Insets(5));
         }
        table.setAlignment(Pos.CENTER);

        return table;
    }

A method to return a component from Table at specific row and column

public static Node getComponent (int row, int column, GridPane table) {
     for (Node component : table.getChildren()) {
         if(GridPane.getRowIndex(component) == row &&
                         GridPane.getColumnIndex(component) == column) {
             return component;
         }
     }

     return null;
 }

This is how I'm adding:

    public void add(GridPane table, int numRows){

       for(int i=0; i<numRows; i++){
           try {

                int valueA = Integer.parseInt(((TextField)(getComponent (i, 0, table))).getText());
                System.out.println(valueA);
                int valueB = Integer.parseInt(((TextField)(getComponent (i, 1, table))).getText());
                System.out.println(valueB);

                int add = valueA+valueB;

                String addToString = Integer.toString(add);

                ((TextField)(getComponent (i, 3, table))).setText(addToString);

                } catch (NullPointerException e) {
                  System.out.print("Caught the NullPointerException");
                    }
       }

    }

Problem: Addition and subtraction using CheckBox:

     public void addPause(GridPane table, int numRows){

                for(int i=0; i<numRows; i++){

                boolean pause = ((CheckBox)(getComponent (i, 2, table))).isSelected();
                int getTextValue = Integer.parseInt(((TextField)(getComponent (i, 3, table))).getText());

                int addPause = getTextValue+10;
                int removePause = addPause-10;

                String addPToString = Integer.toString(addPause);
                String removePToString = Integer.toString(removePause);

                if (pause) {
                    ((TextField)(getComponent (i, 3, table))).setText(addPToString);
                } else {
                    ((TextField)(getComponent (i, 3, table))).setText(removePToString);
                }
       }
    }

This is how I'm triggering using listeners:

        for(Node node : table.getChildren()){
          if(node instanceof TextField){
             ((TextField)node).textProperty().addListener((obs, old, newV)->{
               add(table, numRows);
           });
         }
          else if(node instanceof CheckBox){
              ((CheckBox)node).selectedProperty().addListener((obs, old, newV)->{
                addPause(table, numRows);
             });
           }
       }

Body:
One way to achieve that is by adding a ChangeListener to every CheckBox in the Table(GridPane), something like this:

/**
* This method to change the current value of the TextField at
* column 3 in the Table(GridPane) by ten
* @param table
*/
private static void changeByTen(GridPane table){
   // loop through every node in the GridPane
   for(Node node : table.getChildren()){
       // and for every CheckBox
       if(node instanceof CheckBox){
          // add change listener to the Selected Property
          ((CheckBox)node).selectedProperty().addListener((obs, unSelected, selected)->{
              // get the TextField at third column that corresponds to this CehckBox
              TextField targetTextFeild =
                      ((TextField)getComponent(GridPane.getRowIndex(node), 3, table));
              try{// then try to add/subtract
                  if(selected){// if checked add 10
                     targetTextFeild.setText(String.valueOf(
                         Integer.parseInt(targetTextFeild.getText())+10));
                  }
                  else if(!selected){ // if unchecked subtract 10
                          targetTextFeild.setText(String.valueOf(
                           Integer.parseInt(targetTextFeild.getText())-10));
                  }
               }catch(Exception e){// do nothing}
           });
        }
    }
}

Then add this method in the tabPane ChangeListener:

tabPane.getSelectionModel().selectedItemProperty().addListener(new ChangeListener<Tab>(){
    ......
    ......
    // I think you have here anchorPane not containerB in the original code
    changeByTen((GridPane) containerB.getChildren().get(0));
}

Test


问:
Load image with Glide for AppWidget
I'm working on my first app widget.
Everthing is fine except one thing. I can't find out, how can I load image into ImageView at RemoteViewsFactroy's getViewAt() method with Glide. I allways get error, because I've to run into(AppWidgetTarget) at MainThread, but I can't call new Handler(Looper.getMainLooper()) from RemoteViewsFactory.</p>

答:
Glide has support for this by providing the AppWidgetTarget class.

While updating your widget in onUpdate(), you create a new AppWidgetTarget, pass it the RemoteViews object, the id of your image view, and the appwidgetId and then invoke glide in nearly the same way as you would for an imageview in your app.

```<code>    appWidgetTarget = new AppWidgetTarget( context, rv, R.id.custom_view_image, appWidgetIds );

    Glide
            .with( context.getApplicationContext() ) // safer!
            .load( GlideExampleActivity.eatFoodyImages[3] )
            .asBitmap()
            .into( appWidgetTarget );
</code>```

Example code above taken from this wonderful set of glide tutorials.  The tutorials cover many practical aspects of using glide.

Similarly, a NotificationTarget target class is also provided by glide - it solves the same problem, but for notifications instead of appWidgets.

Title: Load image with Glide for AppWidget

Body:
Glide has support for this by providing the AppWidgetTarget class.

While updating your widget in onUpdate(), you create a new AppWidgetTarget, pass it the RemoteViews object, the id of your image view, and the appwidgetId and then invoke glide in nearly the same way as you would for an imageview in your app.

    appWidgetTarget = new AppWidgetTarget( context, rv, R.id.custom_view_image, appWidgetIds );

    Glide
            .with( context.getApplicationContext() ) // safer!
            .load( GlideExampleActivity.eatFoodyImages[3] )
            .asBitmap()
            .into( appWidgetTarget );

Example code above taken from this wonderful set of glide tutorials.  The tutorials cover many practical aspects of using glide.

Similarly, a NotificationTarget target class is also provided by glide - it solves the same problem, but for notifications instead of appWidgets.


问:
Passing a large const struct to a function
Let's say I compile the following with GCC 5.4 with -O2 or -O3 level of optimization.

```<code>typedef struct {
  int data[90];
} huge_t;

int foo( const huge_t bar );

// ...

huge_t x = { 0 };
foo(x);
</code>```

Here, I would venture to say is not necessary to create a second copy of x on the stack because foo is not (supposed to be) modifying its argument. (When) will GCC come to the same conclusion?

In other words, is it ok for me to work with const arguments of type huge_t for convenience, or should I be using pointers? I could imagine both versions being "good style" in one sense or the other and would very much appreciate an informed opinion.

答:
If you look here:  Why isn't pass struct by reference a common optimization?

Its very unlikely that any C compiler will make this optimisation.  It's generally not a safe thing to do.

Never assume your optimiser will do things the way you want.  Optimisers have to conform to certain rules so that they never break your code.  Sometimes you know something is safe when the optimiser cant.  If, for performance, you need your code to behave a certain way then write it that way.

Body:
Let's say I compile the following with GCC 5.4 with -O2 or -O3 level of optimization.

typedef struct {
  int data[90];
} huge_t;

int foo( const huge_t bar );

// ...

huge_t x = { 0 };
foo(x);

Here, I would venture to say is not necessary to create a second copy of x on the stack because foo is not (supposed to be) modifying its argument. (When) will GCC come to the same conclusion?

In other words, is it ok for me to work with const arguments of type huge_t for convenience, or should I be using pointers? I could imagine both versions being "good style" in one sense or the other and would very much appreciate an informed opinion.


问:
Working through ES6 Katas, extending promises
I'm trying to extend these two promises:

```<code>   it('using `class X extends Promise{}` is possible', function() {
  class MyPromise extends Promise {
    constructor()
    {
      super();
    }
  };
  const mypromise = new MyPromise((resolve) => resolve());

  promise
    .then(() => done())
    .catch(e => done(new Error('Expected to resolve, but failed with: ' + e)));
});

it('must call `super()` in the constructor if it wants to inherit/specialize the behavior', function() {
  class ResolvingPromise extends Promise {
    constructor() {
    super();
    }}

  return new ResolvingPromise((resolve) => resolve());
});

});
</code>```

and am receiving this error:

"Constructor Promise requires 'new'"

I'm using 'new', so what does it want from me?

答:
This seems to be the answer</p>

```<code>it('must call `super()` in the constructor if it wants to inherit/specialize the behavior', function() {
      class ResolvingPromise extends Promise {
        constructor(resolve) {
          super(resolve);
        }
      }

      return new ResolvingPromise((resolve) => resolve());
    });
</code>```

Body:
I'm trying to extend these two promises:

   it('using `class X extends Promise{}` is possible', function() {
  class MyPromise extends Promise {
    constructor()
    {
      super();
    }
  };
  const mypromise = new MyPromise((resolve) => resolve());

  promise
    .then(() => done())
    .catch(e => done(new Error('Expected to resolve, but failed with: ' + e)));
});

it('must call `super()` in the constructor if it wants to inherit/specialize the behavior', function() {
  class ResolvingPromise extends Promise {
    constructor() {
    super();
    }}

  return new ResolvingPromise((resolve) => resolve());
});

});

and am receiving this error:

"Constructor Promise requires 'new'"

I'm using 'new', so what does it want from me?

Body:
This seems to be the answer

it('must call `super()` in the constructor if it wants to inherit/specialize the behavior', function() {
      class ResolvingPromise extends Promise {
        constructor(resolve) {
          super(resolve);
        }
      }

      return new ResolvingPromise((resolve) => resolve());
    });


问:
Java CSV Formatting Issues
I am reading a HashMap and creating a CSV file.
The below code accepts a HashMap and produce a CSV file. However the formatting is a problem. For a HashMap,

```<code>HashMap<String, Integer> hmap = new HashMap<String, Integer>();
hmap.put("Feature1", 1);
hmap.put("Feature2", 2);
</code>```

It produces

```<code>Feature2,Feature2,
2,1,Feature1,Feature1,
2,1,
</code>```

Expected Output (without comma at the end of each line):

```<code>Feature2,Feature1
2,1
</code>```

Which is  a wrong formatting

This is the code I use. How to fix it ?

```<code>public String appendCSV(Map featureset) throws IOException{
    StringBuilder csvReport = new StringBuilder();

    Map<String, Integer> map =featureset;
    Set<String> keys = map.keySet();

    String[] lsitofkeys = {};

    for(String elements:keys){
        for(int i =0 ; i< keys.size(); i++){
             csvReport.append(elements+",");
        }
        csvReport.append("\n");
        for(String key: keys){
            csvReport.append(map.get(key).toString()+",");
        }
    }

  return csvReport.toString();
}
</code>```

答: Just remote the last character of your string if it is longer than 1 character. Here is how to do it: str.substring(0, str.length() - 1);

Title: Java CSV Formatting Issues

Body:
I am reading a HashMap and creating a CSV file.
The below code accepts a HashMap and produce a CSV file. However the formatting is a problem. For a HashMap,

HashMap<String, Integer> hmap = new HashMap<String, Integer>();
hmap.put("Feature1", 1);
hmap.put("Feature2", 2);

It produces

Feature2,Feature2,
2,1,Feature1,Feature1,
2,1,

Expected Output (without comma at the end of each line):

Feature2,Feature1
2,1

Which is  a wrong formatting

This is the code I use. How to fix it ?

public String appendCSV(Map featureset) throws IOException{
    StringBuilder csvReport = new StringBuilder();

    Map<String, Integer> map =featureset;
    Set<String> keys = map.keySet();

    String[] lsitofkeys = {};

    for(String elements:keys){
        for(int i =0 ; i< keys.size(); i++){
             csvReport.append(elements+",");
        }
        csvReport.append("\n");
        for(String key: keys){
            csvReport.append(map.get(key).toString()+",");
        }
    }

  return csvReport.toString();
}


问:
WebLogic doesn't use contextpath for loading javascript files
I created one war which contains my backend application(Spring Boot) and frontend(Angular2). In frontend application i use Angular CLI for creating distribution files.

I need to deploy this war to WebLogic application server.

For building frontend project, i run"ng build" command through exec-maven-plugin.

```<code><plugin>
    <groupId>org.codehaus.mojo</groupId>
    <artifactId>exec-maven-plugin</artifactId>
    <version>1.5.0</version>
    <executions>
        <execution>
            <id>exec-npm-install</id>
            <phase>generate-sources</phase>
            <configuration>
                <workingDirectory>${project.basedir}/src/main/ngapp</workingDirectory>
                <executable>npm.cmd</executable>
                <arguments>
                    <argument>install</argument>
                </arguments>
            </configuration>
            <goals>
                <goal>exec</goal>
            </goals>
        </execution>
        <execution>
            <id>exec-npm-ng-build</id>
            <phase>generate-sources</phase>
            <configuration>
                <workingDirectory>${project.basedir}/src/main/ngapp</workingDirectory>
                <executable>ng.cmd</executable>
                <arguments>
                    <argument>build</argument>
                    <argument>--base-href=/applicationName</argument>
                </arguments>
            </configuration>
            <goals>
                <goal>exec</goal>
            </goals>
        </execution>
    </executions>
</plugin>
</code>```

Content of index.html:

```<code><!doctype html>
<html>
<head>
  <meta charset="utf-8">
  <title>CometTest</title>
  <base href="/applicationName">

  <meta name="viewport" content="width=device-width, initial-scale=1">
  <link rel="icon" type="image/x-icon" href="favicon.ico">
</head>
<body>
  <app>Loading...</app>
<script type="text/javascript" src="inline.bundle.js"></script><script type="text/javascript" src="polyfills.bundle.js"></script><script type="text/javascript" src="scripts.bundle.js"></script><script type="text/javascript" src="styles.bundle.js"></script><script type="text/javascript" src="vendor.bundle.js"></script><script type="text/javascript" src="main.bundle.js"></script></body>
</html>
</code>```

When i deployed resulting war to Tomcat with contextPath='applicationName' on my local machine, it's working fine.

But when i deployed to remote WebLogic it throws error while loading javascript files.

```<code>Failed to load resource: the server responded with a status of 404 (Not Found) http://24.211.213.46:7611/inline.bundle.js
</code>```

Why does WebLogic try to download files without applicationName in url?

And i can reach this javascript file by following url:

```<code>http://24.211.213.46:7611/applicationName/inline.bundle.js
</code>```

答:
I had this same issue. I was able to fix it by changing the routing strategy to use a hash like so:</p>

```<code>imports: [RouterModule.forRoot(APP_ROUTES, { useHash: true })]
</code>```

Body:
I created one war which contains my backend application(Spring Boot) and frontend(Angular2). In frontend application i use Angular CLI for creating distribution files.

I need to deploy this war to WebLogic application server.

For building frontend project, i run"ng build" command through exec-maven-plugin.

<plugin>
    <groupId>org.codehaus.mojo</groupId>
    <artifactId>exec-maven-plugin</artifactId>
    <version>1.5.0</version>
    <executions>
        <execution>
            <id>exec-npm-install</id>
            <phase>generate-sources</phase>
            <configuration>
                <workingDirectory>${project.basedir}/src/main/ngapp</workingDirectory>
                <executable>npm.cmd</executable>
                <arguments>
                    <argument>install</argument>
                </arguments>
            </configuration>
            <goals>
                <goal>exec</goal>
            </goals>
        </execution>
        <execution>
            <id>exec-npm-ng-build</id>
            <phase>generate-sources</phase>
            <configuration>
                <workingDirectory>${project.basedir}/src/main/ngapp</workingDirectory>
                <executable>ng.cmd</executable>
                <arguments>
                    <argument>build</argument>
                    <argument>--base-href=/applicationName</argument>
                </arguments>
            </configuration>
            <goals>
                <goal>exec</goal>
            </goals>
        </execution>
    </executions>
</plugin>

Content of index.html:

<!doctype html>

  <meta charset="utf-8">
  <title>CometTest</title>
  <base href="/applicationName">

  <meta name="viewport" content="width=device-width, initial-scale=1">
  <link rel="icon" type="image/x-icon" href="favicon.ico">

  <app>Loading...</app>

When i deployed resulting war to Tomcat with contextPath='applicationName' on my local machine, it's working fine.

But when i deployed to remote WebLogic it throws error while loading javascript files.

Failed to load resource: the server responded with a status of 404 (Not Found) http://24.211.213.46:7611/inline.bundle.js

Why does WebLogic try to download files without applicationName in url?

And i can reach this javascript file by following url:

http://24.211.213.46:7611/applicationName/inline.bundle.js

Body:
I had this same issue. I was able to fix it by changing the routing strategy to use a hash like so:

imports: [RouterModule.forRoot(APP_ROUTES, { useHash: true })]


问:
OpenTSDB integration with kerberized HBase
I want to do some POC on OpenTSDB. I have installed OpenTSDB as per the installation instruction, but having a tough time starting it. I am using HDP environment which is Kerberos enabled, I am integrating OpenTSDB with Kerberized HBase but facing below exception. If anybody have integrated OpenTSDB with Kerberos HBase, please guide..

Exception:

```<code> 2017-06-07 14:07:14,254 INFO  [main-SendThread(ZKIP1:2181)] ClientCnxn: Opening socket connection to server ZKIP1/192.xxx.xxx.xxx:2181. Will not attempt to authenticate using SASL (unknown error)
</code>```

Console O/P:

```<code>    2017-06-07 14:07:14,233 INFO  [main] ZooKeeper: Client environment:java.library.path=/usr/local/hawq/./lib:/usr/local/hawq/./ext/python/lib::/usr/java/packages/lib/amd64:/usr/lib64:/lib64:/lib:/usr/lib
    2017-06-07 14:07:14,233 INFO  [main] ZooKeeper: Client environment:java.io.tmpdir=/tmp
    2017-06-07 14:07:14,233 INFO  [main] ZooKeeper: Client environment:java.compiler=<NA>
    2017-06-07 14:07:14,233 INFO  [main] ZooKeeper: Client environment:os.name=Linux
    2017-06-07 14:07:14,233 INFO  [main] ZooKeeper: Client environment:os.arch=amd64
    2017-06-07 14:07:14,233 INFO  [main] ZooKeeper: Client environment:os.version=2.6.32-431.29.2.el6.x86_64
    2017-06-07 14:07:14,234 INFO  [main] ZooKeeper: Client environment:user.name=user
    2017-06-07 14:07:14,234 INFO  [main] ZooKeeper: Client environment:user.home=/home/user
    2017-06-07 14:07:14,234 INFO  [main] ZooKeeper: Client environment:user.dir=/home/user/opentsdb-2.3.0
    2017-06-07 14:07:14,235 INFO  [main] ZooKeeper: Initiating client connection, connectString=ZKIP1:2181,ZKIP3:2181,ZKIP2:2181 sessionTimeout=5000 watcher=org.hbase.async.HBaseClient$ZKClient@63d6a00c
 2017-06-07 14:07:14,254 INFO  [main-SendThread(ZKIP1:2181)] ClientCnxn: Opening socket connection to server ZKIP1/192.xxx.xxx.xxx:2181. Will not attempt to authenticate using SASL (unknown error)
    2017-06-07 14:07:14,257 INFO  [main] HBaseClient: Need to find the -ROOT- region
    2017-06-07 14:07:14,263 INFO  [main-SendThread(ZKIP1:2181)] ClientCnxn: Socket connection established to ZKIP1/192.xxx.xxx.xxx:2181, initiating session
    2017-06-07 14:07:14,270 INFO  [main-SendThread(ZKIP1:2181)] ClientCnxn: Session establishment complete on server ZKIP1/192.xxx.xxx.xxx:2181, sessionid = 0x35ae21cf9870828, negotiated timeout = 5000
    2017-06-07 14:07:14,285 ERROR [main-EventThread] HBaseClient: The znode for the -ROOT- region doesn't exist!
    2017-06-07 14:07:15,310 ERROR [main-EventThread] HBaseClient: The znode for the -ROOT- region doesn't exist!
    2017-06-07 14:07:16,329 ERROR [main-EventThread] HBaseClient: The znode for the -ROOT- region doesn't exist!
    2017-06-07 14:07:17,349 ERROR [main-EventThread] HBaseClient: The znode for the -ROOT- region doesn't exist!
    2017-06-07 14:07:18,370 ERROR [main-EventThread] HBaseClient: The znode for the -ROOT- region doesn't exist!
</code>```

答: You might find the following steps useful. Both databases connect to HBase from a Java client, although the Java client in OpenTSDB might be different.</p>

Body:
I want to do some POC on OpenTSDB. I have installed OpenTSDB as per the installation instruction, but having a tough time starting it. I am using HDP environment which is Kerberos enabled, I am integrating OpenTSDB with Kerberized HBase but facing below exception. If anybody have integrated OpenTSDB with Kerberos HBase, please guide..

Exception:

 2017-06-07 14:07:14,254 INFO  [main-SendThread(ZKIP1:2181)] ClientCnxn: Opening socket connection to server ZKIP1/192.xxx.xxx.xxx:2181. Will not attempt to authenticate using SASL (unknown error)

Console O/P:

    2017-06-07 14:07:14,233 INFO  [main] ZooKeeper: Client environment:java.library.path=/usr/local/hawq/./lib:/usr/local/hawq/./ext/python/lib::/usr/java/packages/lib/amd64:/usr/lib64:/lib64:/lib:/usr/lib
    2017-06-07 14:07:14,233 INFO  [main] ZooKeeper: Client environment:java.io.tmpdir=/tmp
    2017-06-07 14:07:14,233 INFO  [main] ZooKeeper: Client environment:java.compiler=<NA>
    2017-06-07 14:07:14,233 INFO  [main] ZooKeeper: Client environment:os.name=Linux
    2017-06-07 14:07:14,233 INFO  [main] ZooKeeper: Client environment:os.arch=amd64
    2017-06-07 14:07:14,233 INFO  [main] ZooKeeper: Client environment:os.version=2.6.32-431.29.2.el6.x86_64
    2017-06-07 14:07:14,234 INFO  [main] ZooKeeper: Client environment:user.name=user
    2017-06-07 14:07:14,234 INFO  [main] ZooKeeper: Client environment:user.home=/home/user
    2017-06-07 14:07:14,234 INFO  [main] ZooKeeper: Client environment:user.dir=/home/user/opentsdb-2.3.0
    2017-06-07 14:07:14,235 INFO  [main] ZooKeeper: Initiating client connection, connectString=ZKIP1:2181,ZKIP3:2181,ZKIP2:2181 sessionTimeout=5000 watcher=org.hbase.async.HBaseClient$ZKClient@63d6a00c
 2017-06-07 14:07:14,254 INFO  [main-SendThread(ZKIP1:2181)] ClientCnxn: Opening socket connection to server ZKIP1/192.xxx.xxx.xxx:2181. Will not attempt to authenticate using SASL (unknown error)
    2017-06-07 14:07:14,257 INFO  [main] HBaseClient: Need to find the -ROOT- region
    2017-06-07 14:07:14,263 INFO  [main-SendThread(ZKIP1:2181)] ClientCnxn: Socket connection established to ZKIP1/192.xxx.xxx.xxx:2181, initiating session
    2017-06-07 14:07:14,270 INFO  [main-SendThread(ZKIP1:2181)] ClientCnxn: Session establishment complete on server ZKIP1/192.xxx.xxx.xxx:2181, sessionid = 0x35ae21cf9870828, negotiated timeout = 5000
    2017-06-07 14:07:14,285 ERROR [main-EventThread] HBaseClient: The znode for the -ROOT- region doesn't exist!
    2017-06-07 14:07:15,310 ERROR [main-EventThread] HBaseClient: The znode for the -ROOT- region doesn't exist!
    2017-06-07 14:07:16,329 ERROR [main-EventThread] HBaseClient: The znode for the -ROOT- region doesn't exist!
    2017-06-07 14:07:17,349 ERROR [main-EventThread] HBaseClient: The znode for the -ROOT- region doesn't exist!
    2017-06-07 14:07:18,370 ERROR [main-EventThread] HBaseClient: The znode for the -ROOT- region doesn't exist!


问:
Mercurial build on push
I'd like for a build to be done (on the server) each time a push is made to our central Mercurial repository.
Builds are usually kicked off on our build server by running a Visual Build file either manually or via a scheduled task.

What are the ways of achieving this?

Simple, low impact solutions are preferred.

答: Another way, in addition to the hooks that Pablo mentions, is to set up a continuous integration server, like TeamCity. Then you could ask TeamCity to monitor your repository, pull new changesets and start the visual build script for you.</p>

Title: Mercurial build on push


问:
React state not updating in app but I can console.log correct updated state
I have a form I have created using es6 class. The form is stateful and updates its state onChange. The information in the state of the form is passed up to the app component onSubmit. I can console.log every step through through the state being passed up in the methods of my form and app component and it is behaving as expected. In this code example I have the console after I setState in app and it logs out the state object with the input value added as I would expect.

The problem is when I look in the react developer tools, the state has not updated. Also, if I move the console statement into a callback function in the setState method, it does not log anything.

My questions are how to fix this and more importantly, why would I be able to log out the state with the values I am looking for when the state in the application has does not appear to have actually updated?

```<code>class App extends Component {
  constructor (props) {
    super(props)
    this.state = {
      appointments: [{title:'first appointment'}]
    };
    this.updateAppointments = this.updateAppointments.bind(this);
  }

  updateAppointments(newAppointment) {
    var newAppointmentList = this.state.appointments;
    newAppointmentList.push(newAppointment);
    this.setState= {
      appointments: newAppointmentList,
      //This console logs nothing
      function() {
        console.log(this.state.appointments);
      }
    };
    //This console logs out the state as expected with the new appointment
    //added even thought the state in the app does not appear to have the
    //appointment added when I look in the react dev tools
    console.log(this.state.appointments);
  }

  render() {
    return (
      <div className="App">
        <AppointmentForm addAppointment = {this.updateAppointments} />
      </div>
    );
  }
}

class AppointmentForm extends Component {
  constructor (props) {
    super(props)
    this.state = {
      appointmentTitle: ''
    };
    this.handleSubmit = this.handleSubmit.bind(this);
    this.handleTitleChange = this.handleTitleChange.bind(this);
  }
  handleTitleChange(event) {
    this.setState({appointmentTitle: event.target.value});
  }
  handleSubmit(e) {
    let newAppointment = {
      title: this.state.appointmentTitle
    }
    e.preventDefault();
    this.props.addAppointment(newAppointment);
  }
  render() {
    return (
      <div>
          <form onSubmit={this.handleSubmit}>
            <FormGroup controlId="appointmentTitle">
              <ControlLabel>Appointment Title</ControlLabel>
              <FormControl type="text" placeholder="Appointment Title" value={this.state.appointmentTitle}
              onChange={this.handleTitleChange}/>
            </FormGroup>
          </form>
      </div>
    );
  }
}
</code>```

答:
You are updating the state in wrong way.

Instead of:

```<code>this.setState = {
</code>```

Write it like this:

```<code>updateAppointments(newAppointment) {
    var newAppointmentList = this.state.appointments.slice();
    newAppointmentList.push(newAppointment);
    this.setState({
        appointments: newAppointmentList, () => {
           console.log(this.state.appointments);
        }
    })
}
</code>```

Suggestion: Never mutate the state value directly, so first create a copy of state array by using slice(), push the new value then use setState to update the state.

Body:
I have a form I have created using es6 class. The form is stateful and updates its state onChange. The information in the state of the form is passed up to the app component onSubmit. I can console.log every step through through the state being passed up in the methods of my form and app component and it is behaving as expected. In this code example I have the console after I setState in app and it logs out the state object with the input value added as I would expect.

The problem is when I look in the react developer tools, the state has not updated. Also, if I move the console statement into a callback function in the setState method, it does not log anything.

My questions are how to fix this and more importantly, why would I be able to log out the state with the values I am looking for when the state in the application has does not appear to have actually updated?

class App extends Component {
  constructor (props) {
    super(props)
    this.state = {
      appointments: [{title:'first appointment'}]
    };
    this.updateAppointments = this.updateAppointments.bind(this);
  }

  updateAppointments(newAppointment) {
    var newAppointmentList = this.state.appointments;
    newAppointmentList.push(newAppointment);
    this.setState= {
      appointments: newAppointmentList,
      //This console logs nothing
      function() {
        console.log(this.state.appointments);
      }
    };
    //This console logs out the state as expected with the new appointment
    //added even thought the state in the app does not appear to have the
    //appointment added when I look in the react dev tools
    console.log(this.state.appointments);
  }

  render() {
    return (

        <AppointmentForm addAppointment = {this.updateAppointments} />

    );
  }
}

class AppointmentForm extends Component {
  constructor (props) {
    super(props)
    this.state = {
      appointmentTitle: ''
    };
    this.handleSubmit = this.handleSubmit.bind(this);
    this.handleTitleChange = this.handleTitleChange.bind(this);
  }
  handleTitleChange(event) {
    this.setState({appointmentTitle: event.target.value});
  }
  handleSubmit(e) {
    let newAppointment = {
      title: this.state.appointmentTitle
    }
    e.preventDefault();
    this.props.addAppointment(newAppointment);
  }
  render() {
    return (

          <form onSubmit={this.handleSubmit}>
            <FormGroup controlId="appointmentTitle">
              <ControlLabel>Appointment Title</ControlLabel>
              <FormControl type="text" placeholder="Appointment Title" value={this.state.appointmentTitle}
              onChange={this.handleTitleChange}/>
            </FormGroup>
          </form>

    );
  }
}

Body:
You are updating the state in wrong way.

Instead of:

this.setState = {

Write it like this:

updateAppointments(newAppointment) {
    var newAppointmentList = this.state.appointments.slice();
    newAppointmentList.push(newAppointment);
    this.setState({
        appointments: newAppointmentList, () => {
           console.log(this.state.appointments);
        }
    })
}

Suggestion: Never mutate the state value directly, so first create a copy of state array by using slice(), push the new value then use setState to update the state.


问:
"Method or data member not found" (VBA Word)
I have this portion of code below that keeps receiving the "Method or data
    member not found" error message:

```<code>If p.myStyle = "Headings_Sub" Then
p.Range.Select

End If
</code>```

Not sure how to solve. Here is the complete code for reference:

```<code>Sub testCopyPasteVBA()

testCopyPasteVBA Macro

Dim wordDoc As Object
Dim oXL As Excel.Application
Dim DocTarget As Word.Document
Dim Target As Excel.Workbook
Dim tSheet As Excel.Worksheet
Dim StrTxt As String
Dim oRng As Word.Range
Dim p As Paragraph
Dim myStyle As Style

Set oRng = ActiveDocument.Range
oRng.Start = ActiveDocument.Bookmarks("D_Start").Range.End
oRng.End = ActiveDocument.Bookmarks("D_End").Range.Start

Set wordDoc = GetObject(, "word.application")
oRng.Select

Set myStyle = ActiveDocument.Styles.Add(Name:="Headings_Sub", _
Type:=wdStyleTypeCharacter)
With myStyle.Font
.Bold = True
.Italic = False
.Name = "Times New Roman"
.Size = 12
.AllCaps = True

End With

If p.myStyle = "Headings_Sub" Then
p.Range.Select

End If

Selection.Copy

'If Excel is running
On Error Resume Next
Set oXL = GetObject(, "Excel.Application")

If Err Then
ExcelWasNotRunning = True
Set oXL = New Excel.Application

End If

oXL.Visible = True
Set Target = oXL.Workbooks.Add
Set tSheet = Target.Sheets(1)
tSheet.Paste

End Sub
</code>```

Thanks!

答:
myStyle is not a property of the Paragraph object

Try:

```<code>If p.Style = "Headings_Sub" Then
</code>```

Body:
I have this portion of code below that keeps receiving the "Method or data
    member not found" error message:

If p.myStyle = "Headings_Sub" Then
p.Range.Select

End If

Not sure how to solve. Here is the complete code for reference:

Sub testCopyPasteVBA()

testCopyPasteVBA Macro

Dim wordDoc As Object
Dim oXL As Excel.Application
Dim DocTarget As Word.Document
Dim Target As Excel.Workbook
Dim tSheet As Excel.Worksheet
Dim StrTxt As String
Dim oRng As Word.Range
Dim p As Paragraph
Dim myStyle As Style

Set oRng = ActiveDocument.Range
oRng.Start = ActiveDocument.Bookmarks("D_Start").Range.End
oRng.End = ActiveDocument.Bookmarks("D_End").Range.Start

Set wordDoc = GetObject(, "word.application")
oRng.Select

Set myStyle = ActiveDocument.Styles.Add(Name:="Headings_Sub", _
Type:=wdStyleTypeCharacter)
With myStyle.Font
.Bold = True
.Italic = False
.Name = "Times New Roman"
.Size = 12
.AllCaps = True

End With

If p.myStyle = "Headings_Sub" Then
p.Range.Select

End If

Selection.Copy

'If Excel is running
On Error Resume Next
Set oXL = GetObject(, "Excel.Application")

If Err Then
ExcelWasNotRunning = True
Set oXL = New Excel.Application

End If

oXL.Visible = True
Set Target = oXL.Workbooks.Add
Set tSheet = Target.Sheets(1)
tSheet.Paste

End Sub

Thanks!

Body:
myStyle is not a property of the Paragraph object

Try:

If p.Style = "Headings_Sub" Then


问:
what is the complexity of function that have loop inside recursion function
im trying to analysis the complexity of this code .
i predicated that its o(n^2)
because for loop take a o(n) inside a recursion function thats take o(n)
o(n) * o(n) = o(n^2)
however im not sure .</p>

```<code>public class main
{

    static Set<String> setString = new HashSet<>();

    public static void main(String[] args)
    {
        // TODO Auto-generated method stub
        main m = new main();
        m.permute("sanad", 0);
        for(String s : setString)
        {
            System.out.println(s);
        }

    }

    public void permute(String str , int i )
    {
        if (i>=str.length())
        {
            return;
        }

        for(int j = 0 ; j < str.length();j++)
        {
            StringBuilder b = new StringBuilder(str. replaceFirst(String.valueOf(str.charAt(i)), ""));
            b.insert(j,str.charAt(i));
            setString.add(b.toString());
        }

        permute(str, ++i);
    }

}
</code>```

答: You are correct in that the total complexity is the product of the nested complexities and that the permute function is called n times, where n is the length of the string, and the loop is called n times as well, leading to n^2 calls of the loop . However you also have to look at the complexity of the code inside the loop, especially replaceFirst and insert, decide, if their runtime depends on the length of the string, and multiply with that as well. As I suspect this is a homework question I leave this to you.

Body:
im trying to analysis the complexity of this code .
i predicated that its o(n^2)
because for loop take a o(n) inside a recursion function thats take o(n)
o(n) * o(n) = o(n^2)
however im not sure .

public class main
{

    static Set<String> setString = new HashSet<>();

    public static void main(String[] args)
    {
        // TODO Auto-generated method stub
        main m = new main();
        m.permute("sanad", 0);
        for(String s : setString)
        {
            System.out.println(s);
        }

    }

    public void permute(String str , int i )
    {
        if (i>=str.length())
        {
            return;
        }

        for(int j = 0 ; j < str.length();j++)
        {
            StringBuilder b = new StringBuilder(str. replaceFirst(String.valueOf(str.charAt(i)), ""));
            b.insert(j,str.charAt(i));
            setString.add(b.toString());
        }

        permute(str, ++i);
    }

}


问:
Trapping Powershell Error in a function
I'm having a bit of trouble preventing a certain error message from bubbling up from a function to my main routine's 'Catch'. I would like to have my function react to a particular error, then do something, and continue processing as usual without alerting my main routine that there was an error. Currently, if the file this script is trying to read is in use (being written to), it will write a System.IO.IOException error to my log. But sometimes I expect this error to occur and it isn't an issue and I don't want to fill my log with these type of errors. I would expect from the code below that the checkFileLock function would catch the error, return 0 to the findErrorInFile function, and no error would be caught to my error log.</p>

```<code>Function findErrorsInFile{
    param(
        [string]$dir,
        [string]$file,
        [String]$errorCode
    )
    If((Get-Item $($dir + "`\" + $file)) -is [System.IO.DirectoryInfo]){ #we dont want to look at directories, only files
    }Else{
        If($(checkFileLock -filePath $($dir + "`\" + $file))){
            $reader = New-Object System.IO.StreamReader($($dir + "`\" + $file))
            $content = $reader.ReadToEnd()
            $results = $content | select-string -Pattern $errorCode #if there is no regex match (no matching error code found), then the string $results will be == $null
                If($results){
                    Return 1 #we found the error in the file
                }Else{
                    Return 0 #no error found in the file
                }
        }Else{
            Return 0 #The file was being written to, we will skip it and assume no error. This is rare.
        }
    }
}

Function checkFileLock{
    param(
    [String]$filePath
    )

    try{
        $openFile = New-Object System.IO.FileInfo $filePath
        $testStream = $openFile.Open([System.IO.FileMode]::Open, [System.IO.FileAccess]::ReadWrite, [System.IO.FileShare]::None) #try to open a filestream
        If($testStream){ #If the filestream opens, then it isn't locked
            $testStream.Close() #close the filestream
        }
        return $false #File is not locked
    }

    catch{
        return $true #File is locked
    }
}

#### START MAIN PROCESS ####

Try{

  if($(findErrorsInFile -dir 'somepath' -file 'somefilename' -errorcode 'abc')){
    write-host "found something"
  }else{
    write-host "didn't find anything"
  }
}

Catch{
  $_.Exception.ToString() >> mylogfile.txt
}
</code>```

答:
try/catch blocks only catch terminating errors. Is your code generating a terminating or non-terminating error?

ArcSet has highlighted essentially what is required: force a non-terminating error to be a terminating error. I suspect it needs to be added to this line, if allowed:

```<code>$testStream = $openFile.Open([System.IO.FileMode]::Open, [System.IO.FileAccess]::ReadWrite, [System.IO.FileShare]::None) -ErrorAction Stop
</code>```

Edit - solution as -ErrorAction not an accepted parameter

I tried the above and it's not allowed. An alternative is to set the $ErrorActionPreference to Stop. This will affect all errors, so recommend reverting. Someone with more experience using  System.IO.FileInfo objects may have a more elegant solution.

```<code>try{
    $currentErrorSetting = $ErrorActionPreference
    $ErrorActionPreference = "Stop"

    $openFile = New-Object System.IO.FileInfo $filePath
    $testStream = $openFile.Open([System.IO.FileMode]::Open, [System.IO.FileAccess]::ReadWrite, [System.IO.FileShare]::None) #try to open a filestream
    If($testStream){ #If the filestream opens, then it isn't locked
        $testStream.Close() #close the filestream
    }
    $ErrorActionPreference = $currentErrorSetting
    return $false #File is not locked
}

catch{
    $ErrorActionPreference = $currentErrorSetting
    return $true #File is locked
}
</code>```

Title: Trapping Powershell Error in a function

Body:
I'm having a bit of trouble preventing a certain error message from bubbling up from a function to my main routine's 'Catch'. I would like to have my function react to a particular error, then do something, and continue processing as usual without alerting my main routine that there was an error. Currently, if the file this script is trying to read is in use (being written to), it will write a System.IO.IOException error to my log. But sometimes I expect this error to occur and it isn't an issue and I don't want to fill my log with these type of errors. I would expect from the code below that the checkFileLock function would catch the error, return 0 to the findErrorInFile function, and no error would be caught to my error log.

Function findErrorsInFile{
    param(
        [string]$dir,
        [string]$file,
        [String]$errorCode
    )
    If((Get-Item $($dir + "`\" + $file)) -is [System.IO.DirectoryInfo]){ #we dont want to look at directories, only files
    }Else{
        If($(checkFileLock -filePath $($dir + "`\" + $file))){
            $reader = New-Object System.IO.StreamReader($($dir + "`\" + $file))
            $content = $reader.ReadToEnd()
            $results = $content | select-string -Pattern $errorCode #if there is no regex match (no matching error code found), then the string $results will be == $null
                If($results){
                    Return 1 #we found the error in the file
                }Else{
                    Return 0 #no error found in the file
                }
        }Else{
            Return 0 #The file was being written to, we will skip it and assume no error. This is rare.
        }
    }
}

Function checkFileLock{
    param(
    [String]$filePath
    )

    try{
        $openFile = New-Object System.IO.FileInfo $filePath
        $testStream = $openFile.Open([System.IO.FileMode]::Open, [System.IO.FileAccess]::ReadWrite, [System.IO.FileShare]::None) #try to open a filestream
        If($testStream){ #If the filestream opens, then it isn't locked
            $testStream.Close() #close the filestream
        }
        return $false #File is not locked
    }

    catch{
        return $true #File is locked
    }
}

#### START MAIN PROCESS ####

Try{

  if($(findErrorsInFile -dir 'somepath' -file 'somefilename' -errorcode 'abc')){
    write-host "found something"
  }else{
    write-host "didn't find anything"
  }
}

Catch{
  $_.Exception.ToString() >> mylogfile.txt
}

Body:
try/catch blocks only catch terminating errors. Is your code generating a terminating or non-terminating error?

ArcSet has highlighted essentially what is required: force a non-terminating error to be a terminating error. I suspect it needs to be added to this line, if allowed:

$testStream = $openFile.Open([System.IO.FileMode]::Open, [System.IO.FileAccess]::ReadWrite, [System.IO.FileShare]::None) -ErrorAction Stop

Edit - solution as -ErrorAction not an accepted parameter

I tried the above and it's not allowed. An alternative is to set the $ErrorActionPreference to Stop. This will affect all errors, so recommend reverting. Someone with more experience using  System.IO.FileInfo objects may have a more elegant solution.

try{
    $currentErrorSetting = $ErrorActionPreference
    $ErrorActionPreference = "Stop"

    $openFile = New-Object System.IO.FileInfo $filePath
    $testStream = $openFile.Open([System.IO.FileMode]::Open, [System.IO.FileAccess]::ReadWrite, [System.IO.FileShare]::None) #try to open a filestream
    If($testStream){ #If the filestream opens, then it isn't locked
        $testStream.Close() #close the filestream
    }
    $ErrorActionPreference = $currentErrorSetting
    return $false #File is not locked
}

catch{
    $ErrorActionPreference = $currentErrorSetting
    return $true #File is locked
}


答:
You have a code error. You're setting the setState property, not calling the setState function. Change this:

```<code>this.setState= {
  appointments: newAppointmentList,
  function() {
    console.log(this.state.appointments);
  }
};
</code>```

to this:

```<code>this.setState({
  appointments: newAppointmentList,
  function() {
    console.log(this.state.appointments);
  }
});
</code>```

Title: React state not updating in app but I can console.log correct updated state

Body:
You have a code error. You're setting the setState property, not calling the setState function. Change this:

this.setState= {
  appointments: newAppointmentList,
  function() {
    console.log(this.state.appointments);
  }
};

to this:

this.setState({
  appointments: newAppointmentList,
  function() {
    console.log(this.state.appointments);
  }
});


问:
How to create Sql Synonym or "Alias" for Database Name?
I'm using ms sql 2008 and trying to create a database name that references another database. For example 'Dev', 'Test', 'Demo' would be database names that i could reference from my multiple config files, but each name would point to another database such as 'db20080101' or 'db20080114'.

[Edit]Some of the configs are for applications that i control the code and some aren't (ex. MS Reporting service datasource file configs)[/Edit]

It seems that sqlserver only supports synonyms for View,Table,Sproc, or Function. And Alias' are for table and column names.

Is there a way to do this that i missed in the docs?
Any one have any suggestions on a workaround?

答:
I've done something similar to this using another config file.

The new config file maps your generic name to all of the information needed to connect to that database (db name, user name, password, etc.) and then your connection function takes your generic name as an argument.

db.config:

```<code>DEV_DB_NAME = db20080101
DEV_DB_USER = dev_user
DEV_DB_PASS = dev_pass
TEST_DB_NAME = db20070101
TEST_DB_USER = test_user
TEST_DB_PASS = test_pass
</code>```

connection code:

```<code>db_connection get_connection(string prefix) {
    db_connection db_conn = new db_connection;
    string db_name = get_config_value(config_path, prefix + "_DB_NAME");
    string db_user = get_config_value(config_path, prefix + "_DB_USER");
    string db_pass = get_config_value(config_path, prefix + "_DB_PASS");

    db_conn.connect(db_name, db_user, db_pass);

    return db_conn;
}
</code>```

Then you just call get_connection() with your db alias as the argument.

OwnerDisplayName: Kevin

LastEditorDisplayName: Cade Roux

Body:
I've done something similar to this using another config file.

The new config file maps your generic name to all of the information needed to connect to that database (db name, user name, password, etc.) and then your connection function takes your generic name as an argument.

db.config:

DEV_DB_NAME = db20080101
DEV_DB_USER = dev_user
DEV_DB_PASS = dev_pass
TEST_DB_NAME = db20070101
TEST_DB_USER = test_user
TEST_DB_PASS = test_pass

connection code:

db_connection get_connection(string prefix) {
    db_connection db_conn = new db_connection;
    string db_name = get_config_value(config_path, prefix + "_DB_NAME");
    string db_user = get_config_value(config_path, prefix + "_DB_USER");
    string db_pass = get_config_value(config_path, prefix + "_DB_PASS");

    db_conn.connect(db_name, db_user, db_pass);

    return db_conn;
}

Then you just call get_connection() with your db alias as the argument.

OwnerDisplayName: Ryan Ahearn


问:
Which Java library should I use for authentication through Facebook, Gmail, local auth, etc.?
Which Java library do you recommend to implement authentication in a Java web app (just servlets & JSPs)?  We want to offer the most common authentication providers (Facebook, Yahoo, Gmail, etc.) and also local account registration.

I have found SocialAuth but it looks pretty new and I don't know if there are better alternatives.  In addition, it looks like SocialAuth will request access to users contacts which I don't need and could annoy our users.

Thanks!

答:
Spring Security is a good starting point to get a flexible authentication system in your project.

http://static.springsource.org/spring-security/site/

There is a spring-security-facebook plugin that will integrate facebook auth.

http://code.google.com/p/spring-security-facebook/

I'm not sure about the others specifically.  If you are talking about OpenID then spring security supports that.


问:
Why dosnt my webdriver method wait until 'Max timeout' for an element to be visible?
Why dosnt my webdriver method wait until 'Max timeout' for an element to be visible?

My method:

```<code>    public boolean WaitUntilWebElementIsVisible(WebElement element) {
    try {
        WebDriverWait tempWait = new WebDriverWait(driver, 30);
        tempWait.pollingEvery(100, TimeUnit.MILLISECONDS);
        tempWait.until(ExpectedConditions.visibilityOf(element));
        System.out.println("WebElement is visible using locator: " + element.toString());
        return true;
    } catch (Exception e) {
        System.out.println("WebElement is NOT visible, using locator: " + element.toString() + " ,Exception: " + e.getMessage());
        Assert.fail("Method failed: WaitUntilWebElementIsVisible");
        //Assert.fail("WebElement is NOT visible, using locator: " + element.toString());
        return false;
    }
}
</code>```

TestNG call:

```<code>    @Test(priority = 27)
public void confirm_BillingAddress_Header_IsVisible_BillingAndPaymentDetails_Section() throws Exception {
    //Verify whether the panel title: 'BILLING ADDRESS:' is visible
    Thread.sleep(1000);
    basePage.WaitUntilWebElementIsVisible(checkoutPage.subheader_BillingAddress);
    Assert.assertEquals(checkoutPage.subheader_BillingAddress.getText(), "BILLING ADDRESS:");
}
</code>```

Example of the issue (during the test the header easily appears before 30seconds):

答: Do you use implicit waiters? Good practice to use explicit waiters without implicit waiter.</p>

Body:
Why dosnt my webdriver method wait until 'Max timeout' for an element to be visible?

My method:

    public boolean WaitUntilWebElementIsVisible(WebElement element) {
    try {
        WebDriverWait tempWait = new WebDriverWait(driver, 30);
        tempWait.pollingEvery(100, TimeUnit.MILLISECONDS);
        tempWait.until(ExpectedConditions.visibilityOf(element));
        System.out.println("WebElement is visible using locator: " + element.toString());
        return true;
    } catch (Exception e) {
        System.out.println("WebElement is NOT visible, using locator: " + element.toString() + " ,Exception: " + e.getMessage());
        Assert.fail("Method failed: WaitUntilWebElementIsVisible");
        //Assert.fail("WebElement is NOT visible, using locator: " + element.toString());
        return false;
    }
}

TestNG call:

    @Test(priority = 27)
public void confirm_BillingAddress_Header_IsVisible_BillingAndPaymentDetails_Section() throws Exception {
    //Verify whether the panel title: 'BILLING ADDRESS:' is visible
    Thread.sleep(1000);
    basePage.WaitUntilWebElementIsVisible(checkoutPage.subheader_BillingAddress);
    Assert.assertEquals(checkoutPage.subheader_BillingAddress.getText(), "BILLING ADDRESS:");
}

Example of the issue (during the test the header easily appears before 30seconds):