问:
C# - Passing different type of objects through the same method
Original Question

So I have this 3 objects...

```<code>public class obj1
{
  public int Id { get; set; }
  public string Name { get; set; }
}

public class obj2
{
  public int AccNum { get; set; }
  public string Name { get; set; }
}

public class obj3
{
  public string Email { get; set; }
  public string Phone { get; set; }
}
</code>```

... and one method that is supposed to receive one of them, after evaluating the object type the program should decide which function to call.

I've tried with generics but it doesn't work as I expected. So far this is what I've got...

```<code>    public class NotificationHelper: INotificationHelper
    {

        public bool SendNotification<TNotInfo>(TNotInfo obj) where TNotInfo : class
        {
            if (contract.GetType() == typeof (obj1))
            {
                var sender = new SendSMS();
                return sender.Send(obj);
            }
            if (contract.GetType() == typeof(obj2))
            {
                var sender = new SendPush();
                return sender.Send(obj);
            }
            else
            {
                var sender = new SendEmail();
                return sender.Send(obj);
            }
        }
    }
</code>```

but I get the error "Cannot convert from TNotInfo to Models.obj1". Is there any way to overcome this issue? Or I have to change my logic?

Appreciate any help, thanks in advance.

*Edit

```<code>using System;

namespace EmailNotifications
{

    public interface IEmailNotification
    {
        void SendEmailNotification();
    }

    public class EmailNotificationA : IEmailNotification
    {

        public void SendEmailNotification(Contract1 a)
        {
            Console.WriteLine($"Sending EmailNotificationA ({a})");
        }
    }

    public class EmailNotificationB : IEmailNotification
    {
        public void SendEmailNotification(Contract2 b)
        {
            Console.WriteLine($"Sending EmailNotificationB ({b})");
        }
    }

    public class EmailNotificationC : IEmailNotification
    {

        public void SendEmailNotification(Contrac3 c)
        {
            Console.WriteLine($"Sending EmailNotificationC ({c})");
        }
    }

    public class EmailNotificationService
    {
        private readonly IEmailNotification _emailNotification;

        public EmailNotificationService(IEmailNotification emailNotification)
        {
            this._emailNotification = emailNotification;
        }

        public void ServiceHelper()
        {
            _emailNotification.SendEmailNotification();
        }
    }
}
</code>```

Above solution is what I was trying to achieve, applying strategy design pattern. But I couldn't manage to make my interface method receive different objects, this is required because each notification has is own implementation. As visible at the none working example above, I have 3 different implementation of the same method all of them receiving different objects. Any idea of how to make this logic work?

答:
This is the kind of thing that interfaces were designed to do. First, define a common interface:

```<code>public interface INotifier
{
    bool Notify();
}
</code>```

Second, implement it in your objX classes:

```<code>public class obj1 : INotifier
{
    public int Id { get; set; }
    public string Name { get; set; }

    public bool Notify()
    {
        var sender = new SendSMS();
        return sender.Send(this);
    }
}

public class obj2 : INotifier
{
    public int AccNum { get; set; }
    public string Name { get; set; }

    public bool Notify()
    {
        var sender = new SendPush();
        return sender.Send(this);
    }
}

public class obj3 : INotifier
{
    public string Email { get; set; }
    public string Phone { get; set; }

    public bool Notify()
    {
        var sender = new SendEmail();
        return sender.Send(this);
    }
}
</code>```

And finally, change your notification method to accept the interface type as the parameter:

```<code>public class NotificationHelper : INotificationHelper
{
    public bool SendNotification(INotifier obj)
    {
        return obj.Notify();
    }
}
</code>```

Edit (2019):

I'm revisiting this answer as it seems to be getting a fair amount of visibility. OP has probably long since moved on, but for others that may stumble upon this answer, here's another solution.

I still believe that interfaces are the way to go. However, the interface suggested above is extremely generic and ultimately not terribly useful. It also runs into some DRY violations because, as Fabio said in a comment, if two objX classes implement notifications in the same way, this approach forces you to duplicate the code between them.

Instead of one global interface, instead have interfaces for each specific notification task, i.e. ISMSNotification, IPushNotification, IEmailNotification. You can then use the mixin pattern to give each interface instance a default implementation of the send method:

```<code>interface ISmsNotifier
{
  int SmsId { get; }
  string SmsName { get; }
}

static class ISmsNotifierExtensions
{
  public static bool NotifySms(this ISmsNotifier obj)
  {
    var sender = new SendSMS();
    return sender.Send(obj);
  }
}

// ---------------------------------------------

interface IPushNotifier
{
  int PushAccNum { get; }
  string PushName { get; }
}

static class IPushNotifierExtensions
{
  public static bool NotifyPush(this IPushNotifier obj)
  {
    var sender = new SendEmail();
    return sender.Send(obj);
  }
}

// ---------------------------------------------

interface IEmailNotifier
{
  string EmailAddress { get; }
  string EmailPhone { get; }
}

static class IEmailNotifierExtensions
{
  public static bool NotifyEmail(this IEmailNotifier obj)
  {
    var sender = new SendEmail();
    return sender.Send(obj);
  }
}
</code>```

You can then implement it in the objX classes like so:

```<code>public class obj1 : INotifier, ISmsNotifier
{
  public int SmsId { get; set; }
  public string SmsName { get; set; }

  public bool Notify() => this.NotifySms();
}

public class obj2 : INotifier, IPushNotifier
{
    public int PushAccNum { get; set; }
    public string PushName { get; set; }

    public bool Notify() => this.NotifyPush();
}

public class obj3 : INotifier, IEmailNotifier
{
    public string EmailAddress { get; set; }
    public string EmailPhone { get; set; }

    public bool Notify() => this.NotifyEmail();
}
</code>```

Notice that using this approach it's easy to not only support objects which use identical notification systems, you can also support objects with multiple notification systems:

```<code>public class obj4 : INotifier, IEmailNotifier, IPushNotifier
{
    public int PushAccNum { get; set; }
    public string PushName { get; set; }
    public string EmailAddress { get; set; }
    public string EmailPhone { get; set; }

    public bool Notify() => this.NotifyEmail() && this.NotifyPush();
}
</code>```

You might notice that this approach makes NotificationHelper obsolete since it's no longer necessary to pass the objects through a processing step to determine which notification system to process the object through. That is true, and maybe rightfully so, since the objects should be fully capable of deciding that for themselves (depending on your mentality approaching this problem). However, NotificationHelper may still have its uses, such as if you wanted to preprocess the information that's getting sent to the notification services, or if you wanted a common point of entry to help with mocking and testing.

C# 8 Note:

A proposed feature of C# 8 is the ability to give interfaces a default implementation of methods within the interface definition itself. When (if) that happens, you don't need to use the mixin pattern anymore and can directly define the default method implementations in the interfaces. The feature hasn't yet been finalized, but it might look something like this:

```<code>interface ISmsNotifier
{
  int SmsId { get; }
  string SmsName { get; }

  public bool NotifySms()
  {
    var sender = new SendSMS();
    return sender.Send(this);
  }
}

// ---------------------------------------------

interface IPushNotifier
{
  int PushAccNum { get; }
  string PushName { get; }

  public bool NotifyPush()
  {
    var sender = new SendEmail();
    return sender.Send(this);
  }
}

// ---------------------------------------------

interface IEmailNotifier
{
  string EmailAddress { get; }
  string EmailPhone { get; }

  public bool NotifyEmail()
  {
    var sender = new SendEmail();
    return sender.Send(this);
  }
}
</code>```

Body:
Original Question

So I have this 3 objects...

public class obj1
{
  public int Id { get; set; }
  public string Name { get; set; }
}

public class obj2
{
  public int AccNum { get; set; }
  public string Name { get; set; }
}

public class obj3
{
  public string Email { get; set; }
  public string Phone { get; set; }
}

... and one method that is supposed to receive one of them, after evaluating the object type the program should decide which function to call.

I've tried with generics but it doesn't work as I expected. So far this is what I've got...

    public class NotificationHelper: INotificationHelper
    {

        public bool SendNotification<TNotInfo>(TNotInfo obj) where TNotInfo : class
        {
            if (contract.GetType() == typeof (obj1))
            {
                var sender = new SendSMS();
                return sender.Send(obj);
            }
            if (contract.GetType() == typeof(obj2))
            {
                var sender = new SendPush();
                return sender.Send(obj);
            }
            else
            {
                var sender = new SendEmail();
                return sender.Send(obj);
            }
        }
    }

but I get the error "Cannot convert from TNotInfo to Models.obj1". Is there any way to overcome this issue? Or I have to change my logic?

Appreciate any help, thanks in advance.

*Edit

using System;

namespace EmailNotifications
{

    public interface IEmailNotification
    {
        void SendEmailNotification();
    }

    public class EmailNotificationA : IEmailNotification
    {

        public void SendEmailNotification(Contract1 a)
        {
            Console.WriteLine($"Sending EmailNotificationA ({a})");
        }
    }

    public class EmailNotificationB : IEmailNotification
    {
        public void SendEmailNotification(Contract2 b)
        {
            Console.WriteLine($"Sending EmailNotificationB ({b})");
        }
    }

    public class EmailNotificationC : IEmailNotification
    {

        public void SendEmailNotification(Contrac3 c)
        {
            Console.WriteLine($"Sending EmailNotificationC ({c})");
        }
    }

    public class EmailNotificationService
    {
        private readonly IEmailNotification _emailNotification;

        public EmailNotificationService(IEmailNotification emailNotification)
        {
            this._emailNotification = emailNotification;
        }

        public void ServiceHelper()
        {
            _emailNotification.SendEmailNotification();
        }
    }
}

Above solution is what I was trying to achieve, applying strategy design pattern. But I couldn't manage to make my interface method receive different objects, this is required because each notification has is own implementation. As visible at the none working example above, I have 3 different implementation of the same method all of them receiving different objects. Any idea of how to make this logic work?

Body:
This is the kind of thing that interfaces were designed to do. First, define a common interface:

public interface INotifier
{
    bool Notify();
}

Second, implement it in your objX classes:

public class obj1 : INotifier
{
    public int Id { get; set; }
    public string Name { get; set; }

    public bool Notify()
    {
        var sender = new SendSMS();
        return sender.Send(this);
    }
}

public class obj2 : INotifier
{
    public int AccNum { get; set; }
    public string Name { get; set; }

    public bool Notify()
    {
        var sender = new SendPush();
        return sender.Send(this);
    }
}

public class obj3 : INotifier
{
    public string Email { get; set; }
    public string Phone { get; set; }

    public bool Notify()
    {
        var sender = new SendEmail();
        return sender.Send(this);
    }
}

And finally, change your notification method to accept the interface type as the parameter:

public class NotificationHelper : INotificationHelper
{
    public bool SendNotification(INotifier obj)
    {
        return obj.Notify();
    }
}

Edit (2019):

I'm revisiting this answer as it seems to be getting a fair amount of visibility. OP has probably long since moved on, but for others that may stumble upon this answer, here's another solution.

