问:
.net Core X Forwarded Proto not working
I am working to get my .net core 1.1 application working behind a load balancer and enforcing https. I have the following setup in my Startup.cs

```<code>public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory, IServiceProvider serviceProvider, IOptions<Auth0Settings> auth0Settings)
{
    loggerFactory.AddConsole(Configuration.GetSection("Logging"));
    loggerFactory.AddDebug();

    var startupLogger = loggerFactory.CreateLogger<Startup>();

    if (env.IsDevelopment())
    {
        app.UseDeveloperExceptionPage();
        app.UseDatabaseErrorPage();
        app.UseBrowserLink();
        startupLogger.LogInformation("In Development");
    }
    else
    {
        startupLogger.LogInformation("NOT in development");
        app.UseExceptionHandler("/Home/Error");
    }

    app.UseMiddleware<HttpsRedirectMiddleware>();
    app.UseForwardedHeaders(new ForwardedHeadersOptions
    {
        ForwardedHeaders = ForwardedHeaders.XForwardedFor | ForwardedHeaders.XForwardedProto
    });`
        app.UseCookieAuthentication(new CookieAuthenticationOptions
        {
            AuthenticationScheme= CookieAuthenticationDefaults.AuthenticationScheme,
            AutomaticAuthenticate = true,
            AutomaticChallenge = true,
            CookieHttpOnly = true,
            SlidingExpiration = true
        });
</code>```

The HttpsRedirectMiddleware is for validating the LB has the X-Forwarded-Proto set, it does, and comes back as https as the only value. When I go to the site (https://myapp.somedomain.net), it knows I am not authenticated and redirects me to (http://myapp.somedomain.net/Account/Logon?ReturnUrl=%2f). It loses the SSL connection and switched back over to port 80 on me. The .net core documentation says to use "UseForwardedHeaders" like below, which does not work in my case. The console logger does not have any error or warnings from the middleware when this switch happens.

For a short term fix, I have put this below "UseForwardedHeaders"

```<code>    app.Use(async (context, next) =>
    {
        var xproto = context.Request.Headers["X-Forwarded-Proto"].ToString();
        if (xproto!=null && xproto.StartsWith("https", StringComparison.OrdinalIgnoreCase)){
            startupLogger.LogInformation("Switched to https");
            context.Request.Scheme = "https";
        }
        await next();

    });
</code>```

The above works perfect, but is a hack. I would like to do it the correct way.

答:
.NET Core has a default set for the forwarded headers. It defaults to 127.0.0.1, for IIS integration.

After tracking down the source code, I found that you can clear the KnownNetworks and KnownProxies lists to accept any forwarded requests. However, it is still best to have a firewall setup or lock the known networks down to a private subnet.

```<code>var forwardingOptions = new ForwardedHeadersOptions()
{
    ForwardedHeaders = ForwardedHeaders.XForwardedFor | ForwardedHeaders.XForwardedProto
};
forwardingOptions.KnownNetworks.Clear(); // Loopback by default, this should be temporary
forwardingOptions.KnownProxies.Clear(); // Update to include

app.UseForwardedHeaders(forwardingOptions);
</code>```

Update for .NET Core 2.x: Remember setting the IP of your proxy/load balancer or the private network after debugging the issue. This prevents bypassing your proxy/load balancer and faking the Forwarded-For headers.

```<code>services.Configure<ForwardedHeadersOptions>(options =>
{
    options.ForwardLimit = 2;

    // Replace with IP of your proxy/load balancer
    options.KnownProxies.Add(IPAddress.Parse("192.168.1.5"));

    // 192.168.1.0/24 allows any from 192.168.1.1-254;
    options.KnownNetworks.Add(new IPNetwork(IPAddress.Parse("192.168.1.0"), 24));
});
</code>```

https://learn.microsoft.com/en-us/aspnet/core/host-and-deploy/proxy-load-balancer?view=aspnetcore-2.2#forwarded-headers-middleware-options

Title: .net Core X Forwarded Proto not working

Body:
I am working to get my .net core 1.1 application working behind a load balancer and enforcing https. I have the following setup in my Startup.cs

public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory, IServiceProvider serviceProvider, IOptions<Auth0Settings> auth0Settings)
{
    loggerFactory.AddConsole(Configuration.GetSection("Logging"));
    loggerFactory.AddDebug();

    var startupLogger = loggerFactory.CreateLogger<Startup>();

    if (env.IsDevelopment())
    {
        app.UseDeveloperExceptionPage();
        app.UseDatabaseErrorPage();
        app.UseBrowserLink();
        startupLogger.LogInformation("In Development");
    }
    else
    {
        startupLogger.LogInformation("NOT in development");
        app.UseExceptionHandler("/Home/Error");
    }

    app.UseMiddleware<HttpsRedirectMiddleware>();
    app.UseForwardedHeaders(new ForwardedHeadersOptions
    {
        ForwardedHeaders = ForwardedHeaders.XForwardedFor | ForwardedHeaders.XForwardedProto
    });`
        app.UseCookieAuthentication(new CookieAuthenticationOptions
        {
            AuthenticationScheme= CookieAuthenticationDefaults.AuthenticationScheme,
            AutomaticAuthenticate = true,
            AutomaticChallenge = true,
            CookieHttpOnly = true,
            SlidingExpiration = true
        });

The HttpsRedirectMiddleware is for validating the LB has the X-Forwarded-Proto set, it does, and comes back as https as the only value. When I go to the site (https://myapp.somedomain.net), it knows I am not authenticated and redirects me to (http://myapp.somedomain.net/Account/Logon?ReturnUrl=%2f). It loses the SSL connection and switched back over to port 80 on me. The .net core documentation says to use "UseForwardedHeaders" like below, which does not work in my case. The console logger does not have any error or warnings from the middleware when this switch happens.

For a short term fix, I have put this below "UseForwardedHeaders"

    app.Use(async (context, next) =>
    {
        var xproto = context.Request.Headers["X-Forwarded-Proto"].ToString();
        if (xproto!=null && xproto.StartsWith("https", StringComparison.OrdinalIgnoreCase)){
            startupLogger.LogInformation("Switched to https");
            context.Request.Scheme = "https";
        }
        await next();

    });

The above works perfect, but is a hack. I would like to do it the correct way.

Body:
.NET Core has a default set for the forwarded headers. It defaults to 127.0.0.1, for IIS integration.

After tracking down the source code, I found that you can clear the KnownNetworks and KnownProxies lists to accept any forwarded requests. However, it is still best to have a firewall setup or lock the known networks down to a private subnet.

var forwardingOptions = new ForwardedHeadersOptions()
{
    ForwardedHeaders = ForwardedHeaders.XForwardedFor | ForwardedHeaders.XForwardedProto
};
forwardingOptions.KnownNetworks.Clear(); // Loopback by default, this should be temporary
forwardingOptions.KnownProxies.Clear(); // Update to include

app.UseForwardedHeaders(forwardingOptions);

Update for .NET Core 2.x: Remember setting the IP of your proxy/load balancer or the private network after debugging the issue. This prevents bypassing your proxy/load balancer and faking the Forwarded-For headers.

services.Configure<ForwardedHeadersOptions>(options =>
{
    options.ForwardLimit = 2;

    // Replace with IP of your proxy/load balancer
    options.KnownProxies.Add(IPAddress.Parse("192.168.1.5"));

    // 192.168.1.0/24 allows any from 192.168.1.1-254;
    options.KnownNetworks.Add(new IPNetwork(IPAddress.Parse("192.168.1.0"), 24));
});

https://learn.microsoft.com/en-us/aspnet/core/host-and-deploy/proxy-load-balancer?view=aspnetcore-2.2#forwarded-headers-middleware-options


来源: stackexchange

问:
Oracle check constraint with case when
What is the right way of writing something like this in ORACLE and is it possible:

```<code>ALTER TABLE REQUESTER ADD CONSTRAINT chk_account_status CHECK
(CASE WHEN (account_status='R' or account_status='A') THEN
(email is not null and address is not null and password is not null and mobile_phone is not null) END);
</code>```

Any advice is very much appreciated.

Thank you,

mismas

[EDIT]

This is how I have done it now:

```<code>ALTER TABLE REQUESTER ADD CONSTRAINT CK_account_status
CHECK ((account_status='R' or account_status='A') AND
(email is not null AND MOBILE_PHONE is not null
AND PASSWORD is not null AND ADDRESS is not null));
</code>```

答:
You don't need a CASE, but a bit of boolean logic:

```<code>    (
        (account_status='R' or account_status='A')
          AND
        (email is not null and address is not null and password is not null and mobile_phone is not null)
    )
OR
     not (account_status='R' or account_status='A')
</code>```

You can rewrite this in a more compact way, I used this one because it's quite self-explanatory, given your code.

ContentLicense: CC BY-SA 3.0

Title: Oracle check constraint with case when

Body:
What is the right way of writing something like this in ORACLE and is it possible:

ALTER TABLE REQUESTER ADD CONSTRAINT chk_account_status CHECK
(CASE WHEN (account_status='R' or account_status='A') THEN
(email is not null and address is not null and password is not null and mobile_phone is not null) END);

Any advice is very much appreciated.

Thank you,

mismas

[EDIT]

This is how I have done it now:

ALTER TABLE REQUESTER ADD CONSTRAINT CK_account_status
CHECK ((account_status='R' or account_status='A') AND
(email is not null AND MOBILE_PHONE is not null
AND PASSWORD is not null AND ADDRESS is not null));

Body:
You don't need a CASE, but a bit of boolean logic:

    (
        (account_status='R' or account_status='A')
          AND
        (email is not null and address is not null and password is not null and mobile_phone is not null)
    )
OR
     not (account_status='R' or account_status='A')

You can rewrite this in a more compact way, I used this one because it's quite self-explanatory, given your code.


问:
Using Entity manager and JPA, returns object only
When i run the following code it was return only object list. i want the list in vehicle. what is the error in my code?

My Dao Class Is:

```<code>public class VehicleDao {

HibernateTemplate template;
private EntityManager emManager;

@PersistenceContext
public void setEm(EntityManager emManager) {
    this.emManager = emManager;
}
public List<Vehicle> getVehicleDataUsing_Sp()
{
Properties prop= new Properties();
    try {
        InputStream input = new FileInputStream("E:\\spring4AndHibernate5\\src\\Query.properties");
        prop.load(input);
        Query query = emManager.createNativeQuery(prop.getProperty("vehicleQuery"));
        List<Vehicle> list = query.getResultList();
        return list;
        }
}
</code>```

答:
You either need to define the result class in your native query definition (use resultClass=Vehicle.class where you have defined your named query)

and/or

you need to map the native class when using createNamedQuery (use createNativeQuery(prop.getProperty("vehicleQuery"), Vehicle.class)).

Body:
When i run the following code it was return only object list. i want the list in vehicle. what is the error in my code?

My Dao Class Is:

public class VehicleDao {

HibernateTemplate template;
private EntityManager emManager;

@PersistenceContext
public void setEm(EntityManager emManager) {
    this.emManager = emManager;
}
public List<Vehicle> getVehicleDataUsing_Sp()
{
Properties prop= new Properties();
    try {
        InputStream input = new FileInputStream("E:\\spring4AndHibernate5\\src\\Query.properties");
        prop.load(input);
        Query query = emManager.createNativeQuery(prop.getProperty("vehicleQuery"));
        List<Vehicle> list = query.getResultList();
        return list;
        }
}


问:
Methods to use the serial port in multiple forms
I'm designing a windows userform to interact with a microcontroller through the serial port.

The GUI includes multiple userforms which will use the same serialport. I researched how to do that and I found different ideas. Some I don't know if it works the others I'm not sure how to implement it in code. Let's say I have

Form1: Start.vb
Form2: Shield1.vb

1) Can I declare the serial port in the start userform as:

```<code>Public Shared SerialPort1 As New System.IO.Ports.SerialPort
</code>```

And use it in the other forms ?

2) First alternative: Use a Module to declare a new Serialport

