问:
C# .Net Core dependency injection, inject multiple parameters to constructor
I have AuthenticationStrategy class which I'm going to inject in controller constructor.

I have two IAuthenticationProviders: InternalAuthenticationProvider and ExternalAuthenticationProvider.

In AuthenticationStrategy constructor I want to inject all providers.

Sample code:

```<code>public class AuthenticationStrategy
{
    private readonly Dictionary<string, IAuthenticationProvider> _authenticationProviders;

    public AuthenticationStrategy(IAuthenticationProvider[] authenticationProviders)
    {
        if (authenticationProviders == null)
        {
            throw new ArgumentNullException("AuthenticationProviders");
        }

        _authenticationProviders = authenticationProviders
            .ToDictionary(x => nameof(x), x => x);
    }
}
</code>```

How can I inject multiple providers using depency injection?
Sample code:

```<code>services.AddScoped<IAuthenticationProvider, InternalAuthenticationProvider>();
services.AddScoped<IAuthenticationProvider, ExternalAuthenticationProvider>();
services.AddScoped<AuthenticationStrategy>();
</code>```

Any ideas?

答:
Assuming you are using Asp.Net Core project type with Visual Studio 2017

Lets say you have the following defination of an interface:

```<code>   public interface IAuthenticationProvider
    {
    }
</code>```

with implementing classes like so:

```<code>public class WindowsAuthentication : IAuthenticationProvider { }

public class NTMLAuthentication : IAuthenticationProvider { }

public class KerberosAuthentication : IAuthenticationProvider { }

public class CustomAuthentication : IAuthenticationProvider { }
</code>```

So far so good. Now to resolve the dependencies for the types implementing the same interface I would use the custom resolver class with its interface:

```<code>public interface IAuthenticationResolver
{
    IAuthenticationProvider GetProvider(Type type);
}
</code>```

and its implementation:

```<code>public class AuthenticationResolver : IAuthenticationResolver
    {
        private readonly IServiceProvider services;
        public AuthenticationResolver(IServiceProvider services)
        {
            this.services = services;
        }

        public IAuthenticationProvider GetProvider(Type type)
        {
            return this.services.GetService(type) as IAuthenticationProvider;
        }
    }
</code>```

In your Startup class, under ConfigureServices register these types

```<code> services.AddTransient<IAuthenticationResolver, AuthenticationResolver>();
            services.AddTransient<WindowsAuthentication>();
            services.AddTransient<KerberosAuthentication>();
            services.AddTransient<NTMLAuthentication>();
            services.AddTransient<CustomAuthentication>();
</code>```

Of course you can use Scopped if thats what you need.

Once this is all set, go back to your controller / client class where the dependencies are injected:

```<code> public class HomeController : Controller
 {
        private readonly Dictionary<string, IAuthenticationProvider> authProvidersDictionary;

        public HomeController(IAuthenticationResolver resolver)
        {
            System.Reflection.Assembly ass = System.Reflection.Assembly.GetEntryAssembly();
            this.authProvidersDictionary = new Dictionary<string, IAuthenticationProvider>();

            foreach (System.Reflection.TypeInfo ti in ass.DefinedTypes)
            {
                if (ti.ImplementedInterfaces.Contains(typeof(IAuthenticationProvider)))
                {

                    this.authProvidersDictionary.Add(ti.Name, resolver.GetProvider(ti.UnderlyingSystemType));
                }
            }
        }
}
</code>```

Hope this helps!

Body:
I have AuthenticationStrategy class which I'm going to inject in controller constructor.

I have two IAuthenticationProviders: InternalAuthenticationProvider and ExternalAuthenticationProvider.

In AuthenticationStrategy constructor I want to inject all providers.

Sample code:

public class AuthenticationStrategy
{
    private readonly Dictionary<string, IAuthenticationProvider> _authenticationProviders;

    public AuthenticationStrategy(IAuthenticationProvider[] authenticationProviders)
    {
        if (authenticationProviders == null)
        {
            throw new ArgumentNullException("AuthenticationProviders");
        }

        _authenticationProviders = authenticationProviders
            .ToDictionary(x => nameof(x), x => x);
    }
}

How can I inject multiple providers using depency injection?
Sample code:

services.AddScoped<IAuthenticationProvider, InternalAuthenticationProvider>();
services.AddScoped<IAuthenticationProvider, ExternalAuthenticationProvider>();
services.AddScoped<AuthenticationStrategy>();

Any ideas?

Body:
Assuming you are using Asp.Net Core project type with Visual Studio 2017

Lets say you have the following defination of an interface:

   public interface IAuthenticationProvider
    {
    }

with implementing classes like so:

public class WindowsAuthentication : IAuthenticationProvider { }

public class NTMLAuthentication : IAuthenticationProvider { }

public class KerberosAuthentication : IAuthenticationProvider { }

public class CustomAuthentication : IAuthenticationProvider { }

So far so good. Now to resolve the dependencies for the types implementing the same interface I would use the custom resolver class with its interface:

public interface IAuthenticationResolver
{
    IAuthenticationProvider GetProvider(Type type);
}

and its implementation:

public class AuthenticationResolver : IAuthenticationResolver
    {
        private readonly IServiceProvider services;
        public AuthenticationResolver(IServiceProvider services)
        {
            this.services = services;
        }

        public IAuthenticationProvider GetProvider(Type type)
        {
            return this.services.GetService(type) as IAuthenticationProvider;
        }
    }

In your Startup class, under ConfigureServices register these types

 services.AddTransient<IAuthenticationResolver, AuthenticationResolver>();
            services.AddTransient<WindowsAuthentication>();
            services.AddTransient<KerberosAuthentication>();
            services.AddTransient<NTMLAuthentication>();
            services.AddTransient<CustomAuthentication>();

Of course you can use Scopped if thats what you need.

Once this is all set, go back to your controller / client class where the dependencies are injected:

 public class HomeController : Controller
 {
        private readonly Dictionary<string, IAuthenticationProvider> authProvidersDictionary;

        public HomeController(IAuthenticationResolver resolver)
        {
            System.Reflection.Assembly ass = System.Reflection.Assembly.GetEntryAssembly();
            this.authProvidersDictionary = new Dictionary<string, IAuthenticationProvider>();

            foreach (System.Reflection.TypeInfo ti in ass.DefinedTypes)
            {
                if (ti.ImplementedInterfaces.Contains(typeof(IAuthenticationProvider)))
                {

                    this.authProvidersDictionary.Add(ti.Name, resolver.GetProvider(ti.UnderlyingSystemType));
                }
            }
        }
}

Hope this helps!


来源: stackexchange

问:
Regular Expressions - String between 2 Strings which have symbols in it
I want to get following content out of the search string

```<code>searchstring = URL:<br/>https://example.com/welcome?code=3Dhe58e21ae1d160d1.53418445<br/>If you prefer

stringoutput = https://example.com/welcome?code=3Dhe58e21ae1d160d1.53418445
</code>```

I tried to use (.*?) but it said that I have to close the /.

Can anyone help me? I'm stuck hard at this point

ContentLicense: CC BY-SA 3.0

Body:
I want to get following content out of the search string

searchstring = URL:
https://example.com/welcome?code=3Dhe58e21ae1d160d1.53418445
If you prefer

stringoutput = https://example.com/welcome?code=3Dhe58e21ae1d160d1.53418445

I tried to use (.*?) but it said that I have to close the /.

Can anyone help me? I'm stuck hard at this point

Body: URL:<br\/>(.*)<br\/>.*


问:
OpenMP: What is the benefit of nesting parallelizations?
From what I understand, #pragma omp parallel and its variations basically execute the following block in a number of concurrent threads, which corresponds to the number of CPUs. When having nested parallelizations - parallel for within parallel for, parallel function within parallel function etc. - what happens on the inner parallelization?

I'm new to OpenMP, and the case I have in mind is probably rather trivial - multiplying a vector with a matrix. This is done in two nested for loops. Assuming the number of CPUs is smaller than the number of elements in the vector, is there any benefit in trying to run the inner loop in parallel? Will the total number of threads be larger than the number of CPUs, or will the inner loop be executed sequentially?

答:
For something like dense linear algebra, where all the potential parallelism is already lain bare in one place in nice wide for loops, you don't need nested parallism -- if you do want to protect against the case of having (say) really narrow matricies where the leading dimension might be smaller than the number of cores, then all you need is the collapse directive which notionally flattens the multiple loops into one.

Nested parallelism is for those cases where the parallelism isn't all exposed at once -- say you want to do 2 simultaneous function evaluations, each of which could usefully utilize 4 cores, and you have an 8 core system.  You call the function in a parallel section, and within the function definition there is an additional, say, parallel for.

ContentLicense: CC BY-SA 2.5


问:
ASP.NET core 1.1 HTTP Error 502.5 - Process Failure on startup
When I try and startup my ASP.NETcore 1.1 on my server I get the error:

HTTP Error 502.5 - Process Failure

Common causes of this issue:

The application process failed to start The application process
  started but then stopped The application process started but failed to
  listen on the configured port

I checked the event viewer.

Application: MyApp.exe Framework Version: v4.0.30319 Description: The
  process was terminated due to an unhandled exception. Exception Info:
  System.IO.FileLoadException at MyApp.Program.Main(System.String[])

MyApp.Program.Main is

```<code>public class Program
    {
        public static void Main(string[] args)
        {
            Console.Title = "IdentityServer";

            var host = new WebHostBuilder()
                .UseKestrel()
                .UseUrls("http://localhost:5000")
                .UseContentRoot(Directory.GetCurrentDirectory())
                .UseIISIntegration()
                .UseStartup<Startup>()
                .Build();

            host.Run();
        }
    }
</code>```

This is based on the Identity Server 4 code.

Stdout has

Unhandled Exception: System.IO.FileLoadException: Could not load file
  or assembly 'Microsoft.AspNetCore.Hosting, Version=1.1.0.0

I have added Microsoft.AspNetCore.Hosting via NuGet to my project. Microsoft.AspNetCore.Hosting.dll is in my published files...

After doing some more digging I found this post Can't load Microsoft.AspNetCore.Hosting 1.1.0.0 #1826. It suggests to remove app.AddBrowserLink();. AddBrowserLink() is not used at all in my code.

By commenting out code the error seems to come when I reference a project that is not .NET Core based that depends on traditional .NET.

I am using Visual Studio 2017.

答:
Hansleman had the answer from his post How to reference an existing .NET Framework Project in an ASP.NET Core 1.0 Web App.

I had created an ASP.NET Core 1.1 app pointing to .NET Core.
I recreated my website as ASP.NET Core 1.1 and had it point to .NET Framework and then the code that was failing ran.

Body:
When I try and startup my ASP.NETcore 1.1 on my server I get the error:

HTTP Error 502.5 - Process Failure

Common causes of this issue:

The application process failed to start The application process
  started but then stopped The application process started but failed to
  listen on the configured port

I checked the event viewer.

Application: MyApp.exe Framework Version: v4.0.30319 Description: The
  process was terminated due to an unhandled exception. Exception Info:
  System.IO.FileLoadException at MyApp.Program.Main(System.String[])

MyApp.Program.Main is

public class Program
    {
        public static void Main(string[] args)
        {
            Console.Title = "IdentityServer";

            var host = new WebHostBuilder()
                .UseKestrel()
                .UseUrls("http://localhost:5000")
                .UseContentRoot(Directory.GetCurrentDirectory())
                .UseIISIntegration()
                .UseStartup<Startup>()
                .Build();

            host.Run();
        }
    }

This is based on the Identity Server 4 code.

Stdout has

Unhandled Exception: System.IO.FileLoadException: Could not load file
  or assembly 'Microsoft.AspNetCore.Hosting, Version=1.1.0.0

I have added Microsoft.AspNetCore.Hosting via NuGet to my project. Microsoft.AspNetCore.Hosting.dll is in my published files...

After doing some more digging I found this post Can't load Microsoft.AspNetCore.Hosting 1.1.0.0 #1826. It suggests to remove app.AddBrowserLink();. AddBrowserLink() is not used at all in my code.