I still believe that interfaces are the way to go. However, the interface suggested above is extremely generic and ultimately not terribly useful. It also runs into some DRY violations because, as Fabio said in a comment, if two objX classes implement notifications in the same way, this approach forces you to duplicate the code between them.

Instead of one global interface, instead have interfaces for each specific notification task, i.e. ISMSNotification, IPushNotification, IEmailNotification. You can then use the mixin pattern to give each interface instance a default implementation of the send method:

interface ISmsNotifier
{
  int SmsId { get; }
  string SmsName { get; }
}

static class ISmsNotifierExtensions
{
  public static bool NotifySms(this ISmsNotifier obj)
  {
    var sender = new SendSMS();
    return sender.Send(obj);
  }
}

// ---------------------------------------------

interface IPushNotifier
{
  int PushAccNum { get; }
  string PushName { get; }
}

static class IPushNotifierExtensions
{
  public static bool NotifyPush(this IPushNotifier obj)
  {
    var sender = new SendEmail();
    return sender.Send(obj);
  }
}

// ---------------------------------------------

interface IEmailNotifier
{
  string EmailAddress { get; }
  string EmailPhone { get; }
}

static class IEmailNotifierExtensions
{
  public static bool NotifyEmail(this IEmailNotifier obj)
  {
    var sender = new SendEmail();
    return sender.Send(obj);
  }
}

You can then implement it in the objX classes like so:

public class obj1 : INotifier, ISmsNotifier
{
  public int SmsId { get; set; }
  public string SmsName { get; set; }

  public bool Notify() => this.NotifySms();
}

public class obj2 : INotifier, IPushNotifier
{
    public int PushAccNum { get; set; }
    public string PushName { get; set; }

    public bool Notify() => this.NotifyPush();
}

public class obj3 : INotifier, IEmailNotifier
{
    public string EmailAddress { get; set; }
    public string EmailPhone { get; set; }

    public bool Notify() => this.NotifyEmail();
}

Notice that using this approach it's easy to not only support objects which use identical notification systems, you can also support objects with multiple notification systems:

public class obj4 : INotifier, IEmailNotifier, IPushNotifier
{
    public int PushAccNum { get; set; }
    public string PushName { get; set; }
    public string EmailAddress { get; set; }
    public string EmailPhone { get; set; }

    public bool Notify() => this.NotifyEmail() && this.NotifyPush();
}

You might notice that this approach makes NotificationHelper obsolete since it's no longer necessary to pass the objects through a processing step to determine which notification system to process the object through. That is true, and maybe rightfully so, since the objects should be fully capable of deciding that for themselves (depending on your mentality approaching this problem). However, NotificationHelper may still have its uses, such as if you wanted to preprocess the information that's getting sent to the notification services, or if you wanted a common point of entry to help with mocking and testing.

C# 8 Note:

A proposed feature of C# 8 is the ability to give interfaces a default implementation of methods within the interface definition itself. When (if) that happens, you don't need to use the mixin pattern anymore and can directly define the default method implementations in the interfaces. The feature hasn't yet been finalized, but it might look something like this:

interface ISmsNotifier
{
  int SmsId { get; }
  string SmsName { get; }

  public bool NotifySms()
  {
    var sender = new SendSMS();
    return sender.Send(this);
  }
}

// ---------------------------------------------

interface IPushNotifier
{
  int PushAccNum { get; }
  string PushName { get; }

  public bool NotifyPush()
  {
    var sender = new SendEmail();
    return sender.Send(this);
  }
}

// ---------------------------------------------

interface IEmailNotifier
{
  string EmailAddress { get; }
  string EmailPhone { get; }

  public bool NotifyEmail()
  {
    var sender = new SendEmail();
    return sender.Send(this);
  }
}


来源: stackexchange

问:
How to wrap content views rather than background drawable?
How can I get a LinearLayout (or any other ViewGroup) to assume the size of it's child views rather than assuming the size of the background image?

```<code><LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:background="@drawable/large_image300x300pix">

 <TextView android:id="@+id/TextView01"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="Hello world!"/>
</LinearLayout>
</code>```

The linear layout becomes the same size as the background image.
How can I get my linear layout to assume the same size as the textview?

答: You can create a FrameLayout and put an ImageView and your LinearLayout there. So you'll be able to configure the layout of your background image.

ContentLicense: CC BY-SA 2.5

Body:
How can I get a LinearLayout (or any other ViewGroup) to assume the size of it's child views rather than assuming the size of the background image?

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:background="@drawable/large_image300x300pix">

 <TextView android:id="@+id/TextView01"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="Hello world!"/>
</LinearLayout>

The linear layout becomes the same size as the background image.
How can I get my linear layout to assume the same size as the textview?


问:
Detect is user has scrolled on iOS and then change colour of view
I am looking for a way in Xcode and Swift to detect if my user has scrolled down the app.

If they have I would like to turn the view at the top of the app from transparent to black. If the user scrolls back to the top again, the view changes from black back to transparent.

Is this something which is achievable in Swift and Xcode?

Thanks in advance! :)

UPDATE Sorry I forgot to mention, I am using uiwebview, with my view overlaying above it. At the top of the app it will be transparent and when I scroll down the webview it will change to black. Can I still detect the scroll the same way?

答:
Yes it is possible in swift. You have to use UIScrollViewDelegate methods to control the scrolling.</p>

```<code> func scrollViewWillBeginDecelerating(_ scrollView: UIScrollView) {

    print("scrollViewWillBeginDecelerating")

    let actualPosition = scrollView.panGestureRecognizer.translation(in: scrollView.superview)
    if (actualPosition.y > 0){
        // Dragging down

        UIView.animate(withDuration: 3, animations: {
           //Change the color of view
        })
    }else{
        // Dragging up

        UIView.animate(withDuration: 3, animations: {
            //Change the color of view
        })
    }
}
</code>```

ContentLicense: CC BY-SA 3.0

Body:
Yes it is possible in swift. You have to use UIScrollViewDelegate methods to control the scrolling.

 func scrollViewWillBeginDecelerating(_ scrollView: UIScrollView) {

    print("scrollViewWillBeginDecelerating")

    let actualPosition = scrollView.panGestureRecognizer.translation(in: scrollView.superview)
    if (actualPosition.y > 0){
        // Dragging down

        UIView.animate(withDuration: 3, animations: {
           //Change the color of view
        })
    }else{
        // Dragging up

        UIView.animate(withDuration: 3, animations: {
            //Change the color of view
        })
    }
}


问:
How to read a dynamic range?
I am trying to create a macro that reads data and does econometrics on the data. At this point I am trying to implement a latent variable MLE estimation.

The data can be of any length, depending on the user input. Suppose there is data in column O and column P. Ex-ante I have no idea how many rows of data exist.

I would like to first read how many data there are and then upload the data into my array variable before I can do any econometrics/statistics on it.

In this problem, the user has 25 data points for each variable. Some other user may enter different data with different number of data points.

In the code below, I am trying to read the variable "D" into an array. I first count the number of non-empty cells and then create an array of that size and try to read the value of the cells into the array. But I am getting a "type mismatch" error.

I've tried both "Variant" and "Array" types. Variant seems to be working but Array is not.

```<code>Sub SampleStats()

Dim Rng As String

Dim Var1(1 To 100) As Double
Dim Var2() As Double
Dim Var3 As Variant
Dim NumElements2 As Integer
Dim length2 As Integer

NumElements2 = WorksheetFunction.Count(Range("P:P"))
length2 = NumElements2+1

MsgBox NumElements2

ReDim Var2(1 To NumElements2)

Rng = "P2:P" & length2

MsgBox Rng

Var3 = Range(Rng).Value
MsgBox Var3(1,1)

Var2 = Range(Rng).Value

MsgBox Var2(1,1)

End Sub
</code>```

My questions are:

Whats the best way to read data when you don't know how long the columns go?

What the best way to store data (Variant or Array or something else) when the final objective is doing some statistics?

答:
```<code>sub createarraywithoutblanks()
creatary ary, Sheets("Table_Types"), "A":
alternative ary:
BuildArrayWithoutBlanks ary
end sub

Sub creatary(ary As Variant, sh As Worksheet, ltr As String)
Dim x, y, rng As range
ReDim ary(0)

Set rng = sh.range(ltr & "2:" & ltr & sh.range("A10000").End(xlUp).Row).SpecialCells(xlCellTypeVisible)

x = 0
For Each y In rng
    ary(x) = y
    x = x + 1
    ReDim Preserve ary(x)
Next y
End Sub

Function Letter(oSheet As Worksheet, name As String, Optional num As Integer)
If num = 0 Then num = 1
Letter = Application.Match(name, oSheet.Rows(num), 0)
Letter = Split(Cells(, Letter).Address, "$")(1)
End Function

Sub alternative(ary As Variant)
Dim Array_2()
Dim Array_toRemove()

Dim dic As New Scripting.Dictionary
Dim arrItem, x As Long
For Each arrItem In ary
    If Not dic.Exists(arrItem) Then
        dic.Add arrItem, arrItem
    Else
        ReDim Preserve Array_toRemove(x)
        Array_toRemove(x) = dic.Item(arrItem)
        x = x + 1
    End If
Next
'For Each arrItem In Array_toRemove
'    dic.Remove (arrItem)
'Next arrItem
ary = dic.Keys

End Sub

Sub BuildArrayWithoutBlanks(ary As Variant)
Dim AryFromRange() As Variant, AryNoBlanks() As Variant
Dim Counter As Long, NoBlankSize As Long

'set references and initialize up-front
ReDim AryNoBlanks(0 To 0)
NoBlankSize = 0

'load the range into array
AryFromRange = ary

'loop through the array from the range, adding
'to the no-blank array as we go
For Counter = LBound(AryFromRange) To UBound(AryFromRange)
    If AryFromRange(Counter) <> 0 Then
        NoBlankSize = NoBlankSize + 1
        AryNoBlanks(UBound(AryNoBlanks)) = AryFromRange(Counter)
        ReDim Preserve AryNoBlanks(0 To UBound(AryNoBlanks) + 1)
    End If
Next Counter

'remove that pesky empty array field at the end
If UBound(AryNoBlanks) > 0 Then
    ReDim Preserve AryNoBlanks(0 To UBound(AryNoBlanks) - 1)
End If

'debug for reference
ary = AryNoBlanks

End Sub
</code>```

Title: How to read a dynamic range?

Body:
I am trying to create a macro that reads data and does econometrics on the data. At this point I am trying to implement a latent variable MLE estimation.

The data can be of any length, depending on the user input. Suppose there is data in column O and column P. Ex-ante I have no idea how many rows of data exist.

I would like to first read how many data there are and then upload the data into my array variable before I can do any econometrics/statistics on it.

In this problem, the user has 25 data points for each variable. Some other user may enter different data with different number of data points.

In the code below, I am trying to read the variable "D" into an array. I first count the number of non-empty cells and then create an array of that size and try to read the value of the cells into the array. But I am getting a "type mismatch" error.

I've tried both "Variant" and "Array" types. Variant seems to be working but Array is not.

Sub SampleStats()

Dim Rng As String