```<code>Module Module1
Public WithEvents mySerialPort1 As New IO.Ports.SerialPort

Private Sub mySerialPort1_DataReceived(sender As Object, _
                                       e As System.IO.Ports.SerialDataReceivedEventArgs) _
                                   Handles mySerialPort1.DataReceived
End Sub
End Module
</code>```

Is this method right? If yes How do I use it in the code of my forms ? How to include the DataReceived Event in the code of the forms ?

3) Second alternative: Constructor of the Serialport in the start form and then pass the data to the other forms as mentionned in this post: Alternate Solution 1

```<code>private void OnSetup(object sender, EventArgs e)
{
this.port = new SerialPort(...);
// TODO: initialize port

Form2 f2 = new Form2(this.port);
f2.Show();
Form3 f3 = new Form3(this.port);
f3.Show();
Form4 f4 = new Form4(this.port);
f4.Show();
</code>```

}

Are then the Events also included ? How do I use them?

4) Third alternative: Use a static class like done in this solution:
Alternate Solution 2

Is the code written in C# here right ? I'm writing my programm in VB.net but I could take this as a reference.

Which is the recommended solution for a beginner ? Could you please write it in a small code if you have another suggestion or a correction ?

I apologize in advance for any ambiguity or falsly used terms.

Thanks you!

答:
I would follow the "Singleton" design pattern, which ensures that only one instance of a class is created.  Here is a well-accepted template for such a class:

```<code>Public NotInheritable Class MySerial
Private Shared ReadOnly _instance As New Lazy(Of MySerial)(Function() New
    MySerial(), System.Threading.LazyThreadSafetyMode.ExecutionAndPublication)

Private Sub New()
End Sub

Public Shared ReadOnly Property Instance() As MySerial
    Get
        Return _instance.Value
    End Get
End Property
</code>```

End Class

In the New() method you should set up your serial port as you need to.  Then no matter where you need to use the port, you make your references to the Instance:

```<code>Dim singletonSerial As MySerial = MySerial.Instance
</code>```

This is the canonical pattern to ensure that you have only one copy of an object without resorting to static classes.  It's a design pattern that dates back more than 20 years and still works great when you need exactly one copy of an object.

Body:
I'm designing a windows userform to interact with a microcontroller through the serial port.

The GUI includes multiple userforms which will use the same serialport. I researched how to do that and I found different ideas. Some I don't know if it works the others I'm not sure how to implement it in code. Let's say I have

Form1: Start.vb
Form2: Shield1.vb

1) Can I declare the serial port in the start userform as:

Public Shared SerialPort1 As New System.IO.Ports.SerialPort

And use it in the other forms ?

2) First alternative: Use a Module to declare a new Serialport

Module Module1
Public WithEvents mySerialPort1 As New IO.Ports.SerialPort

Private Sub mySerialPort1_DataReceived(sender As Object, _
                                       e As System.IO.Ports.SerialDataReceivedEventArgs) _
                                   Handles mySerialPort1.DataReceived
End Sub
End Module

Is this method right? If yes How do I use it in the code of my forms ? How to include the DataReceived Event in the code of the forms ?

3) Second alternative: Constructor of the Serialport in the start form and then pass the data to the other forms as mentionned in this post: Alternate Solution 1

private void OnSetup(object sender, EventArgs e)
{
this.port = new SerialPort(...);
// TODO: initialize port

Form2 f2 = new Form2(this.port);
f2.Show();
Form3 f3 = new Form3(this.port);
f3.Show();
Form4 f4 = new Form4(this.port);
f4.Show();

}

Are then the Events also included ? How do I use them?

4) Third alternative: Use a static class like done in this solution:
Alternate Solution 2

Is the code written in C# here right ? I'm writing my programm in VB.net but I could take this as a reference.

Which is the recommended solution for a beginner ? Could you please write it in a small code if you have another suggestion or a correction ?

I apologize in advance for any ambiguity or falsly used terms.

Thanks you!

Body:
I would follow the "Singleton" design pattern, which ensures that only one instance of a class is created.  Here is a well-accepted template for such a class:

Public NotInheritable Class MySerial
Private Shared ReadOnly _instance As New Lazy(Of MySerial)(Function() New
    MySerial(), System.Threading.LazyThreadSafetyMode.ExecutionAndPublication)

Private Sub New()
End Sub

Public Shared ReadOnly Property Instance() As MySerial
    Get
        Return _instance.Value
    End Get
End Property

End Class

In the New() method you should set up your serial port as you need to.  Then no matter where you need to use the port, you make your references to the Instance:

Dim singletonSerial As MySerial = MySerial.Instance

This is the canonical pattern to ensure that you have only one copy of an object without resorting to static classes.  It's a design pattern that dates back more than 20 years and still works great when you need exactly one copy of an object.


问:
Facebook new nested persistence menu not working
I want to use nested menus for a Facebook bot, but the new API to set the persistent menu does not work.

Even if I remove the nested menu, Facebook returns "success" but the Facebook page does not show the menu.

If I use the old API on thread_settings, then it works. But using the new API I get no menu at all. The new API works for the getting started button, but not the menu.

I have tried everything, and have no idea why it is not working. It returns success but no menu. I am setting the getting started button too.

```<code>curl -X POST -H "Content-Type: application/json" -d '{
  "persistent_menu":[
    {
    "locale":"default",
    "composer_input_disabled":false,
    "call_to_actions":[
        {
          "type":"web_url",
          "title":"Test",
          "url":"https://facebook.com"
        }
      ]
    }
  ]
}' "https://graph.facebook.com/v2.6/me/messenger_profile?access_token={{token}}"
</code>```

答:
I have tried it and it works.
checkout the code here

You can try the bot here: https://www.facebook.com/nautankibot/

I will have to add you as tester if you want to use this bot as its not public.

Screenshot of nested menu in the bot:

It works on fb messenger app as well.

In the above curl call you have not set the type as "nested" in call_to_actions

The above example is taken from fb documentation for menus

Body:
I want to use nested menus for a Facebook bot, but the new API to set the persistent menu does not work.

Even if I remove the nested menu, Facebook returns "success" but the Facebook page does not show the menu.

If I use the old API on thread_settings, then it works. But using the new API I get no menu at all. The new API works for the getting started button, but not the menu.

I have tried everything, and have no idea why it is not working. It returns success but no menu. I am setting the getting started button too.

curl -X POST -H "Content-Type: application/json" -d '{
  "persistent_menu":[
    {
    "locale":"default",
    "composer_input_disabled":false,
    "call_to_actions":[
        {
          "type":"web_url",
          "title":"Test",
          "url":"https://facebook.com"
        }
      ]
    }
  ]
}' "https://graph.facebook.com/v2.6/me/messenger_profile?access_token={{token}}"


问:
Exclude Jenkins jobs from view with regular expression
We're using regular expressions to include jobs in our views for Jenkins.
At the moment the regular expression for the "example"-view is example_(.+).

However we just added a new project called "example_example2" and now the jobs from this project also appear in the "example" view.
Is there any regular expression to exclude the "example_example2"-jobs from the "example"-view? I have been trying to use ^ but no success.

Could you help me out?

答:
You may match example_ not followed with example2 followed with the end of string position using a negative lookahead:

```<code>example_(?!example2$)(.+)
        ^^^^^^^^^^^^^
</code>```

In case you need to anchor the pattern add ^ at the start. .+ will match any 1 or more characters other than line break chars up to the end of the line.

See the regex demo online.

Body:
You may match example_ not followed with example2 followed with the end of string position using a negative lookahead:

example_(?!example2$)(.+)
        ^^^^^^^^^^^^^

In case you need to anchor the pattern add ^ at the start. .+ will match any 1 or more characters other than line break chars up to the end of the line.

See the regex demo online.


问:
Cons for defining logger non-static
Comments for this answer How do you reduce Java logging boilerplate code? strongly suggest not to use loggers as instance member variables. I can think of two negative side-effects:

1) superclass logs with the subclass's logger

2) object cannot be serialized (unless marked transient)

But if serializing is not necessary and logging with subclass name is not a problem, is there anything else why it should be avoided? I think it reduces boilerplate code and avoids copy-paste errors while copying logger variable definition from one class to another. Even Spring framework (which I believe has very good coding standards) uses this method.

答: Another, probably minor con: wasted memory, especially when you have lots of instances, each one with its own logger</p>

OwnerDisplayName: martsraits

ContentLicense: CC BY-SA 2.5

Title: Cons for defining logger non-static

OwnerDisplayName: uzhin


问:
Resources and control position in win32 programming
I'm new in win32 programming and I've some questions about resources.

Must I use a resource editor (from Visual Studio) to make controls? I know it can be post-edited using a Resource Hacker editor. How to prevent it?

GUI created in Windows Forms (.net) or Borland Delphi (VCL) can't be edited using res hacker, maybe it creates controls at runtime.

Is a pointless work make all controls by runtime to prevent it to be edited by res hacker?

```<code>HWND hButton = CreateWindowEx(
    0,
    _T("BUTTON"),
    _T("Click!"),
    WS_CHILD | WS_VISIBLE | BS_PUSHBUTTON | BS_LEFTTEXT,
    5, 5, 80, 25, hwnd, (HMENU)IDC_BUTTON1,
    GetModuleHandle(NULL),
    NULL
);
</code>```

Second question: isn't there a easy way to set position of a control in top right of parent window?

Today I'm doing it in this way:

```<code>case WM_SIZE:
    {
        HWND hButton;
        RECT rcParent, rcButton;

        hButton = GetDlgItem(hwnd, IDC_BUTTON1);

        GetClientRect(hwnd, &rcParent);
        GetClientRect(hButton, &rcButton);

        if(!SetWindowPos(hButton, 0, rcParent.right - (rcButton.right - rcButton.left + 5), 5, 0, 0, SWP_NOSIZE))
        {
            MessageBox(hwnd, _T("Error at WM_SIZE"), _T("Error!"), MB_OK | MB_ICONERROR);
        }
    }
    break;
</code>```

Are there something like Anchors in pure win32 programming?

答: Hi probably no becouse win32 api is base for most all graphics libs in windows. What can i recommend you its use some  graphics libs if you can do it in your project. </p>

Body:
I'm new in win32 programming and I've some questions about resources.

Must I use a resource editor (from Visual Studio) to make controls? I know it can be post-edited using a Resource Hacker editor. How to prevent it?

GUI created in Windows Forms (.net) or Borland Delphi (VCL) can't be edited using res hacker, maybe it creates controls at runtime.

Is a pointless work make all controls by runtime to prevent it to be edited by res hacker?

HWND hButton = CreateWindowEx(
    0,
    _T("BUTTON"),
    _T("Click!"),
    WS_CHILD | WS_VISIBLE | BS_PUSHBUTTON | BS_LEFTTEXT,
    5, 5, 80, 25, hwnd, (HMENU)IDC_BUTTON1,
    GetModuleHandle(NULL),
    NULL
);

Second question: isn't there a easy way to set position of a control in top right of parent window?

Today I'm doing it in this way:

case WM_SIZE:
    {
        HWND hButton;
        RECT rcParent, rcButton;

        hButton = GetDlgItem(hwnd, IDC_BUTTON1);

        GetClientRect(hwnd, &rcParent);
        GetClientRect(hButton, &rcButton);

        if(!SetWindowPos(hButton, 0, rcParent.right - (rcButton.right - rcButton.left + 5), 5, 0, 0, SWP_NOSIZE))
        {
            MessageBox(hwnd, _T("Error at WM_SIZE"), _T("Error!"), MB_OK | MB_ICONERROR);
        }
    }
    break;