By commenting out code the error seems to come when I reference a project that is not .NET Core based that depends on traditional .NET.

I am using Visual Studio 2017.


问:
Grouping Variables in C#?
I'm new to C# started recently and had an idea to make a small text based RPG sort of a game, I am using Visual Studio 2017. I want to have a few different files, including one that marks down all the different types of enemies in the game, how much damage one of their attacks do, their defense and how much health they have. I have this so far:

```<code>        string rat;
        int enemyHealth;
        int enemyAtkDmg;
        int enemyDef;
</code>```

But then I started wondering how I could group "string rat;" and the rest together, so for example:

Rat - 10 Health, 2 Attack Damage, 0 Defense.

Any suggestions on how I could do that?
Thank you.

答:
You can create a class with a Custom  name and add these as properties inside

```<code> public class MyClass
    {
        public string rat { get; set; }
        public int enemyHealth { get; set; }
        public int enemyAtkDmg { get; set; }
        public int enemyDef { get; set; }

    }
</code>```

then ,

```<code>        MyClass myObj = new MyClass();
        myObj.rat = "sample";
        myObj.enemyAtkDmg = 10;
        ....
        etc
</code>```

Title: Grouping Variables in C#?

Body:
I'm new to C# started recently and had an idea to make a small text based RPG sort of a game, I am using Visual Studio 2017. I want to have a few different files, including one that marks down all the different types of enemies in the game, how much damage one of their attacks do, their defense and how much health they have. I have this so far:

        string rat;
        int enemyHealth;
        int enemyAtkDmg;
        int enemyDef;

But then I started wondering how I could group "string rat;" and the rest together, so for example:

Rat - 10 Health, 2 Attack Damage, 0 Defense.

Any suggestions on how I could do that?
Thank you.

Body:
You can create a class with a Custom  name and add these as properties inside

 public class MyClass
    {
        public string rat { get; set; }
        public int enemyHealth { get; set; }
        public int enemyAtkDmg { get; set; }
        public int enemyDef { get; set; }

    }

then ,

        MyClass myObj = new MyClass();
        myObj.rat = "sample";
        myObj.enemyAtkDmg = 10;
        ....
        etc


问:
sort array according to date
Sort array according to date,
problem is date saved in string format can this is possible to sort array without change date in NSDate object.(Core Data).

string format is mm/dd/yyyy

答: You can create the sort with sortDescriptorWithKey:ascending:comparator: and supply a block that will compare any two of your date strings. Available in iOS 4.0 and later. </p>

Title: sort array according to date


问:
What's the R equivalent of Stata's _n function?
I am wondering whether there is a function in R like in Stata, where you are able to use the value of the observation n numbers before or after each observation. For instance if I need to multiply or divide with the observation before I would write something like this variable_x/variable_x[_n-1]

答:
The shortest way is:

bysort vect:gen n=_n

```<code>vect=c(1,1,1,2,2,2,2,3,3,3,3,3,4)
n=ave(1:length(vect), vect, FUN = seq_along)
</code>```

bysort vect:gen N=_N

```<code>ave(1:length(vect), vect, FUN = length)
</code>```

Body:
The shortest way is:

bysort vect:gen n=_n

vect=c(1,1,1,2,2,2,2,3,3,3,3,3,4)
n=ave(1:length(vect), vect, FUN = seq_along)

bysort vect:gen N=_N

ave(1:length(vect), vect, FUN = length)


问:
What is the best way to implement a RESTful architecture in .NET today?
Before you mention it I am aware that this question has been asked before but not since the launch of WCF4!

So, after a lot of reading I've decided that a RESTful architecture is the way forward to begin a data providing API. Considering the release WCF 4, ASP.NET MVC 2 and WCF REST starter kit, what is the best way to begin implementing a RESTful architecture NOW?

Me:
I am very familiar with ASP.NET MVC so I'd feel quite comfortable there. My knowledge of WCF, however, is lacking.

So WCF4 or ASP.NET MVC? (or something else like the wcf rest starter kit)? Specifically I'm looking for:

Ease of implementation

I know ASP.NET MVC, not WCF. Is WCF worth the learning curve?

Is WCF4 overkill for REST or will ASP.NET MVC falls short at some point?

答:
If your project is built on top of an ORM Framework or you can hold all your data in memory collections OData is the way to go. If not (i.e. you get your data via stored procedures or something similar) go for WCF HTTP Services (a.k.a. WCF REST)

OData is really promising and has great flexibility built on top of the IQueryable interface. Actually it is something like RESTful LINQ. However unless you have some ORM underneath you will have to implemet the IQueryable stuff yourself which is almost like implementing an ORM. At this point you'd better use the lower level WCF HTTP services that give you more control and you can shape your resources the way you want. Clients libraries will not be as powerful but will not expect the service to implement all the query operators.


问:
How to create a Popup login
In Visual Studio, I've created a default MVC app with login.

I would now like to change the login so that instead of going to a page, it appears as a popup.

The reason for this is that the user will be part way through the checkout steps, and I don't want to lose the position or state.

Is there an example of how to do this?

答:
You can use jQuery load function...

Here is the modal body

```<code><div class="modal-body">
    <div id="login-div"></div>
</div>
</code>```

here is the jQuery which has the login form id "#loginFor"

```<code>$(document).ready(function () {
        $('#login-div').load('/Account/Login?ReturnUrl=WhereYouWanttoGo #loginForm');
    });
</code>```

Title: How to create a Popup login

Body:
You can use jQuery load function...

Here is the modal body

<div class="modal-body">
    <div id="login-div"></div>
</div>

here is the jQuery which has the login form id "#loginFor"

$(document).ready(function () {
        $('#login-div').load('/Account/Login?ReturnUrl=WhereYouWanttoGo #loginForm');
    });


问:
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?

答:
You have to implement scrollView method for detecting scrolling direction like bellow:

```<code>private var lastContentOffset: CGFloat = 0

    func scrollViewDidScroll(scrollView: UIScrollView!) {
        if (self.lastContentOffset > scrollView.contentOffset.y) {
            // move up
        }
        else if (self.lastContentOffset < scrollView.contentOffset.y) {
           // move down
        }

        // update the new position
        self.lastContentOffset = scrollView.contentOffset.y
    }
</code>```

reference : How to get UIScrollView vertical direction in Swift?

Body:
You have to implement scrollView method for detecting scrolling direction like bellow:

private var lastContentOffset: CGFloat = 0

    func scrollViewDidScroll(scrollView: UIScrollView!) {
        if (self.lastContentOffset > scrollView.contentOffset.y) {
            // move up
        }
        else if (self.lastContentOffset < scrollView.contentOffset.y) {
           // move down
        }

        // update the new position
        self.lastContentOffset = scrollView.contentOffset.y
    }

reference : How to get UIScrollView vertical direction in Swift?


答:
From model summary looks like you are working on multi-class problem with 5 output classes. For multi-class setting softmax is good fit instead of sigmoid. I guess this is the major reason for very poor performance. On multi-class problem if you set network with sigmoid and categorical_crossentropy then during trainin by simply predicting all class to 1 could achieve 100% training accuracy, but this assumption fails badly on test data.

And if you are working with binary classification problem then binary_crossentropy is good choice for loss function.

Few other useful suggestions, may be helpful, but it's all up to your modeling assumptions.

I guess you are following similar kind of approach explained in example. But If your training data is small the best practice is to use pretrained word embedding and allow fine tuning. You can find pretrained embedding initialization example here. But allow fine tuning by setting trainable=True in embedding layer.

In paper mentioned, he pulls single feature from each filter,pool_size = max_sent_len-filter_size+1. This will extract only single important feature from whole sentence. This setting will allow you to reduce your model complexity. Very good explained in Reference: here

In same approach they used only single dense layer, you can remove your one hidden dense layer. Number of output features are quit small from pulling layer(will be equal to number of filters, each filter will only output one feature)

Title: How to avoid overfitting in the given Convnet

Body:
I am trying to implement a CNN network for sentence classification; I am trying to follow the architecture proposed in the paper. I am using Keras (with tensor-flow) for that. The following is the summary of my model:

____________________________________________________________________________________________________
Layer (type)                     Output Shape          Param #     Connected to
====================================================================================================
input_4 (InputLayer)             (None, 56)            0
____________________________________________________________________________________________________
embedding (Embedding)            (None, 56, 300)       6510000
____________________________________________________________________________________________________
dropout_7 (Dropout)              (None, 56, 300)       0
____________________________________________________________________________________________________
conv1d_10 (Conv1D)               (None, 54, 100)       90100
____________________________________________________________________________________________________
conv1d_11 (Conv1D)               (None, 53, 100)       120100
____________________________________________________________________________________________________
conv1d_12 (Conv1D)               (None, 52, 100)       150100
____________________________________________________________________________________________________
max_pooling1d_10 (MaxPooling1D)  (None, 27, 100)       0
____________________________________________________________________________________________________
max_pooling1d_11 (MaxPooling1D)  (None, 26, 100)       0
____________________________________________________________________________________________________
max_pooling1d_12 (MaxPooling1D)  (None, 26, 100)       0
____________________________________________________________________________________________________
flatten_10 (Flatten)             (None, 2700)          0
____________________________________________________________________________________________________
flatten_11 (Flatten)             (None, 2600)          0
____________________________________________________________________________________________________
flatten_12 (Flatten)             (None, 2600)          0
____________________________________________________________________________________________________
concatenate_4 (Concatenate)      (None, 7900)          0
____________________________________________________________________________________________________
dropout_8 (Dropout)              (None, 7900)          0
____________________________________________________________________________________________________
dense_7 (Dense)                  (None, 50)            395050
____________________________________________________________________________________________________
dense_8 (Dense)                  (None, 5)             255
====================================================================================================
Total params: 7,265,605.0
Trainable params: 7,265,605.0
Non-trainable params: 0.0

With the given architecture I am experiencing serious overfitting. The following are my results:

I am unable to understand what is the reason for the overfitting please suggest me some changes to the architecture for avoiding that. If you need some more information then please let me know.

Source code:

if model_type in ['CNN-non-static', 'CNN-static']:
    embedding_wts = train_word2vec( np.vstack((x_train, x_test, x_valid)),
                                    ind_to_wrd, num_features = embedding_dim)
    if model_type == 'CNN-static':
        x_train = embedding_wts[0][x_train]
        x_test  = embedding_wts[0][x_test]
        x_valid = embedding_wts[0][x_valid]

elif model_type == 'CNN-rand':
    embedding_wts = None

else:
    raise ValueError("Unknown model type")

batch_size   = 50
filter_sizes = [3,4,5]
num_filters  = 75
dropout_prob = (0.5, 0.8)
hidden_dims  = 50

l2_reg = 0.3

# Deciding dimension of input based on the model
input_shape = (max_sent_len, embedding_dim) if model_type == "CNN-static" else (max_sent_len,)
model_input = Input(shape = input_shape)

# Static model do not have embedding layer
if model_type == "CNN-static":
    z = Dropout(dropout_prob[0])(model_input)
else:
    z = Embedding(vocab_size, embedding_dim, input_length = max_sent_len, name="embedding")(model_input)
    z = Dropout(dropout_prob[0])(z)

# Convolution layers
z1 = Conv1D(    filters=num_filters, kernel_size=3,
                padding="valid", activation="relu",
                strides=1)(z)
z1 = MaxPooling1D(pool_size=2)(z1)
z1 = Flatten()(z1)

z2 = Conv1D(    filters=num_filters, kernel_size=4,
                padding="valid", activation="relu",
                strides=1)(z)
z2 = MaxPooling1D(pool_size=2)(z2)
z2 = Flatten()(z2)

z3 = Conv1D(    filters=num_filters, kernel_size=5,
                padding="valid", activation="relu",
                strides=1)(z)
z3 = MaxPooling1D(pool_size=2)(z3)
z3 = Flatten()(z3)

# Concatenate the output of all convolution layers
z = Concatenate()([z1, z2, z3])
z = Dropout(dropout_prob[1])(z)