Dim Var1(1 To 100) As Double
Dim Var2() As Double
Dim Var3 As Variant
Dim NumElements2 As Integer
Dim length2 As Integer

NumElements2 = WorksheetFunction.Count(Range("P:P"))
length2 = NumElements2+1

MsgBox NumElements2

ReDim Var2(1 To NumElements2)

Rng = "P2:P" & length2

MsgBox Rng

Var3 = Range(Rng).Value
MsgBox Var3(1,1)

Var2 = Range(Rng).Value

MsgBox Var2(1,1)

End Sub

My questions are:

Whats the best way to read data when you don't know how long the columns go?

What the best way to store data (Variant or Array or something else) when the final objective is doing some statistics?


问:
How to wrap existing function in C
I am trying to wrap existing function.

below code is perfectly worked.

```<code>#include<stdio.h>

int __real_main();

int __wrap_main()
{
    printf("Wrapped main\n");
    return __real_main();
}

int main()
{
    printf("main\n");
    return 0;
}
</code>```

command:

```<code>gcc main.c -Wl,-wrap,main
</code>```

output:

```<code>Wrapped main
main
</code>```

So i have changed main function with temp. my goal is to wrap temp() function.

Below is the code

temp.c

```<code>#include<stdio.h>

int temp();

int __real_temp();

int __wrap_temp()
{
    printf("Wrapped temp\n");
    return __real_temp();
}

int temp()
{
    printf("temp\n");
    return 0;
}

int main()
{
    temp();
    return 0;
}
</code>```

command:

```<code>gcc temp.c -Wl,-wrap,temp
</code>```

output:

```<code>temp
</code>```

Wrapped temp is not printing. please guide me to wrap funciton temp.

答:
The manpage for ld says:

```<code>   --wrap=symbol
       Use a wrapper function for symbol.  Any undefined reference to symbol will be resolved to "__wrap_symbol".  Any
       undefined reference to "__real_symbol" will be resolved to symbol.
</code>```

The keyword here is undefined.

If you put the definition temp in the same translation unit as the code that uses it, it will not be undefined in the code that uses it.

You need to split the code definition and the code that uses it:

```<code>#!/bin/sh

cat > user.c  <<'EOF'
#include<stdio.h>

int temp(void);

int __real_temp(void);

int __wrap_temp()
{
    printf("Wrapped temp\n");
    return __real_temp();
}
int main()
{
    temp();
    return 0;
}
EOF

cat > temp.c <<'EOF'
#include<stdio.h>
int temp()
{
    printf("temp\n");
    return 0;
}
EOF

gcc user.c  -Wl,-wrap,temp temp.c  # OK
./a.out
</code>```

Splitting the build into two separate compiles perhaps makes it clearer:

```<code>$ gcc -c user.c
$ gcc -c temp.c
$ nm user.o temp.o

temp.o:
                 U puts
0000000000000000 T temp

user.o:
0000000000000015 T main
                 U puts
                 U __real_temp
                 U temp
0000000000000000 T __wrap_temp
</code>```

Now since temp is undefined in user.c, the linker can do its __real_/__wrap_magic on it.

```<code>$ gcc  user.o temp.o  -Wl,-wrap=temp
$ ./a.out
  Wrapped temp
  temp
</code>```

Title: How to wrap existing function in C

Body:
I am trying to wrap existing function.

below code is perfectly worked.

#include<stdio.h>

int __real_main();

int __wrap_main()
{
    printf("Wrapped main\n");
    return __real_main();
}

int main()
{
    printf("main\n");
    return 0;
}

command:

gcc main.c -Wl,-wrap,main

output:

Wrapped main
main

So i have changed main function with temp. my goal is to wrap temp() function.

Below is the code

temp.c

#include<stdio.h>

int temp();

int __real_temp();

int __wrap_temp()
{
    printf("Wrapped temp\n");
    return __real_temp();
}

int temp()
{
    printf("temp\n");
    return 0;
}

int main()
{
    temp();
    return 0;
}

command:

gcc temp.c -Wl,-wrap,temp

output:

temp

Wrapped temp is not printing. please guide me to wrap funciton temp.

Body:
The manpage for ld says:

   --wrap=symbol
       Use a wrapper function for symbol.  Any undefined reference to symbol will be resolved to "__wrap_symbol".  Any
       undefined reference to "__real_symbol" will be resolved to symbol.

The keyword here is undefined.

If you put the definition temp in the same translation unit as the code that uses it, it will not be undefined in the code that uses it.

You need to split the code definition and the code that uses it:

#!/bin/sh

cat > user.c  <<'EOF'
#include<stdio.h>

int temp(void);

int __real_temp(void);

int __wrap_temp()
{
    printf("Wrapped temp\n");
    return __real_temp();
}
int main()
{
    temp();
    return 0;
}
EOF

cat > temp.c <<'EOF'
#include<stdio.h>
int temp()
{
    printf("temp\n");
    return 0;
}
EOF

gcc user.c  -Wl,-wrap,temp temp.c  # OK
./a.out

Splitting the build into two separate compiles perhaps makes it clearer:

$ gcc -c user.c
$ gcc -c temp.c
$ nm user.o temp.o

temp.o:
                 U puts
0000000000000000 T temp

user.o:
0000000000000015 T main
                 U puts
                 U __real_temp
                 U temp
0000000000000000 T __wrap_temp

Now since temp is undefined in user.c, the linker can do its __real_/__wrap_magic on it.

$ gcc  user.o temp.o  -Wl,-wrap=temp
$ ./a.out
  Wrapped temp
  temp


问:
Best way to use background location updates in iOS (Swift)
I have to make an app in iOS using Swift 3 that sends the user's location via API every 3 or 5 minutes, while the app is backgrounded. I don't know which is the best way to do this, or if it's even possible because of Apple's strict background rules. The location has to be quite precise and the app needs to run for a long time backgrounded, possibly not consuming too much battery.
If it isn't possible, it would be nice to know which would be the best approach in this case. Thank you very much.</p>

答:
that sends the user's location via API every 3 or 5 minutes, while the
  app is backgrounded

Does not make much sense. What if user stands in same location for 5 minutes? you will make same location entry in your server multiple times? Isn't it better rather than updating location at certain interval, if you could update your server with user location once user's location changes??

So use locationManager, set its delegates and start updating your server via API when user location changes rather than at regular interval.

I don't know which is the best way to do this, or if it's even
  possible because of Apple's strict background rules

Its absolutely possible. All you have to do is to opt for Location Updates capability in Xcode.

Now whats the best way? Its a relative term. This depends on how your app will use the users location info. If you unnecessarily start observing users location, you will unnecessarily drain the users iPhone battery, hence apple will reject your app.

How apple process's app using location update capability?

Its pretty simple. Location updates capability comes with the cost, that if your app observes user location updates accurately in background, it will drain out the device battery. Because its a costly trade off, apple expects you to use this only if its necessary for your app.

For example : If you are making a map app or an app that tracks the users location changes and then later plots on a map or something and lets the user know about his movement (like running apps) its absolutely fine to use location update capability because you are adding value to user.

If you try to think creepy! and try to use the location update just to keep your app alive and do some thing completely unrelated to location update in background app will reject your app. Like few developers try to be over smart and use location updates to keep their app in sync with server or to upload/download files at regular interval or something like that which are no way related to location updates, apple will reject such apps.

So no way to be creepy? And use location updates to do something useful which is not related to location itself?

Yes, you can. Apple is generous enough to allow that. For example : Dropbox uploads your images in background, when you move from one location to another. All it does is, it looks for user location changes, once location changes delegates triggers, creates a upload task with background session and starts uploading files.

How to do that?

You can still use the location manager. All you have to do is to use

```<code>locationManager.startMonitoringSignificantLocationChanges()
</code>```

This will trigger your location delegates only when there is a significant location changes :)

On the other hand, if your app actually makes use of user locations and use

```<code>startLocationUpdates()
</code>```

make sure you dont consume location updates unnecessarily. Make sure u put distance filter properly according to your apps requirements. Dont be greedy and dont waste iOS resources unnecessarily and apple will be happy and will not trouble you :)

Conclusion:

If your app actually makes use of location and adds some value to user (like map app/running apps/travel apps) only then use startLocationUpdates and use distance filters properly (optional, but good to have it).

If you are being creepy always use startMonitoringSignificantLocationChanges else app is bound to get rejected

Body:
that sends the user's location via API every 3 or 5 minutes, while the
  app is backgrounded

Does not make much sense. What if user stands in same location for 5 minutes? you will make same location entry in your server multiple times? Isn't it better rather than updating location at certain interval, if you could update your server with user location once user's location changes??

So use locationManager, set its delegates and start updating your server via API when user location changes rather than at regular interval.

I don't know which is the best way to do this, or if it's even
  possible because of Apple's strict background rules

Its absolutely possible. All you have to do is to opt for Location Updates capability in Xcode.

Now whats the best way? Its a relative term. This depends on how your app will use the users location info. If you unnecessarily start observing users location, you will unnecessarily drain the users iPhone battery, hence apple will reject your app.

How apple process's app using location update capability?

Its pretty simple. Location updates capability comes with the cost, that if your app observes user location updates accurately in background, it will drain out the device battery. Because its a costly trade off, apple expects you to use this only if its necessary for your app.

For example : If you are making a map app or an app that tracks the users location changes and then later plots on a map or something and lets the user know about his movement (like running apps) its absolutely fine to use location update capability because you are adding value to user.

If you try to think creepy! and try to use the location update just to keep your app alive and do some thing completely unrelated to location update in background app will reject your app. Like few developers try to be over smart and use location updates to keep their app in sync with server or to upload/download files at regular interval or something like that which are no way related to location updates, apple will reject such apps.

So no way to be creepy? And use location updates to do something useful which is not related to location itself?

Yes, you can. Apple is generous enough to allow that. For example : Dropbox uploads your images in background, when you move from one location to another. All it does is, it looks for user location changes, once location changes delegates triggers, creates a upload task with background session and starts uploading files.

How to do that?

You can still use the location manager. All you have to do is to use

locationManager.startMonitoringSignificantLocationChanges()

This will trigger your location delegates only when there is a significant location changes :)

On the other hand, if your app actually makes use of user locations and use

startLocationUpdates()

make sure you dont consume location updates unnecessarily. Make sure u put distance filter properly according to your apps requirements. Dont be greedy and dont waste iOS resources unnecessarily and apple will be happy and will not trouble you :)

Conclusion:

If your app actually makes use of location and adds some value to user (like map app/running apps/travel apps) only then use startLocationUpdates and use distance filters properly (optional, but good to have it).

If you are being creepy always use startMonitoringSignificantLocationChanges else app is bound to get rejected


问:
java.lang.IllegalArgumentException in java spring using constructor injection
Hello i am using constructor injection in my spring demo app when i run this program i got :

java.lang.IllegalArgumentException exception

Anyone have solution where i am wong and whenever i run same program using setter injection it runs perfectly .

Here is my EmployeeBean.java