Are there something like Anchors in pure win32 programming?


问:
How can I print the bits of a __m128i variable in C?
I don't have any idea how to print the bits of a __m128i variable in C
so feel free to tell me your ideas!

Thank you!

答:
It's really not much different than printing the bits of a 32-bit integer.  Stash the 128-bit vector to four 32-bit integers and then print the bits of each of them in order.</p>

```<code>void print_bits128(__m128i v) {
  int t[4];
  _mm_storeu_si128((__m128i*)t, v);
  for(int i=0; i<4; i++) {
    int num = t[i];
    for(int j=0; j<32; j++){
      printf("%u",num&0x80000000 ? 1 : 0);
      num <<= 1;
    }
  }
  puts("");
}
</code>```

Body:
It's really not much different than printing the bits of a 32-bit integer.  Stash the 128-bit vector to four 32-bit integers and then print the bits of each of them in order.

void print_bits128(__m128i v) {
  int t[4];
  _mm_storeu_si128((__m128i*)t, v);
  for(int i=0; i<4; i++) {
    int num = t[i];
    for(int j=0; j<32; j++){
      printf("%u",num&0x80000000 ? 1 : 0);
      num <<= 1;
    }
  }
  puts("");
}


问:
No implementation for play.api.db.slick.DatabaseConfigProvider was bound
I can't get slick to work with play 2.5.x

I get the following runtime error:

```<code>ProvisionException: Unable to provision, see the following errors:

1) No implementation for play.api.db.slick.DatabaseConfigProvider was bound.
  while locating play.api.db.slick.DatabaseConfigProvider
</code>```

My DAO looks like:

```<code>@Singleton
class UserDAO @Inject() (protected val dbConfigProvider: DatabaseConfigProvider)
extends HasDatabaseConfigProvider[JdbcProfile] {
    import driver.api._

...

}
</code>```

And I just inject it in my controller like:

```<code>@Singleton
class UserController @Inject() (ws: WSClient, cache: CacheApi, userDAO: UserDAO) extends Controller {
...
}
</code>```

build.sbt

```<code>scalaVersion := "2.11.7"

libraryDependencies ++= Seq(
  cache,
  ws,
  "org.scalatestplus.play" %% "scalatestplus-play" % "1.5.1" % Test,
  // database
  jdbc,
  "org.postgresql"     %  "postgresql" % "9.3-1102-jdbc41",
  "com.typesafe.play" %% "play-slick" % "2.0.0"
)
</code>```

My application.conf has:

```<code>play.db {
  # The combination of these two settings results in "db.default" as the
  # default JDBC pool:
  #config = "db"
  #default = "default"

  # Play uses HikariCP as the default connection pool.  You can override
  # settings by changing the prototype:
  prototype {
    # Sets a fixed JDBC connection pool size of 50
    #hikaricp.minimumIdle = 50
    #hikaricp.maximumPoolSize = 50
  }
}

## JDBC Datasource
db {
  default.driver = org.postgresql.Driver
  default.url = "jdbc:postgresql://localhost/testdb_development"
  default.username = "blankman"
  #default.password = ""
}
</code>```

If I change my database name I get a connection error, so the pool is picking up my config settings correctly.

答:
I solve this problem with this config in application.conf

```<code>slick.dbs.default.profile="slick.jdbc.PostgresProfile$"
slick.dbs.default.driver="slick.driver.PostgresDriver$"
slick.dbs.default.db.url="jdbc:postgresql://127.0.0.1:5432/[db_name]"
slick.dbs.default.db.user=[name_db]
slick.dbs.default.db.password=[pw_bd]
</code>```

Please note to change database name to something else other than default. Only change db_name.

Body:
I can't get slick to work with play 2.5.x

I get the following runtime error:

ProvisionException: Unable to provision, see the following errors:

1) No implementation for play.api.db.slick.DatabaseConfigProvider was bound.
  while locating play.api.db.slick.DatabaseConfigProvider

My DAO looks like:

@Singleton
class UserDAO @Inject() (protected val dbConfigProvider: DatabaseConfigProvider)
extends HasDatabaseConfigProvider[JdbcProfile] {
    import driver.api._

...

}

And I just inject it in my controller like:

@Singleton
class UserController @Inject() (ws: WSClient, cache: CacheApi, userDAO: UserDAO) extends Controller {
...
}

build.sbt

scalaVersion := "2.11.7"

libraryDependencies ++= Seq(
  cache,
  ws,
  "org.scalatestplus.play" %% "scalatestplus-play" % "1.5.1" % Test,
  // database
  jdbc,
  "org.postgresql"     %  "postgresql" % "9.3-1102-jdbc41",
  "com.typesafe.play" %% "play-slick" % "2.0.0"
)

My application.conf has:

play.db {
  # The combination of these two settings results in "db.default" as the
  # default JDBC pool:
  #config = "db"
  #default = "default"

  # Play uses HikariCP as the default connection pool.  You can override
  # settings by changing the prototype:
  prototype {
    # Sets a fixed JDBC connection pool size of 50
    #hikaricp.minimumIdle = 50
    #hikaricp.maximumPoolSize = 50
  }
}

## JDBC Datasource
db {
  default.driver = org.postgresql.Driver
  default.url = "jdbc:postgresql://localhost/testdb_development"
  default.username = "blankman"
  #default.password = ""
}

If I change my database name I get a connection error, so the pool is picking up my config settings correctly.

Body:
I solve this problem with this config in application.conf

slick.dbs.default.profile="slick.jdbc.PostgresProfile$"
slick.dbs.default.driver="slick.driver.PostgresDriver$"
slick.dbs.default.db.url="jdbc:postgresql://127.0.0.1:5432/[db_name]"
slick.dbs.default.db.user=[name_db]
slick.dbs.default.db.password=[pw_bd]

Please note to change database name to something else other than default. Only change db_name.

ContentLicense: CC BY-SA 4.0


问:
limit imput length to max 10 chars
I try to limit a form of input to 10 chars

var max_chars = 10;

$('input#ctl00$bc$custom_element_44').keydown( function(e){
    if ($(this).val().length >= max_chars) {
        $(this).val($(this).val().substr(0, max_chars));
    }
});