# Dense(64, input_dim=64, kernel_regularizer=regularizers.l2(0.01), activity_regularizer=regularizers.l1(0.01))

z = Dense(hidden_dims, activation="relu", kernel_regularizer=regularizers.l2(0.01))(z)
model_output = Dense(N_category, activation="sigmoid")(z)

model = Model(model_input, model_output)
model.compile(loss="categorical_crossentropy", optimizer=optimizers.Adadelta(lr=1, decay=0.005), metrics=["accuracy"])
model.summary()


问:
Extract lines corresponding to the minimum value in the last column
I need help with extracting all the lines from the file that has minimum number in the last column, i.e 7 in in this case.

The sample file is as below:

File-1.txt

```<code>VALID_PATH :  [102, 80, 112, 109, 23, 125, 111] 7
VALID_PATH :  [102, 81, 112, 109, 23, 125, 111] 7
VALID_PATH :  [102, 112, 37, 109, 23, 125, 111] 7
VALID_PATH :  [102, 112, 37, 56, 23, 125, 111]  7
VALID_PATH :  [102, 80, 112, 37, 109, 23, 125, 111] 8
VALID_PATH :  [102, 80, 112, 37, 56, 23, 125, 111]  8
VALID_PATH :  [102, 80, 112, 109, 23, 125, 110, 111]    8
VALID_PATH :  [102, 80, 127, 6, 112, 109, 23, 125, 111] 9
VALID_PATH :  [102, 80, 127, 88, 112, 109, 23, 125, 111]    9
VALID_PATH :  [102, 80, 112, 37, 109, 23, 125, 110, 111]    9
VALID_PATH :  [102, 80, 112, 37, 56, 23, 125, 110, 111] 9
VALID_PATH :  [102, 80, 127, 6, 112, 37, 109, 23, 125, 111] 10
VALID_PATH :  [102, 80, 127, 6, 112, 37, 56, 23, 125, 111]  10
VALID_PATH :  [102, 80, 127, 6, 112, 109, 23, 125, 110, 111]    10
</code>```

Here, I want to extract all the lines that have 7, which is the least value (minimum value) in the last column and save the output into another file File-2.txt by only extracting the values enclosed in [], as shown below.

File-2.txt

```<code>102, 80, 112, 109, 23, 125, 111
102, 81, 112, 109, 23, 125, 111
102, 112, 37, 109, 23, 125, 111
102, 112, 37, 56, 23, 125, 111
</code>```

I could use awk to get the least value as "7" from the last column using the code as below:

```<code>awk 'BEGIN{getline;min=max=$NF}
NF{
    max=(max>$NF)?max:$NF
    min=(min>$NF)?$NF:min
}
END{print min,max}' File-1.txt
</code>```

and to print only the values in square brackets [] buy using the awk code as below:

```<code>awk 'NR > 1 {print $1}' RS='[' FS=']' File-1.txt
</code>```

but, I am stuck in assigning the least value obtained from first awk script, i.e. 7 in this case to extract the corresponding numbers enclosed in [], as shown in File-2.txt.

Any help in resolving this problem will be appreciated.

答:
```<code>$ awk -F'[][]' -vmin=99999 '$NF<=min{min=$NF;print $2}'
</code>```

-F'[][]' set FS to regexp [][] which mean "or [ or ]", i.e. your input string will be splited in 3 field.

-vmin=99999 set variable min to 99999. In this variable will be stored minum value of last field

$NF <= min {min = $NF; print $2} if current last field less or equal then stored in variable min,
then update min, and output what we need.

Body:
I need help with extracting all the lines from the file that has minimum number in the last column, i.e 7 in in this case.

The sample file is as below:

File-1.txt

VALID_PATH :  [102, 80, 112, 109, 23, 125, 111] 7
VALID_PATH :  [102, 81, 112, 109, 23, 125, 111] 7
VALID_PATH :  [102, 112, 37, 109, 23, 125, 111] 7
VALID_PATH :  [102, 112, 37, 56, 23, 125, 111]  7
VALID_PATH :  [102, 80, 112, 37, 109, 23, 125, 111] 8
VALID_PATH :  [102, 80, 112, 37, 56, 23, 125, 111]  8
VALID_PATH :  [102, 80, 112, 109, 23, 125, 110, 111]    8
VALID_PATH :  [102, 80, 127, 6, 112, 109, 23, 125, 111] 9
VALID_PATH :  [102, 80, 127, 88, 112, 109, 23, 125, 111]    9
VALID_PATH :  [102, 80, 112, 37, 109, 23, 125, 110, 111]    9
VALID_PATH :  [102, 80, 112, 37, 56, 23, 125, 110, 111] 9
VALID_PATH :  [102, 80, 127, 6, 112, 37, 109, 23, 125, 111] 10
VALID_PATH :  [102, 80, 127, 6, 112, 37, 56, 23, 125, 111]  10
VALID_PATH :  [102, 80, 127, 6, 112, 109, 23, 125, 110, 111]    10

Here, I want to extract all the lines that have 7, which is the least value (minimum value) in the last column and save the output into another file File-2.txt by only extracting the values enclosed in [], as shown below.

File-2.txt

102, 80, 112, 109, 23, 125, 111
102, 81, 112, 109, 23, 125, 111
102, 112, 37, 109, 23, 125, 111
102, 112, 37, 56, 23, 125, 111

I could use awk to get the least value as "7" from the last column using the code as below:

awk 'BEGIN{getline;min=max=$NF}
NF{
    max=(max>$NF)?max:$NF
    min=(min>$NF)?$NF:min
}
END{print min,max}' File-1.txt

and to print only the values in square brackets [] buy using the awk code as below:

awk 'NR > 1 {print $1}' RS='[' FS=']' File-1.txt

but, I am stuck in assigning the least value obtained from first awk script, i.e. 7 in this case to extract the corresponding numbers enclosed in [], as shown in File-2.txt.

Any help in resolving this problem will be appreciated.

Body:
$ awk -F'[][]' -vmin=99999 '$NF<=min{min=$NF;print $2}'

-F'[][]' set FS to regexp [][] which mean "or [ or ]", i.e. your input string will be splited in 3 field.

-vmin=99999 set variable min to 99999. In this variable will be stored minum value of last field

$NF <= min {min = $NF; print $2} if current last field less or equal then stored in variable min,
then update min, and output what we need.


问:
Hooking windows API functions to intercept dll loading (Windows only)
I want to intercept dll's loading so I can use them. My first idea was to hook GetProcAddress. Surprisingly, by hooking it, I can only intercept calls made within the process that owns my library. (I opened another executables that call GetProcAddress and those calls don't get intercepted) (I guess because it is dynamically compiled against my lib)

Example of the output:

C:\Windows\syswow64\kernel32.dll
  Module32NextW

C:\Windows\syswow64\kernel32.dll
  CreateToolhelp32Snapshot

C:\Windows\system32\DINPUT.dll
  DirectInputCreateW

C:\Windows\SysWOW64\ntdll.dll
  DirectDrawCreate

Anyway, what I want to know is where I should start to be able to intercept dlls loading so I can then use their functions.

Basically, I want to be able to call GetModuleInformation for any dll loaded.

答:
First, what are you doing that requires a global hook?

If you want to be notified that a DLL has loaded in any process, you can look into PsSetImageLoadNotifyRoutine, which is a kernel-mode routine.
Despite it being kernel mode, it's not very hard to use and writing a basic driver is pretty fun.

Another way would be to force a load of your library in every process. There are a variety of methods, one of the more legit ones would be Windows Message hooks.


问:
Add playground to existing Workspace (with cocoapods)
The question:

How to add a playground to the workspace, if i already have an app project and a pod project in this workspace ?

It should look something like this:

Now it can't find dependencies from cocoapods project:

What did i try:

https://github.com/segiddins/ThisCouldBeUsButYouPlaying

How to add a CocoaPod framework to Xcode 8 Playground

How to use cocoapods with playground?

https://github.com/WhisperSystems/Signal-iOS/pull/1180

Didn't work.

答:
Make sure of all of the following:

You build your entire project (CMD+B), before trying to import pods into your playground.

You build your project for a simulator, building for a device would build it for the wrong platform (playgrounds run in a simulator).

You build your project for the correct platform (tvOS, macOS, iOS). You can see which platform your playground is in through the File Inspector (ALT+CMD+1).


问:
replacing ZFS medium, adapting partitions
I have a HP microserver gen8 running FreeBSD with mirrored boot media: one USB stick (16GB) and one microSD card (16GB). The stick recently showed checksum errors, so I replaced it, but I only had a 32GB stick at hand. After resilvering, zpool seems to be content but I cannot write the bootcode and gpart does not even recognize the media.

In detail.

This is the zpool status when the problem arose:

```<code>
Checking status of zfs pools:
NAME           SIZE  ALLOC   FREE  EXPANDSZ   FRAG    CAP  DEDUP  HEALTH  ALTROOT
freenas-boot  14.5G   791M  13.7G         -      -     5%  1.00x  ONLINE  -
freising       928G  84.6G   843G         -     6%     9%  1.00x  ONLINE  /mnt

  pool: freenas-boot
 state: ONLINE
status: One or more devices has experienced an unrecoverable error.  An
        attempt was made to correct the error.  Applications are unaffected.
action: Determine if the device needs to be replaced, and clear the errors
        using 'zpool clear' or replace the device with 'zpool replace'.
   see: http://illumos.org/msg/ZFS-8000-9P
  scan: scrub repaired 213K in 0h15m with 0 errors on Thu Mar 23 04:00:56 2017
config:

        NAME        STATE     READ WRITE CKSUM
        freenas-boot  ONLINE     0     0     0
          mirror-0  ONLINE       0     0     0
            da0p2   ONLINE       0     0     3
            da1p2   ONLINE       0     0     0

errors: No known data errors
</code>```

I powered the machine down, replaced the stick with a 32GB one, rebooted. zpool status yielded:

```<code>
        NAME                     STATE     READ WRITE CKSUM
        freenas-boot             DEGRADED     0     0     0
          mirror-0               DEGRADED     0     0     0
            3278622582862864884  UNAVAIL      0     0     0  was /dev/da0p2
            da1p2                ONLINE       0     0     0
</code>```

Fine, so I told zpool to use the new media:

```<code>
sudo zpool replace freenas-boot 3278622582862864884 /dev/da0
</code>```