```<code>package cris;

public class Employee {
    private int id;
    private String name;
    public Employee() { }
    public Employee(int id,String name) {
        this.id=id;
        this.name=name;
    }

    public int getId() {
        return id;
    }

    public void setId(int id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }
    void show() {
        System.out.println(id+" "+name);

    }
}
</code>```

Here is my Address Bean using setter injection

```<code>package cris;

public class Address {
private String city,state,country;

public String getCity() {
    return city;
}

public void setCity(String city) {
    this.city = city;
}

public String getState() {
    return state;
}

public void setState(String state) {
    this.state = state;
}

public String getCountry() {
    return country;
}

public void setCountry(String country) {
    this.country = country;
}

public String toString()
{
    return city+" "+state+" "+country;
}
}
</code>```

Here is my spring.xml ie spring config file

```<code>    <?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE beans PUBLIC "-//SPRING//DTD BEAN 2.0//EN" "http://www.springframework.org/dtd/spring-beans-2.0.dtd">
<beans>
<bean id="a1" class="cris.Address">
<property name="city" value="Tikamgarh"></property>
<property name="state" value="Mp"></property>
<property name="country" value="India"></property>
</bean>
<bean id="e" class="cris.Employee">
<constructor-arg type="int" value="12"></constructor-arg>
<constructor-arg type="String" value="anil"></constructor-arg>
</bean>
</beans>
</code>```

And here is my Application Main Method

```<code>package cris;

import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

public class Test {
public static void main(String[] args) {
    ApplicationContext context=new ClassPathXmlApplicationContext("cris/spring.xml");
    Employee emp = (Employee)context.getBean("e");
    emp.show();
}
}
</code>```

kindly provide me suggestion where i am wrong so i will catch the exception thanks

The Exception:

```<code>Apr 03, 2017 4:16:16 PM org.springframework.context.support.ClassPathXmlApplicationContext prepareRefresh
INFO: Refreshing org.springframework.context.support.ClassPathXmlApplicationContext@27f8302d: startup date [Mon Apr 03 16:16:16 IST 2017]; root of context hierarchy
Apr 03, 2017 4:16:16 PM org.springframework.beans.factory.xml.XmlBeanDefinitionReader loadBeanDefinitions
INFO: Loading XML bean definitions from class path resource [cris/spring.xml]
Apr 03, 2017 4:16:16 PM org.springframework.beans.factory.support.DefaultListableBeanFactory preInstantiateSingletons
INFO: Pre-instantiating singletons in org.springframework.beans.factory.support.DefaultListableBeanFactory@17550481: defining beans [a1,e]; root of factory hierarchy
Exception in thread "main" java.lang.IllegalArgumentException
    at org.springframework.asm.ClassReader.<init>(Unknown Source)
    at org.springframework.asm.ClassReader.<init>(Unknown Source)
    at org.springframework.asm.ClassReader.<init>(Unknown Source)
    at org.springframework.core.LocalVariableTableParameterNameDiscoverer.inspectClass(LocalVariableTableParameterNameDiscoverer.java:112)
    at org.springframework.core.LocalVariableTableParameterNameDiscoverer.getParameterNames(LocalVariableTableParameterNameDiscoverer.java:86)
    at org.springframework.beans.factory.support.ConstructorResolver.autowireConstructor(ConstructorResolver.java:193)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.autowireConstructor(AbstractAutowireCapableBeanFactory.java:1049)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBeanInstance(AbstractAutowireCapableBeanFactory.java:953)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:490)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:461)
    at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:295)
    at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:223)
    at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:292)
    at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:194)
    at org.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons(DefaultListableBeanFactory.java:607)
    at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:932)
    at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:479)
    at org.springframework.context.support.ClassPathXmlApplicationContext.<init>(ClassPathXmlApplicationContext.java:139)
    at org.springframework.context.support.ClassPathXmlApplicationContext.<init>(ClassPathXmlApplicationContext.java:83)
at cris.Test.main(Test.java:8)
</code>```

答:
Have spring.xml like this:

```<code><?xml version = "1.0" encoding = "UTF-8"?>

<beans xmlns = "http://www.springframework.org/schema/beans"
       xmlns:xsi = "http://www.w3.org/2001/XMLSchema-instance"
       xsi:schemaLocation = "http://www.springframework.org/schema/beans
   http://www.springframework.org/schema/beans/spring-beans-3.0.xsd">

    <bean id="a1" class="cris.Address">
<property name="city" value="Tikamgarh"></property>
<property name="state" value="Mp"></property>
<property name="country" value="India"></property>
</bean>
<bean id="e" class="cris.Employee">
<constructor-arg type="int" value="12"></constructor-arg>
<constructor-arg type="String" value="anil"></constructor-arg>
</bean>

</beans>
</code>```

EDIT
My example:

spring.xml

```<code><?xml version = "1.0" encoding = "UTF-8"?>

<beans xmlns = "http://www.springframework.org/schema/beans"
       xmlns:xsi = "http://www.w3.org/2001/XMLSchema-instance"
       xsi:schemaLocation = "http://www.springframework.org/schema/beans
   http://www.springframework.org/schema/beans/spring-beans-3.0.xsd">

    <bean id="bean" class="Bean">
        <constructor-arg index="0" value="Test"/>
        <constructor-arg index="1" value="2"/>
    </bean>

</beans>
</code>```

Bean.java

```<code>public class Bean {

    private String test1;
    private int test2;

    public Bean(String test1, int test2) {
        this.test1 = test1;
        this.test2 = test2;
    }

    public String getTest1() {
        return test1;
    }

    public void setTest1(String test1) {
        this.test1 = test1;
    }

    public int getTest2() {
        return test2;
    }

    public void setTest2(int test2) {
        this.test2 = test2;
    }

    @Override
    public String toString() {
        return "Bean{" +
                "test1='" + test1 + '\'' +
                ", test2=" + test2 +
                '}';
    }
}
</code>```

Test.java

```<code>import org.springframework.context.support.ClassPathXmlApplicationContext;

public class Test {

    public static void main(String[] args) {

        final ClassPathXmlApplicationContext ctx = new ClassPathXmlApplicationContext("spring.xml");

        final Bean bean = (Bean) ctx.getBean("bean");

        System.out.println(bean.toString());
    }
}
</code>```

prints:
Bean{test1='Test', test2=2}

Body:
Hello i am using constructor injection in my spring demo app when i run this program i got :

java.lang.IllegalArgumentException exception

Anyone have solution where i am wong and whenever i run same program using setter injection it runs perfectly .

Here is my EmployeeBean.java

package cris;

public class Employee {
    private int id;
    private String name;
    public Employee() { }
    public Employee(int id,String name) {
        this.id=id;
        this.name=name;
    }

    public int getId() {
        return id;
    }

    public void setId(int id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }
    void show() {
        System.out.println(id+" "+name);

    }
}

Here is my Address Bean using setter injection

package cris;

public class Address {
private String city,state,country;

public String getCity() {
    return city;
}

public void setCity(String city) {
    this.city = city;
}

public String getState() {
    return state;
}

public void setState(String state) {
    this.state = state;
}

public String getCountry() {
    return country;
}

public void setCountry(String country) {
    this.country = country;
}

public String toString()
{
    return city+" "+state+" "+country;
}
}

Here is my spring.xml ie spring config file

    <?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE beans PUBLIC "-//SPRING//DTD BEAN 2.0//EN" "http://www.springframework.org/dtd/spring-beans-2.0.dtd">
<beans>
<bean id="a1" class="cris.Address">
<property name="city" value="Tikamgarh"></property>
<property name="state" value="Mp"></property>
<property name="country" value="India"></property>
</bean>
<bean id="e" class="cris.Employee">
<constructor-arg type="int" value="12"></constructor-arg>
<constructor-arg type="String" value="anil"></constructor-arg>
</bean>
</beans>

And here is my Application Main Method

package cris;

import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

public class Test {
public static void main(String[] args) {
    ApplicationContext context=new ClassPathXmlApplicationContext("cris/spring.xml");
    Employee emp = (Employee)context.getBean("e");
    emp.show();
}
}

kindly provide me suggestion where i am wrong so i will catch the exception thanks

The Exception:

Apr 03, 2017 4:16:16 PM org.springframework.context.support.ClassPathXmlApplicationContext prepareRefresh
INFO: Refreshing org.springframework.context.support.ClassPathXmlApplicationContext@27f8302d: startup date [Mon Apr 03 16:16:16 IST 2017]; root of context hierarchy
Apr 03, 2017 4:16:16 PM org.springframework.beans.factory.xml.XmlBeanDefinitionReader loadBeanDefinitions
INFO: Loading XML bean definitions from class path resource [cris/spring.xml]
Apr 03, 2017 4:16:16 PM org.springframework.beans.factory.support.DefaultListableBeanFactory preInstantiateSingletons
INFO: Pre-instantiating singletons in org.springframework.beans.factory.support.DefaultListableBeanFactory@17550481: defining beans [a1,e]; root of factory hierarchy
Exception in thread "main" java.lang.IllegalArgumentException
    at org.springframework.asm.ClassReader.<init>(Unknown Source)
    at org.springframework.asm.ClassReader.<init>(Unknown Source)
    at org.springframework.asm.ClassReader.<init>(Unknown Source)
    at org.springframework.core.LocalVariableTableParameterNameDiscoverer.inspectClass(LocalVariableTableParameterNameDiscoverer.java:112)
    at org.springframework.core.LocalVariableTableParameterNameDiscoverer.getParameterNames(LocalVariableTableParameterNameDiscoverer.java:86)
    at org.springframework.beans.factory.support.ConstructorResolver.autowireConstructor(ConstructorResolver.java:193)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.autowireConstructor(AbstractAutowireCapableBeanFactory.java:1049)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBeanInstance(AbstractAutowireCapableBeanFactory.java:953)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:490)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:461)
    at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:295)
    at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:223)
    at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:292)
    at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:194)
    at org.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons(DefaultListableBeanFactory.java:607)
    at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:932)
    at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:479)
    at org.springframework.context.support.ClassPathXmlApplicationContext.<init>(ClassPathXmlApplicationContext.java:139)
    at org.springframework.context.support.ClassPathXmlApplicationContext.<init>(ClassPathXmlApplicationContext.java:83)
at cris.Test.main(Test.java:8)

Body:
Have spring.xml like this:

<?xml version = "1.0" encoding = "UTF-8"?>

<beans xmlns = "http://www.springframework.org/schema/beans"
       xmlns:xsi = "http://www.w3.org/2001/XMLSchema-instance"
       xsi:schemaLocation = "http://www.springframework.org/schema/beans
   http://www.springframework.org/schema/beans/spring-beans-3.0.xsd">

    <bean id="a1" class="cris.Address">
<property name="city" value="Tikamgarh"></property>
<property name="state" value="Mp"></property>
<property name="country" value="India"></property>
</bean>
<bean id="e" class="cris.Employee">
<constructor-arg type="int" value="12"></constructor-arg>
<constructor-arg type="String" value="anil"></constructor-arg>
</bean>

</beans>

EDIT
My example:

spring.xml

<?xml version = "1.0" encoding = "UTF-8"?>