$('input#ctl00$bc$custom_element_44').keyup( function(e){
    if ($(this).val().length >= max_chars) {
        $(this).val($(this).val().substr(0, max_chars));
    }
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>
<input name="ctl00$bc$custom_element_44" type="text" id="ctl00_bc_custom_element_44"></code>```

But it does not seem to work, advice is sought;)

Regards Pete

答:
Use below code

 var max_chars = 10;

    $('#ctl00_bc_custom_element_44').keydown(function(e) {
      if ($(this).val().length >= max_chars) {

        $(this).val($(this).val().substr(0, max_chars));
      }
    });
    $('#ctl00_bc_custom_element_44').keyup(function(e) {

      if ($(this).val().length >= max_chars) {

        $(this).val($(this).val().substr(0, max_chars));
      }
    });

or use max length with input tag

Title: limit imput length to max 10 chars

Body:
I try to limit a form of input to 10 chars

var max_chars = 10;

$('input#ctl00$bc$custom_element_44').keydown( function(e){
    if ($(this).val().length >= max_chars) {
        $(this).val($(this).val().substr(0, max_chars));
    }
});

$('input#ctl00$bc$custom_element_44').keyup( function(e){
    if ($(this).val().length >= max_chars) {
        $(this).val($(this).val().substr(0, max_chars));
    }
});

<input name="ctl00$bc$custom_element_44" type="text" id="ctl00_bc_custom_element_44">

But it does not seem to work, advice is sought;)

Regards Pete


问:
Array in structure
I'm new to C. Below are codes written in C. </p>

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

typedef struct {
    char name[256];
    int age;
    int sex;
} People;

void InputPeople(People *data);
void ShowPeople(People data);

int main(void)
{
    int i,count,datasize;
    People *data;

    datasize = 10;
    data = (People*)malloc(sizeof(People) * datasize);

    count = 0;
    while (1) {
        InputPeople(&data[count]);
        if (data[count].age == -1) break;
        count++;

        if (count >= datasize) {
            datasize += 10;
            data = (People*)realloc(data,sizeof(People) * datasize);
        }
    }

    for (i = 0;i < count;i++) {
        ShowPeople(data[i]);
    }

    free(data);

    return 0;
}
</code>```

<p>I have no idea why it is possible to write like "data[count]". I've learned Structure and Array. I would appreciate if somebody could explain to me. </p>

答:
People is your struct.

You declare a People pointer, which then points to the memory that you dynamically allocated with malloc(). How big is that memory chunk you allocated? datasize * size of the struct, i.e. 10 structs, since datasize = 10.

That means that data now points to a 1D array, thus you can index it like data[0] to get the first element (struct). count is a counter, which can be 0 as well.

You can think it like you had done People data[10];, which statically declares an array of 10 structs People, although it's not the same, since in your code the memory is dynamically allocated.

BTW, Do I cast the result of malloc? No.

Also, I would suggest you to read a C book.

Title: Array in structure

Body:
I'm new to C. Below are codes written in C.

#include <stdio.h>
#include <string.h>
#include <stdlib.h>

typedef struct {
    char name[256];
    int age;
    int sex;
} People;

void InputPeople(People *data);
void ShowPeople(People data);

int main(void)
{
    int i,count,datasize;
    People *data;

    datasize = 10;
    data = (People*)malloc(sizeof(People) * datasize);

    count = 0;
    while (1) {
        InputPeople(&data[count]);
        if (data[count].age == -1) break;
        count++;

        if (count >= datasize) {
            datasize += 10;
            data = (People*)realloc(data,sizeof(People) * datasize);
        }
    }

    for (i = 0;i < count;i++) {
        ShowPeople(data[i]);
    }

    free(data);

    return 0;
}

I have no idea why it is possible to write like "data[count]". I've learned Structure and Array. I would appreciate if somebody could explain to me.


问:
SQL to merge rows in Oracle
I want to merge some rows.

First, my table and data exist as below

```<code>GRP     CRRO_NO  TYPE_CD  TYPE_ID
PERSON  1111     FATHER   Tom
PERSON  1111     MOTHER   Jennifer
PERSON  1111     JOB_     Teacher
PERSON  1111     FRIEND   Jimmy
PERSON  1111     FRIEND   Kim
PERSON  1111     FRIEND   Michael
</code>```

And I want to get the result like

```<code>GRP     CRRO_NO   FATHER    MOTHER     JOB_      FRIEND
PERSON  1111      Tom       Jennifer   Teacher   Jimmy
PERSON  1111      Tom       Jennifer   Teacher   Kim
PERSON  1111      Tom       Jennifer   Teacher   Michael
</code>```

With this situation, how to write SQL?

I've been trying like

```<code>SELECT  T1.GRP_CD GRP, T1.CRRO_NO CRRO
      , MAX(T1.MOTHER) MOTHER, MAX(T1.FATHER) FATHER, MAX(T1.JOB_) JOB, T1.FRIEND FRIEND
  FROM (
        SELECT  DISTINCT
                GRP_CD
               ,CRRO_NO
               ,CASE WHEN TYPE_CD  = 'FATHER'  THEN TYPE_ID   ELSE '' END FATHER
               ,CASE WHEN TYPE_CD  = 'MOTHER'  THEN TYPE_ID   ELSE '' END MOTHER
               ,CASE WHEN TYPE_CD  = 'JOB_'    THEN TYPE_ID    ELSE '' END JOB_
               ,CASE WHEN TYPE_CD  = 'FRIEND'  THEN TYPE_ID   ELSE '' END FRIEND
         FROM    TMP
        WHERE   1=1   AND     TRIM(CRRO_NO) = '1111'
       ) T1
  WHERE T1.CRRO_NO = '1111'
        GROUP BY T1.GRP_CD, T1.CRRO_NO, T1.FRIEND
;
</code>```

Then, the result of sql above is

```<code>GRP      CRRO_NO  MOTHER     FATHER    JOB       FRIEND
PERSON   1111     Jennifer   Tom       Teacher   (null)
PERSON   1111     (null)     (null)    (null)    Jimmy
PERSON   1111     (null)     (null)    (null)    Kim
PERSON   1111     (null)     (null)    (null)    Michael
</code>```

Now I know why the result of my query is wrong(not the one I want), but still I can't find the way.

Actually, there are strict rules to classify which one would be duplicated (Mother, Father, Job) and which would not (friend)

For some reasons, I can't modify the structure of my table.
(I've changed contents of this question from my business terms and simplified the situation to explain)

Please give any advice to try again

答:
Assuming that 'MOTHER', 'FATHER' and 'JOB_' are unique type_cd values, you could achieve your aims like so:

```<code>WITH sample_data AS (SELECT 'PERSON' grp, 1111 crro_no, 'FATHER' type_cd, 'Tom' type_id FROM dual UNION ALL
                     SELECT 'PERSON' grp, 1111 crro_no, 'MOTHER' type_cd, 'Jennifer' type_id FROM dual UNION ALL
                     SELECT 'PERSON' grp, 1111 crro_no, 'JOB_' type_cd, 'Teacher' type_id FROM dual UNION ALL
                     SELECT 'PERSON' grp, 1111 crro_no, 'FRIEND' type_cd, 'Jimmy' type_id FROM dual UNION ALL
                     SELECT 'PERSON' grp, 1111 crro_no, 'FRIEND' type_cd, 'Kim' type_id FROM dual UNION ALL
                     SELECT 'PERSON' grp, 1111 crro_no, 'FRIEND' type_cd, 'Michael' type_id FROM dual)
-- end of mimicking a table called "sample_data" with your data in it.
-- see the SQL below:
SELECT grp,
       crro_no,
       father,
       mother,
       job_,
       type_id friend
FROM   (SELECT grp,
               crro_no,
               type_cd,
               type_id,
               MAX(CASE WHEN type_cd = 'FATHER' THEN type_id END) OVER (PARTITION BY grp, crro_no) father,
               MAX(CASE WHEN type_cd = 'MOTHER' THEN type_id END) OVER (PARTITION BY grp, crro_no) mother,
               MAX(CASE WHEN type_cd = 'JOB_' THEN type_id END) OVER (PARTITION BY grp, crro_no) job_
        FROM   sample_data)
WHERE  type_cd = 'FRIEND';

GRP       CRRO_NO FATHER   MOTHER   JOB_     FRIEND
------ ---------- -------- -------- -------- --------
PERSON       1111 Tom      Jennifer Teacher  Michael
PERSON       1111 Tom      Jennifer Teacher  Jimmy
PERSON       1111 Tom      Jennifer Teacher  Kim
</code>```

This works by using the MAX() analytic function to output the type_id for the father, mother and job type_cd's in separate columns across all rows.

Then it's simply a matter of filtering the rows to show just the type_cd = 'FRIEND' rows.

Title: SQL to merge rows in Oracle

Body:
I want to merge some rows.

First, my table and data exist as below

GRP     CRRO_NO  TYPE_CD  TYPE_ID
PERSON  1111     FATHER   Tom
PERSON  1111     MOTHER   Jennifer
PERSON  1111     JOB_     Teacher
PERSON  1111     FRIEND   Jimmy
PERSON  1111     FRIEND   Kim
PERSON  1111     FRIEND   Michael

And I want to get the result like

GRP     CRRO_NO   FATHER    MOTHER     JOB_      FRIEND
PERSON  1111      Tom       Jennifer   Teacher   Jimmy
PERSON  1111      Tom       Jennifer   Teacher   Kim
PERSON  1111      Tom       Jennifer   Teacher   Michael

With this situation, how to write SQL?

I've been trying like

SELECT  T1.GRP_CD GRP, T1.CRRO_NO CRRO
      , MAX(T1.MOTHER) MOTHER, MAX(T1.FATHER) FATHER, MAX(T1.JOB_) JOB, T1.FRIEND FRIEND
  FROM (
        SELECT  DISTINCT
                GRP_CD
               ,CRRO_NO
               ,CASE WHEN TYPE_CD  = 'FATHER'  THEN TYPE_ID   ELSE '' END FATHER
               ,CASE WHEN TYPE_CD  = 'MOTHER'  THEN TYPE_ID   ELSE '' END MOTHER
               ,CASE WHEN TYPE_CD  = 'JOB_'    THEN TYPE_ID    ELSE '' END JOB_
               ,CASE WHEN TYPE_CD  = 'FRIEND'  THEN TYPE_ID   ELSE '' END FRIEND
         FROM    TMP
        WHERE   1=1   AND     TRIM(CRRO_NO) = '1111'
       ) T1
  WHERE T1.CRRO_NO = '1111'
        GROUP BY T1.GRP_CD, T1.CRRO_NO, T1.FRIEND
;

Then, the result of sql above is

GRP      CRRO_NO  MOTHER     FATHER    JOB       FRIEND
PERSON   1111     Jennifer   Tom       Teacher   (null)
PERSON   1111     (null)     (null)    (null)    Jimmy
PERSON   1111     (null)     (null)    (null)    Kim
PERSON   1111     (null)     (null)    (null)    Michael

Now I know why the result of my query is wrong(not the one I want), but still I can't find the way.

Actually, there are strict rules to classify which one would be duplicated (Mother, Father, Job) and which would not (friend)

For some reasons, I can't modify the structure of my table.
(I've changed contents of this question from my business terms and simplified the situation to explain)

Please give any advice to try again

Body:
Assuming that 'MOTHER', 'FATHER' and 'JOB_' are unique type_cd values, you could achieve your aims like so:

WITH sample_data AS (SELECT 'PERSON' grp, 1111 crro_no, 'FATHER' type_cd, 'Tom' type_id FROM dual UNION ALL
                     SELECT 'PERSON' grp, 1111 crro_no, 'MOTHER' type_cd, 'Jennifer' type_id FROM dual UNION ALL
                     SELECT 'PERSON' grp, 1111 crro_no, 'JOB_' type_cd, 'Teacher' type_id FROM dual UNION ALL
                     SELECT 'PERSON' grp, 1111 crro_no, 'FRIEND' type_cd, 'Jimmy' type_id FROM dual UNION ALL
                     SELECT 'PERSON' grp, 1111 crro_no, 'FRIEND' type_cd, 'Kim' type_id FROM dual UNION ALL
                     SELECT 'PERSON' grp, 1111 crro_no, 'FRIEND' type_cd, 'Michael' type_id FROM dual)
-- end of mimicking a table called "sample_data" with your data in it.
-- see the SQL below:
SELECT grp,
       crro_no,
       father,
       mother,
       job_,
       type_id friend
FROM   (SELECT grp,
               crro_no,
               type_cd,
               type_id,
               MAX(CASE WHEN type_cd = 'FATHER' THEN type_id END) OVER (PARTITION BY grp, crro_no) father,
               MAX(CASE WHEN type_cd = 'MOTHER' THEN type_id END) OVER (PARTITION BY grp, crro_no) mother,
               MAX(CASE WHEN type_cd = 'JOB_' THEN type_id END) OVER (PARTITION BY grp, crro_no) job_
        FROM   sample_data)
WHERE  type_cd = 'FRIEND';

GRP       CRRO_NO FATHER   MOTHER   JOB_     FRIEND
------ ---------- -------- -------- -------- --------
PERSON       1111 Tom      Jennifer Teacher  Michael
PERSON       1111 Tom      Jennifer Teacher  Jimmy
PERSON       1111 Tom      Jennifer Teacher  Kim

This works by using the MAX() analytic function to output the type_id for the father, mother and job type_cd's in separate columns across all rows.

Then it's simply a matter of filtering the rows to show just the type_cd = 'FRIEND' rows.


问:
Searching Solr index for concatenated words
I'm struggling with two similar use cases.

Here's an example document from my index:

```<code>{
        "id":"E850AC8D844010AFA76203B390DD3135",
        "brand_txt_en":"Tom Ford",
        "catch_all":["Tom Ford",
          "FT 5163",
          "Tom Ford",
          "FT 5163",
          "DARK HAVANA"],
        "model_txt_en":"FT 5163",
        "brand_txt_en_split":"Tom Ford",
        "model_txt_en_split":"FT 5163",
        "color_txt_en":"DARK HAVANA",
        "material_s":"acetato",
        "gender_s":"uomo",
        "shape_s":"Wayfarer",
        "lens_s":"cerchiata",
        "modelkey_s":"86_1_FT 5163",
        "sales_i":0,
        "brand_s":"Tom Ford",
        "model_s":"FT 5163",
        "color_s":"DARK HAVANA",
        "_version_":1569456572504997895
}
</code>```

Query: brand_txt_en_split:tomford

No results!

Field type is Solr's default one:

```<code><fieldType name="text_en_splitting" class="solr.TextField" autoGeneratePhraseQueries="true" positionIncrementGap="100">
    <analyzer type="index">
      <tokenizer class="solr.WhitespaceTokenizerFactory"/>
      <filter class="solr.StopFilterFactory" words="lang/stopwords_en.txt" ignoreCase="true"/>
      <filter class="solr.WordDelimiterFilterFactory" catenateNumbers="1" generateNumberParts="1" splitOnCaseChange="1" generateWordParts="1" catenateAll="0" catenateWords="1"/>
      <filter class="solr.LowerCaseFilterFactory"/>
      <filter class="solr.KeywordMarkerFilterFactory" protected="protwords.txt"/>
      <filter class="solr.PorterStemFilterFactory"/>
    </analyzer>
    <analyzer type="query">
      <tokenizer class="solr.WhitespaceTokenizerFactory"/>
      <filter class="solr.SynonymFilterFactory" expand="true" ignoreCase="true" synonyms="synonyms.txt"/>
      <filter class="solr.StopFilterFactory" words="lang/stopwords_en.txt" ignoreCase="true"/>
      <filter class="solr.WordDelimiterFilterFactory" catenateNumbers="0" generateNumberParts="1" splitOnCaseChange="1" generateWordParts="1" catenateAll="0" catenateWords="0"/>
      <filter class="solr.LowerCaseFilterFactory"/>
      <filter class="solr.KeywordMarkerFilterFactory" protected="protwords.txt"/>
      <filter class="solr.PorterStemFilterFactory"/>
    </analyzer>
  </fieldType>
</code>```

I expect WordDelimiterFilterFactory to generate "tomford" token by concatenating words but it looks like that's not working as expected.

The 'inverse' use case is:

```<code>{
   ...  "model_txt_en_split": "The Clubmaster", ...
}
</code>```

I want that document to be found after this query:
club master

I guess I should use EdgeNGram filter for the latter case, but really can't get how to do that.

Thanks for your help

答:
The WordDelimiterFilterFactory has the catenateWords and catenateAll. It works where you have :

```<code>catenateWords: (integer, default 0) If non-zero, maximal runs of word parts will be joined: "hot-spot-sensor's" -> "hotspotsensor"

catenateAll: (0/1, default 0) If non-zero, runs of word and number parts will be joined: "Zap-Master-9000" -> "ZapMaster9000"`
</code>```

To remove the space between the words please try the below filter.

```<code><filter class="solr.PatternReplaceFilterFactory" pattern="(\s+)" replacement="" replace="all" />
</code>```

Once you add/update the schema.xml. Restart the server and re-index the data.

You can try the below fieldType for you field name.

```<code><analyzer>
  <tokenizer class="solr.KeywordTokenizerFactory"/>
  <filter class="solr.EdgeNGramFilterFactory" minGramSize="4" maxGramSize="25"/>
</analyzer>
</code>```

Input String: "John Oliver W Clane"

Tokenizer to Filter: "John Oliver W Clane"

Output Tokens :

```<code>"John", "John ", "John O", "John Ol", "John Oli", "John Oli", "John Oliv", "John Olive", "John Oliver", "John Oliver ", "John Oliver W", "John Oliver W "
, "John Oliver W C", "John Oliver W Cl", "John Oliver W Cla", "John Oliver W Clan", "John Oliver W Clane".
</code>```

There is another filter you can try the same .

```<code><filter class="solr.NGramFilterFactory" minGramSize="4" maxGramSize="25"/>
</code>```

You can read more about the analyzers and filters Solr Analyzers and Filters

Body:
I'm struggling with two similar use cases.

Here's an example document from my index:

{
        "id":"E850AC8D844010AFA76203B390DD3135",
        "brand_txt_en":"Tom Ford",
        "catch_all":["Tom Ford",
          "FT 5163",
          "Tom Ford",
          "FT 5163",
          "DARK HAVANA"],
        "model_txt_en":"FT 5163",
        "brand_txt_en_split":"Tom Ford",
        "model_txt_en_split":"FT 5163",
        "color_txt_en":"DARK HAVANA",
        "material_s":"acetato",
        "gender_s":"uomo",
        "shape_s":"Wayfarer",
        "lens_s":"cerchiata",
        "modelkey_s":"86_1_FT 5163",
        "sales_i":0,
        "brand_s":"Tom Ford",
        "model_s":"FT 5163",
        "color_s":"DARK HAVANA",
        "_version_":1569456572504997895
}

Query: brand_txt_en_split:tomford

No results!

Field type is Solr's default one:

<fieldType name="text_en_splitting" class="solr.TextField" autoGeneratePhraseQueries="true" positionIncrementGap="100">
    <analyzer type="index">
      <tokenizer class="solr.WhitespaceTokenizerFactory"/>
      <filter class="solr.StopFilterFactory" words="lang/stopwords_en.txt" ignoreCase="true"/>
      <filter class="solr.WordDelimiterFilterFactory" catenateNumbers="1" generateNumberParts="1" splitOnCaseChange="1" generateWordParts="1" catenateAll="0" catenateWords="1"/>
      <filter class="solr.LowerCaseFilterFactory"/>
      <filter class="solr.KeywordMarkerFilterFactory" protected="protwords.txt"/>
      <filter class="solr.PorterStemFilterFactory"/>
    </analyzer>
    <analyzer type="query">
      <tokenizer class="solr.WhitespaceTokenizerFactory"/>
      <filter class="solr.SynonymFilterFactory" expand="true" ignoreCase="true" synonyms="synonyms.txt"/>
      <filter class="solr.StopFilterFactory" words="lang/stopwords_en.txt" ignoreCase="true"/>
      <filter class="solr.WordDelimiterFilterFactory" catenateNumbers="0" generateNumberParts="1" splitOnCaseChange="1" generateWordParts="1" catenateAll="0" catenateWords="0"/>
      <filter class="solr.LowerCaseFilterFactory"/>
      <filter class="solr.KeywordMarkerFilterFactory" protected="protwords.txt"/>
      <filter class="solr.PorterStemFilterFactory"/>
    </analyzer>
  </fieldType>

I expect WordDelimiterFilterFactory to generate "tomford" token by concatenating words but it looks like that's not working as expected.

The 'inverse' use case is:

{
   ...  "model_txt_en_split": "The Clubmaster", ...
}

I want that document to be found after this query:
club master

I guess I should use EdgeNGram filter for the latter case, but really can't get how to do that.

Thanks for your help

Body:
The WordDelimiterFilterFactory has the catenateWords and catenateAll. It works where you have :

catenateWords: (integer, default 0) If non-zero, maximal runs of word parts will be joined: "hot-spot-sensor's" -> "hotspotsensor"

catenateAll: (0/1, default 0) If non-zero, runs of word and number parts will be joined: "Zap-Master-9000" -> "ZapMaster9000"`

To remove the space between the words please try the below filter.

<filter class="solr.PatternReplaceFilterFactory" pattern="(\s+)" replacement="" replace="all" />

Once you add/update the schema.xml. Restart the server and re-index the data.

You can try the below fieldType for you field name.

<analyzer>
  <tokenizer class="solr.KeywordTokenizerFactory"/>
  <filter class="solr.EdgeNGramFilterFactory" minGramSize="4" maxGramSize="25"/>
</analyzer>

Input String: "John Oliver W Clane"

Tokenizer to Filter: "John Oliver W Clane"

Output Tokens :

"John", "John ", "John O", "John Ol", "John Oli", "John Oli", "John Oliv", "John Olive", "John Oliver", "John Oliver ", "John Oliver W", "John Oliver W "
, "John Oliver W C", "John Oliver W Cl", "John Oliver W Cla", "John Oliver W Clan", "John Oliver W Clane".

There is another filter you can try the same .

<filter class="solr.NGramFilterFactory" minGramSize="4" maxGramSize="25"/>

You can read more about the analyzers and filters Solr Analyzers and Filters


问:
Android Instant App
I got this error in "Declare Website Association" of "App link Assistant". Does anyone know how to solve that problem. I am very new to Android Instant App.

答:
1) Click on save file.

2) Create .well-known folder and save it there

3) Now upload your .well-known folder to your website. Done.

Title: Android Instant App


问:
Monitor Refresh Token for web push FCM and replace that with the old one in DB
Currently I am trying to do a web push ( Push notifications ) NOT APP only though browser

I have generated the Application Token
Token generated

Then saving that token to db. Now, issues is when I clear my cache the token changes. How can I monitor thus replacing the new token with old one(replace only that particular token)?

Here is current code app.js

```<code>var config = {
    apiKey: "xxxxxxxx",
    authDomain: "*********",
    databaseURL: "*********",
    projectId: "t********",
    storageBucket: "******",
    messagingSenderId: "******"
  };
  firebase.initializeApp(config);

  const messaging = firebase.messaging();

  messaging.requestPermission()
  .then(function(){

    console.log("have permission");
    alert("have permission");

    return messaging.getToken();
  })
  .then(function(token){
    console.log(token);
    var newToken = token;
   alert("newToken");
  })
  .catch(function(err){

console.log("error Occurred");
alert("error occurred");

  })

  messaging.onMessage(function(payload){
console.log("onMessage",payload);
  });
</code>```

答:
As stated in the documentation on monitoring token refresh:

The onTokenRefresh callback fires whenever a new token is generated, so calling getToken in its context ensures that you are accessing a current, available registration token.

```<code>// Callback fired if Instance ID token is updated.
messaging.onTokenRefresh(function() {
  messaging.getToken()
  .then(function(refreshedToken) {
    console.log('Token refreshed.');
    // Indicate that the new Instance ID token has not yet been sent to the
    // app server.
    setTokenSentToServer(false);
    // Send Instance ID token to app server.
    sendTokenToServer(refreshedToken);
    // ...
  })
  .catch(function(err) {
    console.log('Unable to retrieve refreshed token ', err);
    showToken('Unable to retrieve refreshed token ', err);
  });
});
</code>```

Body:
Currently I am trying to do a web push ( Push notifications ) NOT APP only though browser

I have generated the Application Token
Token generated

Then saving that token to db. Now, issues is when I clear my cache the token changes. How can I monitor thus replacing the new token with old one(replace only that particular token)?

Here is current code app.js

var config = {
    apiKey: "xxxxxxxx",
    authDomain: "*********",
    databaseURL: "*********",
    projectId: "t********",
    storageBucket: "******",
    messagingSenderId: "******"
  };
  firebase.initializeApp(config);

  const messaging = firebase.messaging();

  messaging.requestPermission()
  .then(function(){

    console.log("have permission");
    alert("have permission");

    return messaging.getToken();
  })
  .then(function(token){
    console.log(token);
    var newToken = token;
   alert("newToken");
  })
  .catch(function(err){

console.log("error Occurred");
alert("error occurred");

  })

  messaging.onMessage(function(payload){
console.log("onMessage",payload);
  });

Body:
As stated in the documentation on monitoring token refresh:

The onTokenRefresh callback fires whenever a new token is generated, so calling getToken in its context ensures that you are accessing a current, available registration token.

// Callback fired if Instance ID token is updated.
messaging.onTokenRefresh(function() {
  messaging.getToken()
  .then(function(refreshedToken) {
    console.log('Token refreshed.');
    // Indicate that the new Instance ID token has not yet been sent to the
    // app server.
    setTokenSentToServer(false);
    // Send Instance ID token to app server.
    sendTokenToServer(refreshedToken);
    // ...
  })
  .catch(function(err) {
    console.log('Unable to retrieve refreshed token ', err);
    showToken('Unable to retrieve refreshed token ', err);
  });
});


问:
Caffe deploy.prototxt with multiple inputs of different dimensions
I have a network in Caffe that accepts multiple image inputs (possibly of different dimensions) and uses them as separate blobs for the initial part of the network.

For the training phase, I implemented this by creating a HDF5 database as suggested in the documentation.

However, for the deploy phase, I need to replace the data layer from the training phase with an input layer, and specify the dimensions of the input blob.

For a single blob, this is done with the shape property of input_param. How can I do it in this case, where I have multiple blobs, possibly of different dimensions?

Thank you.

答:
If you look closely at caffe.proto you'll see that input and input_shape has the property of repeated:

```<code>// DEPRECATED. See InputParameter. The input blobs to the network.
repeated string input = 3;
// DEPRECATED. See InputParameter. The shape of the input blobs.
repeated BlobShape input_shape = 8;
</code>```

Which means you can have several such entries:

```<code>name: "AnAmazingNetWithMultipleInputs_ThankYouShai_IwillForeverBeInYourDebt"
input: "first_input_1x3x127x127"
input_shape { dim: 1 dim: 3 dim: 127 dim: 127 }
input: "second_input_2x4x224x224"
input_shape { dim: 2 dim: 4 dim: 224 dim: 224 }
# I hope you can take it from here ;)
</code>```

If you look even closer at the relevant section of caffe.proto, you'll notice that this form of "input shape declaration" is DEPRECATED.

A better way is to use "Input" layer:

```<code>layer {
  type: "Input"
  name: "one_input_layer"
  top: "first_input_1x3x127x127"
  shape { dim: 1 dim: 3 dim: 127 dim: 127 }
  top: "second_input_2x4x224x224"
  shape { dim: 2 dim: 4 dim: 224 dim: 224 }
}
</code>```

You can also have a different "Input" layer for each input, if you find it easier to understand/read.

Body:
If you look closely at caffe.proto you'll see that input and input_shape has the property of repeated:

// DEPRECATED. See InputParameter. The input blobs to the network.
repeated string input = 3;
// DEPRECATED. See InputParameter. The shape of the input blobs.
repeated BlobShape input_shape = 8;

Which means you can have several such entries:

name: "AnAmazingNetWithMultipleInputs_ThankYouShai_IwillForeverBeInYourDebt"
input: "first_input_1x3x127x127"
input_shape { dim: 1 dim: 3 dim: 127 dim: 127 }
input: "second_input_2x4x224x224"
input_shape { dim: 2 dim: 4 dim: 224 dim: 224 }
# I hope you can take it from here ;)

If you look even closer at the relevant section of caffe.proto, you'll notice that this form of "input shape declaration" is DEPRECATED.

A better way is to use "Input" layer:

layer {
  type: "Input"
  name: "one_input_layer"
  top: "first_input_1x3x127x127"
  shape { dim: 1 dim: 3 dim: 127 dim: 127 }
  top: "second_input_2x4x224x224"
  shape { dim: 2 dim: 4 dim: 224 dim: 224 }
}

You can also have a different "Input" layer for each input, if you find it easier to understand/read.


问:
PHP MVC Globals Variables
I have a little doubt, I understand that using global variables is a bad practice.

I have a small MVC application with php, in which I would like to create a file .. called config.php and inside it, save the global variables that I will use in my classes, example ...

```<code>$config = array ();
$config ['db_host'] = 'localhost';
</code>```

Now, I would like to know what would be the recommended way to include this file in my application .. I have implemented a autoloader, I could include it in this ...

```<code>Class Autoload
{
    public function __construct () {
        global $ config;
        require_once 'config.php';
    }
}
</code>```

But I really do not know if this is a good practice ...

Thank you very much in advance..

答:
Generally speaking it's not a good practice to use globals or singletons.  What you want instead is called "dependency injection."  This pattern enables you to use mock objects for testing.  Some of the philosophy and practice of dependency injection is available in this article.
https://iconoun.com/blog/2017/05/05/php-globals-vs-dependencies/</p>

Title: PHP MVC Globals Variables

Body:
I have a little doubt, I understand that using global variables is a bad practice.

I have a small MVC application with php, in which I would like to create a file .. called config.php and inside it, save the global variables that I will use in my classes, example ...

$config = array ();
$config ['db_host'] = 'localhost';

Now, I would like to know what would be the recommended way to include this file in my application .. I have implemented a autoloader, I could include it in this ...

Class Autoload
{
    public function __construct () {
        global $ config;
        require_once 'config.php';
    }
}

But I really do not know if this is a good practice ...

Thank you very much in advance..


问:
How to fetch data in to custom wordpress table using wp_list_table
<img src="https://i.stack.imgur.com/cAhni.png" alt="enter image description here">I am trying to create a custom table in wordpress using wp_list_table. I am trying to display the id , username and user mail. i have created the custom table as a plugin. My issue is the table have been created but am unable to fetch the data. Here is my code . and why is there 2 tables displaying. Please Help me </p>

```<code><?php
/*
Plugin Name: Custom Tables

*/
?>

<?php
if( ! class_exists( 'WP_List_Table' ) ) {
    require_once( ABSPATH . 'wp-admin/includes/class-wp-list-table.php' );

class My_List_Table extends WP_List_Table {

function getdata($user_id){

         $args= array(

            'user_id'   =>'ID',
            'role'      =>'',
            'orderby'   =>'login',
            'fields'    => 'ID','user_login','user_email');

         $data = get_users($args);

}

function get_columns(){
  $columns = array(
    'ID' => 'Case ID',
    'user_login'    => 'Patient Name',
    'user_email'      => 'Patient Email'
  );
  return $columns;
}

function prepare_items() {
  $columns = $this->get_columns();
  $hidden = array();
  $sortable = array();
  $this->_column_headers = array($columns, $hidden, $sortable);
  $this->items = $this->example_data;;
}

function column_default( $item, $column_name ) {
  switch( $column_name ) {
    case 'ID':
    case 'user_login':
    case 'user_email':
      return $item[ $column_name ];
    default:
      return print_r( $item, true ) ; //Show the whole array for troubleshooting purposes
  }
}
}

// $myListTable = new My__List_Table();

function my_render_list_page(){
  $myListTable = new My_List_Table();
  echo '<div class="wrap"><h2>My List Table Test</h2>';
  $myListTable->prepare_items();
  $myListTable->display();
  echo '</div>';
}

function my_add_menu_items(){
    add_menu_page( 'My Plugin List Table', 'My List Table Example', 'activate_plugins', 'my_list_test', 'my_render_list_page' );
}
add_action( 'admin_menu', 'my_add_menu_items' );

}
?>
</code>```

答:
Here is an example you may like to follow. and also a plugin . Look into this line it will give you a better idea, function table_data() prepares your data.

May be you would like to use it and modify . I have used it many times in my plugins. List Table Example

Body:
I am trying to create a custom table in wordpress using wp_list_table. I am trying to display the id , username and user mail. i have created the custom table as a plugin. My issue is the table have been created but am unable to fetch the data. Here is my code . and why is there 2 tables displaying. Please Help me

<?php
/*
Plugin Name: Custom Tables

*/
?>

<?php
if( ! class_exists( 'WP_List_Table' ) ) {
    require_once( ABSPATH . 'wp-admin/includes/class-wp-list-table.php' );

class My_List_Table extends WP_List_Table {

function getdata($user_id){

         $args= array(

            'user_id'   =>'ID',
            'role'      =>'',
            'orderby'   =>'login',
            'fields'    => 'ID','user_login','user_email');

         $data = get_users($args);

}

function get_columns(){
  $columns = array(
    'ID' => 'Case ID',
    'user_login'    => 'Patient Name',
    'user_email'      => 'Patient Email'
  );
  return $columns;
}

function prepare_items() {
  $columns = $this->get_columns();
  $hidden = array();
  $sortable = array();
  $this->_column_headers = array($columns, $hidden, $sortable);
  $this->items = $this->example_data;;
}

function column_default( $item, $column_name ) {
  switch( $column_name ) {
    case 'ID':
    case 'user_login':
    case 'user_email':
      return $item[ $column_name ];
    default:
      return print_r( $item, true ) ; //Show the whole array for troubleshooting purposes
  }
}
}

// $myListTable = new My__List_Table();

function my_render_list_page(){
  $myListTable = new My_List_Table();
  echo '

My List Table Test
';
  $myListTable->prepare_items();
  $myListTable->display();
  echo '
';
}

function my_add_menu_items(){
    add_menu_page( 'My Plugin List Table', 'My List Table Example', 'activate_plugins', 'my_list_test', 'my_render_list_page' );
}
add_action( 'admin_menu', 'my_add_menu_items' );

}
?>


问:
Using LPtoDP API problem (GDI API)

I am hooking the ExtTextOut GDI API.
There I want to retrieve the exact location of the output String.

```<code>BOOL ExtTextOut(
  __in  HDC hdc,
  __in  int X,
  __in  int Y,
  __in  UINT fuOptions,
  __in  const RECT *lprc,
  __in  LPCTSTR lpString,
  __in  UINT cbCount,
  __in  const INT *lpDx
);
</code>```

In a specific case I am getting ETO_CLIPPED for the fuOptions param which mean I can get the location of the string from the RECT param or from the X,Y params.

However when I use the LPtoDP API for translating the location (RECT or X,Y) I get wrong location (before translating I get negative values).

I guess it has a wrong offset, however when I check the followings I see no indicaton for that:

Map Mode is MM_TEXT (default)

  GetWindowOrgEx is 0,0

  GetViewportOrgEx is 0,0

  GetWindowExtEx is 1,1

  GetViewportExtEx is 1,1

Does anyone have any idea, any help will be appreciated.
Thanks.

答:
Apparently, specifying ETO_CLIPPED in the ExtTextOut fuOptions param
does not imply that the text will be output to that clip, meaning that it is not guaranteed that the device context is of type display device context, and the device context that is used can be a memory device context, as in my case,  and therefore do not contains the right coordinates.

msdn: ETO_CLIPPED The text will be clipped to the rectangle.

Title: Using LPtoDP API problem (GDI API)

Body:
I am hooking the ExtTextOut GDI API.
There I want to retrieve the exact location of the output String.

BOOL ExtTextOut(
  __in  HDC hdc,
  __in  int X,
  __in  int Y,
  __in  UINT fuOptions,
  __in  const RECT *lprc,
  __in  LPCTSTR lpString,
  __in  UINT cbCount,
  __in  const INT *lpDx
);

In a specific case I am getting ETO_CLIPPED for the fuOptions param which mean I can get the location of the string from the RECT param or from the X,Y params.

However when I use the LPtoDP API for translating the location (RECT or X,Y) I get wrong location (before translating I get negative values).

I guess it has a wrong offset, however when I check the followings I see no indicaton for that:

Map Mode is MM_TEXT (default)

  GetWindowOrgEx is 0,0

  GetViewportOrgEx is 0,0

  GetWindowExtEx is 1,1

  GetViewportExtEx is 1,1

Does anyone have any idea, any help will be appreciated.
Thanks.


问:
'mv' command throwing error but executing fine in docker
When I execute the following command (which moves all files with the .txt and .sbreaks extension to another folder):

```<code>sudo docker exec name mv xyz/data/outputs/*.{sbreaks,txt} <>/data/spare
</code>```

I get the following error:

```<code>mv: cannot stat ‘xyz/data/outputs/*.sbreaks’: No such file or directory
mv: cannot stat ‘xyz/data/outputs/*.txt’: No such file or directory
</code>```

But, when I go into docker via sudo docker exec -it name bash and execute the same command: mv xyz/data/outputs/*.{sbreaks,txt} xyz/data/spare, it executes fine.

What am I doing wrong here?

PS: Both local and the Docker container are ubuntu environments

答:
That is because the * is expanded by a shell program (i.e. bash). (Psst, this is typical interview question).

So pass your command to a shell and let it launch the mv for you:

```<code>sudo docker exec cypher bash -c 'mv xyz/data/outputs/*.{sbreaks,txt} .......'
</code>```

When you do docker exec some_program some_param, docker searches for some_program and executes it directly without doing anything extra, and just pass some_param as a parameter (a star in your case). mv expects real file names, and not *.

Body:
When I execute the following command (which moves all files with the .txt and .sbreaks extension to another folder):

sudo docker exec name mv xyz/data/outputs/*.{sbreaks,txt} <>/data/spare

I get the following error:

mv: cannot stat ‘xyz/data/outputs/*.sbreaks’: No such file or directory
mv: cannot stat ‘xyz/data/outputs/*.txt’: No such file or directory

But, when I go into docker via sudo docker exec -it name bash and execute the same command: mv xyz/data/outputs/*.{sbreaks,txt} xyz/data/spare, it executes fine.

What am I doing wrong here?

PS: Both local and the Docker container are ubuntu environments

Body:
That is because the * is expanded by a shell program (i.e. bash). (Psst, this is typical interview question).

So pass your command to a shell and let it launch the mv for you:

sudo docker exec cypher bash -c 'mv xyz/data/outputs/*.{sbreaks,txt} .......'

When you do docker exec some_program some_param, docker searches for some_program and executes it directly without doing anything extra, and just pass some_param as a parameter (a star in your case). mv expects real file names, and not *.


问:
Increasing Variables
So I am writing a program that will need to increase some variables by the amount that the user types. I thought a code like this would work:

```<code>var = 0
increase = input("Increase by: ")
var + increase
print(var)
</code>```

But it just says that var is 0. I even tried making the input type int, int(input(""))

Still didn't work. Why won't it increase the variable?

Keep in mind, I am using Python 2.7

EDIT It was solved! I just made it var += increase

答:
You need to understand the difference between a statement and an assignment.
You're making the statement var + increase, but its result is never used. You're basically asking the computer to evaluate it, but there is no side-effect (like printing it to the screen, sending it over the network or putting it somewhere in memory)

You can use the result of your statement in many ways, for example, you can print it directly:

```<code>print var + increase
</code>```

Or you can assign it to a variable

```<code>var = var + increase
</code>```

Even better, to a NEW variable:

```<code>result = var + increase
</code>```

Actually, in python, if you make just a statement, it is not entirely lost, it's kept in a magic variable called "ans" which is denoted by an underscore (_).

So you could do

```<code>var + increase
print(_)
</code>```

Title: Increasing Variables

Body:
So I am writing a program that will need to increase some variables by the amount that the user types. I thought a code like this would work:

var = 0
increase = input("Increase by: ")
var + increase
print(var)

But it just says that var is 0. I even tried making the input type int, int(input(""))

Still didn't work. Why won't it increase the variable?

Keep in mind, I am using Python 2.7

EDIT It was solved! I just made it var += increase

Body:
You need to understand the difference between a statement and an assignment.
You're making the statement var + increase, but its result is never used. You're basically asking the computer to evaluate it, but there is no side-effect (like printing it to the screen, sending it over the network or putting it somewhere in memory)

You can use the result of your statement in many ways, for example, you can print it directly:

print var + increase

Or you can assign it to a variable

var = var + increase

Even better, to a NEW variable:

result = var + increase

Actually, in python, if you make just a statement, it is not entirely lost, it's kept in a magic variable called "ans" which is denoted by an underscore (_).

So you could do

var + increase
print(_)


问:
react - redux - router setup issues
Can anyone help me figure out how to get this setup working.

```<code>import 'babel-polyfill';
    import React from 'react';
    import ReactDOM from "react-dom";
    import {Provider} from 'react-redux';
    import {createStore, applyMiddleware} from 'redux';
    import thunk from 'redux-thunk';
    import promise from 'redux-promise';
    import createLogger from 'redux-logger';
    import allReducers from './reducers';
    import App from './components/App';
    import createHistory from 'history/createBrowserHistory'
    import { Route } from 'react-router-dom'
    import { ConnectedRouter, routerMiddleware, push } from 'react-router-redux'

    const logger = createLogger();

    // Create a history of your choosing (we're using a browser history in this case)
    const history = createHistory()

    // Build the middleware for intercepting and dispatching navigation actions
    const middleware = routerMiddleware(history)

    // Add the reducer to your store on the `router` key
    // Also apply our middleware for navigating
    const store = createStore(
    allReducers,
    applyMiddleware(middleware, thunk, promise, logger)
    )

    ReactDOM.render(
        <Provider store={store}>
            <ConnectedRouter history={history}>
            <div>
                <Route exact path="/" component={App}/>
            </div>
            </ConnectedRouter>
        </Provider>,
        document.getElementById('root')
    );
</code>```

I seem to be getting an error called. Warning: React.createElement: type is invalid -- expected a string (for built-in components) or a class/function (for composite components) but got: undefined. You likely forgot to export your component from the file it's defined in.

答:
Make sure all your Components down the App hierarchy are properly exported as default export.

Also take a look at where do you take your react-router Components from. It's kind of common mistake to try to import Link component from react-router module, while it exists in react-router-dom module only.

Title: react - redux - router setup issues

Body:
Can anyone help me figure out how to get this setup working.

import 'babel-polyfill';
    import React from 'react';
    import ReactDOM from "react-dom";
    import {Provider} from 'react-redux';
    import {createStore, applyMiddleware} from 'redux';
    import thunk from 'redux-thunk';
    import promise from 'redux-promise';
    import createLogger from 'redux-logger';
    import allReducers from './reducers';
    import App from './components/App';
    import createHistory from 'history/createBrowserHistory'
    import { Route } from 'react-router-dom'
    import { ConnectedRouter, routerMiddleware, push } from 'react-router-redux'

    const logger = createLogger();

    // Create a history of your choosing (we're using a browser history in this case)
    const history = createHistory()

    // Build the middleware for intercepting and dispatching navigation actions
    const middleware = routerMiddleware(history)

    // Add the reducer to your store on the `router` key
    // Also apply our middleware for navigating
    const store = createStore(
    allReducers,
    applyMiddleware(middleware, thunk, promise, logger)
    )

    ReactDOM.render(
        <Provider store={store}>
            <ConnectedRouter history={history}>

                <Route exact path="/" component={App}/>

            </ConnectedRouter>
        </Provider>,
        document.getElementById('root')
    );

I seem to be getting an error called. Warning: React.createElement: type is invalid -- expected a string (for built-in components) or a class/function (for composite components) but got: undefined. You likely forgot to export your component from the file it's defined in.


问:
heap space issues in hadoop cluster while running map reducer program from command prompt
I'm running sample map reduce job which takes .csv file as input from hdfs and insert into hbase through java map program. I tried with below options to avoid java heap error.

```<code>configuration.set("mapreduce.map.java.opts", "-Xmx5g");
configuration.set("mapreduce.map.memory.mb", "-1");
</code>```

But I am getting Java Heap issue while running map reduce program.

2016-08-30 12:47:26,764 INFO [main] org.apache.hadoop.conf.Configuration.deprecation: mapred.skip.on is deprecated. Instead, use mapreduce.job.skiprecords
  2016-08-30 12:50:57,663 FATAL [main] org.apache.hadoop.mapred.YarnChild: Error running child : java.lang.OutOfMemoryError: Java heap space
      at com.google.protobuf.ByteString.copyFrom(ByteString.java:194)
      at com.google.protobuf.CodedInputStream.readBytes(CodedInputStream.java:324)
      at org.apache.hadoop.hbase.protobuf.generated.ClientProtos$MutationProto$ColumnValue$QualifierValue.(ClientProtos.java:9144)
      at org.apache.hadoop.hbase.protobuf.generated.ClientProtos$MutationProto$ColumnValue$QualifierValue.(ClientProtos.java:9089)
      at org.apache.hadoop.hbase.protobuf.generated.ClientProtos$MutationProto$ColumnValue$QualifierValue$1.parsePartialFrom(ClientProtos.java:9198)
      at org.apache.hadoop.hbase.protobuf.generated.ClientProtos$MutationProto$ColumnValue$QualifierValue$1.parsePartialFrom(ClientProtos.java:9193)

```<code>Driver program configuration as below :
Job job = new Job(configuration);
job.setJarByClass(HbaseTest.class);
job.setJobName("Data loading to HBase Table::"+TABLE_NAME);
job.setInputFormatClass(TextInputFormat.class);
job.setMapOutputKeyClass(ImmutableBytesWritable.class);
job.setMapperClass(HbaseTestMapper.class);
job.setNumReduceTasks(0);
FileInputFormat.addInputPaths(job, args[0]);
FileSystem.getLocal(getConf()).delete(new Path(outputPath), true);
FileOutputFormat.setOutputPath(job, new Path(outputPath));
job.setMapOutputValueClass(Put.class);
</code>```

I am using hadoop 2.x with three node cluster and each node has 32GB. My input file size is 831MB. Kindly help me what is the issue and how to resolve.

答:
You can increase the configuration like </p>

```<code>configuration.set("mapreduce.child.java.opts", "-Xmx6553m");
configuration.set("mapreduce.map.memory.mb", "8192");
</code>```

Body:
I'm running sample map reduce job which takes .csv file as input from hdfs and insert into hbase through java map program. I tried with below options to avoid java heap error.

configuration.set("mapreduce.map.java.opts", "-Xmx5g");
configuration.set("mapreduce.map.memory.mb", "-1");

But I am getting Java Heap issue while running map reduce program.

2016-08-30 12:47:26,764 INFO [main] org.apache.hadoop.conf.Configuration.deprecation: mapred.skip.on is deprecated. Instead, use mapreduce.job.skiprecords
  2016-08-30 12:50:57,663 FATAL [main] org.apache.hadoop.mapred.YarnChild: Error running child : java.lang.OutOfMemoryError: Java heap space
      at com.google.protobuf.ByteString.copyFrom(ByteString.java:194)
      at com.google.protobuf.CodedInputStream.readBytes(CodedInputStream.java:324)
      at org.apache.hadoop.hbase.protobuf.generated.ClientProtos$MutationProto$ColumnValue$QualifierValue.(ClientProtos.java:9144)
      at org.apache.hadoop.hbase.protobuf.generated.ClientProtos$MutationProto$ColumnValue$QualifierValue.(ClientProtos.java:9089)
      at org.apache.hadoop.hbase.protobuf.generated.ClientProtos$MutationProto$ColumnValue$QualifierValue$1.parsePartialFrom(ClientProtos.java:9198)
      at org.apache.hadoop.hbase.protobuf.generated.ClientProtos$MutationProto$ColumnValue$QualifierValue$1.parsePartialFrom(ClientProtos.java:9193)

Driver program configuration as below :
Job job = new Job(configuration);
job.setJarByClass(HbaseTest.class);
job.setJobName("Data loading to HBase Table::"+TABLE_NAME);
job.setInputFormatClass(TextInputFormat.class);
job.setMapOutputKeyClass(ImmutableBytesWritable.class);
job.setMapperClass(HbaseTestMapper.class);
job.setNumReduceTasks(0);
FileInputFormat.addInputPaths(job, args[0]);
FileSystem.getLocal(getConf()).delete(new Path(outputPath), true);
FileOutputFormat.setOutputPath(job, new Path(outputPath));
job.setMapOutputValueClass(Put.class);

I am using hadoop 2.x with three node cluster and each node has 32GB. My input file size is 831MB. Kindly help me what is the issue and how to resolve.

Body:
You can increase the configuration like

configuration.set("mapreduce.child.java.opts", "-Xmx6553m");
configuration.set("mapreduce.map.memory.mb", "8192");


问:
MySQL Syntax Error, Unrecognized keyword null
MySqli/phpmyadmin query not working - unrecognized keyword 'NULL'

I use

```<code>PHP - mysqli
MySQL + phpMyAdmin
</code>```

Sql :

```<code>update User set name = null;
</code>```

Error :

Unrecognized keyword null

thank for any help !

答:
try this:

```<code>UPDATE your_table
SET    your_column = NULL
WHERE  some_id = 1;
</code>```

or:

```<code>UPDATE your_table SET your_column = NULL;
</code>```

Body:
MySqli/phpmyadmin query not working - unrecognized keyword 'NULL'

I use

PHP - mysqli
MySQL + phpMyAdmin

Sql :

update User set name = null;

Error :

Unrecognized keyword null

thank for any help !

Body:
try this:

UPDATE your_table
SET    your_column = NULL
WHERE  some_id = 1;

or:

UPDATE your_table SET your_column = NULL;


问:
How to get the difference between 2 int arrays as a percentage
Mathematically we can solve it like Given Amount / Total Amount * 100 to get the percentage difference. But what I need is to compare 2 Integer Arrays (in C# Win App) and get the percentage of the difference.
Like :

```<code>1 -----> -2
2 ----->  3
3 ----->  7
4 ----->  456
5 ----->  13
</code>```

These two columns are 2 Integer Arrays and I should get the difference between them.

How can I get this? A mathematical answer or an algorithm, whatever can be used to solve the problem.

答:
How about using LINQ:

```<code>        Int32[] array1 = new Int32[] { 1, 2, 3, 4, 5, 6, 7, 8, 9 };
        Int32[] array2 = new Int32[] { 9, 8, 7, 6, 5, 4, 3, 2, 1 };

        Int32[] array3 = array1.Zip(array2, (a1, a2) => (a1 + a2) / 2).ToArray(); // Put whatever formula you want in there.
</code>```

EDIT: Daniel and CD are correct. Code has been corrected. Thanks guys.

Body:
Mathematically we can solve it like Given Amount / Total Amount * 100 to get the percentage difference. But what I need is to compare 2 Integer Arrays (in C# Win App) and get the percentage of the difference.
Like :

1 -----> -2
2 ----->  3
3 ----->  7
4 ----->  456
5 ----->  13

These two columns are 2 Integer Arrays and I should get the difference between them.

How can I get this? A mathematical answer or an algorithm, whatever can be used to solve the problem.

Body:
How about using LINQ:

        Int32[] array1 = new Int32[] { 1, 2, 3, 4, 5, 6, 7, 8, 9 };
        Int32[] array2 = new Int32[] { 9, 8, 7, 6, 5, 4, 3, 2, 1 };

        Int32[] array3 = array1.Zip(array2, (a1, a2) => (a1 + a2) / 2).ToArray(); // Put whatever formula you want in there.

EDIT: Daniel and CD are correct. Code has been corrected. Thanks guys.


问:
how to trigger Jenkins job from ant script running on same Jenkins server
I'm running an ant job that runs several thing on master node and need to trigger several jobs on slave servers based on the options i select from the main job parameters </p>

<p>is there a way to call another job from within ant script without using jenkins-cli.jar as external command </p>

答:
You can trigger Jenkins jobs by doing an HTTP request:

Go to your Job Configuration

Build triggers > Check 'Trigger Builds Remotely' and think of an access token, e.g. SOME_SECURE_TOKEN.

In your ant script: execute a POST request to JENKINS_URL/job/JOB_NAME/build?token=SOME_SECURE_TOKEN

Note that if you have authentication in place, you need to set up a user who is authorized to start the other jobs. In that case read this more detailed explanation: https://www.nczonline.net/blog/2015/10/triggering-jenkins-builds-by-url/

Another solution would be to use the Parameterized Trigger Plugin to trigger builds from a Jenkins step. You mention that the jobs that need to be triggered may depend on the job parameters. In that case you can combine the Conditional Buildstep plugin with the Parameterized Trigger plugin.

Body:
I'm running an ant job that runs several thing on master node and need to trigger several jobs on slave servers based on the options i select from the main job parameters

is there a way to call another job from within ant script without using jenkins-cli.jar as external command


问:
How to calculate the current row with the next one?
In Spark-Sql version 1.6, using DataFrames, is there a way to calculate, for a specific column, the sum of the current row and the next one, for every row?

For example, if I have a table with one column, like so

```<code>Age
12
23
31
67
</code>```

I'd like the following output

```<code>Sum
35
54
98
</code>```

The last row is dropped because it has no "next row" to be added to.

Right now I am doing it by ranking the table and joining it with itself, where the rank is equals to rank+1.

Is there a better way to do this?
Can this be done with a Window function?

答:
Yes definitely you can do with Window function by using rowsBetween function. I have used person column for grouping purpose in my following example.

```<code>import sqlContext.implicits._
import org.apache.spark.sql.functions._

val dataframe = Seq(
  ("A",12),
  ("A",23),
  ("A",31),
  ("A",67)
).toDF("person", "Age")

val windowSpec = Window.partitionBy("person").orderBy("Age").rowsBetween(0, 1)
val newDF = dataframe.withColumn("sum", sum(dataframe("Age")) over(windowSpec))
  newDF.filter(!(newDF("Age") === newDF("sum"))).show
</code>```

Body:
In Spark-Sql version 1.6, using DataFrames, is there a way to calculate, for a specific column, the sum of the current row and the next one, for every row?

For example, if I have a table with one column, like so

Age
12
23
31
67

I'd like the following output

Sum
35
54
98

The last row is dropped because it has no "next row" to be added to.

Right now I am doing it by ranking the table and joining it with itself, where the rank is equals to rank+1.

Is there a better way to do this?
Can this be done with a Window function?

Body:
Yes definitely you can do with Window function by using rowsBetween function. I have used person column for grouping purpose in my following example.

import sqlContext.implicits._
import org.apache.spark.sql.functions._

val dataframe = Seq(
  ("A",12),
  ("A",23),
  ("A",31),
  ("A",67)
).toDF("person", "Age")

val windowSpec = Window.partitionBy("person").orderBy("Age").rowsBetween(0, 1)
val newDF = dataframe.withColumn("sum", sum(dataframe("Age")) over(windowSpec))
  newDF.filter(!(newDF("Age") === newDF("sum"))).show


问:
How to return to previously nested `while True` loops?
Say I have something in this kind of format:

```<code>while True1:
    if something:
        do some thing
    elif something else:
        do something else
        while True2:
            if something1:
                do some thing1
            if something2:
                do some thing2
            if want to end this while True2 loop
                go back to first while True1 loop
    elif something else else:
        do some thing else else
</code>```

etc.

How can I make something within a while True loop go back to a previous while True loop that it was nested inside?

答:
Use the break statement.

```<code>x = 0
while True:
    x += 1
    if x == 5:
        print(x)
        break
</code>```

will output 5 and exits

Body:
Say I have something in this kind of format:

while True1:
    if something:
        do some thing
    elif something else:
        do something else
        while True2:
            if something1:
                do some thing1
            if something2:
                do some thing2
            if want to end this while True2 loop
                go back to first while True1 loop
    elif something else else:
        do some thing else else

etc.

How can I make something within a while True loop go back to a previous while True loop that it was nested inside?

Body:
Use the break statement.

x = 0
while True:
    x += 1
    if x == 5:
        print(x)
        break

will output 5 and exits


问:
How to pass long number through javascript?
I want to convert numberLong date from the mongo db database into dd/mm/yyyy format in javascript.

When I put direct hardcoded value like the following code, it gives me correct result:

```<code>function getDateIfDate(d) {
    var m = d.match(/\/Date\((\d+)\)\//);
    return m ? (new Date(+m[1])).toLocaleDateString('en-US', {month: '2-digit', day: '2-digit', year: 'numeric'}) : d;
}

console.log(getDateIfDate("/Date(1460008501597)/"));
</code>```

Here is my code :

```<code>for(var i=0;i<keys;i++)
                {
                var tr="<tr>";
                tr+= "<td><input type='checkbox' name='record'></td>"
                tr+="<td>"+positionList[i]["fromDate"]+"</td>";
                var j = (positionList[i]["fromDate"]);
                console.log("value of j is =========="+j);
                console.log(getDateIfDate("/Date(j)/")); // actual conversion should happen here
}
</code>```

What changes I should make in my code to get the date in required format?

答:
You can use momentjs for your case. It's really simple to use, if you want to format your date to DD/MM/YYYY, just add the row below:

```<code>var formattedDate = moment(new Date()).format("DD/MM/YYYY");
</code>```

Body:
I want to convert numberLong date from the mongo db database into dd/mm/yyyy format in javascript.

When I put direct hardcoded value like the following code, it gives me correct result:

function getDateIfDate(d) {
    var m = d.match(/\/Date\((\d+)\)\//);
    return m ? (new Date(+m[1])).toLocaleDateString('en-US', {month: '2-digit', day: '2-digit', year: 'numeric'}) : d;
}

console.log(getDateIfDate("/Date(1460008501597)/"));

Here is my code :

for(var i=0;i<keys;i++)
                {
                var tr="
";
                tr+= "<input type='checkbox' name='record'>	"
                tr+=""+positionList[i]["fromDate"]+"	";
                var j = (positionList[i]["fromDate"]);
                console.log("value of j is =========="+j);
                console.log(getDateIfDate("/Date(j)/")); // actual conversion should happen here
}

What changes I should make in my code to get the date in required format?

Body:
You can use momentjs for your case. It's really simple to use, if you want to format your date to DD/MM/YYYY, just add the row below:

var formattedDate = moment(new Date()).format("DD/MM/YYYY");


问:
How to pause video recording in ios application (objective-c)
Using AVCam I'm abel to start and stop video recording.
This method to start recording:

```<code>-(void)captureOutput:(AVCaptureFileOutput *)captureOutput didStartRecordingToOutputFileAtURL:(NSURL *)fileURL fromConnections:(NSArray *)connections;
</code>```

and to stop recording :

```<code>-(void)captureOutput:(AVCaptureFileOutput *)captureOutput didFinishRecordingToOutputFileAtURL:(NSURL *)outputFileURL fromConnections:(NSArray *)connections error:(NSError *)error;
</code>```

My question is how can I pause recording? looking into the AVFoundation I can found a pause method which is :

```<code>-(void)captureOutput:(AVCaptureFileOutput *)captureOutput didPauseRecordingToOutputFileAtURL:(NSURL *)fileURL fromConnections:(NSArray *)connections
</code>```

but I can't find a way to make it function.
I searched a lot but nothing seemed to solve my problem, so please help.
Thank you in advance.

答:
What about changing the method
From AVCam
to CameraEngine?

```<code>    #import "CameraEngine.h"

- (void) startPreview
{
    AVCaptureVideoPreviewLayer* preview = [[CameraEngine engine] getPreviewLayer];
    [preview removeFromSuperlayer];
    preview.frame = self.cameraView.bounds;
    [[preview connection] setVideoOrientation:UIInterfaceOrientationLandscapeRight];

    [self.cameraView.layer addSublayer:preview];
}

    - (IBAction)startRecording:(id)sender
    {
        [[CameraEngine engine] startCapture];
    }

    - (IBAction)pauseRecording:(id)sender
    {
        [[CameraEngine engine] pauseCapture];
    }

    - (IBAction)stopRecording:(id)sender
    {
        [[CameraEngine engine] stopCapture];
    }
    - (IBAction)resumeRecording:(id)sender
    {
        [[CameraEngine engine] resumeCapture];
    }
</code>```

Body:
Using AVCam I'm abel to start and stop video recording.
This method to start recording:

-(void)captureOutput:(AVCaptureFileOutput *)captureOutput didStartRecordingToOutputFileAtURL:(NSURL *)fileURL fromConnections:(NSArray *)connections;

and to stop recording :

-(void)captureOutput:(AVCaptureFileOutput *)captureOutput didFinishRecordingToOutputFileAtURL:(NSURL *)outputFileURL fromConnections:(NSArray *)connections error:(NSError *)error;

My question is how can I pause recording? looking into the AVFoundation I can found a pause method which is :

-(void)captureOutput:(AVCaptureFileOutput *)captureOutput didPauseRecordingToOutputFileAtURL:(NSURL *)fileURL fromConnections:(NSArray *)connections

but I can't find a way to make it function.
I searched a lot but nothing seemed to solve my problem, so please help.
Thank you in advance.

Body:
What about changing the method
From AVCam
to CameraEngine?

    #import "CameraEngine.h"

- (void) startPreview
{
    AVCaptureVideoPreviewLayer* preview = [[CameraEngine engine] getPreviewLayer];
    [preview removeFromSuperlayer];
    preview.frame = self.cameraView.bounds;
    [[preview connection] setVideoOrientation:UIInterfaceOrientationLandscapeRight];

    [self.cameraView.layer addSublayer:preview];
}

    - (IBAction)startRecording:(id)sender
    {
        [[CameraEngine engine] startCapture];
    }

    - (IBAction)pauseRecording:(id)sender
    {
        [[CameraEngine engine] pauseCapture];
    }

    - (IBAction)stopRecording:(id)sender
    {
        [[CameraEngine engine] stopCapture];
    }
    - (IBAction)resumeRecording:(id)sender
    {
        [[CameraEngine engine] resumeCapture];
    }


问:
Django DRF authentication and permissions
I am currently using DRF and django-allauth for authentication to my website. What should I use to only allow specific users who have an account on my website to use the DRF on the website? Some users I would like to only allow GET and some users I would like to allow GET, PUT, POST for the API.</p>

答:
In DRF, you can define custom permissions that allow you to restrict access to your api based on the request method used.

http://www.django-rest-framework.org/api-guide/permissions/#custom-permissions

you can then set this permissions as the default permission class in the DEFAULT_PERMISSION_CLASSES in your REST_FRAMEWORK settings. Or you can also set it in your view with permission_classes.


问:
Update values incrementally in mysql
One field of my table's field is set to 0 for all rows. But I want to update the incremental value by step 1 in an update query.

How can I do that in mysql?

答:
Try this:</p>

```<code>mysql> select @i := 0;
mysql> update bar set c = (select @i := @i + 1);
</code>```

Title: Update values incrementally in mysql

Body:
Try this:

mysql> select @i := 0;
mysql> update bar set c = (select @i := @i + 1);