(zpool didn't let me use '/dev/da0p2')

It took about 8 hours to resilver the thing, now zpool seems to be happy:

```<code>
sudo zpool status -xv
all pools are healthy
</code>```

But I cannot write the bootcode:

```<code>
sudo gpart bootcode -b /boot/pmbr -p /boot/gptzfsboot -i 1 da0
gpart: No such geom: da0.
</code>```

gpart does not even recognize the new stick:

```<code>
sudo gpart status
  Name  Status  Components
ada0p1      OK  ada0
ada0p2      OK  ada0
ada1p1      OK  ada1
ada1p2      OK  ada1
 da1p1      OK  da1
 da1p2      OK  da1
</code>```

What would be the best way to proceed? I am quite uncertain what I should control via gpart and what is better left to zfs and its magic.

答:
If you still have the old stick, you could use it. Checksum errors, especially on low counts like 3 in your case, are nothing to worry about. They could be the result of a flaky cable connection or a forced removal of the device, or sudden power loss or reconnect (especially with USB, which was designed for frequent removal instead of perfect stability).

So, if you just experienced those errors once (and no write or read errors), and still have a healthy mirror, I would personally continue to use the old device that is already setup properly for booting. You can replace a device with itself by specifying its name twice: zpool replace poolname device device, or just clear the errors with zpool clear poolname. Unless it happens again, I would not throw away a functioning device.

Body:
I have a HP microserver gen8 running FreeBSD with mirrored boot media: one USB stick (16GB) and one microSD card (16GB). The stick recently showed checksum errors, so I replaced it, but I only had a 32GB stick at hand. After resilvering, zpool seems to be content but I cannot write the bootcode and gpart does not even recognize the media.

In detail.

This is the zpool status when the problem arose:

Checking status of zfs pools:
NAME           SIZE  ALLOC   FREE  EXPANDSZ   FRAG    CAP  DEDUP  HEALTH  ALTROOT
freenas-boot  14.5G   791M  13.7G         -      -     5%  1.00x  ONLINE  -
freising       928G  84.6G   843G         -     6%     9%  1.00x  ONLINE  /mnt

  pool: freenas-boot
 state: ONLINE
status: One or more devices has experienced an unrecoverable error.  An
        attempt was made to correct the error.  Applications are unaffected.
action: Determine if the device needs to be replaced, and clear the errors
        using 'zpool clear' or replace the device with 'zpool replace'.
   see: http://illumos.org/msg/ZFS-8000-9P
  scan: scrub repaired 213K in 0h15m with 0 errors on Thu Mar 23 04:00:56 2017
config:

        NAME        STATE     READ WRITE CKSUM
        freenas-boot  ONLINE     0     0     0
          mirror-0  ONLINE       0     0     0
            da0p2   ONLINE       0     0     3
            da1p2   ONLINE       0     0     0

errors: No known data errors

I powered the machine down, replaced the stick with a 32GB one, rebooted. zpool status yielded:

        NAME                     STATE     READ WRITE CKSUM
        freenas-boot             DEGRADED     0     0     0
          mirror-0               DEGRADED     0     0     0
            3278622582862864884  UNAVAIL      0     0     0  was /dev/da0p2
            da1p2                ONLINE       0     0     0

Fine, so I told zpool to use the new media:

sudo zpool replace freenas-boot 3278622582862864884 /dev/da0

(zpool didn't let me use '/dev/da0p2')

It took about 8 hours to resilver the thing, now zpool seems to be happy:

sudo zpool status -xv
all pools are healthy

But I cannot write the bootcode:

sudo gpart bootcode -b /boot/pmbr -p /boot/gptzfsboot -i 1 da0
gpart: No such geom: da0.

gpart does not even recognize the new stick:

sudo gpart status
  Name  Status  Components
ada0p1      OK  ada0
ada0p2      OK  ada0
ada1p1      OK  ada1
ada1p2      OK  ada1
 da1p1      OK  da1
 da1p2      OK  da1

What would be the best way to proceed? I am quite uncertain what I should control via gpart and what is better left to zfs and its magic.


问:
Ruby - Extract value of a particular key from array of hashes
I have an array of hashes - @profiles which has data as:

```<code>[{:user_id=>5, :full_name=>"Emily Spot"},{:user_id=>7, :full_name=>"Kevin Walls"}]
</code>```

I want to get full_name of say user_id = 7? I'm doing the following: but it's throwing an error that expression @profiles.find{|h| h[':user_id'] == current_user.id} is nil.

```<code>name = @profiles.find{ |h| h[':user_id'] == current_user.id }[':full_name']
</code>```

if I use select instead of find then error is - no implicit conversion of String into Integer.

How do I search through the array of hashes?

UPDATE:

After @Eric's answer, I restructured my job model & view actions:

```<code>  def full_names
    profile_arr||= []
    profile_arr = self.applications.pluck(:user_id)
    @profiles = Profile.where(:user_id => profile_arr).select([:user_id, :first_name, :last_name]).map {|e| {user_id: e.user_id, full_name: e.full_name} }
    @full_names = @profiles.each_with_object({}) do |profile, names|
      names[profile[:user_id]] = profile[:full_name]
    end
  end
</code>```

In the view....,

```<code>p @current_job.full_names[current_user.id]
</code>```

答:
As you've noticed, it's not very convenient to extract the name of user_id 7. You could modify your data structure a bit :

```<code>@profiles = [{:user_id=>5, :full_name=>"Emily Spot"},
             {:user_id=>7, :full_name=>"Kevin Walls"}]

@full_names = @profiles.each_with_object({}) do |profile, names|
  names[profile[:user_id]] = profile[:full_name]
end

p @full_names
# {5=>"Emily Spot", 7=>"Kevin Walls"}
p @full_names[7]
# "Kevin Walls"
p @full_names[6]
# nil
</code>```

You didn't lose any information but name look-up is now much faster, easier and more robust.

Body:
I have an array of hashes - @profiles which has data as:

[{:user_id=>5, :full_name=>"Emily Spot"},{:user_id=>7, :full_name=>"Kevin Walls"}]

I want to get full_name of say user_id = 7? I'm doing the following: but it's throwing an error that expression @profiles.find{|h| h[':user_id'] == current_user.id} is nil.

name = @profiles.find{ |h| h[':user_id'] == current_user.id }[':full_name']

if I use select instead of find then error is - no implicit conversion of String into Integer.

How do I search through the array of hashes?

UPDATE:

After @Eric's answer, I restructured my job model & view actions:

  def full_names
    profile_arr||= []
    profile_arr = self.applications.pluck(:user_id)
    @profiles = Profile.where(:user_id => profile_arr).select([:user_id, :first_name, :last_name]).map {|e| {user_id: e.user_id, full_name: e.full_name} }
    @full_names = @profiles.each_with_object({}) do |profile, names|
      names[profile[:user_id]] = profile[:full_name]
    end
  end

In the view....,

p @current_job.full_names[current_user.id]

Body:
As you've noticed, it's not very convenient to extract the name of user_id 7. You could modify your data structure a bit :

@profiles = [{:user_id=>5, :full_name=>"Emily Spot"},
             {:user_id=>7, :full_name=>"Kevin Walls"}]

@full_names = @profiles.each_with_object({}) do |profile, names|
  names[profile[:user_id]] = profile[:full_name]
end

p @full_names
# {5=>"Emily Spot", 7=>"Kevin Walls"}
p @full_names[7]
# "Kevin Walls"
p @full_names[6]
# nil

You didn't lose any information but name look-up is now much faster, easier and more robust.


问:
align center and center tag are not working
i am trying to show pagination in center but its show on left side. i am also try center tag and align=center attributes but its not working....

Pagination show in the center of page

#pagination {
  margin: 40 40 0;
  float: left;
}
ul.tsc_pagination li a {
  border:solid 1px;
  border-radius:3px;
  -moz-border-radius:3px;
  -webkit-border-radius:3px;
  padding:6px 9px 6px 9px;
}
ul.tsc_pagination li {
  padding-bottom:1px;
}
ul.tsc_pagination li a:hover,
ul.tsc_pagination li a.current {
  color:#FFFFFF;
  box-shadow:0px 1px #EDEDED;
  -moz-box-shadow:0px 1px #EDEDED;
  -webkit-box-shadow:0px 1px #EDEDED;
}
ul.tsc_pagination {
  margin:4px 0;
  padding:0px;
  height:100%;
  overflow:hidden;
  font:12px 'Tahoma';
  list-style-type:none;
}
ul.tsc_pagination li {
  float:left;
  margin:0px;
  padding:0px;
  margin-left:5px;
}
ul.tsc_pagination li a {
  color:black;
  display:block;
  text-decoration:none;
  padding:7px 10px 7px 10px;
}
ul.tsc_pagination li a img {
  border:none;
}
ul.tsc_pagination li a {
  color:#0A7EC5;
  border-color:#8DC5E6;
  background:#F8FCFF;
}
ul.tsc_pagination li a:hover,
ul.tsc_pagination li a.current {
  text-shadow:0px 1px #388DBE;
  border-color:#3390CA;
  background:#58B0E7;
  background:-moz-linear-gradient(top, #B4F6FF 1px, #63D0FE 1px, #58B0E7);
  background:-webkit-gradient(linear, 0 0, 0 100%, color-stop(0.02, #B4F6FF), color-stop(0.02, #63D0FE), color-stop(1, #58B0E7));
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div id="pagination">
  <ul class="tsc_pagination">
    <!-- Show pagination links -->
    <li></li>
    <li>1</li>
    <li>2</li>
    <li>Next</li>
    <li></li>
  </ul>
</div></code>```

you can see this

答:
There are 2 changes to make.

Change 1- Change css of #pagination to below.

```<code>#pagination {
  width: 100%;
  text-align: center;
}
</code>```

Change 2- Make the ul.tsc_pagination li not have float instead of
  that use display:inline-block. Change css as below.

```<code>ul.tsc_pagination li {
  /*  float: left;*/
  /*Dont use float:left*/
  display: inline-block;
  margin: 0px;
  padding: 0px;
  margin-left: 5px;
}
</code>```

#pagination {
  width: 100%;
  text-align: center;
}

ul.tsc_pagination li a {
  border: solid 1px;
  border-radius: 3px;
  -moz-border-radius: 3px;
  -webkit-border-radius: 3px;
  padding: 6px 9px 6px 9px;
}

ul.tsc_pagination li {
  padding-bottom: 1px;
}

ul.tsc_pagination li a:hover,
ul.tsc_pagination li a.current {
  color: #FFFFFF;
  box-shadow: 0px 1px #EDEDED;
  -moz-box-shadow: 0px 1px #EDEDED;
  -webkit-box-shadow: 0px 1px #EDEDED;
}

ul.tsc_pagination {
  margin: 4px 0;
  padding: 0px;
  height: 100%;
  overflow: hidden;
  font: 12px 'Tahoma';
  list-style-type: none;
}

ul.tsc_pagination li {
  /*  float: left;*/
  /*Dont use float:left*/
  display: inline-block;
  margin: 0px;
  padding: 0px;
  margin-left: 5px;
}

ul.tsc_pagination li a {
  color: black;
  display: block;
  text-decoration: none;
  padding: 7px 10px 7px 10px;
}

ul.tsc_pagination li a img {
  border: none;
}

ul.tsc_pagination li a {
  color: #0A7EC5;
  border-color: #8DC5E6;
  background: #F8FCFF;
}

ul.tsc_pagination li a:hover,
ul.tsc_pagination li a.current {
  text-shadow: 0px 1px #388DBE;
  border-color: #3390CA;
  background: #58B0E7;
  background: -moz-linear-gradient(top, #B4F6FF 1px, #63D0FE 1px, #58B0E7);
  background: -webkit-gradient(linear, 0 0, 0 100%, color-stop(0.02, #B4F6FF), color-stop(0.02, #63D0FE), color-stop(1, #58B0E7));
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div id="pagination">

  <ul class="tsc_pagination">

    <!-- Show pagination links -->
    <li></li>
    <li>1</li>
    <li>2</li>
    <li>Next</li>
    <li></li>
  </ul>

</div></code>```

Body:
i am trying to show pagination in center but its show on left side. i am also try center tag and align=center attributes but its not working....

Pagination show in the center of page

#pagination {
  margin: 40 40 0;
  float: left;
}
ul.tsc_pagination li a {
  border:solid 1px;
  border-radius:3px;
  -moz-border-radius:3px;
  -webkit-border-radius:3px;
  padding:6px 9px 6px 9px;
}
ul.tsc_pagination li {
  padding-bottom:1px;
}
ul.tsc_pagination li a:hover,
ul.tsc_pagination li a.current {
  color:#FFFFFF;
  box-shadow:0px 1px #EDEDED;
  -moz-box-shadow:0px 1px #EDEDED;
  -webkit-box-shadow:0px 1px #EDEDED;
}
ul.tsc_pagination {
  margin:4px 0;
  padding:0px;
  height:100%;
  overflow:hidden;
  font:12px 'Tahoma';
  list-style-type:none;
}
ul.tsc_pagination li {
  float:left;
  margin:0px;
  padding:0px;
  margin-left:5px;
}
ul.tsc_pagination li a {
  color:black;
  display:block;
  text-decoration:none;
  padding:7px 10px 7px 10px;
}
ul.tsc_pagination li a img {
  border:none;
}
ul.tsc_pagination li a {
  color:#0A7EC5;
  border-color:#8DC5E6;
  background:#F8FCFF;
}
ul.tsc_pagination li a:hover,
ul.tsc_pagination li a.current {
  text-shadow:0px 1px #388DBE;
  border-color:#3390CA;
  background:#58B0E7;
  background:-moz-linear-gradient(top, #B4F6FF 1px, #63D0FE 1px, #58B0E7);
  background:-webkit-gradient(linear, 0 0, 0 100%, color-stop(0.02, #B4F6FF), color-stop(0.02, #63D0FE), color-stop(1, #58B0E7));
}

1

2

Next

you can see this

Body:
There are 2 changes to make.

Change 1- Change css of #pagination to below.

#pagination {
  width: 100%;
  text-align: center;
}

Change 2- Make the ul.tsc_pagination li not have float instead of
  that use display:inline-block. Change css as below.

ul.tsc_pagination li {
  /*  float: left;*/
  /*Dont use float:left*/
  display: inline-block;
  margin: 0px;
  padding: 0px;
  margin-left: 5px;
}

#pagination {
  width: 100%;
  text-align: center;
}

ul.tsc_pagination li a {
  border: solid 1px;
  border-radius: 3px;
  -moz-border-radius: 3px;
  -webkit-border-radius: 3px;
  padding: 6px 9px 6px 9px;
}

ul.tsc_pagination li {
  padding-bottom: 1px;
}

ul.tsc_pagination li a:hover,
ul.tsc_pagination li a.current {
  color: #FFFFFF;
  box-shadow: 0px 1px #EDEDED;
  -moz-box-shadow: 0px 1px #EDEDED;
  -webkit-box-shadow: 0px 1px #EDEDED;
}

ul.tsc_pagination {
  margin: 4px 0;
  padding: 0px;
  height: 100%;
  overflow: hidden;
  font: 12px 'Tahoma';
  list-style-type: none;
}

ul.tsc_pagination li {
  /*  float: left;*/
  /*Dont use float:left*/
  display: inline-block;
  margin: 0px;
  padding: 0px;
  margin-left: 5px;
}

ul.tsc_pagination li a {
  color: black;
  display: block;
  text-decoration: none;
  padding: 7px 10px 7px 10px;
}

ul.tsc_pagination li a img {
  border: none;
}

ul.tsc_pagination li a {
  color: #0A7EC5;
  border-color: #8DC5E6;
  background: #F8FCFF;
}

ul.tsc_pagination li a:hover,
ul.tsc_pagination li a.current {
  text-shadow: 0px 1px #388DBE;
  border-color: #3390CA;
  background: #58B0E7;
  background: -moz-linear-gradient(top, #B4F6FF 1px, #63D0FE 1px, #58B0E7);
  background: -webkit-gradient(linear, 0 0, 0 100%, color-stop(0.02, #B4F6FF), color-stop(0.02, #63D0FE), color-stop(1, #58B0E7));
}

<div id="pagination">

  <ul class="tsc_pagination">

    <!-- Show pagination links -->
    <li></li>
    <li><a class="current">1</a></li>
    <li><a href="http://localhost/helpmesave/index.php/home/viewcompaigns/1">2</a></li>
    <li><a href="http://localhost/helpmesave/index.php/home/viewcompaigns/1">Next</a></li>
    <li></li>
  </ul>

</div>


问:
How to find the index of the permutation
```<code>% index(+List, -Idx) Predicate will get List with permutation and I want to
know index of permutation

For example: ?- index([4,1,3,2],X).
                X= 19.
</code>```

My solution:

```<code>index([],0).
index([_],1).
index([X,Y],2):- Y > X.
index([H,X|T],Idx):-index([X|T],Idx+1),H > X.
</code>```

Why is it wrong?
And how can I make incremention of Idx?

答:
I found cleaner version of same idea so I show the code:

```<code>permutation_index([X|Xs], I) :-
    prerequisite(
        (   sort([X|Xs], S),
            length([X|Xs], Len),
            length(S, Len)
        )),
    permutation_index(Xs, X, _N, _N_fac, I).

prerequisite(P) :- P.

permutation_index([], _Last, 0, 1, 0).
permutation_index([X|Xs], Prev, N, N_fac, I) :-
    permutation_index(Xs, X, N0, N_fac0, I0),
    succ(N0, N),
    N_fac is N*N_fac0,
    element_rank([X|Xs], Prev, R),
    I is I0 + R*N_fac.

element_rank([], _, 0).
element_rank([X|Xs], Y, R) :-
    element_rank(Xs, Y, R0),
    (   X @< Y
    ->  succ(R0, R)
    ;   R0 = R
    ).
</code>```

This solution is not tail recursion because it seems that depth of recursion will not be a problem? It is easier to not do tail recursion, it needs less arguments. It works with any elements, only prerequisite is that elements are unique. No stupid unnecessary use of foldl or nth0/4! If you want you can additionally give it your own comparison function that only needs to be evaluated inside element_rank but this is overkill. However C++ standard library has next_permutation which lets you give it comparison predicate so maybe there is use case for this?

Now we can see if really it is possible to find the index of permutation of all letters of the English alphabet in reasonable time.

```<code>?- bagof(C, ( char_type(C, lower), C @> b, C @=< z ), Cs),
   reverse(Cs, Cs_rev),
   append(Cs_rev, [a,b], Letters),
   time( permutation_index(Letters, I) ).
% 1,103 inferences, 0.000 CPU in 0.000 seconds (98% CPU, 4226847 Lips)
Cs = [c, d, e, f, g, h, i, j, k|...],
Cs_rev = [z, y, x, w, v, u, t, s, r|...],
Letters = [z, y, x, w, v, u, t, s, r|...],
I = 403291461126605635583999998.
</code>```

You can see that index is exactly 26!-2 so maybe it is correct? Below you can find original answer which has some explanation of algorithm and inadequate implementation. This implementation is not good but at least it is a bit better I hope?

You really want to enumerate all possible permutations? This is maybe too many in many of the cases? If you have a permutation of all the letters in the English alphabet for example you already have 26! = a very big number (403291461126605635584000000).

So maybe it is better to just calculate without enumerating? Also I don't think the library permutation/2 has this option but you should be able to calcuate just "next permutation" lexicographically, without enumerating all permutations. Because when you say "index of permutation" this assumes that all possible permutations are in some order, but you don't say what order this is. Maybe it is lexicographical order? And the library permutation/2 as in the other answer by @CapelliC has one annoying "feature" that it does not care if it is really a permutation or not:

```<code>?- permutation([1,1,1], P).
P = [1, 1, 1] ;
P = [1, 1, 1] ;
P = [1, 1, 1] ;
P = [1, 1, 1] ;
P = [1, 1, 1] ;
P = [1, 1, 1] ;
false.
</code>```

This does not look correct to me at all. If you ask your program, "what is the index of permutation [1,1,1], should it answer "it is 1, and 2, and 3, and 4, and 5, and 6?" I am very uncomfortable with this answer.

Before you begin asking "what is the index of permutaton" first you need to ask "how are permutations ordered?" (lexicographically??) and you also need to make sure that all elements of your list are actually unique, and that they have an order, too. I will assume that if you have list of length n then in this list you have all integers between 1 and n, as in your example!!! If you have other elements (like letters) than you must make sure that they are unique and can be ordered and then you can assign them numbers between 1 and n but I think this is trivial so I don't want to write code for it. But it can look like this:

```<code>?- list_indices_len([c,b,a,x], Ns, Is, Len).
Ns = [3, 2, 1, 4],
Is = [1, 2, 3, 4],
Len = 4.
</code>```

Do you see why? If not I can explain why this is important.

Then once you have a list like [4,1,3,2] and its length then you can use following algorithm:

```<code>permutation_index(P, Es, Len, I) :-
    succ(Len0, Len),
    P = [N|Ns],
    permutation_index(Ns, N, Len0, Es, 0, I).
</code>```

This already knows the length of the permutation and the list because we made it with list_indices_len/4. Then now we only have to do n-1 steps and each time we multiply the 0-based index of the number in the list of remaining numbers with the factorial of the number of remaining numbers.

```<code>permutation_index([], _, _, _, I, I).
permutation_index([N|Ns], N0, X, Es, Acc, I) :-
    once( nth0(N_i, Es, N0, Es0) ),
    factorial_expr(X, X_fac),
    succ(X0, X),
    Acc1 is N_i*X_fac + Acc,
    permutation_index(Ns, N, X0, Es0, Acc1, I).

factorial_expr(F, E) :-
    (   F =:= 0
    ->  E = 1
    ;   F =:= 1
    ->  E = 1
    ;   F > 1
    ->  X is F,
        numlist(2, X, [N|Ns]),
        foldl(prod, Ns, N, E)
    ).

prod(X, Y, Y*X).
</code>```

There must be better way to calculate factorial but this works?

So now I get as expected:

```<code>?- permutation_index([4,1,3,2], [1,2,3,4], 4, I).
I = 19.

?- permutation_index([4,3,2,1], [1,2,3,4], 4, I).
I = 23.

?- permutation_index([1,2,3,4], [1,2,3,4], 4, I).
I = 0.

?- permutation_index([1,2,4,3], [1,2,3,4], 4, I).
I = 1.

?- permutation_index([10,9,8,7,6,5,4,3,1,2], [1,2,3,4,5,6,7,8,9,10], 10, I).
I = 3628798.
</code>```

The last one is exactly 10!-2 as expected.

If you need more explaining I can do it but it looks quite easy to understand if you can understand the logic. Or maybe I am wrong about the logic? It seems to work however.

I made test myself to see that I am not confused about the complexity of my approach so I test again with even bigger number and it looks correct.

```<code>?- time(permutation_index([12,11,10,9,8,7,6,5,4,3,1,2], [1,2,3,4,5,6,7,8,9,10,11,12], 12, I)).
% 466 inferences, 0.000 CPU in 0.000 seconds (99% CPU, 1498045 Lips)
I = 479001598.

?- factorial_expr(12, E), X is E - 2.
E = ... * ... * 4*5*6*7*8*9*10*11*12,
X = 479001598.
</code>```

There are also even more efficient ways to calculate index of permutation but maybe you should read first... you can start at the beginning:

https://en.wikipedia.org/wiki/Permutation#Permutations_in_computing

Body:
% index(+List, -Idx) Predicate will get List with permutation and I want to
know index of permutation

For example: ?- index([4,1,3,2],X).
                X= 19.

My solution:

index([],0).
index([_],1).
index([X,Y],2):- Y > X.
index([H,X|T],Idx):-index([X|T],Idx+1),H > X.

Why is it wrong?
And how can I make incremention of Idx?

Body:
I found cleaner version of same idea so I show the code:

permutation_index([X|Xs], I) :-
    prerequisite(
        (   sort([X|Xs], S),
            length([X|Xs], Len),
            length(S, Len)
        )),
    permutation_index(Xs, X, _N, _N_fac, I).

prerequisite(P) :- P.

permutation_index([], _Last, 0, 1, 0).
permutation_index([X|Xs], Prev, N, N_fac, I) :-
    permutation_index(Xs, X, N0, N_fac0, I0),
    succ(N0, N),
    N_fac is N*N_fac0,
    element_rank([X|Xs], Prev, R),
    I is I0 + R*N_fac.

element_rank([], _, 0).
element_rank([X|Xs], Y, R) :-
    element_rank(Xs, Y, R0),
    (   X @< Y
    ->  succ(R0, R)
    ;   R0 = R
    ).

This solution is not tail recursion because it seems that depth of recursion will not be a problem? It is easier to not do tail recursion, it needs less arguments. It works with any elements, only prerequisite is that elements are unique. No stupid unnecessary use of foldl or nth0/4! If you want you can additionally give it your own comparison function that only needs to be evaluated inside element_rank but this is overkill. However C++ standard library has next_permutation which lets you give it comparison predicate so maybe there is use case for this?

Now we can see if really it is possible to find the index of permutation of all letters of the English alphabet in reasonable time.

?- bagof(C, ( char_type(C, lower), C @> b, C @=< z ), Cs),
   reverse(Cs, Cs_rev),
   append(Cs_rev, [a,b], Letters),
   time( permutation_index(Letters, I) ).
% 1,103 inferences, 0.000 CPU in 0.000 seconds (98% CPU, 4226847 Lips)
Cs = [c, d, e, f, g, h, i, j, k|...],
Cs_rev = [z, y, x, w, v, u, t, s, r|...],
Letters = [z, y, x, w, v, u, t, s, r|...],
I = 403291461126605635583999998.

You can see that index is exactly 26!-2 so maybe it is correct? Below you can find original answer which has some explanation of algorithm and inadequate implementation. This implementation is not good but at least it is a bit better I hope?

You really want to enumerate all possible permutations? This is maybe too many in many of the cases? If you have a permutation of all the letters in the English alphabet for example you already have 26! = a very big number (403291461126605635584000000).

So maybe it is better to just calculate without enumerating? Also I don't think the library permutation/2 has this option but you should be able to calcuate just "next permutation" lexicographically, without enumerating all permutations. Because when you say "index of permutation" this assumes that all possible permutations are in some order, but you don't say what order this is. Maybe it is lexicographical order? And the library permutation/2 as in the other answer by @CapelliC has one annoying "feature" that it does not care if it is really a permutation or not:

?- permutation([1,1,1], P).
P = [1, 1, 1] ;
P = [1, 1, 1] ;
P = [1, 1, 1] ;
P = [1, 1, 1] ;
P = [1, 1, 1] ;
P = [1, 1, 1] ;
false.

This does not look correct to me at all. If you ask your program, "what is the index of permutation [1,1,1], should it answer "it is 1, and 2, and 3, and 4, and 5, and 6?" I am very uncomfortable with this answer.

Before you begin asking "what is the index of permutaton" first you need to ask "how are permutations ordered?" (lexicographically??) and you also need to make sure that all elements of your list are actually unique, and that they have an order, too. I will assume that if you have list of length n then in this list you have all integers between 1 and n, as in your example!!! If you have other elements (like letters) than you must make sure that they are unique and can be ordered and then you can assign them numbers between 1 and n but I think this is trivial so I don't want to write code for it. But it can look like this:

?- list_indices_len([c,b,a,x], Ns, Is, Len).
Ns = [3, 2, 1, 4],
Is = [1, 2, 3, 4],
Len = 4.

Do you see why? If not I can explain why this is important.

Then once you have a list like [4,1,3,2] and its length then you can use following algorithm:

permutation_index(P, Es, Len, I) :-
    succ(Len0, Len),
    P = [N|Ns],
    permutation_index(Ns, N, Len0, Es, 0, I).

This already knows the length of the permutation and the list because we made it with list_indices_len/4. Then now we only have to do n-1 steps and each time we multiply the 0-based index of the number in the list of remaining numbers with the factorial of the number of remaining numbers.

permutation_index([], _, _, _, I, I).
permutation_index([N|Ns], N0, X, Es, Acc, I) :-
    once( nth0(N_i, Es, N0, Es0) ),
    factorial_expr(X, X_fac),
    succ(X0, X),
    Acc1 is N_i*X_fac + Acc,
    permutation_index(Ns, N, X0, Es0, Acc1, I).

factorial_expr(F, E) :-
    (   F =:= 0
    ->  E = 1
    ;   F =:= 1
    ->  E = 1
    ;   F > 1
    ->  X is F,
        numlist(2, X, [N|Ns]),
        foldl(prod, Ns, N, E)
    ).

prod(X, Y, Y*X).

There must be better way to calculate factorial but this works?

So now I get as expected:

?- permutation_index([4,1,3,2], [1,2,3,4], 4, I).
I = 19.

?- permutation_index([4,3,2,1], [1,2,3,4], 4, I).
I = 23.

?- permutation_index([1,2,3,4], [1,2,3,4], 4, I).
I = 0.

?- permutation_index([1,2,4,3], [1,2,3,4], 4, I).
I = 1.

?- permutation_index([10,9,8,7,6,5,4,3,1,2], [1,2,3,4,5,6,7,8,9,10], 10, I).
I = 3628798.

The last one is exactly 10!-2 as expected.

If you need more explaining I can do it but it looks quite easy to understand if you can understand the logic. Or maybe I am wrong about the logic? It seems to work however.

I made test myself to see that I am not confused about the complexity of my approach so I test again with even bigger number and it looks correct.

?- time(permutation_index([12,11,10,9,8,7,6,5,4,3,1,2], [1,2,3,4,5,6,7,8,9,10,11,12], 12, I)).
% 466 inferences, 0.000 CPU in 0.000 seconds (99% CPU, 1498045 Lips)
I = 479001598.

?- factorial_expr(12, E), X is E - 2.
E = ... * ... * 4*5*6*7*8*9*10*11*12,
X = 479001598.

There are also even more efficient ways to calculate index of permutation but maybe you should read first... you can start at the beginning:

https://en.wikipedia.org/wiki/Permutation#Permutations_in_computing


问:
splitting List<Object> based on the value of a variable in that Object
I am trying to split my list into multiple smaller lists but don't know how i should do it.

```<code>List<Object> list = new List<Object>();
</code>```

This is my original list that contains the object Object. I am trying to split this list based on the variables of this Object.

example:

```<code>public class Object {
   string var1;
   int var2;
   int var3;
}
</code>```

lets say the list Object has 3 possible var1 ("yes","no","maybe") then i want 3 Lists where each list are all the objects that have "yes","no" or "maybe" as var1 (this can be a list of 100 objects long with each object being one of this string) (the amount of possibilities in var1 is not constant)

答:
Have a look at ILookup: </p>

```<code>var splitted = list.ToLookup(item => item.var1);
</code>```

Body:
I am trying to split my list into multiple smaller lists but don't know how i should do it.

List<Object> list = new List<Object>();

This is my original list that contains the object Object. I am trying to split this list based on the variables of this Object.

example:

public class Object {
   string var1;
   int var2;
   int var3;
}

lets say the list Object has 3 possible var1 ("yes","no","maybe") then i want 3 Lists where each list are all the objects that have "yes","no" or "maybe" as var1 (this can be a list of 100 objects long with each object being one of this string) (the amount of possibilities in var1 is not constant)

Body:
Have a look at ILookup:

var splitted = list.ToLookup(item => item.var1);


答:
Remove Float:left from li and add display:inline-block

#pagination{
  margin: 40 40 0;
  float: left;
  width:100%;
}
ul.tsc_pagination li a{
  border:solid 1px;
  border-radius:3px;
  -moz-border-radius:3px;
  -webkit-border-radius:3px;
  padding:6px 9px 6px 9px;
}
ul.tsc_pagination li{
  padding-bottom:1px;
}
ul.tsc_pagination li a:hover,
ul.tsc_pagination li a.current{
  color:#FFFFFF;
  box-shadow:0px 1px #EDEDED;
  -moz-box-shadow:0px 1px #EDEDED;
  -webkit-box-shadow:0px 1px #EDEDED;
}
ul.tsc_pagination{
  margin:4px 0;
  padding:0px;
  height:100%;
  overflow:hidden;
  font:12px 'Tahoma';
  list-style-type:none;
  text-align:center;
}
ul.tsc_pagination li{
  display:inline-block;
  margin:0px;
  padding:0px;
margin-left:5px;
}
ul.tsc_pagination li a{
  color:black;
  display:block;
  text-decoration:none;
  padding:7px 10px 7px 10px;
}
ul.tsc_pagination li a img{
  border:none;
}
ul.tsc_pagination li a{
  color:#0A7EC5;
  border-color:#8DC5E6;
  background:#F8FCFF;
}
ul.tsc_pagination li a:hover,
ul.tsc_pagination li a.current{
  text-shadow:0px 1px #388DBE;
  border-color:#3390CA;
  background:#58B0E7;
  background:-moz-linear-gradient(top, #B4F6FF 1px, #63D0FE 1px, #58B0E7);
  background:-webkit-gradient(linear, 0 0, 0 100%, color-stop(0.02, #B4F6FF), color-stop(0.02, #63D0FE), color-stop(1, #58B0E7));
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div id="pagination">
  <ul class="tsc_pagination">
  <!-- Show pagination links -->
    <li></li>
    <li>1</li>
    <li>2</li>
    <li>Next</li>
    <li></li>
  </ul>
</div></code>```

Title: align center and center tag are not working

Body:
Remove Float:left from li and add display:inline-block

#pagination{
  margin: 40 40 0;
  float: left;
  width:100%;
}
ul.tsc_pagination li a{
  border:solid 1px;
  border-radius:3px;
  -moz-border-radius:3px;
  -webkit-border-radius:3px;
  padding:6px 9px 6px 9px;
}
ul.tsc_pagination li{
  padding-bottom:1px;
}
ul.tsc_pagination li a:hover,
ul.tsc_pagination li a.current{
  color:#FFFFFF;
  box-shadow:0px 1px #EDEDED;
  -moz-box-shadow:0px 1px #EDEDED;
  -webkit-box-shadow:0px 1px #EDEDED;
}
ul.tsc_pagination{
  margin:4px 0;
  padding:0px;
  height:100%;
  overflow:hidden;
  font:12px 'Tahoma';
  list-style-type:none;
  text-align:center;
}
ul.tsc_pagination li{
  display:inline-block;
  margin:0px;
  padding:0px;
margin-left:5px;
}
ul.tsc_pagination li a{
  color:black;
  display:block;
  text-decoration:none;
  padding:7px 10px 7px 10px;
}
ul.tsc_pagination li a img{
  border:none;
}
ul.tsc_pagination li a{
  color:#0A7EC5;
  border-color:#8DC5E6;
  background:#F8FCFF;
}
ul.tsc_pagination li a:hover,
ul.tsc_pagination li a.current{
  text-shadow:0px 1px #388DBE;
  border-color:#3390CA;
  background:#58B0E7;
  background:-moz-linear-gradient(top, #B4F6FF 1px, #63D0FE 1px, #58B0E7);
  background:-webkit-gradient(linear, 0 0, 0 100%, color-stop(0.02, #B4F6FF), color-stop(0.02, #63D0FE), color-stop(1, #58B0E7));
}

<div id="pagination">
  <ul class="tsc_pagination">
  <!-- Show pagination links -->
    <li></li>
    <li><a class="current">1</a></li>
    <li><a href="http://localhost/helpmesave/index.php/home/viewcompaigns/1">2</a></li>
    <li><a href="http://localhost/helpmesave/index.php/home/viewcompaigns/1">Next</a></li>
    <li></li>
  </ul>
</div>


问:
How to SELECT * but without "Column names must be unique in each view"
I need to encapsulate a set of tables JOINs that we freqently make use of on a vendor's database server.  We reuse the same JOIN logic in many places in extracts etc. and it seemed a VIEW would allow the JOINs to be defined and maintained in one place.

```<code>CREATE VIEW MasterView
AS
SELECT *
FROM entity_1 e1
INNER JOIN entity_2 e2 ON e2.parent_id = entity_1.id
INNER JOIN entity_3 e3 ON e3.parent_id = entity_2.id
/* other joins including business logic */
etc.
</code>```

The trouble is that the vendor makes regular changes to the DB (column additions, name changes) and I want that to be reflected in the "MasterView" automatically.

SELECT * would allow this, but the underlying tables all have ID columns so I get the "Column names in each view must be unique" error.

I specifically want to avoid listing the column names from the tables because a) it requires frequent maintenance b) there are several hundred columns per table.

Is there any way to achieve the dynamism of SELECT * but effectively exclude certain columns (i.e. the ID ones)

Thanks

答:
I had the same issue, see example below:

ALTER VIEW Summary AS
SELECT * FROM Table1 AS t1
INNER JOIN Table2 AS t2 ON t1.Id = t2.Id

and I encountered that error you mentioned, the easiest solution is using the alias before * like this:

SELECT t1.* FROM Table1 AS t1
INNER JOIN Table2 AS t2 ON t1.Id = t2.Id

You shouldn't see that error anymore.

Body:
I need to encapsulate a set of tables JOINs that we freqently make use of on a vendor's database server.  We reuse the same JOIN logic in many places in extracts etc. and it seemed a VIEW would allow the JOINs to be defined and maintained in one place.

CREATE VIEW MasterView
AS
SELECT *
FROM entity_1 e1
INNER JOIN entity_2 e2 ON e2.parent_id = entity_1.id
INNER JOIN entity_3 e3 ON e3.parent_id = entity_2.id
/* other joins including business logic */
etc.

The trouble is that the vendor makes regular changes to the DB (column additions, name changes) and I want that to be reflected in the "MasterView" automatically.

SELECT * would allow this, but the underlying tables all have ID columns so I get the "Column names in each view must be unique" error.

I specifically want to avoid listing the column names from the tables because a) it requires frequent maintenance b) there are several hundred columns per table.

Is there any way to achieve the dynamism of SELECT * but effectively exclude certain columns (i.e. the ID ones)

Thanks


问:
Full-text search on in-memory optimize table sql server
How can I do a full-text search like containstable or freetexttable on in-memory optimize table SQL Server?</p>

答:
Fulltext indexes are not supported for memory-optimized tables.

https://learn.microsoft.com/en-us/sql/relational-databases/in-memory-oltp/transact-sql-constructs-not-supported-by-in-memory-oltp


问:
How do I print oldest file and include its timestamp from a directory via UNIX
I have a number of files in a directory, and I would like to print the oldest file along with its timestamp.

The following command is giving me the correct filename, however it does not show me the timestamp.

```<code>ls -ltr | head -1
</code>```

EDIT: non-gnu based system.

答:
```<code>ls -ltr | head -1 |  awk '{OFS="\t"} {print $6, $7, $8, $9}'
</code>```

awk's print statement takes an index,

If the output of your ls -ltr is

-rw-r--r-- 1 abc abc 185 Dec 19 11:23 testfile.csv

then

```<code> $6: date (19)
 $7: month (Dec)
 $8: time (11:23)
 $9: file name (testfile.csv)
</code>```

index starts with 1 from left to right.

Note: https://www.gnu.org/s/gawk/manual/gawk.html awk is crazy powerful.

Body:
I have a number of files in a directory, and I would like to print the oldest file along with its timestamp.

The following command is giving me the correct filename, however it does not show me the timestamp.

ls -ltr | head -1

EDIT: non-gnu based system.

Body:
ls -ltr | head -1 |  awk '{OFS="\t"} {print $6, $7, $8, $9}'

awk's print statement takes an index,

If the output of your ls -ltr is

-rw-r--r-- 1 abc abc 185 Dec 19 11:23 testfile.csv

then

 $6: date (19)
 $7: month (Dec)
 $8: time (11:23)
 $9: file name (testfile.csv)

index starts with 1 from left to right.

Note: https://www.gnu.org/s/gawk/manual/gawk.html awk is crazy powerful.


问:
Brace placement after init list in C++
For anyone who places braces thus:

```<code>void f() {
    stuff();
}
</code>```

How do you prefer to place braces after long initializer lists?

The same way?

```<code>Object::Object()
    : foo(1)
    , bar(2) {
    stuff();
}
</code>```

Or make an exception so you actually see where the init list ends?

```<code>Object::Object()
    : foo(1)
    , bar(2)
{
    stuff();
}
</code>```

Or leave a blank line?

```<code>Object::Object()
    : foo(1)
    , bar(2) {

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

Or maybe make a weird hybrid?

```<code>Object::Object()
    : foo(1)
    , bar(2)
    {
    stuff();
}
</code>```

Or abuse indentation

```<code>Object::Object()
: foo(1)
, bar(2) {
    stuff();
}

Object::Object() : foo(1)
                            , bar(2) {
    stuff();
}
</code>```

In this small example all are pretty but crank a dozen initializers and a moderately long function body and this quickly changes.

答:
I am admitted inconsistent globally in lots of things I do, meaning I do not have one global brace method, instead each language construct may have its own brace method which I use consistently.

```<code> function()
 {
 }

 control-flow () {
 } else {
 }

 type name {
 };
</code>```

As a constructor is a function...

```<code> foo::foo()
  : bar(1)
  , baz(2)
 {
 }
</code>```

OwnerDisplayName: Iraimbilanja

LastEditorDisplayName: Iraimbilanja

Title: Brace placement after init list in C++

Body:
For anyone who places braces thus:

void f() {
    stuff();
}

How do you prefer to place braces after long initializer lists?

The same way?

Object::Object()
    : foo(1)
    , bar(2) {
    stuff();
}

Or make an exception so you actually see where the init list ends?

Object::Object()
    : foo(1)
    , bar(2)
{
    stuff();
}

Or leave a blank line?

Object::Object()
    : foo(1)
    , bar(2) {

    stuff();
}

Or maybe make a weird hybrid?

Object::Object()
    : foo(1)
    , bar(2)
    {
    stuff();
}

Or abuse indentation

Object::Object()
: foo(1)
, bar(2) {
    stuff();
}

Object::Object() : foo(1)
                            , bar(2) {
    stuff();
}

In this small example all are pretty but crank a dozen initializers and a moderately long function body and this quickly changes.

Body:
I am admitted inconsistent globally in lots of things I do, meaning I do not have one global brace method, instead each language construct may have its own brace method which I use consistently.

 function()
 {
 }

 control-flow () {
 } else {
 }

 type name {
 };

As a constructor is a function...

 foo::foo()
  : bar(1)
  , baz(2)
 {
 }


问:
WPF Fade Out on a control
In my WPF app, I have a feedback control that I want to appear after a user action completes (save data, delete...).  The visibility is set to Hidden to begin and style set to the animateFadeOut style defined as a resource (see below).  Then I want to set the text and control Visibility to visible in my C# code and have the feedback control display the message and fade out after 5 seconds and remain hidden (Visibility.Hidden).

The following XAML works the first time I call control.Visiblity= Visibility.Visible but the control doesn't reappear the second time.  I figure that is because the animation is still running, which has control over the feedback control.  I then tried to set FillBehavior to "Stop" but that just made the control visible again and I want it hidden.  Then, with FillBehavior="Stop", I tried to set a trigger "when Opacity = 0, set the Visibility to Hidden".  The trigger didn't seem to fire and I was left with the visible control once more after the animation completed.

Please help point out what I am doing wrong here.

Alternatively, if you can suggest a better way to display a control that fades after 5 seconds and can be called over and over, I would appreciate it.

Thanks!

```<code><Style TargetType="{x:Type FrameworkElement}" x:Key="animateFadeOut">
        <Style.Triggers>
            <Trigger Property="Visibility" Value="Visible">
                <Trigger.EnterActions>
                    <BeginStoryboard >
                        <Storyboard>
                            <DoubleAnimation BeginTime="0:0:5.0" Storyboard.TargetProperty="Opacity"
                         From="1.0" To="0.0" Duration="0:0:0.5"/>
                        </Storyboard>
                    </BeginStoryboard>
                </Trigger.EnterActions>
            </Trigger>
        </Style.Triggers>
    </Style>
</code>```

答:
The problem is that after your animation completes your control still has Visibility=Visible, so it cannot be entered again.

I would rather use animation that does the whole thing, first shows the control, then hides it.

```<code><Storyboard x:Key="animate">
    <ObjectAnimationUsingKeyFrames BeginTime="0:0:0" Storyboard.TargetProperty="Visibility">
        <DiscreteObjectKeyFrame KeyTime="0">
            <DiscreteObjectKeyFrame.Value>
                <Visibility>Visible</Visibility>
            </DiscreteObjectKeyFrame.Value>
        </DiscreteObjectKeyFrame>
    </ObjectAnimationUsingKeyFrames>
    <DoubleAnimation BeginTime="0:0:0.0" Storyboard.TargetProperty="Opacity" From="0" To="1" Duration="0:0:0.2"/>
    <DoubleAnimation BeginTime="0:0:5.0" Storyboard.TargetProperty="Opacity" From="1" To="0" Duration="0:0:0.5"/>
    <ObjectAnimationUsingKeyFrames BeginTime="0:0:5.5" Storyboard.TargetProperty="Visibility">
        <DiscreteObjectKeyFrame KeyTime="0">
            <DiscreteObjectKeyFrame.Value>
                <Visibility>Hidden</Visibility>
            </DiscreteObjectKeyFrame.Value>
        </DiscreteObjectKeyFrame>
    </ObjectAnimationUsingKeyFrames>
</Storyboard>
</code>```

And use it as follows:

```<code>((Storyboard)FindResource("animate")).Begin(someControl);
</code>```

Title: WPF Fade Out on a control

Body:
In my WPF app, I have a feedback control that I want to appear after a user action completes (save data, delete...).  The visibility is set to Hidden to begin and style set to the animateFadeOut style defined as a resource (see below).  Then I want to set the text and control Visibility to visible in my C# code and have the feedback control display the message and fade out after 5 seconds and remain hidden (Visibility.Hidden).

The following XAML works the first time I call control.Visiblity= Visibility.Visible but the control doesn't reappear the second time.  I figure that is because the animation is still running, which has control over the feedback control.  I then tried to set FillBehavior to "Stop" but that just made the control visible again and I want it hidden.  Then, with FillBehavior="Stop", I tried to set a trigger "when Opacity = 0, set the Visibility to Hidden".  The trigger didn't seem to fire and I was left with the visible control once more after the animation completed.

Please help point out what I am doing wrong here.

Alternatively, if you can suggest a better way to display a control that fades after 5 seconds and can be called over and over, I would appreciate it.

Thanks!

    </Style>

Body:
The problem is that after your animation completes your control still has Visibility=Visible, so it cannot be entered again.

I would rather use animation that does the whole thing, first shows the control, then hides it.

<Storyboard x:Key="animate">
    <ObjectAnimationUsingKeyFrames BeginTime="0:0:0" Storyboard.TargetProperty="Visibility">
        <DiscreteObjectKeyFrame KeyTime="0">
            <DiscreteObjectKeyFrame.Value>
                <Visibility>Visible</Visibility>
            </DiscreteObjectKeyFrame.Value>
        </DiscreteObjectKeyFrame>
    </ObjectAnimationUsingKeyFrames>
    <DoubleAnimation BeginTime="0:0:0.0" Storyboard.TargetProperty="Opacity" From="0" To="1" Duration="0:0:0.2"/>
    <DoubleAnimation BeginTime="0:0:5.0" Storyboard.TargetProperty="Opacity" From="1" To="0" Duration="0:0:0.5"/>
    <ObjectAnimationUsingKeyFrames BeginTime="0:0:5.5" Storyboard.TargetProperty="Visibility">
        <DiscreteObjectKeyFrame KeyTime="0">
            <DiscreteObjectKeyFrame.Value>
                <Visibility>Hidden</Visibility>
            </DiscreteObjectKeyFrame.Value>
        </DiscreteObjectKeyFrame>
    </ObjectAnimationUsingKeyFrames>
</Storyboard>

And use it as follows:

((Storyboard)FindResource("animate")).Begin(someControl);


问:
Calling startIntentSenderForResult from Fragment (Android Billing v3)
The new Android Billing v3 documentation and helper code uses startIntentSenderForResult() when launching a purchase flow. I want to start a purchase flow (and receive the result) from a Fragment.

For example the documentation suggests calling

```<code>startIntentSenderForResult(pendingIntent.getIntentSender(),
    1001, new Intent(), Integer.valueOf(0), Integer.valueOf(0),
    Integer.valueOf(0));
</code>```

and the helper code calls

```<code>mHelper.launchPurchaseFlow(this, SKU_GAS, 10001,
    mPurchaseFinishedListener, "bGoa+V7g/yqDXvKRqq+JTFn4uQZbPiQJo4pf9RzJ");
</code>```

which calls startIntentSenderForResult().

The problem is, calling startIntentSenderForResult() causes onActivityResult() to be called on the parent Activity rather than on the Fragment that it was called from (where the IabHelper resides).

I could receive the onActivityResult() in the parent Activity and then manually call the onActivityResult() on the Fragment, but is there a way to make a call to startIntentSenderForResult() from a Fragment that returns the result directly to that Fragment's onActivityResult()?

答:
You need to pass fragment and data to parent activity, then call the fragment from onActivityResult in parent activity.

like this

in fragment:

HomeActivity activity = (HomeActivity) getActivity();
activity.purchaseLauncher(this, mHelper, productDTO.getSku(), RC_REQUEST, mPurchaseFinishedListener, PAYLOAD);```
</div>
</div>
</p>
<p>in parent activity:</p>
<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-html lang-html prettyprint-override"><code>@Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (storeFragment != null) {
            storeFragment.onActivityResult(requestCode, resultCode, data);
        }
    }

    public void purchaseLauncher(StoreFragment storeFragment, IabHelper mHelper, String sku, int requestCode, IabHelper.OnIabPurchaseFinishedListener mPurchaseFinishedListener, String payload) {
        this.storeFragment = storeFragment;
        mHelper.launchPurchaseFlow(this, sku, requestCode, mPurchaseFinishedListener, payload);
    }</code>```

Body:
The new Android Billing v3 documentation and helper code uses startIntentSenderForResult() when launching a purchase flow. I want to start a purchase flow (and receive the result) from a Fragment.

For example the documentation suggests calling

startIntentSenderForResult(pendingIntent.getIntentSender(),
    1001, new Intent(), Integer.valueOf(0), Integer.valueOf(0),
    Integer.valueOf(0));

and the helper code calls

mHelper.launchPurchaseFlow(this, SKU_GAS, 10001,
    mPurchaseFinishedListener, "bGoa+V7g/yqDXvKRqq+JTFn4uQZbPiQJo4pf9RzJ");

which calls startIntentSenderForResult().

The problem is, calling startIntentSenderForResult() causes onActivityResult() to be called on the parent Activity rather than on the Fragment that it was called from (where the IabHelper resides).

I could receive the onActivityResult() in the parent Activity and then manually call the onActivityResult() on the Fragment, but is there a way to make a call to startIntentSenderForResult() from a Fragment that returns the result directly to that Fragment's onActivityResult()?

Body:
You need to pass fragment and data to parent activity, then call the fragment from onActivityResult in parent activity.

like this

in fragment:

HomeActivity activity = (HomeActivity) getActivity();
activity.purchaseLauncher(this, mHelper, productDTO.getSku(), RC_REQUEST, mPurchaseFinishedListener, PAYLOAD);

in parent activity:

@Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (storeFragment != null) {
            storeFragment.onActivityResult(requestCode, resultCode, data);
        }
    }

    public void purchaseLauncher(StoreFragment storeFragment, IabHelper mHelper, String sku, int requestCode, IabHelper.OnIabPurchaseFinishedListener mPurchaseFinishedListener, String payload) {
        this.storeFragment = storeFragment;
        mHelper.launchPurchaseFlow(this, sku, requestCode, mPurchaseFinishedListener, payload);
    }

ContentLicense: CC BY-SA 4.0


答:
```<code>            List<Object> list1 = new List<Object>();
            List<Object> list2 = new List<Object>();

            for (int i=0;i<list.Count;i++)
            {
                if (list.var1 == 0)
                {
                    list1.Add(list[i]);
                }
                if (list.var1 == 1)
                {
                    list2.Add(list[i]);
                }

            }
</code>```

Title: splitting List<Object> based on the value of a variable in that Object


问:
How to pass controller action in Jquery AJAX Call in Oxid eSHOP
I am working on Jquery AJAX in OXID eSHOP.

I want to pass proper action (function) name in AJAX url parameter.

Below is my code:

```<code>jQuery.ajax({
        type: "POST",
        data: {
            variable: value
        },
        url: "",
        success: function(data) {

        }
    });
</code>```

I want to call one function in url parameter.

But don't know how to pass its value in url paramaeter.

Anyone knows then please help me.

答:
You should include function name as URL parameter, just like the shop does it in most situations:
http://your-shop.com/index.php?cl=controller&fnc=functionname</p>

Body:
I am working on Jquery AJAX in OXID eSHOP.

I want to pass proper action (function) name in AJAX url parameter.

Below is my code:

jQuery.ajax({
        type: "POST",
        data: {
            variable: value
        },
        url: "",
        success: function(data) {

        }
    });

I want to call one function in url parameter.

But don't know how to pass its value in url paramaeter.

Anyone knows then please help me.


问:
wordpress shortcode content is showing two times
I am developing a shortcode for wordpress.

using the shortcode in word file as :

```<code>add_shortcode('LATEST_NOT_ROHIT','latest_notification_rohit');
function latest_notification_rohit()
{
    include("shortcode.php");
}
</code>```

in shortcode.php file the code is as follow :

```<code><div class='alert alert-info'>Latest Notifications</div>

<?php
global $wpdb;
$select_qury = "select * from `ln_category`";
$select_cat = $wpdb->get_results($select_qury);
foreach($select_cat as $select_cat)
{
    echo "<h4>Latest Notifications For <span style='color:#800000'>".$select_cat->category."</span></h4>";
    $cat_id = $select_cat->id;

    $select_qury2 = "select * from `ln_notification` where `cat_id`='$cat_id'";
    $select_notification = $wpdb->get_results($select_qury2);
?>
<table class="responsive display table table-bordered">
<tr><th>Sr No</th><th>Organisation</th><th>Post Name</th><th>No of Post</th><th>Qualification</th><th>Fees</th><th>Adervst Date</th><th>Application Start Date</th>
<th>Application Last Date</th><th>Status</th></tr>
<?php
$i=1;
foreach($select_notification as $select_notification)
{
    $current_date = date('Y-m-d');
    $start_date = $select_notification->start_date;
    $last_date = $select_notification->last_date;
    if($current_date < $start_date)
    {
        $remark = "<span style='color:green'>Form is about to start</span>";
    }
    elseif($current_date > $last_date)
    {
        $remark ="<span style='color:red'>Last Date is over</span>";
    }
    else
    {
        $remark = "Application is going on";
    }
    echo "<tr><td>$i</td><td>".$select_notification->organisation."</td><td>".$select_notification->post_name."</td><td>".$select_notification->no_of_post.
    "</td><td>".$select_notification->qualification."</td><td>".$select_notification->fees."</td><td>".date('d-M-Y',strtotime($select_notification->adv_date))."</td><td>".date('d-M-Y',strtotime($start_date))."</td><td>".date('d-M-Y',strtotime($last_date))."</td><td>$remark</td></tr>";
    $i++;
}
?>
</table>
<?php
}
?>
</code>```

but when I am running this code in wordpress page/post then the content is displayed two times. The demo is at the front end

http://singhalrohitashv.com/latest-notification/

How can I resolve this problem ???

答:
You are probably calling the latest_notification_rohit() function on one of the following files :

Header.php for the page

Page template file

You might also be calling the content function twice for that page. Doing a search all for the_content() or latest_notification_rohit() might show you the places where the code is being called multiple times.

Body:
I am developing a shortcode for wordpress.

using the shortcode in word file as :

add_shortcode('LATEST_NOT_ROHIT','latest_notification_rohit');
function latest_notification_rohit()
{
    include("shortcode.php");
}

in shortcode.php file the code is as follow :

Latest Notifications

<?php
global $wpdb;
$select_qury = "select * from `ln_category`";
$select_cat = $wpdb->get_results($select_qury);
foreach($select_cat as $select_cat)
{
    echo "
Latest Notifications For ".$select_cat->category."
";
    $cat_id = $select_cat->id;

    $select_qury2 = "select * from `ln_notification` where `cat_id`='$cat_id'";
    $select_notification = $wpdb->get_results($select_qury2);
?>

Sr No	Organisation	Post Name	No of Post	Qualification	Fees	Adervst Date	Application Start Date
Application Last Date	Status

<?php
$i=1;
foreach($select_notification as $select_notification)
{
    $current_date = date('Y-m-d');
    $start_date = $select_notification->start_date;
    $last_date = $select_notification->last_date;
    if($current_date < $start_date)
    {
        $remark = "Form is about to start";
    }
    elseif($current_date > $last_date)
    {
        $remark ="Last Date is over";
    }
    else
    {
        $remark = "Application is going on";
    }
    echo "
$i	".$select_notification->organisation."	".$select_notification->post_name."	".$select_notification->no_of_post.
    "	".$select_notification->qualification."	".$select_notification->fees."	".date('d-M-Y',strtotime($select_notification->adv_date))."	".date('d-M-Y',strtotime($start_date))."	".date('d-M-Y',strtotime($last_date))."	$remark
";
    $i++;
}
?>

<?php
}
?>

but when I am running this code in wordpress page/post then the content is displayed two times. The demo is at the front end

http://singhalrohitashv.com/latest-notification/

How can I resolve this problem ???


问:
How to detect when FileDownloader in vaadin finish
How can I detect fileDownloader finish to export my csv-file:

Here is the part, where I implemented the download-button

```<code> Button downloadButton = new Button("Download");
    Exporter exporter = new Exporter();
    downloadButton.addClickListener(clickEvent -> {
     //something here
    });
    exporter.getFileDownloader().extend(downloadButton);
</code>```

This is my exporter with the fileDownloader:

```<code>class Exporter{
    private FileDownloader fileDownloader;

    Exporter() {
        StreamResource streamResource = createResource();
        fileDownloader = new FileDownloader(streamResource);
    }

    private StreamResource createResource() {
        return new StreamResource(new StreamResource.StreamSource() {
            @Override
            public InputStream getStream() {
            // some logic here
            }
        }, "myfile.csv");
    }

    FileDownloader getFileDownloader() {
        return fileDownloader;
    }

    ...
</code>```

答: I checked official documentation, it seems there is no way to detect that using FileDownloader. There is also similar thread you can check it. How to detect when Vaadin FileDownloader succeeds or fails</p>

Body:
How can I detect fileDownloader finish to export my csv-file:

Here is the part, where I implemented the download-button

 Button downloadButton = new Button("Download");
    Exporter exporter = new Exporter();
    downloadButton.addClickListener(clickEvent -> {
     //something here
    });
    exporter.getFileDownloader().extend(downloadButton);

This is my exporter with the fileDownloader:

class Exporter{
    private FileDownloader fileDownloader;

    Exporter() {
        StreamResource streamResource = createResource();
        fileDownloader = new FileDownloader(streamResource);
    }

    private StreamResource createResource() {
        return new StreamResource(new StreamResource.StreamSource() {
            @Override
            public InputStream getStream() {
            // some logic here
            }
        }, "myfile.csv");
    }

    FileDownloader getFileDownloader() {
        return fileDownloader;
    }

    ...


问:
How to expend a div to alway be 100% of the page?
I want to expand my menu height to always take 100% of the visible height.

For the moment it only take the 100% at the loading, then if I scroll down there is a white block and it's ugly.

I can't post images because I haven't 10points

The CSS of my menu is the following one:

```<code>.nav-sm .container.body .col-md-3.left_col {
    min-height: 100%;
    width: 70px;
    padding: 0;
    z-index: 9999;
    position: absolute;
}
</code>```

The thing I want to achieve is to have my menu who always took all the visible height and I can't find how to do that.

答:
Try this:

div#navi{
    width:100px;
    height:auto;
    top:0px;
    bottom:0px;
    position:fixed;
    background:maroon;
}

body {
    height:2000px;
    margin: 0px;
    padding: 0px;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div id="navi">
test
</div></code>```

Body:
I want to expand my menu height to always take 100% of the visible height.

For the moment it only take the 100% at the loading, then if I scroll down there is a white block and it's ugly.

I can't post images because I haven't 10points

The CSS of my menu is the following one:

.nav-sm .container.body .col-md-3.left_col {
    min-height: 100%;
    width: 70px;
    padding: 0;
    z-index: 9999;
    position: absolute;
}

The thing I want to achieve is to have my menu who always took all the visible height and I can't find how to do that.

Body:
Try this:

div#navi{
    width:100px;
    height:auto;
    top:0px;
    bottom:0px;
    position:fixed;
    background:maroon;
}

body {
    height:2000px;
    margin: 0px;
    padding: 0px;
}

<div id="navi">
test
</div>