<beans xmlns = "http://www.springframework.org/schema/beans"
       xmlns:xsi = "http://www.w3.org/2001/XMLSchema-instance"
       xsi:schemaLocation = "http://www.springframework.org/schema/beans
   http://www.springframework.org/schema/beans/spring-beans-3.0.xsd">

    <bean id="bean" class="Bean">
        <constructor-arg index="0" value="Test"/>
        <constructor-arg index="1" value="2"/>
    </bean>

</beans>

Bean.java

public class Bean {

    private String test1;
    private int test2;

    public Bean(String test1, int test2) {
        this.test1 = test1;
        this.test2 = test2;
    }

    public String getTest1() {
        return test1;
    }

    public void setTest1(String test1) {
        this.test1 = test1;
    }

    public int getTest2() {
        return test2;
    }

    public void setTest2(int test2) {
        this.test2 = test2;
    }

    @Override
    public String toString() {
        return "Bean{" +
                "test1='" + test1 + '\'' +
                ", test2=" + test2 +
                '}';
    }
}

Test.java

import org.springframework.context.support.ClassPathXmlApplicationContext;

public class Test {

    public static void main(String[] args) {

        final ClassPathXmlApplicationContext ctx = new ClassPathXmlApplicationContext("spring.xml");

        final Bean bean = (Bean) ctx.getBean("bean");

        System.out.println(bean.toString());
    }
}

prints:
Bean{test1='Test', test2=2}


问:
.Net Standard or Portable Class Library moving forward?
I am writing a Portable Class Library(PCL) in my Xamarin platform and expecting to reuse that in UWP and .Net Core platform. So instead of writing as Portable class library (PCL), I should write as Standard Class Library ? So current version of Standard Library with VS2017 is 2.0 ?</p>

答: Use .NET Standard; it is compatible with a wide range of frameworks - see compatibility grid. The current version used by VS2017 is 1.6, but you can target earlier versions of .NET Standard to support earlier versions of various frameworks.</p>


问:
When i add new datepicker dynamically the previous datepicker values reset?
I have form which contain Add more field button ,which dynamically adds new datepicker's whenever i click Add More field button.

The problem is ,Currently date field in the datepicker display the current date.
But when i add new Datepicker by clicking on the Add more Field Button , it adds one more Datepicker but this time it resets the previous value of Datepicker which i had set manually.

Below is my code:
html

```<code><div id="container">
<input class="datepick" type="text"></input><button class="add">Add</button>
<input
</div>
</code>```

javascript

```<code> $(".datepick").datepicker();
$(".datepick").datepicker().datepicker("setDate", new Date());
$(document).on('click', '.add', function() {
    var appendTxt = '<input class="datepick"  type="text" /><button class="add">Add</button>';
    $("#container").append(appendTxt);
    $(".datepick").datepicker();
    $(".datepick`enter code here`").datepicker().datepicker("setDate", new Date());

});
</code>```

答:
Because of this line:

```<code>$(".datepick").datepicker();
</code>```

All inputs which have the class .datepick will reinitialize. You should do something like this:

```<code>$(".datepick").last().datepicker();
</code>```

or

```<code>$(".datepick:last").datepicker();
</code>```

after you add the new input.datepick. This was the simple solution.

If you have any other .datepick's in another container after this container, this won't work too. You should be very specific about the appended datepicker element.

You should do this :

```<code>var appendTxt = '<input class="datepick"  type="text" /><button class="add">Add</button>';
var newInput = $(appendTxt).appendTo("#container");
newInput.datepicker();
newInput.datepicker().datepicker("setDate", new Date());
</code>```

Body:
I have form which contain Add more field button ,which dynamically adds new datepicker's whenever i click Add More field button.

The problem is ,Currently date field in the datepicker display the current date.
But when i add new Datepicker by clicking on the Add more Field Button , it adds one more Datepicker but this time it resets the previous value of Datepicker which i had set manually.

Below is my code:
html

<input class="datepick" type="text"></input><button class="add">Add</button>
<input

javascript

 $(".datepick").datepicker();
$(".datepick").datepicker().datepicker("setDate", new Date());
$(document).on('click', '.add', function() {
    var appendTxt = '<input class="datepick"  type="text" /><button class="add">Add</button>';
    $("#container").append(appendTxt);
    $(".datepick").datepicker();
    $(".datepick`enter code here`").datepicker().datepicker("setDate", new Date());

});

Body:
Because of this line:

$(".datepick").datepicker();

All inputs which have the class .datepick will reinitialize. You should do something like this:

$(".datepick").last().datepicker();

or

$(".datepick:last").datepicker();

after you add the new input.datepick. This was the simple solution.

If you have any other .datepick's in another container after this container, this won't work too. You should be very specific about the appended datepicker element.

You should do this :

var appendTxt = '<input class="datepick"  type="text" /><button class="add">Add</button>';
var newInput = $(appendTxt).appendTo("#container");
newInput.datepicker();
newInput.datepicker().datepicker("setDate", new Date());


问:
How to reboot CentOS 7 with Ansible?
I'm trying to reboot server running CentOS 7 on VirtualBox. I use this task:

```<code>- name: Restart server
  command: /sbin/reboot
  async: 0
  poll: 0
  ignore_errors: true
</code>```

Server is rebooted, but I get this error:

```<code>TASK: [common | Restart server] ***********************************************
fatal: [rolcabox] => SSH Error: Shared connection to 127.0.0.1 closed.
It is sometimes useful to re-run the command using -vvvv, which prints SSH debug output to help diagnose the issue.

FATAL: all hosts have already failed -- aborting
</code>```

What am I doing wrong? How can I fix this?

答:
```<code>- name: restart server
  shell: sleep 2 && shutdown -r now "Ansible updates triggered"
  async: 1
  poll: 0
  become: true
  ignore_errors: true

- name: waiting for the server to come back
  local_action: wait_for host=testcentos state=started delay=30 timeout=300
  sudo: false
</code>```

Title: How to reboot CentOS 7 with Ansible?

Body:
I'm trying to reboot server running CentOS 7 on VirtualBox. I use this task:

- name: Restart server
  command: /sbin/reboot
  async: 0
  poll: 0
  ignore_errors: true

Server is rebooted, but I get this error:

TASK: [common | Restart server] ***********************************************
fatal: [rolcabox] => SSH Error: Shared connection to 127.0.0.1 closed.
It is sometimes useful to re-run the command using -vvvv, which prints SSH debug output to help diagnose the issue.

FATAL: all hosts have already failed -- aborting

What am I doing wrong? How can I fix this?


问:
NSFetchedResultsController with sections created by first letter of a string
Learning Core Data on the iPhone. There seem to be few examples on Core Data populating a table view with sections.  The CoreDataBooks example uses sections, but they're generated from full strings within the model.  I want to organize the Core Data table into sections by the first letter of a last name, a la the Address Book.

I could go in and create another attribute, i.e. a single letter, for each person in order to act as the section division, but this seems kludgy.

Here's what I'm starting with ... the trick seems to be fooling the sectionNameKeyPath:

```<code>- (NSFetchedResultsController *)fetchedResultsController {
//.........SOME STUFF DELETED
    // Edit the sort key as appropriate.
    NSSortDescriptor *orderDescriptor = [[NSSortDescriptor alloc] initWithKey:@"personName" ascending:YES];
    NSArray *sortDescriptors = [[NSArray alloc] initWithObjects:orderDescriptor, nil];

    [fetchRequest setSortDescriptors:sortDescriptors];
    // Edit the section name key path and cache name if appropriate.
    // nil for section name key path means "no sections".
    NSFetchedResultsController *aFetchedResultsController =
            [[NSFetchedResultsController alloc] initWithFetchRequest:fetchRequest
            managedObjectContext:managedObjectContext
            sectionNameKeyPath:@"personName" cacheName:@"Root"];
//....
}
</code>```

答:
swift 3

first, create extension to NSString (because CoreData is using basically NSString)

```<code>extension NSString{
    func firstChar() -> String{
        if self.length == 0{
            return ""
        }
        return self.substring(to: 1)
    }
}
</code>```

Then sort using firstChar keypath, in my case, lastname.firstChar

```<code>request.sortDescriptors = [
            NSSortDescriptor(key: "lastname.firstChar", ascending: true),
            NSSortDescriptor(key: "lastname", ascending: true),
            NSSortDescriptor(key: "firstname", ascending: true)
        ]
</code>```

And Finally
Use the firstChar keypath for sectionNameKeyPath

```<code>let controller = NSFetchedResultsController(fetchRequest: request, managedObjectContext: context, sectionNameKeyPath: "lastname.firstChar", cacheName: "your_cache_name")
</code>```

Body:
Learning Core Data on the iPhone. There seem to be few examples on Core Data populating a table view with sections.  The CoreDataBooks example uses sections, but they're generated from full strings within the model.  I want to organize the Core Data table into sections by the first letter of a last name, a la the Address Book.

I could go in and create another attribute, i.e. a single letter, for each person in order to act as the section division, but this seems kludgy.

Here's what I'm starting with ... the trick seems to be fooling the sectionNameKeyPath:

- (NSFetchedResultsController *)fetchedResultsController {
//.........SOME STUFF DELETED
    // Edit the sort key as appropriate.
    NSSortDescriptor *orderDescriptor = [[NSSortDescriptor alloc] initWithKey:@"personName" ascending:YES];
    NSArray *sortDescriptors = [[NSArray alloc] initWithObjects:orderDescriptor, nil];

    [fetchRequest setSortDescriptors:sortDescriptors];
    // Edit the section name key path and cache name if appropriate.
    // nil for section name key path means "no sections".
    NSFetchedResultsController *aFetchedResultsController =
            [[NSFetchedResultsController alloc] initWithFetchRequest:fetchRequest
            managedObjectContext:managedObjectContext
            sectionNameKeyPath:@"personName" cacheName:@"Root"];
//....
}

Body:
swift 3

first, create extension to NSString (because CoreData is using basically NSString)

extension NSString{
    func firstChar() -> String{
        if self.length == 0{
            return ""
        }
        return self.substring(to: 1)
    }
}

Then sort using firstChar keypath, in my case, lastname.firstChar

request.sortDescriptors = [
            NSSortDescriptor(key: "lastname.firstChar", ascending: true),
            NSSortDescriptor(key: "lastname", ascending: true),
            NSSortDescriptor(key: "firstname", ascending: true)
        ]

And Finally
Use the firstChar keypath for sectionNameKeyPath

let controller = NSFetchedResultsController(fetchRequest: request, managedObjectContext: context, sectionNameKeyPath: "lastname.firstChar", cacheName: "your_cache_name")


问:
App store app submission issue in ios
My app got rejected from app store with a reason that it crashes on launch screen. However, I've searched tremendously for any possibility that could cause the crash on launch, but unfortunately I am not able to reproduce the issue at all.

I've tried all steps mentioned by apple's team: symbolicated the crash logs, changed region of the device from India to US, tried keep the internet connection off/on while launching and so many things.

I have successfully uploaded more than 30 apps on app store and dealt with rejection several times... this time it is really killing me. I would really appreciate any help in this matter.

UPDATE

one thing I just noticed in the log: the app crashed when it was using 9.0.2 and now I've upgraded to 9.1 and it looks impossible to degrade again to 9.0.2 so is there any possibility that issue only occurs in 9.0.2 and if so, how can I resolve it without being able to reproduce it?

答:
You should analyze the crash reports before submitting the app to app store.

You can find the guidelines to submit crash reports in Apple's documentation.

https://developer.apple.com/library/content/documentation/IDEs/Conceptual/AppDistributionGuide/AnalyzingCrashReports/AnalyzingCrashReports.html

Title: App store app submission issue in ios


问:
How to add a border radius invertedly?
I'm currently trying to achieve this:

But when  border-radius: 15px 15px 0 0 I get this:

答:
Border-radius alone doesn't answer this but you can do it like this:

Overflow hidden on an outer box with circle corners:
https://codepen.io/sergejmueller/pen/fJEml

```<code>border-radius: 50%;
</code>```

You can also use radial gradients:
http://lea.verou.me/2011/03/beveled-corners-negative-border-radius-with-css3-gradients/

```<code>background-image:
radial-gradient(circle at 0 0, rgba(204,0,0,0) 14px, #c00 15px),
radial-gradient(circle at 100% 0, rgba(204,0,0,0) 14px, #c00 15px),
radial-gradient(circle at 100% 100%, rgba(204,0,0,0) 14px, #c00     15px),
radial-gradient(circle at 0 100%, rgba(204,0,0,0) 14px, #c00 15px);
</code>```

Also mask image for a modern solution:

```<code>-webkit-mask-image: radial-gradient(circle 10px at 0 0, transparent 0, transparent 20px, black 21px);
</code>```

Title: How to add a border radius invertedly?

Body:
Border-radius alone doesn't answer this but you can do it like this:

Overflow hidden on an outer box with circle corners:
https://codepen.io/sergejmueller/pen/fJEml

border-radius: 50%;

You can also use radial gradients:
http://lea.verou.me/2011/03/beveled-corners-negative-border-radius-with-css3-gradients/

background-image:
radial-gradient(circle at 0 0, rgba(204,0,0,0) 14px, #c00 15px),
radial-gradient(circle at 100% 0, rgba(204,0,0,0) 14px, #c00 15px),
radial-gradient(circle at 100% 100%, rgba(204,0,0,0) 14px, #c00     15px),
radial-gradient(circle at 0 100%, rgba(204,0,0,0) 14px, #c00 15px);

Also mask image for a modern solution:

-webkit-mask-image: radial-gradient(circle 10px at 0 0, transparent 0, transparent 20px, black 21px);


问:
How to bind highcharts from database using DotNet.Highcharts in asp.net
how to get this data "{ 29.9, 71.5, 106.4}" from database???

```<code>DotNet.Highcharts.Highcharts chart = new DotNet.Highcharts.Highcharts("chart")
.InitChart(new Chart { Type = ChartTypes.Bar })
.SetTitle(new Title { Text = "Wind speed during two days" })
.SetLegend(new Legend { Enabled = false })
.SetXAxis(new XAxis{
Categories = new[] { "Jan", "Feb", "Mar" }
 }).SetSeries(new Series{
Data = new Data(new object[] { 29.9, 71.5, 106.4})
 });
ltrChart.Text = chart.ToHtmlString();
</code>```

答:
I use this code and its work.....

```<code>DataTable dt2 = new DataTable();
dt2 = Chart_BL.fetch_Chart_Data(1);

decimal[] ar1 = new decimal[dt2.Rows.Count];

for (int i = 0; i < dt2.Rows.Count; i++)
    {
      ar1[i] = Convert.ToDecimal(dt2.Rows[i]["age"].ToString());

    }

DotNet.Highcharts.Highcharts chart2 = new DotNet.Highcharts.Highcharts("chart_2")
               .InitChart(new Chart { Type = ChartTypes.Bar })
               .SetTitle(new Title { Text = "" })
               .SetLegend(new Legend { Enabled = true })
               .SetXAxis(new XAxis
               {
                   Categories = new String[] { "10th", "11th", "10th", "11th" }
               })
                .SetSeries(new Series
                {
                    Data = new Data(ar1.Select(x => (object)x).ToArray())

                });
</code>```

enter image description here

Body:
how to get this data "{ 29.9, 71.5, 106.4}" from database???

DotNet.Highcharts.Highcharts chart = new DotNet.Highcharts.Highcharts("chart")
.InitChart(new Chart { Type = ChartTypes.Bar })
.SetTitle(new Title { Text = "Wind speed during two days" })
.SetLegend(new Legend { Enabled = false })
.SetXAxis(new XAxis{
Categories = new[] { "Jan", "Feb", "Mar" }
 }).SetSeries(new Series{
Data = new Data(new object[] { 29.9, 71.5, 106.4})
 });
ltrChart.Text = chart.ToHtmlString();

Body:
I use this code and its work.....

DataTable dt2 = new DataTable();
dt2 = Chart_BL.fetch_Chart_Data(1);

decimal[] ar1 = new decimal[dt2.Rows.Count];

for (int i = 0; i < dt2.Rows.Count; i++)
    {
      ar1[i] = Convert.ToDecimal(dt2.Rows[i]["age"].ToString());

    }

DotNet.Highcharts.Highcharts chart2 = new DotNet.Highcharts.Highcharts("chart_2")
               .InitChart(new Chart { Type = ChartTypes.Bar })
               .SetTitle(new Title { Text = "" })
               .SetLegend(new Legend { Enabled = true })
               .SetXAxis(new XAxis
               {
                   Categories = new String[] { "10th", "11th", "10th", "11th" }
               })
                .SetSeries(new Series
                {
                    Data = new Data(ar1.Select(x => (object)x).ToArray())

                });

enter image description here


问:
Print null or transparent label in Gnuplot
I would like to place a few graphs beside each other horizontally. The issue is only the one at the middle should have an xlabel.

On implementing that, the other graphs appear to start a bit below on merging all the images together. I have tried to change the color of xlabel, but it hasn't been working on epslatex. Neither supplying a null value worked ("").

```<code>set format "$%g$"
set terminal epslatex size 5.25,4.2 color standalone
set output "count.tex"

unset key
set yrange [0:18]
set xrange [0:18]
set cbrange [0:1400]
unset colorbox
set ylabel "Species 2 ----->"
set xlabel "Species 1 ----->" tc rgb "white"

plot 'combine.txt' u 1:2:3 with points pointtype 7 pointsize 3 palette
</code>```

Please help me regarding this.

答:
Most (if not all) labels and similar can be deactivated by unset. So you are looking for:

```<code>unset xlabel
</code>```

Body:
I would like to place a few graphs beside each other horizontally. The issue is only the one at the middle should have an xlabel.

On implementing that, the other graphs appear to start a bit below on merging all the images together. I have tried to change the color of xlabel, but it hasn't been working on epslatex. Neither supplying a null value worked ("").

set format "$%g$"
set terminal epslatex size 5.25,4.2 color standalone
set output "count.tex"

unset key
set yrange [0:18]
set xrange [0:18]
set cbrange [0:1400]
unset colorbox
set ylabel "Species 2 ----->"
set xlabel "Species 1 ----->" tc rgb "white"

plot 'combine.txt' u 1:2:3 with points pointtype 7 pointsize 3 palette

Please help me regarding this.

Body:
Most (if not all) labels and similar can be deactivated by unset. So you are looking for:

unset xlabel


问:
Simple getter logic in ViewModels
Is it ok to have simple logic (without any dependencies) in ViewModels getters or it should contain just automatic properties? in this case just checking for null so I don't have to do that in controller each time I am using this ViewModel. TicketSearchParameters is a simple model containing string and date properties, there is no Repository or any other dependencies.</p>

```<code>public class MyViewModel
{
    private TicketSearchParameters _searchParams;
    public TicketSearchParameters SearchParams
    {
        get
        {
            if (_searchParams == null)
            {
                _searchParams = new TicketSearchParameters();
                _searchParams.CreatedFrom = DateTime.Now.AddDays(-7);
                _searchParams.CreatedTo = DateTime.Now;
            }
            return _searchParams;
        }
        set
        {
            _searchParams = value;
        }
    }

    /*** other properties ***/

}
</code>```

答:
You code is fairly ok. But you can use NULL Object Design Pattern to check null and create NullObject.

make a class named NullSearchParams inherited from SearchParams and initialize it when needed.

You can see Null design pattern documentation here.

https://sourcemaking.com/design_patterns/null_object

Title: Simple getter logic in ViewModels

Body:
Is it ok to have simple logic (without any dependencies) in ViewModels getters or it should contain just automatic properties? in this case just checking for null so I don't have to do that in controller each time I am using this ViewModel. TicketSearchParameters is a simple model containing string and date properties, there is no Repository or any other dependencies.

public class MyViewModel
{
    private TicketSearchParameters _searchParams;
    public TicketSearchParameters SearchParams
    {
        get
        {
            if (_searchParams == null)
            {
                _searchParams = new TicketSearchParameters();
                _searchParams.CreatedFrom = DateTime.Now.AddDays(-7);
                _searchParams.CreatedTo = DateTime.Now;
            }
            return _searchParams;
        }
        set
        {
            _searchParams = value;
        }
    }

    /*** other properties ***/

}


问:
AES encryption, InvalidKeyException: Unsupported key size: 6 bytes?
I am trying to encrypt a string as follows

```<code>public class AES256Cipher {
static byte[] ivBytes = new byte[]{0x49, 0x76, 0x61, 0x6e, 0x20, 0x4d, 0x65, 0x64, 0x76, 0x65, 0x64, 0x65, 0x76};
static String EncryptionKey = "abc123";

public static byte[] encrypt(String plainText)
        throws java.io.UnsupportedEncodingException,
        NoSuchAlgorithmException,
        NoSuchPaddingException,
        InvalidKeyException,
        InvalidAlgorithmParameterException,
        IllegalBlockSizeException,
        BadPaddingException {
    byte[] keyBytes = EncryptionKey.getBytes("UTF-8");

    AlgorithmParameterSpec ivSpec = new IvParameterSpec(ivBytes);
    SecretKeySpec newKey = new SecretKeySpec(keyBytes, "AES");
    Cipher cipher = null;
    cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
    cipher.init(Cipher.ENCRYPT_MODE, newKey, ivSpec);
    byte[] cipherData = cipher.doFinal(plainText.getBytes("UTF-8"));
    Log.e("cipher", Base64.encodeToString(cipherData, Base64.DEFAULT));
    return cipher.doFinal(plainText.getBytes("UTF-8"));
}
}
</code>```

I am getting this exception

```<code>java.security.InvalidKeyException: Unsupported key size: 6 bytes
at com.android.org.conscrypt.OpenSSLCipher$EVP_CIPHER$AES.checkSupportedKeySize(OpenSSLCipher.java:686)
at com.android.org.conscrypt.OpenSSLCipher.checkAndSetEncodedKey(OpenSSLCipher.java:442)
at com.android.org.conscrypt.OpenSSLCipher.engineInit(OpenSSLCipher.java:272)
at javax.crypto.Cipher.tryTransformWithProvider(Cipher.java:608)
at javax.crypto.Cipher.tryCombinations(Cipher.java:532)
at javax.crypto.Cipher.getSpi(Cipher.java:437)
at javax.crypto.Cipher.init(Cipher.java:909)
at javax.crypto.Cipher.init(Cipher.java:859)
at com.vfirst.util.netwrok.AES256Cipher.encrypt(AES256Cipher.java:36)
at com.vfirst.LoginActivity.onCreate(LoginActivity.java:61)
at android.app.Activity.performCreate(Activity.java:6321)
</code>```

String to encrypt

```<code>AES256Cipher.encrypt("12345");
</code>```

答:
If you want to use a password you should derive an AES key from your password instead of trying to use the password directly as a key.

The simplest way would be to hash the password using SHA-256 and use the hashed password as AES key.

The common way (preferred) is to use PBKDF2 e.g. with HMAC-SHA1 that generates an AES key (128/192 or 256 bit) from an password:

```<code>byte[] salt = new byte[8];
random.nextBytes(salt);
KeySpec spec = new PBEKeySpec(EncryptionKey.toCharArray(), salt, 65536, 128);
SecretKeyFactory f = SecretKeyFactory.getInstance("PBKDF2WithHmacSHA1");
byte[] keyBytes = f.generateSecret(spec).getEncoded();
</code>```

Note that you have to store the random salt if you want to generate later the same key from the password.

Body:
I am trying to encrypt a string as follows

public class AES256Cipher {
static byte[] ivBytes = new byte[]{0x49, 0x76, 0x61, 0x6e, 0x20, 0x4d, 0x65, 0x64, 0x76, 0x65, 0x64, 0x65, 0x76};
static String EncryptionKey = "abc123";

public static byte[] encrypt(String plainText)
        throws java.io.UnsupportedEncodingException,
        NoSuchAlgorithmException,
        NoSuchPaddingException,
        InvalidKeyException,
        InvalidAlgorithmParameterException,
        IllegalBlockSizeException,
        BadPaddingException {
    byte[] keyBytes = EncryptionKey.getBytes("UTF-8");

    AlgorithmParameterSpec ivSpec = new IvParameterSpec(ivBytes);
    SecretKeySpec newKey = new SecretKeySpec(keyBytes, "AES");
    Cipher cipher = null;
    cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
    cipher.init(Cipher.ENCRYPT_MODE, newKey, ivSpec);
    byte[] cipherData = cipher.doFinal(plainText.getBytes("UTF-8"));
    Log.e("cipher", Base64.encodeToString(cipherData, Base64.DEFAULT));
    return cipher.doFinal(plainText.getBytes("UTF-8"));
}
}

I am getting this exception

java.security.InvalidKeyException: Unsupported key size: 6 bytes
at com.android.org.conscrypt.OpenSSLCipher$EVP_CIPHER$AES.checkSupportedKeySize(OpenSSLCipher.java:686)
at com.android.org.conscrypt.OpenSSLCipher.checkAndSetEncodedKey(OpenSSLCipher.java:442)
at com.android.org.conscrypt.OpenSSLCipher.engineInit(OpenSSLCipher.java:272)
at javax.crypto.Cipher.tryTransformWithProvider(Cipher.java:608)
at javax.crypto.Cipher.tryCombinations(Cipher.java:532)
at javax.crypto.Cipher.getSpi(Cipher.java:437)
at javax.crypto.Cipher.init(Cipher.java:909)
at javax.crypto.Cipher.init(Cipher.java:859)
at com.vfirst.util.netwrok.AES256Cipher.encrypt(AES256Cipher.java:36)
at com.vfirst.LoginActivity.onCreate(LoginActivity.java:61)
at android.app.Activity.performCreate(Activity.java:6321)

String to encrypt

AES256Cipher.encrypt("12345");

Body:
If you want to use a password you should derive an AES key from your password instead of trying to use the password directly as a key.

The simplest way would be to hash the password using SHA-256 and use the hashed password as AES key.

The common way (preferred) is to use PBKDF2 e.g. with HMAC-SHA1 that generates an AES key (128/192 or 256 bit) from an password:

byte[] salt = new byte[8];
random.nextBytes(salt);
KeySpec spec = new PBEKeySpec(EncryptionKey.toCharArray(), salt, 65536, 128);
SecretKeyFactory f = SecretKeyFactory.getInstance("PBKDF2WithHmacSHA1");
byte[] keyBytes = f.generateSecret(spec).getEncoded();

Note that you have to store the random salt if you want to generate later the same key from the password.


问:
Text becomes "Red" color; Can't find the code that makes it "Red"
I have a simple php page which outputs a table (which has been created dynamically).

The text on the page is all red marked, unless you specifically put a font color element and force it to become black.

I use FF and have Firebug installed, so I wonder if you guys have any tips on how to troubleshoot why this text isn't black?

I have tried:

1- Setting the body text color to 000 both with css and html... Didn't work!

2- Checking all classes.

Any tips???

All I have figured out is that when I DONT include my css files, the text becomes black standard. And I have looked at the css files without finding anything suspicious.

How should I troubleshoot?

Isn't there any way to check which styles if any, a text has applied to it somehow?

答:
Ahhh, I forgot the cache of the browser!

I have used 3 different browsers, and none of them updated the cache when I hit F5 several times, so all 3 where showing the old color.

Sorry guys, and thanks!


问:
Routing to static html page in /public
How can I route /foo to display /public/foo.html in Rails?

答:
This can be done without triggering a redirect. Follow the steps further down to be able to route static files in config/routes.rb as shown in this example:

```<code># This route will serve public/index.html at the /login URL
# path, and have a URL helper named `login_path`:
get "/login", to: static("index.html")

# This route will serve public/register.html at the /register
# URL path, and have URL helper named `new_user_registration_path`:
get "/register", to: static("register.html"), as: :new_user_registration
</code>```

Install the rails-static-router gem: https://github.com/mufid/rails-static-router#installation

Restart app (first bin/spring stop to be sure app is completely reloaded).

Start using the static(path) method in your config/routes.rb.

Title: Routing to static html page in /public

Body:
This can be done without triggering a redirect. Follow the steps further down to be able to route static files in config/routes.rb as shown in this example:

# This route will serve public/index.html at the /login URL
# path, and have a URL helper named `login_path`:
get "/login", to: static("index.html")

# This route will serve public/register.html at the /register
# URL path, and have URL helper named `new_user_registration_path`:
get "/register", to: static("register.html"), as: :new_user_registration

Install the rails-static-router gem: https://github.com/mufid/rails-static-router#installation

Restart app (first bin/spring stop to be sure app is completely reloaded).

Start using the static(path) method in your config/routes.rb.

ContentLicense: CC BY-SA 4.0


问:
How to restricts firebase storage access with my own authentication service
I am using firebase storage in my app, And i am using my own user name and password authentication service, I have changed the rules to public so that i can upload and download data, but now i it gives me this warning

Your security rules are set to public. Anyone can read or write to
  your storage bucket

How can i protect app data without using any firebase sign-in or authentication methods ??

答:
Firebase rules are for both read and write </p>

```<code>{
  "rules": {
    "foo": {
      ".read": true,
      ".write": false
    }
  }
}
</code>```

<p>you can make a variable read as true so that others can read the data but they can write into your data. hence your data is safe .
Hope you got it </p>

Body:
Firebase rules are for both read and write

{
  "rules": {
    "foo": {
      ".read": true,
      ".write": false
    }
  }
}

you can make a variable read as true so that others can read the data but they can write into your data. hence your data is safe .
Hope you got it


问:
Can "git pull --all" update all my local branches?
I often have at least 3 remote branches: master, staging and production. I have 3 local branches that track those remote branches.

Updating all my local branches is tedious:

```<code>git fetch --all
git rebase origin/master
git checkout staging
git rebase origin/staging
git checkout production
git rebase origin/production
</code>```

I'd love to be able to just do a "git pull -all", but I haven't been able to get it to work. It seems to do a "fetch --all", then updates (fast forward or merges) the current working branch, but not the other local branches.

I'm still stuck manually switching to each local branch and updating.

答:
It's not so hard to automate:</p>

```<code>#!/bin/sh
# Usage: fetchall.sh branch ...

set -x
git fetch --all
for branch in "$@"; do
    git checkout "$branch"      || exit 1
    git rebase "origin/$branch" || exit 1
done
</code>```

Body:
I often have at least 3 remote branches: master, staging and production. I have 3 local branches that track those remote branches.

Updating all my local branches is tedious:

git fetch --all
git rebase origin/master
git checkout staging
git rebase origin/staging
git checkout production
git rebase origin/production

I'd love to be able to just do a "git pull -all", but I haven't been able to get it to work. It seems to do a "fetch --all", then updates (fast forward or merges) the current working branch, but not the other local branches.

I'm still stuck manually switching to each local branch and updating.

Body:
It's not so hard to automate:

#!/bin/sh
# Usage: fetchall.sh branch ...

set -x
git fetch --all
for branch in "$@"; do
    git checkout "$branch"      || exit 1
    git rebase "origin/$branch" || exit 1
done


问:
SBT - task to transitively gather subprojects information
I'm trying to implement a simple task (and learn SBT - again - at the same time). After spending about 8 hours trying to figure the solution, hit many dead-end ways, read a lot of SBT docs and SO entries and having built up a massive heap of anger and frustration, I'm posting the question here.

I need to implement a task, transitiveBaseDirectories, that will (in sbt console) allow me to query projects for it's dependening projects tasks in a multi-project build (an example structure is at the end of this post) like this:

projectA/transitiveBaseDirectories

(made up desired output)

Seq(File("./projectA"), File("./projectAA"), File("./projectAAA"), File("./projectAB")))

for this example project

lazy val transitiveBaseDirectories = taskKey[Seq[File]](
    "Returns a list of baseDirectory-ies of all projects a given project transitively depends on."
)

def transitiveBaseDirectoriesImpl = ???

lazy val root = project.dependsOn(projectA, projectB)

lazy val projectA = project.dependsOn(projectAA, projectAB)

lazy val projectAA = project.dependsOn(projectAAA)

lazy val projectAAA = project

lazy val projectAB = project.dependsOn(projectAB)

lazy val projectB = project
```

Then it will be necessary to somehow make transitiveBaseDirectories available for all projects - I also don't know how to do that.

I'm deliberately not showing here all my failed attempts (various takes on Product.extract(state.value), baseDirectory.all(ScopeFilter(inDependencies(...))) etc). On my SBT explorations I've had the "almost-there" feeling on several occasions, followed by waves of confusion and realization that I just don't get the SBT big picture necessary to complete the task, and more frustration. I've given up, again, this is my maybe third occasion to implement a non-trivial task in SBT, and it has never ended well (in the better cases, I've succeeded, but didn't really understand what I did).

I would really appreciate a minimal, but complete solution here, because I've been halfway through too many times, if I'm not asking too much.

Thank you very much.

答:
Many thanks to Justin Kaeser. Just for completeness, the whole solution, which also adds the tasks to all projects, is to

create a file project/TransitiveDirsPlugin.scala with the following contents:

import sbt.Keys._
import sbt._

object TransitiveDirsPlugin extends AutoPlugin {
  override def trigger: PluginTrigger = allRequirements

  private[this] val directProjectDeps =
    taskKey[Map[String, Seq[ProjectRef]]]("project dependencies!")

  private[this] val transitiveProjectDeps =
    taskKey[Map[String, Seq[ProjectRef]]]("transitive project dependencies!")

  private[this] val transitiveProjectDirs =
    taskKey[Map[String, Seq[File]]]("transitive project dependencies!")

  private[this] val myTransitiveProjectDirs: TaskKey[Seq[File]] =
    taskKey[Seq[File]]("just my dirs")

  override lazy val projectSettings = Seq(
    directProjectDeps := {
      val extracted = Project extract state.value
      extracted.structure.allProjects.map { p ⇒
        val deps = p.dependencies.map(_.project)
        (p.id, deps)
      }.toMap
    },

    transitiveProjectDeps := {
      val deps = directProjectDeps.value

      def transitives(id: String): Seq[ProjectRef] = {
        val direct = deps(id)
        direct ++ direct.flatMap(d => transitives(d.project))
      }

      deps.map { case (id, _) => (id, transitives(id)) }
    },

    transitiveProjectDirs := {
      val extracted = Project extract state.value
      transitiveProjectDeps.value.mapValues { v =>
        v.map(ref => extracted.get(baseDirectory in ref))
      }
    },

    myTransitiveProjectDirs :=
      transitiveProjectDirs.value.apply(thisProjectRef.value.project)
  )
}
```

Now I can use show projectA/myTransitiveProjectDirs et al. Thank you, Justin.

Body:
I'm trying to implement a simple task (and learn SBT - again - at the same time). After spending about 8 hours trying to figure the solution, hit many dead-end ways, read a lot of SBT docs and SO entries and having built up a massive heap of anger and frustration, I'm posting the question here.

I need to implement a task, transitiveBaseDirectories, that will (in sbt console) allow me to query projects for it's dependening projects tasks in a multi-project build (an example structure is at the end of this post) like this:

projectA/transitiveBaseDirectories

(made up desired output)

Seq(File("./projectA"), File("./projectAA"), File("./projectAAA"), File("./projectAB")))

for this example project

lazy val transitiveBaseDirectories = taskKey[Seq[File]](
    "Returns a list of baseDirectory-ies of all projects a given project transitively depends on."
)

def transitiveBaseDirectoriesImpl = ???

lazy val root = project.dependsOn(projectA, projectB)

lazy val projectA = project.dependsOn(projectAA, projectAB)

lazy val projectAA = project.dependsOn(projectAAA)

lazy val projectAAA = project

lazy val projectAB = project.dependsOn(projectAB)

lazy val projectB = project

Then it will be necessary to somehow make transitiveBaseDirectories available for all projects - I also don't know how to do that.

I'm deliberately not showing here all my failed attempts (various takes on Product.extract(state.value), baseDirectory.all(ScopeFilter(inDependencies(...))) etc). On my SBT explorations I've had the "almost-there" feeling on several occasions, followed by waves of confusion and realization that I just don't get the SBT big picture necessary to complete the task, and more frustration. I've given up, again, this is my maybe third occasion to implement a non-trivial task in SBT, and it has never ended well (in the better cases, I've succeeded, but didn't really understand what I did).

I would really appreciate a minimal, but complete solution here, because I've been halfway through too many times, if I'm not asking too much.

Thank you very much.

Body:
Many thanks to Justin Kaeser. Just for completeness, the whole solution, which also adds the tasks to all projects, is to

create a file project/TransitiveDirsPlugin.scala with the following contents:

import sbt.Keys._
import sbt._

object TransitiveDirsPlugin extends AutoPlugin {
  override def trigger: PluginTrigger = allRequirements

  private[this] val directProjectDeps =
    taskKey[Map[String, Seq[ProjectRef]]]("project dependencies!")

  private[this] val transitiveProjectDeps =
    taskKey[Map[String, Seq[ProjectRef]]]("transitive project dependencies!")

  private[this] val transitiveProjectDirs =
    taskKey[Map[String, Seq[File]]]("transitive project dependencies!")

  private[this] val myTransitiveProjectDirs: TaskKey[Seq[File]] =
    taskKey[Seq[File]]("just my dirs")

  override lazy val projectSettings = Seq(
    directProjectDeps := {
      val extracted = Project extract state.value
      extracted.structure.allProjects.map { p ⇒
        val deps = p.dependencies.map(_.project)
        (p.id, deps)
      }.toMap
    },

    transitiveProjectDeps := {
      val deps = directProjectDeps.value

      def transitives(id: String): Seq[ProjectRef] = {
        val direct = deps(id)
        direct ++ direct.flatMap(d => transitives(d.project))
      }

      deps.map { case (id, _) => (id, transitives(id)) }
    },

    transitiveProjectDirs := {
      val extracted = Project extract state.value
      transitiveProjectDeps.value.mapValues { v =>
        v.map(ref => extracted.get(baseDirectory in ref))
      }
    },

    myTransitiveProjectDirs :=
      transitiveProjectDirs.value.apply(thisProjectRef.value.project)
  )
}

Now I can use show projectA/myTransitiveProjectDirs et al. Thank you, Justin.


问:
find multiple occurences as part of larger pattern
I have a string the looks like such:

```<code>string = 0.033 0.0331
string2   =  0.0022e+002  123.4
</code>```

In this case the list of numbers is two for both strings, but this can be one or more.

I want to match the string and numbers such that I use the numbers and put them in a list. However I can't seem to match all the individual numbers. I use the following regex (example string as input):

```<code>matchNum = re.findall(r'(\S+)\s*=\s*((\d+\.?\d*e?[+-]?\d*)\s*)+', 'string2   =  0.0022e+002  123.4')
</code>```

This however only returns the string and the last number (twice), like such:

```<code>[('String2', '123.4\n', '123.4')]
</code>```

Any idea how I would be able to get this (?):

```<code>[('String2', '0.0022e+002', '123.4')]
</code>```

As mentioned there can also be one or more numbers but there will always be one string in the front.

答:
You may collect the matches first, capturing the part before = into Group 1
and the part after = into Group 2, and use a second regex to only extract the numbers. Here is a snippet that you may adjust further to suit any specific requirements:

```<code>import re
s = 'string2   =  0.0022e+002  123.4'
r1 = re.compile(r'(\S+)\s*=\s*((?:(?:-?\d+\.?\d*(?:e[+-]?\d+)?)\s*)+)', re.I)
r2 = re.compile(r'-?\d+\.?\d*(?:e?[+-]?\d+)?', re.I)
matches = r1.finditer(s)
res = []
for x in matches:
    tmp = [x.group(1)]
    tmp.extend(r2.findall(x.group(2)))
    res.append(tmp)
print(res)
</code>```

See the Python demo

The r1 regex finds the matches with all the data you need, and r2 will extract the necessary numbers from Group 2 once there is a match.

Body:
I have a string the looks like such:

string = 0.033 0.0331
string2   =  0.0022e+002  123.4

In this case the list of numbers is two for both strings, but this can be one or more.

I want to match the string and numbers such that I use the numbers and put them in a list. However I can't seem to match all the individual numbers. I use the following regex (example string as input):

matchNum = re.findall(r'(\S+)\s*=\s*((\d+\.?\d*e?[+-]?\d*)\s*)+', 'string2   =  0.0022e+002  123.4')

This however only returns the string and the last number (twice), like such:

[('String2', '123.4\n', '123.4')]

Any idea how I would be able to get this (?):

[('String2', '0.0022e+002', '123.4')]

As mentioned there can also be one or more numbers but there will always be one string in the front.

Body:
You may collect the matches first, capturing the part before = into Group 1
and the part after = into Group 2, and use a second regex to only extract the numbers. Here is a snippet that you may adjust further to suit any specific requirements:

import re
s = 'string2   =  0.0022e+002  123.4'
r1 = re.compile(r'(\S+)\s*=\s*((?:(?:-?\d+\.?\d*(?:e[+-]?\d+)?)\s*)+)', re.I)
r2 = re.compile(r'-?\d+\.?\d*(?:e?[+-]?\d+)?', re.I)
matches = r1.finditer(s)
res = []
for x in matches:
    tmp = [x.group(1)]
    tmp.extend(r2.findall(x.group(2)))
    res.append(tmp)
print(res)

See the Python demo

The r1 regex finds the matches with all the data you need, and r2 will extract the necessary numbers from Group 2 once there is a match.


问:
How do I determine if my Selenium script was able to log in?
How can I make this selenium script know if it was able to log in or not? Currently I am using is_displayed() to see if the login form is still on the page. Is there a better way?

```<code>driver.find_element_by_id("uname").send_keys("admin")
driver.find_element_by_id("pwd").send_keys("admin")
driver.find_element_by_xpath('//*[@id="login_form"]/div/button').click()

# below xpath is code for invalid user id or password message
if driver.find_element_by_xpath('//*[@id="login_form"]/div[1]').is_displayed():
    output=open("OutputAdmin","w+")
    output.write("Login unsuccessful")
    output.close()
else:
    output = open("OutputAdmin", "w+")
    output.write("Login successful")
    output.close()
driver.quit()
</code>```

Now if user id or password is incorrect it is working fine but if they are correct it doesn't execute else code.

答:
```<code>try:
    LoginFailMessage = driver.find_element_by_xpath('//*[@id="login_form"]/div[1]')
    if LoginFailMessage.is_displayed():
        output=open("OutputAdmin","w+")
        output.write("Login unsuccessful")
        output.close()
except:
    output = open("OutputAdmin", "w+")
    output.write("Login successful")
    output.close()
</code>```

i have solved the issue.thanks to those who tried to solve it.

Body:
How can I make this selenium script know if it was able to log in or not? Currently I am using is_displayed() to see if the login form is still on the page. Is there a better way?

driver.find_element_by_id("uname").send_keys("admin")
driver.find_element_by_id("pwd").send_keys("admin")
driver.find_element_by_xpath('//*[@id="login_form"]/div/button').click()

# below xpath is code for invalid user id or password message
if driver.find_element_by_xpath('//*[@id="login_form"]/div[1]').is_displayed():
    output=open("OutputAdmin","w+")
    output.write("Login unsuccessful")
    output.close()
else:
    output = open("OutputAdmin", "w+")
    output.write("Login successful")
    output.close()
driver.quit()

Now if user id or password is incorrect it is working fine but if they are correct it doesn't execute else code.

Body:
try:
    LoginFailMessage = driver.find_element_by_xpath('//*[@id="login_form"]/div[1]')
    if LoginFailMessage.is_displayed():
        output=open("OutputAdmin","w+")
        output.write("Login unsuccessful")
        output.close()
except:
    output = open("OutputAdmin", "w+")
    output.write("Login successful")
    output.close()

i have solved the issue.thanks to those who tried to solve it.