问:
URL rewrite for dynamic websites
I am trying to rewrite my dynamic URLs here is some information about it.

Entire data is coming from single table no other table created.
URL Rewrite is active on Apache server.

MY CURRENT URL

http://www.example.com/list.php?city=Mumbai&business_category=Accounting+services

EXPECTED URL

http://www.example.com/Mumbai/Accounting-services

MY CODE

```<code>RewriteEngine On    # Turn on the rewriting engine
RewriteRule    ^([A-Za-z0-9-]+)/([A-Za-z0-9-]+)/?$    list.php?city=$1&business_category=$2    [NC,L]    # Process product requests
</code>```

答:
You could give the following a try - I think it does more or less what you were after</p>

```<code>RewriteCond %{THE_REQUEST} /(?:list\.php)?\?city=([^&\s]+)&business_category=([^&\s]+) [NC]
RewriteRule ^ %1/%2? [R=302,L,NE]
</code>```

Title: URL rewrite for dynamic websites

Body:
I am trying to rewrite my dynamic URLs here is some information about it.

Entire data is coming from single table no other table created.
URL Rewrite is active on Apache server.

MY CURRENT URL

http://www.example.com/list.php?city=Mumbai&business_category=Accounting+services

EXPECTED URL

http://www.example.com/Mumbai/Accounting-services

MY CODE

RewriteEngine On    # Turn on the rewriting engine
RewriteRule    ^([A-Za-z0-9-]+)/([A-Za-z0-9-]+)/?$    list.php?city=$1&business_category=$2    [NC,L]    # Process product requests

Body:
You could give the following a try - I think it does more or less what you were after

RewriteCond %{THE_REQUEST} /(?:list\.php)?\?city=([^&\s]+)&business_category=([^&\s]+) [NC]
RewriteRule ^ %1/%2? [R=302,L,NE]


来源: stackexchange

问:
CORS in IIS issue with credentials and wildcard in Access-Control-Allow-Origin
I inherited a fairly basic site that serves up data and handles some socket connections. It's running NodeJS behind IIS using iisnode as a bridge. That's all working fine from a "serve normal pages" perspective.

Part of the problem is that the actual connections to the server are coming from desktop clients where the content is loaded through a different application as a gadget and from potentially changing and varying parts of the network, mobiles devices, etc. etc. i.e. - an unknown number of client domains.

I already set Access-Control-Allow origin to * to just throw the barn doors open but now am getting the following error in the client:

11:29:57.668 Cross-Origin Request Blocked: The Same Origin Policy
  disallows reading the remote resource at
  ‘http://server/socket.io/?EIO=3&transport=polling&t=1486150196479-0’.
  (Reason: Credential is not supported if the CORS header
  ‘Access-Control-Allow-Origin’ is ‘*’). 1 (unknown)

I have attempted to set the Access-Control-Allow-Credentials explicitly to false (as well as true, as well as leaving it out entirely) but none of my attempts have allowed me to get past this.

The raw response headers look like this currently:

```<code>Access-Control-Allow-Credentials: false
Access-Control-Allow-Headers: Origin,Content-Type,Accept
Access-Control-Allow-Methods: GET,HEAD,PUT,POST,DELETE,OPTIONS
Access-Control-Allow-Origin: *
Cache-Control: no-cache
Content-Encoding: gzip
Content-Length: 969
Content-Type: text/html
Date: Fri, 03 Feb 2017 19:30:21 GMT
Server: Microsoft-IIS/8.5
Vary: Accept-Encoding
X-Powered-By: ASP.NET
</code>```

I can't seem to sort out after looking at A LOT of CORS sites and articles over the last few days why it's still complaining about Credentials - and more specifically, how do I get around this?

Thanks!

UPDATE 2017-02-06

The client code is not terribly exciting. Since the server is NodeJS behind IIS, all I'm really doing for this is implementing a socket connection:

```<code>var socket = io('http://' + currentServer, {path: '/broadcast/socket.io', reconnection: false, forceNew: true});
socket.on('update message', function (data) {
// do some fancy things
}
</code>```

This works from within the same domain.

I've also been doing some more digging based on sideshowbarker's comments that led me to this article There are some extra steps to add the variables, and some other things to get that piece working.

My applicationHost.config currently contains this section:

```<code><location path="Default Web Site">
    <system.webServer>
        <rewrite>
            <allowedServerVariables>
                <add name="CAPTURED_ORIGIN" />
                <add name="RESPONSE_Access-Control-Allow-Origin" />
            </allowedServerVariables>
        </rewrite>
    </system.webServer>
</location>
</code>```

and my web.config is here:

```<code><?xml version="1.0" encoding="UTF-8"?>
<configuration>
<system.webServer>
    <rewrite>
        <rules>
            <rule name="Fail bad requests">
                <match url="." />
                <conditions>
                    <add input="{HTTP_HOST}" negate="true" pattern="localhost" />
                </conditions>
                <action type="AbortRequest" />
            </rule>
            <rule name="Capture Origin Header">
                <match url=".*" />
                <conditions>
                    <add input="{HTTP_ORIGIN}" pattern=".+" />
                </conditions>
                <serverVariables>
                    <set name="CAPTURED_ORIGIN" value="{C:0}" />
                </serverVariables>
                <action type="None" />
            </rule>
        </rules>
        <outboundRules>
            <rule name="Set-Access-Control-Allow-Origin for known origins">
                <match serverVariable="RESPONSE_Access-Control-Allow-Origin" pattern=".+" negate="true" />
                <!--<action type="Rewrite" value="{C:0}" /> -->
            </rule>
        </outboundRules>
    </rewrite>
    <tracing>
        <traceFailedRequests>
            <add path="*">
                <traceAreas>
                    <add provider="ASP" verbosity="Verbose" />
                    <add provider="ASPNET" areas="Infrastructure,Module,Page,AppServices" verbosity="Verbose" />
                    <add provider="ISAPI Extension" verbosity="Verbose" />
                    <add provider="WWW Server" areas="Authentication,Security,Filter,StaticFile,CGI,Compression,Cache,RequestNotifications,Module,FastCGI,WebSocket" verbosity="Verbose" />
                </traceAreas>
                <failureDefinitions statusCodes="400-599" />
            </add>
        </traceFailedRequests>
    </tracing>
</system.webServer>
</configuration>
</code>```

on the outboundRules I currently have the action type="Rewrite" line commented out because when I enable that, it throws up an error.

```<code>HTTP Error 500.52 - URL Rewrite Module Error.

The page cannot be displayed because an internal server error has occurred.

Most likely causes:
•IIS received the request; however, an internal error occurred during the processing of the request. The root cause of this error depends on which module handles the request and what was happening in the worker process when this error occurred.
•IIS was not able to access the web.config file for the Web site or application. This can occur if the NTFS permissions are set incorrectly.
•IIS was not able to process configuration for the Web site or application.
•The authenticated user does not have permission to use this DLL.
•The request is mapped to a managed handler but the .NET Extensibility Feature is not installed.

Detailed Error Information:
Module: RewriteModule
Notification: SendResponse
Handler: StaticFile
Error Code: 0x80070585

Requested URL: http://localhost:80/iisstart.htm
Physical Path: C:\inetpub\wwwroot\iisstart.htm
Logon Method: Anonymous
Logon User: Anonymous
Request Tracing Directory: C:\inetpub\logs\FailedReqLogFiles
</code>```

The Failed Request Logs are not overly helpful, they show the following for the warning:

```<code>411.  -MODULE_SET_RESPONSE_ERROR_STATUS
ModuleName: RewriteModule
Notification: SEND_RESPONSE
HttpStatus: 500
HttpReason: URL Rewrite Module Error.
HttpSubStatus: 52
ErrorCode: Invalid index. (0x80070585)
ConfigExceptionInfo:
</code>```

答:
I had the same issue, I had both http and https bindings on one website with Access-Control-Allow-Origin: *
in this case http request will fail with the above error.
you can create a separate website for http binding and remove Access-Control-Allow-Origin header from it.</p>

ContentLicense: CC BY-SA 3.0

Body:
I inherited a fairly basic site that serves up data and handles some socket connections. It's running NodeJS behind IIS using iisnode as a bridge. That's all working fine from a "serve normal pages" perspective.

Part of the problem is that the actual connections to the server are coming from desktop clients where the content is loaded through a different application as a gadget and from potentially changing and varying parts of the network, mobiles devices, etc. etc. i.e. - an unknown number of client domains.

I already set Access-Control-Allow origin to * to just throw the barn doors open but now am getting the following error in the client:

11:29:57.668 Cross-Origin Request Blocked: The Same Origin Policy
  disallows reading the remote resource at
  ‘http://server/socket.io/?EIO=3&transport=polling&t=1486150196479-0’.
  (Reason: Credential is not supported if the CORS header
  ‘Access-Control-Allow-Origin’ is ‘*’). 1 (unknown)

I have attempted to set the Access-Control-Allow-Credentials explicitly to false (as well as true, as well as leaving it out entirely) but none of my attempts have allowed me to get past this.

The raw response headers look like this currently:

Access-Control-Allow-Credentials: false
Access-Control-Allow-Headers: Origin,Content-Type,Accept
Access-Control-Allow-Methods: GET,HEAD,PUT,POST,DELETE,OPTIONS
Access-Control-Allow-Origin: *
Cache-Control: no-cache
Content-Encoding: gzip
Content-Length: 969
Content-Type: text/html
Date: Fri, 03 Feb 2017 19:30:21 GMT
Server: Microsoft-IIS/8.5
Vary: Accept-Encoding
X-Powered-By: ASP.NET

I can't seem to sort out after looking at A LOT of CORS sites and articles over the last few days why it's still complaining about Credentials - and more specifically, how do I get around this?

Thanks!

UPDATE 2017-02-06

The client code is not terribly exciting. Since the server is NodeJS behind IIS, all I'm really doing for this is implementing a socket connection:

var socket = io('http://' + currentServer, {path: '/broadcast/socket.io', reconnection: false, forceNew: true});
socket.on('update message', function (data) {
// do some fancy things
}

This works from within the same domain.

I've also been doing some more digging based on sideshowbarker's comments that led me to this article There are some extra steps to add the variables, and some other things to get that piece working.

My applicationHost.config currently contains this section:

<location path="Default Web Site">
    <system.webServer>
        <rewrite>
            <allowedServerVariables>
                <add name="CAPTURED_ORIGIN" />
                <add name="RESPONSE_Access-Control-Allow-Origin" />
            </allowedServerVariables>
        </rewrite>
    </system.webServer>
</location>

and my web.config is here:

<?xml version="1.0" encoding="UTF-8"?>
<configuration>
<system.webServer>
    <rewrite>
        <rules>
            <rule name="Fail bad requests">
                <match url="." />
                <conditions>
                    <add input="{HTTP_HOST}" negate="true" pattern="localhost" />
                </conditions>
                <action type="AbortRequest" />
            </rule>
            <rule name="Capture Origin Header">
                <match url=".*" />
                <conditions>
                    <add input="{HTTP_ORIGIN}" pattern=".+" />
                </conditions>
                <serverVariables>
                    <set name="CAPTURED_ORIGIN" value="{C:0}" />
                </serverVariables>
                <action type="None" />
            </rule>
        </rules>
        <outboundRules>
            <rule name="Set-Access-Control-Allow-Origin for known origins">
                <match serverVariable="RESPONSE_Access-Control-Allow-Origin" pattern=".+" negate="true" />

            </rule>
        </outboundRules>
    </rewrite>
    <tracing>
        <traceFailedRequests>
            <add path="*">
                <traceAreas>
                    <add provider="ASP" verbosity="Verbose" />
                    <add provider="ASPNET" areas="Infrastructure,Module,Page,AppServices" verbosity="Verbose" />
                    <add provider="ISAPI Extension" verbosity="Verbose" />
                    <add provider="WWW Server" areas="Authentication,Security,Filter,StaticFile,CGI,Compression,Cache,RequestNotifications,Module,FastCGI,WebSocket" verbosity="Verbose" />
                </traceAreas>
                <failureDefinitions statusCodes="400-599" />
            </add>
        </traceFailedRequests>
    </tracing>
</system.webServer>
</configuration>

on the outboundRules I currently have the action type="Rewrite" line commented out because when I enable that, it throws up an error.

HTTP Error 500.52 - URL Rewrite Module Error.

The page cannot be displayed because an internal server error has occurred.

Most likely causes:
•IIS received the request; however, an internal error occurred during the processing of the request. The root cause of this error depends on which module handles the request and what was happening in the worker process when this error occurred.
•IIS was not able to access the web.config file for the Web site or application. This can occur if the NTFS permissions are set incorrectly.
•IIS was not able to process configuration for the Web site or application.
•The authenticated user does not have permission to use this DLL.
•The request is mapped to a managed handler but the .NET Extensibility Feature is not installed.

Detailed Error Information:
Module: RewriteModule
Notification: SendResponse
Handler: StaticFile
Error Code: 0x80070585

Requested URL: http://localhost:80/iisstart.htm
Physical Path: C:\inetpub\wwwroot\iisstart.htm
Logon Method: Anonymous
Logon User: Anonymous
Request Tracing Directory: C:\inetpub\logs\FailedReqLogFiles

The Failed Request Logs are not overly helpful, they show the following for the warning:

411.  -MODULE_SET_RESPONSE_ERROR_STATUS
ModuleName: RewriteModule
Notification: SEND_RESPONSE
HttpStatus: 500
HttpReason: URL Rewrite Module Error.
HttpSubStatus: 52
ErrorCode: Invalid index. (0x80070585)
ConfigExceptionInfo:


问:
php or mysql select data from each combination in random order
I have a table named it_vit_qs from which i have to make a question set. Each question set should obtain qs from every category (e.g. cat_id) and every level (e.g lavel_id) in random order.

Note that each category(cat_id) have 3 level. There are 7 category. That means there will be 3*7= 21 combination. That means cat_id 1 have level_id 1,2 and 3, cat_id 2 have level_id 1,2 and 3 and so on.

Now how i can select 5 question from each cat & level combination in random order??? i have tried the below query but it seems like slow and bad practice. I have included my sql and its result. But I want to do it in efficient & easier way.

```<code>SELECT
  a.*
FROM
  (SELECT
    *
  FROM
    it_vit_qs
  WHERE cat_id = 1 AND level_id=1
  ORDER BY RAND()
  LIMIT 3) a
UNION
SELECT
  b.*
FROM
  (SELECT
    *
  FROM
    it_vit_qs
    WHERE cat_id = 1 AND level_id=2
  ORDER BY RAND()
  LIMIT 3) b

  UNION

  SELECT
  b.*
FROM
  (SELECT
    *
  FROM
    it_vit_qs
    WHERE cat_id = 1 AND level_id=3
  ORDER BY RAND()
  LIMIT 3) b

  UNION

  SELECT
  b.*
FROM
  (SELECT
    *
  FROM
    it_vit_qs
    WHERE cat_id = 2 AND level_id=1
  ORDER BY RAND()
  LIMIT 3) b

  UNION

  SELECT
  b.*
FROM
  (SELECT
    *
  FROM
    it_vit_qs
    WHERE cat_id = 2 AND level_id=2
  ORDER BY RAND()
  LIMIT 3) b
</code>```

Updated:

I think it can also be done in php after running the query.

SELECT * FROM it_vit_qs ORDER BY RAND();

Can you please help me to do it in php from mysql query result.

答:
You might consider populating a hashmap with rows fetched from this query:

```<code>SELECT * FROM it_vit_qs ORDER BY RAND()
</code>```

As you fetch a row, you add a tuple as the value of a hashmap whose key is a combination of cat_id and level_id (e.g., (cat_id*10) + level_id). When the number of tuples for a combination reaches 5 you mark that key as being complete by adding the key to another hashmap, called C.

When the number of entries in C reaches 7, you stop fetching rows.

The reason your code takes so long is because your query makes 21 full passes on it_vit_qs.

The worst case for my approach is you make one full pass on it_vit_qs. And that remains true if you add more categories or levels.

Addendum 1 php example

```<code><?php

$db = new mysqli(localhost, DB_USER, DB_PASSWORD, DB_NAME);
$stmt = $db->prepare("SELECT cat_id, level_id, other_id FROM it_vit_qs ORDER BY RAND()");
$stmt->execute();
$stmt->bind_result($cat_id, $level_id, $other_id);

$found = Array();
$complete = Array();

while ($stmt->fetch()) {
    $key = "$cat_id:$level_id";

    #if (count($found[$key]) < 5) {     # this might suffice

    if (!array_key_exists($key, $found) || count($found[$key]) < 5) {
       # if it_vit_qs has more than 3 columns, then push a list instead of a scalar
       if (count($found[$key]) == 0) {
          $found[$key] = Array();
       }
       array_push($found[$key], $other_id);
    } else {
       $complete[$key] = 1;
       if (count($complete) == 7) {
          break;
       }
   }
}
print_r($found);
?>
</code>```

Addendum 2

```<code><?php

$db = new mysqli(localhost, DB_USER, DB_PASSWORD, DB_NAME);
$stmt = $db->prepare("SELECT cat_id, level_id, other_id FROM it_vit_qs ORDER BY RAND()");
$stmt->execute();
$stmt->bind_result($cat_id, $level_id, $other_id);

$found = Array();
$complete = Array();

while ($stmt->fetch()) {
   $key = "$cat_id:$level_id";
   if (!array_key_exists($key, $found)) {
      $found[$key] = Array();
   }
   if (count($found[$key]) < 5) {
      array_push($found[$key], $other_id);
   } else {
      $complete[$key] = 1;
      if (count($complete) == 7) {
         break;
      }
   }
}
print_r($found);
?>
</code>```

Body:
I have a table named it_vit_qs from which i have to make a question set. Each question set should obtain qs from every category (e.g. cat_id) and every level (e.g lavel_id) in random order.

Note that each category(cat_id) have 3 level. There are 7 category. That means there will be 3*7= 21 combination. That means cat_id 1 have level_id 1,2 and 3, cat_id 2 have level_id 1,2 and 3 and so on.

Now how i can select 5 question from each cat & level combination in random order??? i have tried the below query but it seems like slow and bad practice. I have included my sql and its result. But I want to do it in efficient & easier way.

SELECT
  a.*
FROM
  (SELECT
    *
  FROM
    it_vit_qs
  WHERE cat_id = 1 AND level_id=1
  ORDER BY RAND()
  LIMIT 3) a
UNION
SELECT
  b.*
FROM
  (SELECT
    *
  FROM
    it_vit_qs
    WHERE cat_id = 1 AND level_id=2
  ORDER BY RAND()
  LIMIT 3) b

  UNION

  SELECT
  b.*
FROM
  (SELECT
    *
  FROM
    it_vit_qs
    WHERE cat_id = 1 AND level_id=3
  ORDER BY RAND()
  LIMIT 3) b

  UNION

  SELECT
  b.*
FROM
  (SELECT
    *
  FROM
    it_vit_qs
    WHERE cat_id = 2 AND level_id=1
  ORDER BY RAND()
  LIMIT 3) b

  UNION

  SELECT
  b.*
FROM
  (SELECT
    *
  FROM
    it_vit_qs
    WHERE cat_id = 2 AND level_id=2
  ORDER BY RAND()
  LIMIT 3) b

Updated:

I think it can also be done in php after running the query.

SELECT * FROM it_vit_qs ORDER BY RAND();

Can you please help me to do it in php from mysql query result.

Body:
You might consider populating a hashmap with rows fetched from this query:

SELECT * FROM it_vit_qs ORDER BY RAND()

As you fetch a row, you add a tuple as the value of a hashmap whose key is a combination of cat_id and level_id (e.g., (cat_id*10) + level_id). When the number of tuples for a combination reaches 5 you mark that key as being complete by adding the key to another hashmap, called C.

When the number of entries in C reaches 7, you stop fetching rows.

The reason your code takes so long is because your query makes 21 full passes on it_vit_qs.

The worst case for my approach is you make one full pass on it_vit_qs. And that remains true if you add more categories or levels.

Addendum 1 php example

<?php

$db = new mysqli(localhost, DB_USER, DB_PASSWORD, DB_NAME);
$stmt = $db->prepare("SELECT cat_id, level_id, other_id FROM it_vit_qs ORDER BY RAND()");
$stmt->execute();
$stmt->bind_result($cat_id, $level_id, $other_id);

$found = Array();
$complete = Array();

while ($stmt->fetch()) {
    $key = "$cat_id:$level_id";

    #if (count($found[$key]) < 5) {     # this might suffice

    if (!array_key_exists($key, $found) || count($found[$key]) < 5) {
       # if it_vit_qs has more than 3 columns, then push a list instead of a scalar
       if (count($found[$key]) == 0) {
          $found[$key] = Array();
       }
       array_push($found[$key], $other_id);
    } else {
       $complete[$key] = 1;
       if (count($complete) == 7) {
          break;
       }
   }
}
print_r($found);
?>

Addendum 2

<?php

$db = new mysqli(localhost, DB_USER, DB_PASSWORD, DB_NAME);
$stmt = $db->prepare("SELECT cat_id, level_id, other_id FROM it_vit_qs ORDER BY RAND()");
$stmt->execute();
$stmt->bind_result($cat_id, $level_id, $other_id);

$found = Array();
$complete = Array();

while ($stmt->fetch()) {
   $key = "$cat_id:$level_id";
   if (!array_key_exists($key, $found)) {
      $found[$key] = Array();
   }
   if (count($found[$key]) < 5) {
      array_push($found[$key], $other_id);
   } else {
      $complete[$key] = 1;
      if (count($complete) == 7) {
         break;
      }
   }
}
print_r($found);
?>


问:
ModelValidation on posted action parameter not happening
Why doesn't ASP.NET Core validate [FromBody] attributed action parameters? In the example below the paramter value of type SomeClass does not get validated. It doesn't even appear in the ModelState dictionary (only id). this.ModelState.IsValid is always true, even though the Name property is set to a string longer than 2 letters.

Even TryValidateModel is always true no matter what the request body contains (JSON).

Sample Repo here

```<code>public class Startup
{
    public IConfigurationRoot Configuration { get; }

    public void ConfigureServices(IServiceCollection services)
    {
        services
            .AddMvcCore()
            .AddJsonFormatters();
    }

    public void Configure(IApplicationBuilder app, ILoggerFactory loggerFactory)
    {
        loggerFactory.AddConsole();
        loggerFactory.AddDebug();

        app.UseMvc();
    }
}
</code>```

and

```<code>using Microsoft.AspNetCore.Mvc;
using System;
using System.ComponentModel.DataAnnotations;

namespace WebApplication3.Controllers
{
    [Route("api/[controller]")]
    public class ValuesController : Controller
    {
        [HttpPut("{id:int}")]
        public IActionResult Put(
            int id,
            [FromBody]SomeClass value)
        {
            if (this.ModelState.IsValid == false)
                throw new Exception();

            if (this.TryValidateModel(value) == false)
                throw new Exception();

            return this.BadRequest(this.ModelState);
        }
    }

    public class SomeClass
    {
        [StringLength(2)]
        [Required(AllowEmptyStrings = false)]
        [DisplayFormat(ConvertEmptyStringToNull = false)]
        public string Name { get; set; }
    }
}
</code>```

答:
You need to register MVC data annotation. It is not added by default when you use the light AddMvcCore method instead of AddMvc. Modify your ConfigureServices method:

```<code>services
   .AddMvcCore()
   .AddJsonFormatters()
   .AddDataAnnotations(); // add this line
</code>```

Body:
Why doesn't ASP.NET Core validate [FromBody] attributed action parameters? In the example below the paramter value of type SomeClass does not get validated. It doesn't even appear in the ModelState dictionary (only id). this.ModelState.IsValid is always true, even though the Name property is set to a string longer than 2 letters.

Even TryValidateModel is always true no matter what the request body contains (JSON).

Sample Repo here

public class Startup
{
    public IConfigurationRoot Configuration { get; }

    public void ConfigureServices(IServiceCollection services)
    {
        services
            .AddMvcCore()
            .AddJsonFormatters();
    }

    public void Configure(IApplicationBuilder app, ILoggerFactory loggerFactory)
    {
        loggerFactory.AddConsole();
        loggerFactory.AddDebug();

        app.UseMvc();
    }
}

and

using Microsoft.AspNetCore.Mvc;
using System;
using System.ComponentModel.DataAnnotations;

namespace WebApplication3.Controllers
{
    [Route("api/[controller]")]
    public class ValuesController : Controller
    {
        [HttpPut("{id:int}")]
        public IActionResult Put(
            int id,
            [FromBody]SomeClass value)
        {
            if (this.ModelState.IsValid == false)
                throw new Exception();

            if (this.TryValidateModel(value) == false)
                throw new Exception();

            return this.BadRequest(this.ModelState);
        }
    }

    public class SomeClass
    {
        [StringLength(2)]
        [Required(AllowEmptyStrings = false)]
        [DisplayFormat(ConvertEmptyStringToNull = false)]
        public string Name { get; set; }
    }
}

Body:
You need to register MVC data annotation. It is not added by default when you use the light AddMvcCore method instead of AddMvc. Modify your ConfigureServices method:

services
   .AddMvcCore()
   .AddJsonFormatters()
   .AddDataAnnotations(); // add this line


问:
Android: fling detection on ListView with complex rows
Dear Android hackers, I am attaching a gestureListener recognizing flings to a ListView. The rows of the ListView consist of a LinearView and some TextViews. Unfortunately, the fling is not detected, when it starts on one of the TextViews:

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

    <LinearLayout
        android:orientation="horizontal"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:layout_weight="1"
        android:background="#000000" >
        <TextView
            android:id="@+id/author"
            android:textSize="14sp"
            android:textColor="#ffffff"
            android:textStyle="bold"
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"
            android:layout_weight="1"/>
        <TextView
            android:id="@+id/date"
            android:textSize="11sp"
            android:textColor="#eeeeee"
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:gravity="right"/>
    </LinearLayout>
    <TextView
        android:id="@+id/text"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:paddingTop="5dp"
        android:paddingRight="5dp"
        android:paddingLeft="5dp"
        android:textColor="#333333"

        android:paddingBottom="5dp"
        android:textSize="14sp"
        android:layout_weight="2"/>
</LinearLayout>
</code>```

So, when I start the fling on the horizontal LinearLayout, everything works fine, but when I start it on the TextView at the bottom, nothing happens. It containts editable text, if that could be the problem... As is said, the Listener is attached to the ListView itself.

I'd be glad if somebody could help!

Jan Oliver

答:
Your editable TextView is returning true from onTouch(), preventing the event from being processed by the LinearLayout higher up the view hierarchy.

There is nothing stopping you attaching a custom OnTouchListener to your TextView to override this and pass the event to your existing GestureDetector.

```<code>textView.setOnTouchListener(new OnTouchListener() {
    public boolean onTouch(View arg0, MotionEvent ev) {
        return gestureDetector.onTouchEvent(ev);
    }
};
</code>```

ContentLicense: CC BY-SA 2.5

Body:
Dear Android hackers, I am attaching a gestureListener recognizing flings to a ListView. The rows of the ListView consist of a LinearView and some TextViews. Unfortunately, the fling is not detected, when it starts on one of the TextViews:

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

    <LinearLayout
        android:orientation="horizontal"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:layout_weight="1"
        android:background="#000000" >
        <TextView
            android:id="@+id/author"
            android:textSize="14sp"
            android:textColor="#ffffff"
            android:textStyle="bold"
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"
            android:layout_weight="1"/>
        <TextView
            android:id="@+id/date"
            android:textSize="11sp"
            android:textColor="#eeeeee"
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:gravity="right"/>
    </LinearLayout>
    <TextView
        android:id="@+id/text"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:paddingTop="5dp"
        android:paddingRight="5dp"
        android:paddingLeft="5dp"
        android:textColor="#333333"

        android:paddingBottom="5dp"
        android:textSize="14sp"
        android:layout_weight="2"/>
</LinearLayout>

So, when I start the fling on the horizontal LinearLayout, everything works fine, but when I start it on the TextView at the bottom, nothing happens. It containts editable text, if that could be the problem... As is said, the Listener is attached to the ListView itself.

I'd be glad if somebody could help!

Jan Oliver

Body:
Your editable TextView is returning true from onTouch(), preventing the event from being processed by the LinearLayout higher up the view hierarchy.

There is nothing stopping you attaching a custom OnTouchListener to your TextView to override this and pass the event to your existing GestureDetector.

textView.setOnTouchListener(new OnTouchListener() {
    public boolean onTouch(View arg0, MotionEvent ev) {
        return gestureDetector.onTouchEvent(ev);
    }
};


问:
Stopping and Starting IIS in C#
I need to be able to Start/Stop the IIS in C#. I've been tasked with creating this module by my manager. The following is my attempt:

```<code>ServiceController service = new ServiceController("w3svc");
service.Stop();
</code>```

I am getting the following exception:

Cannot open w3svc service on computer '.'.

I am writing the code to stop the IIS on the local machine.

I also tried IISAdmin as the servicename, but IISAdmin could not be found on my computer.

答:
You have to work with Microsoft.Web.Administration .

The Microsoft.Web.Administration (MWA) APIs are built as a managed
  code wrapper over the Application Host Administration API (AHADMIN)
  which is a native code interface library. It provides a programmatic
  way to access and update the web server configuration and
  administration information.

```<code>using System;
using System.Linq;
using Microsoft.Web.Administration;

class Program
{
    static void Main(string[] args)
    {
        var server = new ServerManager();
        var site = server.Sites.FirstOrDefault(s => s.Name == "Default Web Site");
        if (site != null)
        {
            //stop the site
            site.Stop();
            //start the site
            site.Start();
        }

    }
}
</code>```

This article discuss detailed scenarios for using Microsoft.Web.Administration.

Please note that you have to run your C# application as Administrator to do anything on IIS.Otherwise you may get Access denied.

Title: Stopping and Starting IIS in C#

Body:
I need to be able to Start/Stop the IIS in C#. I've been tasked with creating this module by my manager. The following is my attempt:

ServiceController service = new ServiceController("w3svc");
service.Stop();

I am getting the following exception:

Cannot open w3svc service on computer '.'.

I am writing the code to stop the IIS on the local machine.

I also tried IISAdmin as the servicename, but IISAdmin could not be found on my computer.

Body:
You have to work with Microsoft.Web.Administration .

The Microsoft.Web.Administration (MWA) APIs are built as a managed
  code wrapper over the Application Host Administration API (AHADMIN)
  which is a native code interface library. It provides a programmatic
  way to access and update the web server configuration and
  administration information.

using System;
using System.Linq;
using Microsoft.Web.Administration;

class Program
{
    static void Main(string[] args)
    {
        var server = new ServerManager();
        var site = server.Sites.FirstOrDefault(s => s.Name == "Default Web Site");
        if (site != null)
        {
            //stop the site
            site.Stop();
            //start the site
            site.Start();
        }

    }
}

This article discuss detailed scenarios for using Microsoft.Web.Administration.

Please note that you have to run your C# application as Administrator to do anything on IIS.Otherwise you may get Access denied.


问:
short Glitch in making android dynamic
I am sending a json request using params and the glitch is when I hardcode the user name and password , it works and when I set the variables it doesn't ?
What to write inplace of "ankur@gmail.com" & "123456"

```<code>    EditText username = (EditText)findViewById(R.id.edituser);
            EditText password = (EditText)findViewById(R.id.editpass);
            Button button = (Button)findViewById(R.id.signin);
            final JSONObject jsonObject = new JSONObject();
            String temp = '\u0022' +username.getText().toString().trim()+'\u0022';
            String temp1 ='\u0022'+password.getText().toString().trim()+'\u0022';

.........

final HashMap<String,String> params = new HashMap<String, String>();
    params.put("user_email","ankur@gmail.com");
    params.put("user_password","123456");
    Log.d("jsonobject", "jsonobjectResponse: "+params);

.........

    button.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    JsonObjectRequest jsonObjectRequest = new JsonObjectRequest(Request.Method.POST,url,new JSONObject(params),
                            new Response.Listener<JSONObject>() {   .........
</code>```

logs

```<code>07-06 12:23:32.365 4701-4701/com.production.vy.triqsquad D/jsonobject: jsonobjectResponse: {user_password=, user_email=}
07-06 12:23:56.046 4701-4701/com.production.vy.triqsquad D/aaa: onErrorResponse: org.json.JSONException: Value <br of type java.lang.String cannot be converted to JSONObject
07-06 12:24:04.765 4701-4701/com.production.vy.triqsquad D/aaa: onErrorResponse: org.json.JSONException: Value <br of type java.lang.String cannot be converted to JSONObject
07-06 12:24:07.584 4701-4701/com.production.vy.triqsquad D/aaa: onErrorResponse: org.json.JSONException: Value <br of type java.lang.String cannot be converted to JSONObject
</code>```

why the password is before username when I am writing username above password

答:
```<code> EditText username = (EditText)findViewById(R.id.edituser);
            EditText password = (EditText)findViewById(R.id.editpass);
            Button button = (Button)findViewById(R.id.signin);
            final JSONObject jsonObject = new JSONObject();
            String temp = '\u0022' +username.getText().toString().trim()+'\u0022';
            String temp1 ='\u0022'+password.getText().toString().trim()+'\u0022';

.........

final HashMap<String,String> params = new HashMap<String, String>();

.........

    button.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
params.put("user_email","ankur@gmail.com");
        params.put("user_password","123456");
        Log.d("jsonobject", "jsonobjectResponse: "+params);
                        JsonObjectRequest jsonObjectRequest = new JsonObjectRequest(Request.Method.POST,url,new JSONObject(params),
                                new Response.Listener<JSONObject>() {   .........
</code>```

It's done

Title: short Glitch in making android dynamic

Body:
I am sending a json request using params and the glitch is when I hardcode the user name and password , it works and when I set the variables it doesn't ?
What to write inplace of "ankur@gmail.com" & "123456"

    EditText username = (EditText)findViewById(R.id.edituser);
            EditText password = (EditText)findViewById(R.id.editpass);
            Button button = (Button)findViewById(R.id.signin);
            final JSONObject jsonObject = new JSONObject();
            String temp = '\u0022' +username.getText().toString().trim()+'\u0022';
            String temp1 ='\u0022'+password.getText().toString().trim()+'\u0022';

.........

final HashMap<String,String> params = new HashMap<String, String>();
    params.put("user_email","ankur@gmail.com");
    params.put("user_password","123456");
    Log.d("jsonobject", "jsonobjectResponse: "+params);

.........

    button.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    JsonObjectRequest jsonObjectRequest = new JsonObjectRequest(Request.Method.POST,url,new JSONObject(params),
                            new Response.Listener<JSONObject>() {   .........

logs

07-06 12:23:32.365 4701-4701/com.production.vy.triqsquad D/jsonobject: jsonobjectResponse: {user_password=, user_email=}
07-06 12:23:56.046 4701-4701/com.production.vy.triqsquad D/aaa: onErrorResponse: org.json.JSONException: Value <br of type java.lang.String cannot be converted to JSONObject
07-06 12:24:04.765 4701-4701/com.production.vy.triqsquad D/aaa: onErrorResponse: org.json.JSONException: Value <br of type java.lang.String cannot be converted to JSONObject
07-06 12:24:07.584 4701-4701/com.production.vy.triqsquad D/aaa: onErrorResponse: org.json.JSONException: Value <br of type java.lang.String cannot be converted to JSONObject

why the password is before username when I am writing username above password

Body:
 EditText username = (EditText)findViewById(R.id.edituser);
            EditText password = (EditText)findViewById(R.id.editpass);
            Button button = (Button)findViewById(R.id.signin);
            final JSONObject jsonObject = new JSONObject();
            String temp = '\u0022' +username.getText().toString().trim()+'\u0022';
            String temp1 ='\u0022'+password.getText().toString().trim()+'\u0022';

.........

final HashMap<String,String> params = new HashMap<String, String>();

.........

    button.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
params.put("user_email","ankur@gmail.com");
        params.put("user_password","123456");
        Log.d("jsonobject", "jsonobjectResponse: "+params);
                        JsonObjectRequest jsonObjectRequest = new JsonObjectRequest(Request.Method.POST,url,new JSONObject(params),
                                new Response.Listener<JSONObject>() {   .........

It's done


问:
How to get the character between a character and a space
I have an application that gets a parameter of a certain SQL query.

How will I get the characters between @ and space?

Example: Select Name From SomeTable Where Id=@ID Group By Name

so the output would be: ID

I am using the following code but it only extract characters after @. In the above example it extracts: ID Group By Name.

```<code>strParamName = sqlQuery.Substring(sqlQuery.IndexOf('@') + 1);
</code>```

答:
Try following :</p>

```<code>            string sqlQuery = "Select Name From SomeTable Where Id=@ID Group By Name";
            int startIndex = sqlQuery.IndexOf('@') + 1;
            int length = sqlQuery.Substring(startIndex).IndexOf(' ');
            string strParamName = sqlQuery.Substring(startIndex, length);
</code>```

Body:
I have an application that gets a parameter of a certain SQL query.

How will I get the characters between @ and space?

Example: Select Name From SomeTable Where Id=@ID Group By Name

so the output would be: ID

I am using the following code but it only extract characters after @. In the above example it extracts: ID Group By Name.

strParamName = sqlQuery.Substring(sqlQuery.IndexOf('@') + 1);

Body:
Try following :

            string sqlQuery = "Select Name From SomeTable Where Id=@ID Group By Name";
            int startIndex = sqlQuery.IndexOf('@') + 1;
            int length = sqlQuery.Substring(startIndex).IndexOf(' ');
            string strParamName = sqlQuery.Substring(startIndex, length);


问:
Has anybody been able to install PyWeka?
I need to install in python 2.6 or 2.7 for windows the library PyWeka0.3dev, It says it requires setuptools, which I installed but then they told me it was a deprecated instalation library and I installed distribute, then I downloaded the PyWeka compressed package and each time I try to install it neither with setup.py nor with easy_install (where it says something like no module ez_setup). Can anybody give me a clue about how to do this?</p>

答:
A punk/goth approach to programming probably has the right to be..

To get the C-compliation part to work on windows you either need (1) to have Visual Studio of the same version that was used to compile the python version you are using, or (2) mingw which is a bit trickier to set up.


问:
You have an error in your SQL syntax; when try to submit form

You have an error in your SQL syntax; check the manual that corresponds to your MariaDB server version for the right syntax to use near '','1','7','123tw')' at line 2

I got the above error when submitting the form.

```<code> <?php
    session_start();
    $branch=$_SESSION['branch'];
    include('../dist/includes/dbcon.php');
        $name = $_POST['prod_name'];
        $price = $_POST['prod_price'];
        $desc = $_POST['prod_desc'];
        $supplier = $_POST['supplier'];
        $reorder = $_POST['reorder'];
        $category = $_POST['category'];
        //$quantity = $_POST['prod_qty'];
        $serialn = $_POST['serialn'];

        $query2=mysqli_query($con,"select * from product where prod_name='$name' and branch_id='$branch'")or die(mysqli_error($con));
            $count=mysqli_num_rows($query2);

            if ($count>0)
            {
                echo "<script type='text/javascript'>alert('Product already exist!');</script>";
                echo "<script>document.location='product.php'</script>";
            }
            else
            {

                $pic = $_FILES["image"]["name"];
                if ($pic=="")
                {
                    $pic="default.gif";
                }
                else
                {
                    $pic = $_FILES["image"]["name"];
                    $type = $_FILES["image"]["type"];
                    $size = $_FILES["image"]["size"];
                    $temp = $_FILES["image"]["tmp_name"];
                    $error = $_FILES["image"]["error"];

                    if ($error > 0)
                    {
                        die("Error uploading file! Code $error.");
                        }
                    else{
                        if($size > 100000000000) //conditions for the file
                            {
                            die("Format is not allowed or file size is too big!");
                            }
                    else
                          {
                        move_uploaded_file($temp, "../dist/uploads/".$pic);
                          }
                        }
                }

                mysqli_query($con,"INSERT INTO product(prod_name,prod_price,prod_desc,prod_pic,cat_id,reorder,supplier_id,branch_id,serialn)
                VALUES('$name','$price','$desc','$pic','$category', $reorder','$supplier','$branch','$serialn')")or die(mysqli_error($con));

                echo "<script type='text/javascript'>alert('Successfully added new product!');</script>";
                          echo "<script>document.location='product.php'</script>";
            }
    ?>
</code>```

答:
Error in your SQL INSERT Query.

```<code>mysqli_query($con,"INSERT INTO product(prod_name,prod_price,prod_desc,prod_pic,cat_id,reorder,supplier_id,branch_id,serialn)
VALUES('$name','$price','$desc','$pic','$category','$reorder','$supplier','$branch','$serialn')")or die(mysqli_error($con))
</code>```

try now..

Body:
You have an error in your SQL syntax; check the manual that corresponds to your MariaDB server version for the right syntax to use near '','1','7','123tw')' at line 2

I got the above error when submitting the form.

 <?php
    session_start();
    $branch=$_SESSION['branch'];
    include('../dist/includes/dbcon.php');
        $name = $_POST['prod_name'];
        $price = $_POST['prod_price'];
        $desc = $_POST['prod_desc'];
        $supplier = $_POST['supplier'];
        $reorder = $_POST['reorder'];
        $category = $_POST['category'];
        //$quantity = $_POST['prod_qty'];
        $serialn = $_POST['serialn'];

        $query2=mysqli_query($con,"select * from product where prod_name='$name' and branch_id='$branch'")or die(mysqli_error($con));
            $count=mysqli_num_rows($query2);

            if ($count>0)
            {
                echo "";
                echo "";
            }
            else
            {

                $pic = $_FILES["image"]["name"];
                if ($pic=="")
                {
                    $pic="default.gif";
                }
                else
                {
                    $pic = $_FILES["image"]["name"];
                    $type = $_FILES["image"]["type"];
                    $size = $_FILES["image"]["size"];
                    $temp = $_FILES["image"]["tmp_name"];
                    $error = $_FILES["image"]["error"];

                    if ($error > 0)
                    {
                        die("Error uploading file! Code $error.");
                        }
                    else{
                        if($size > 100000000000) //conditions for the file
                            {
                            die("Format is not allowed or file size is too big!");
                            }
                    else
                          {
                        move_uploaded_file($temp, "../dist/uploads/".$pic);
                          }
                        }
                }

                mysqli_query($con,"INSERT INTO product(prod_name,prod_price,prod_desc,prod_pic,cat_id,reorder,supplier_id,branch_id,serialn)
                VALUES('$name','$price','$desc','$pic','$category', $reorder','$supplier','$branch','$serialn')")or die(mysqli_error($con));

                echo "";
                          echo "";
            }
    ?>

Body:
Error in your SQL INSERT Query.

mysqli_query($con,"INSERT INTO product(prod_name,prod_price,prod_desc,prod_pic,cat_id,reorder,supplier_id,branch_id,serialn)
VALUES('$name','$price','$desc','$pic','$category','$reorder','$supplier','$branch','$serialn')")or die(mysqli_error($con))

try now..


问:
Joining 2 Tables (Having 3 common columns) on the basis of only two common columns
I have 2 Tables - Employee and Job_History
and
Both the tables have 3 common columns in it - EMPLOYEE_ID, JOB_ID, DEPARTMENT_ID.

Now, I want to Join both the tables using JOIN but not on the basis of all 3 common columns BUT on the basis of only 2 common columns - EMPLOYEE_ID and JOB_ID.

How can i get the result ?

答:
You can pass multiple condition in  JOIN on clause   like this

```<code>select E.* ,J.*
from Employee as E
   inner join Job_History as J
   on (E.EMPLOYEE_ID=J.EMPLOYEE_ID
        and E.JOB_ID=J.JOB_ID)
</code>```

Body:
You can pass multiple condition in  JOIN on clause   like this

select E.* ,J.*
from Employee as E
   inner join Job_History as J
   on (E.EMPLOYEE_ID=J.EMPLOYEE_ID
        and E.JOB_ID=J.JOB_ID)


问:
CodeIgniter - how to remove class name in url route
I have http://localhost/CIrbbps/index.php/class_name/method_name . how to remove class name?, so i can get just http://localhost/CIrbbps/index.php/method_name . thank you</p>

答:
In order to map www.domain.com/services to pages/services you would go like:

```<code>$route['services'] = 'pages/services'
</code>```

If you want to map www.domain.com/whatever to pages/whatever and whatever has a few variants and you have a few controllers, then you would do :

// create rules above this one for all the controllers.

```<code>$route['(:any)'] = 'pages/$1'
</code>```

That is, you need to create rules for all your controllers/actions and the last one should be a catch-all rule, as pointed above.

If you have too many controllers and you want to tackle this particular route, the in your routes.php file it is safe to:

```<code>$path = trim($_SERVER['PATH_INFO'], '/');
$toMap = array('services', 'something');
foreach ($toMap as $map) {
    if (strpos($path, $map) === 0) {
       $route[$map] = 'pages/'.$map;
    }
}
</code>```

Note, instead of $_SERVER['PATH_INFO'] you might want to try $_SERVER['ORIG_PATH_INFO'] or whatever component that gives you the full url path.
Also, the above is not tested, it's just an example to get you started.

CodeIgniter Routes - remove a classname from URL for one class only

Body:
In order to map www.domain.com/services to pages/services you would go like:

$route['services'] = 'pages/services'

If you want to map www.domain.com/whatever to pages/whatever and whatever has a few variants and you have a few controllers, then you would do :

// create rules above this one for all the controllers.

$route['(:any)'] = 'pages/$1'

That is, you need to create rules for all your controllers/actions and the last one should be a catch-all rule, as pointed above.

If you have too many controllers and you want to tackle this particular route, the in your routes.php file it is safe to:

$path = trim($_SERVER['PATH_INFO'], '/');
$toMap = array('services', 'something');
foreach ($toMap as $map) {
    if (strpos($path, $map) === 0) {
       $route[$map] = 'pages/'.$map;
    }
}

Note, instead of $_SERVER['PATH_INFO'] you might want to try $_SERVER['ORIG_PATH_INFO'] or whatever component that gives you the full url path.
Also, the above is not tested, it's just an example to get you started.

CodeIgniter Routes - remove a classname from URL for one class only


问:
How to save and get data in other components using Angular
I am using JSON object in all components. Is there any global declaration and reuse JSON object in Angular?

Otherwise same object we will load in all components?

Where should I declare that object and how can I call it in other components?

I am maintaining onload functions in  HomePage components and I am using in home.html.

I am maintaining the WebserviceProvider for getting values.

But where will I declare and store JSON object and how to re-use other components?

答:
If you want to define some data that is shared across all of your components, build a service.

I have a simple service example here: https://blogs.msmvps.com/deborahk/build-a-simple-angular-service-to-share-data/


问:
Incrementally build Docker image hierarchy with Makefile
In a project of mine I have several Docker images that base on each others, because I don't need to rebuild basic parts of it every time and just want to incrementally build the upper layers of the hierarchy.

I build the images by means of a Makefile. I do this because I'm admittedly lazy and don't want to enter the whole docker build commands manually every time. And also because I want to avoid making mistakes in the process.

What I would like to do now is make make able to detect whether a Docker image has to be rebuild instead of Docker itself because for the latter the Docker build context has to be sent to the Docker daemon every time. The image is quite large because it is based on ubuntu:xenial and so the "Sending build context to Docker daemon" always takes a lot of time for each individual Docker image, independently of whether they need to be rebuilt or not.

If make was able to detect whether the docker build command needs to be executed that would help a lot to speed up the process.

So I would like to know if there's a way for make to detect if a specific Docker image needs to be rebuilt.

答:
Assuming:

your docker images are named dia, dib, dic...

their respective docker files are named dockerfile.dia, dockerfile.dib, dockerfile.dic...

their corresponding build directories are ./dia.dir/, ./dib.dir/, ./dic.dir/...

dia depends on files foo, bar in ./dia.dir/

dib depends on file cuz in ./dib.dir/ and the docker image dia

dic depends on file baz in ./dic.dir/ and the docker image dib

you can try something like (not tested):

```<code>DOCKERIMAGES := dia dib dic
TAGS := $(patsubst %,.%.tag,$(DOCKERIMAGES))
diaDEPS := foo bar
dibDEPS := cuz
dicDEPS := baz

all: $(TAGS)

$(TAGS): .%.tag: dockerfile.%
    docker build -f $< -t $* $*.dir && \
    echo '$* image built' && \
    touch $@

define DEPS_rule
.$(1).tag: $$(addprefix $(1).dir/,$$($(1)DEPS))
endef

$(foreach d,$(DOCKERIMAGES),$(eval $(call DEPS_rule,$(d))))

.dib.tag: .dia.tag
.dic.tag: .dib.tag

clean:
    rm -f $(TAGS)
</code>```

It should rebuild the docker images only if their docker file changed, or the files they depend on in their directories changed, or the docker image they depend on, changed.

Body:
Assuming:

your docker images are named dia, dib, dic...

their respective docker files are named dockerfile.dia, dockerfile.dib, dockerfile.dic...

their corresponding build directories are ./dia.dir/, ./dib.dir/, ./dic.dir/...

dia depends on files foo, bar in ./dia.dir/

dib depends on file cuz in ./dib.dir/ and the docker image dia

dic depends on file baz in ./dic.dir/ and the docker image dib

you can try something like (not tested):

DOCKERIMAGES := dia dib dic
TAGS := $(patsubst %,.%.tag,$(DOCKERIMAGES))
diaDEPS := foo bar
dibDEPS := cuz
dicDEPS := baz

all: $(TAGS)

$(TAGS): .%.tag: dockerfile.%
    docker build -f $< -t $* $*.dir && \
    echo '$* image built' && \
    touch $@

define DEPS_rule
.$(1).tag: $$(addprefix $(1).dir/,$$($(1)DEPS))
endef

$(foreach d,$(DOCKERIMAGES),$(eval $(call DEPS_rule,$(d))))

.dib.tag: .dia.tag
.dic.tag: .dib.tag

clean:
    rm -f $(TAGS)

It should rebuild the docker images only if their docker file changed, or the files they depend on in their directories changed, or the docker image they depend on, changed.


问:
Receive email with AWS SES without MX record
I'll like to process incoming email on a specific email. In aws docs it says

Although you are not required to publish an MX record to receive mail through Amazon SES, if you don't publish the record, Amazon SES will receive mail for your domain only if you explicitly route it to Amazon SES.

http://docs.aws.amazon.com/ses/latest/DeveloperGuide/receiving-email-mx-record.html

How do I explicitly route email to SES?

答:
After hours of research and failed attempts of having SES receive emails without the use of a MX record (had set up an additional Route via gSuite / Google Apps), here is my best suggestion on how to go about this.

Short Version

Create a subdomain and point its MX record to SES after inserting the TXT verification record.
 After creating the necessary ruleset to receive and save email from any@sub.domain.com, you can now have SES receive email from any email address you own (even if it's not verified with SES) by simply forwarding its emails to the SES enabled subdomain email address.

Long Version

Unfortunately, it does still require an MX record, but check it out...

You can create a custom subdomain on your primary domain and call it anything. In my case, I called it ses.mydomain.com
Next, I added my newly created subdomain to SES via the Domains link.

Immediately upon adding it as a domain to SES, a pop-up window appears displaying the required TXT verification record and MX mail record.

Shortly after assigning these two DNS records to my subdomain, the subdomain is verified and able to receive email after setting a few quick rules via Rule Sets!

Here's the cool part - you can still have SES receive email from any email address you have access to.

How you might ask?

By just setting up a forwarder on the email address you do want to send to SES, by forwarding it to the SES-enabled subdomain email address.

Meaning - If SES is able to receive email from someone@ses.example.com, but you want it to actually receive email from someone-else@example.com, then all you need to do is forward someone-else@example.com to someone@ses.example.com!

Remember, you still need to create the necessary rules to receive emails. See this AWS Blog Post for more information.


问:
How to center a div fixed over another?
I am trying to center a div (overlay) over another. I've managed to center it inside the div. But then it will be cut off and not stick to the center when the content of the parent is scrolled. Unfortunately, the overlay cannot just be set to fixed: https://stackoverflow.com/a/20621323/1981832.

Here is my code so far:

https://codepen.io/anon/pen/PjyYwV

.parent {
  position: relative;
  height: 50px;
  width: 200px;
  border: 1px solid blue;
  white-space:nowrap;
  overflow: scroll;
}

.overlay {
  position: absolute;
  margin: auto;
  top: 0;
  left: 0;
  bottom: 0;
  right: 0;
  height: 100px;
  width: 100px;
  background-color: red;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="parent">
  <div class="overlay"></div>
  Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.
</div></code>```

答:
Found a way to get what I wanted. However, I consider it non-ideal since it needs an additional wrapper element.

.parent {
  position: relative;
  height: 50px;
  width: 200px;
  border: 1px solid blue;
  white-space:nowrap;
  overflow: scroll;
}

.wrapper {
  position: relative;
  display: inline-block;
  border: 1px solid red;
}

.overlay {
  position: absolute;
  margin: auto;
  top: 0;
  left: 0;
  bottom: 0;
  right: 0;
  height: 100px;
  width: 100px;
  background-color: red;
  z-index: 100;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="wrapper">
  <div class="overlay"></div>
  <div class="parent">
    Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.
  </div>
</div></code>```

Title: How to center a div fixed over another?

Body:
I am trying to center a div (overlay) over another. I've managed to center it inside the div. But then it will be cut off and not stick to the center when the content of the parent is scrolled. Unfortunately, the overlay cannot just be set to fixed: https://stackoverflow.com/a/20621323/1981832.

Here is my code so far:

https://codepen.io/anon/pen/PjyYwV

.parent {
  position: relative;
  height: 50px;
  width: 200px;
  border: 1px solid blue;
  white-space:nowrap;
  overflow: scroll;
}

.overlay {
  position: absolute;
  margin: auto;
  top: 0;
  left: 0;
  bottom: 0;
  right: 0;
  height: 100px;
  width: 100px;
  background-color: red;
}

  Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.

Body:
Found a way to get what I wanted. However, I consider it non-ideal since it needs an additional wrapper element.

.parent {
  position: relative;
  height: 50px;
  width: 200px;
  border: 1px solid blue;
  white-space:nowrap;
  overflow: scroll;
}

.wrapper {
  position: relative;
  display: inline-block;
  border: 1px solid red;
}

.overlay {
  position: absolute;
  margin: auto;
  top: 0;
  left: 0;
  bottom: 0;
  right: 0;
  height: 100px;
  width: 100px;
  background-color: red;
  z-index: 100;
}

<div class="wrapper">
  <div class="overlay"></div>
  <div class="parent">
    Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.
  </div>
</div>


问:
edit text in android
hi
i want to restrict the special characters (!,@,#,$ etc.) from entering in to Edit Text field in android. how to do this please any body help..
thnx.</p>

答: You need to use input filter and set it on Edit Text with setFilters method</p>

Title: edit text in android


问:
how to fetch data in single array instead of arrays of arrays
Controller:

```<code>$student = $this->school_model->get_school_students($institute);
echo "```";
print_r($student);
echo implode(',',$student);
exit;
```

<p>Model:       </p>

```function get_school_students($institute=''){
    $query=$this->db->query("SELECT id FROM users as u where
    u.current_educational_institution = '$institute' and u.deleted=0 AND     u.role=2");
    $result=$query->result_array();
    if($query->num_rows()>0){
        // $output=array();
        $output=$result;
    }
    return $output;
}
```

<p>Output:     </p>

```Array
(
    [0] => Array
        (
            [id] => 280
        )

    [1] => Array
        (
            [id] => 282
        )
)

Array,Array ......
```

I want to echo 280,282 from implode but it is showing array array??? help me?

答:
Reason:- Data that you are getting from function is multi-dimensional-array and implode() works on single-dimensional-array .That's why you are facing problem.

Solution:-

convert your multi-dimensional-array to single-dimensional-array using array_colum()like below:-

```<code>echo implode(',',array_column($student,'id'));
</code>```

Output:-https://eval.in/829544

Reference:- array_column()

Body:
Controller:

$student = $this->school_model->get_school_students($institute);
echo "
";
print_r($student);
echo implode(',',$student);
exit;

Model:

function get_school_students($institute=''){
    $query=$this->db->query("SELECT id FROM users as u where
    u.current_educational_institution = '$institute' and u.deleted=0 AND     u.role=2");
    $result=$query->result_array();
    if($query->num_rows()>0){
        // $output=array();
        $output=$result;
    }
    return $output;
}

Output:

Array
(
    [0] => Array
        (
            [id] => 280
        )

    [1] => Array
        (
            [id] => 282
        )
)

Array,Array ......

I want to echo 280,282 from implode but it is showing array array??? help me?

Body:
Reason:- Data that you are getting from function is multi-dimensional-array and implode() works on single-dimensional-array .That's why you are facing problem.

Solution:-

convert your multi-dimensional-array to single-dimensional-array using array_colum()like below:-

echo implode(',',array_column($student,'id'));

Output:-https://eval.in/829544

Reference:- array_column()


问:
Why Status Bar Color Not Changing?
I have this code :

```<code>import React from 'react';
import { View, StatusBar } from 'react-native';

export default class App extends React.Component {
  render() {
    return (
      <View>
         <StatusBar
           backgroundColor="blue"
           barStyle="light-content"
         />
       </View>
    );
  }
}
</code>```

and I run it under EXPO apps on Android 6 - MiUI 8.5. My question is, why status bar still in white. not blue? and nothing is changed. I only got blank white screen (because status bar text in MiUI is also white).

答: I closed the EXPO app and start it once again. and it works. I think the problem is with the EXPO app.</p>

Title: Why Status Bar Color Not Changing?

Body:
I have this code :

import React from 'react';
import { View, StatusBar } from 'react-native';

export default class App extends React.Component {
  render() {
    return (
      <View>
         <StatusBar
           backgroundColor="blue"
           barStyle="light-content"
         />
       </View>
    );
  }
}

and I run it under EXPO apps on Android 6 - MiUI 8.5. My question is, why status bar still in white. not blue? and nothing is changed. I only got blank white screen (because status bar text in MiUI is also white).


问:
How do I get the wxpython combo box selection and change value?
```<code># -*- coding: utf-8 -*-
import wx

class Main(wx.Frame):
    def __init__(self):
        wx.Frame.__init__(self, None, size=(430,550))
        self.mainPanel = wx.Panel(self, size=(0,500))

        self.data1 = [1,2,3]
        self.data2 = ['google','amazon']

        self.listCtrl = wx.ListCtrl(self.mainPanel, size=(0,0), style=wx.LC_REPORT|wx.BORDER_SUNKEN)
        self.listCtrl.InsertColumn(0, 'ONE', format=wx.LIST_FORMAT_CENTRE, width=wx.LIST_AUTOSIZE_USEHEADER)
        self.listCtrl.InsertColumn(1, 'TWO', format=wx.LIST_FORMAT_CENTRE, width=wx.LIST_AUTOSIZE)
        self.listCtrl.InsertColumn(2, 'THREE', format=wx.LIST_FORMAT_CENTRE, width=wx.LIST_AUTOSIZE)

        self.ComboBoxs = wx.ComboBox(self.mainPanel, choices=self.data2, style=wx.CB_READONLY)
        self.ComboBoxs.Bind(wx.EVT_COMBOBOX, self.ComboSelect, self.ComboBoxs)

        self.textLabel = wx.StaticText(self.mainPanel)
        self.autoRefreshCount = 0

        self.BoxSizer = wx.BoxSizer(wx.VERTICAL)
        self.BoxSizer.Add(self.ComboBoxs, 0, wx.ALL, 5)
        self.BoxSizer.Add(self.listCtrl, 1, wx.EXPAND | wx.ALL, 5)
        self.BoxSizer.Add(self.textLabel, 0, wx.EXPAND | wx.ALL, 5)
        self.mainPanel.SetSizer(self.BoxSizer)

        self.timer = wx.Timer(self)
        self.Bind(wx.EVT_TIMER, self.autoRefresh, self.timer)
        self.timer.Start(5000)

        self.ComboSelect(self)

    def ComboSelect(self, event):
        self.listCtrl.Append(self.data1)

    def autoRefresh(self, evnet):
        if self.ComboBoxs.GetStringSelection() in self.data2:
            self.ComboSelect(self)
            self.textLabel.SetLabel('count : ' + str(self.autoRefreshCount))
            self.autoRefreshCount += 1
        else:
            self.textLabel.SetLabel('count : ' + str(0))
            self.autoRefreshCount = 0

if __name__ == '__main__':
    app = wx.App()
    frame = Main()
    frame.Show(True)
    app.MainLoop()
</code>```

I have created an automatic import after the combo box selection value.

If the problem changes the combo box selection, the changed value self.textLabel.SetLabel ('count:' + str (self.autoRefreshCount)) must be initialized.

I've tried a lot but I do not know how to do it.

if self.ComboBoxs.GetStringSelection () in self.data2: There seems to be a problem in the conditional expression.

答:
It is not clear what you are trying to achieve in this code.

Your test if self.ComboBoxs.GetStringSelection() in self.data2: is always going to be True because self.ComboBoxs is read only and therefore cannot change, so whatever the selection is, it will always be in self.data2.

Try the following replacement and see if it gets you closer to what you want.

```<code>    def ComboSelect(self, event):
#        self.listCtrl.Append(self.data1)
        self.autoRefreshCount = 0

    def autoRefresh(self, evnet):
#        if self.ComboBoxs.GetStringSelection() in self.data2:
#            self.ComboSelect(self)
        self.listCtrl.Append(self.data1)
        self.textLabel.SetLabel('count : ' + str(self.autoRefreshCount))
        self.autoRefreshCount += 1
#        else:
#            self.textLabel.SetLabel('count : ' + str(0))
#            self.autoRefreshCount = 0
</code>```

Edit:

based on your comment, I suspect that you want is EVT_TEXT this event fires when the text in the combobox changes.

Bind it like this and see if this was what you were looking for.

```<code>self.ComboBoxs.Bind(wx.EVT_TEXT, self.ComboChange, self.ComboBoxs)
</code>```

Body:
# -*- coding: utf-8 -*-
import wx

class Main(wx.Frame):
    def __init__(self):
        wx.Frame.__init__(self, None, size=(430,550))
        self.mainPanel = wx.Panel(self, size=(0,500))

        self.data1 = [1,2,3]
        self.data2 = ['google','amazon']

        self.listCtrl = wx.ListCtrl(self.mainPanel, size=(0,0), style=wx.LC_REPORT|wx.BORDER_SUNKEN)
        self.listCtrl.InsertColumn(0, 'ONE', format=wx.LIST_FORMAT_CENTRE, width=wx.LIST_AUTOSIZE_USEHEADER)
        self.listCtrl.InsertColumn(1, 'TWO', format=wx.LIST_FORMAT_CENTRE, width=wx.LIST_AUTOSIZE)
        self.listCtrl.InsertColumn(2, 'THREE', format=wx.LIST_FORMAT_CENTRE, width=wx.LIST_AUTOSIZE)

        self.ComboBoxs = wx.ComboBox(self.mainPanel, choices=self.data2, style=wx.CB_READONLY)
        self.ComboBoxs.Bind(wx.EVT_COMBOBOX, self.ComboSelect, self.ComboBoxs)

        self.textLabel = wx.StaticText(self.mainPanel)
        self.autoRefreshCount = 0

        self.BoxSizer = wx.BoxSizer(wx.VERTICAL)
        self.BoxSizer.Add(self.ComboBoxs, 0, wx.ALL, 5)
        self.BoxSizer.Add(self.listCtrl, 1, wx.EXPAND | wx.ALL, 5)
        self.BoxSizer.Add(self.textLabel, 0, wx.EXPAND | wx.ALL, 5)
        self.mainPanel.SetSizer(self.BoxSizer)

        self.timer = wx.Timer(self)
        self.Bind(wx.EVT_TIMER, self.autoRefresh, self.timer)
        self.timer.Start(5000)

        self.ComboSelect(self)

    def ComboSelect(self, event):
        self.listCtrl.Append(self.data1)

    def autoRefresh(self, evnet):
        if self.ComboBoxs.GetStringSelection() in self.data2:
            self.ComboSelect(self)
            self.textLabel.SetLabel('count : ' + str(self.autoRefreshCount))
            self.autoRefreshCount += 1
        else:
            self.textLabel.SetLabel('count : ' + str(0))
            self.autoRefreshCount = 0

if __name__ == '__main__':
    app = wx.App()
    frame = Main()
    frame.Show(True)
    app.MainLoop()

I have created an automatic import after the combo box selection value.

If the problem changes the combo box selection, the changed value self.textLabel.SetLabel ('count:' + str (self.autoRefreshCount)) must be initialized.

I've tried a lot but I do not know how to do it.

if self.ComboBoxs.GetStringSelection () in self.data2: There seems to be a problem in the conditional expression.

Body:
It is not clear what you are trying to achieve in this code.

Your test if self.ComboBoxs.GetStringSelection() in self.data2: is always going to be True because self.ComboBoxs is read only and therefore cannot change, so whatever the selection is, it will always be in self.data2.

Try the following replacement and see if it gets you closer to what you want.

    def ComboSelect(self, event):
#        self.listCtrl.Append(self.data1)
        self.autoRefreshCount = 0

    def autoRefresh(self, evnet):
#        if self.ComboBoxs.GetStringSelection() in self.data2:
#            self.ComboSelect(self)
        self.listCtrl.Append(self.data1)
        self.textLabel.SetLabel('count : ' + str(self.autoRefreshCount))
        self.autoRefreshCount += 1
#        else:
#            self.textLabel.SetLabel('count : ' + str(0))
#            self.autoRefreshCount = 0

Edit:

based on your comment, I suspect that you want is EVT_TEXT this event fires when the text in the combobox changes.

Bind it like this and see if this was what you were looking for.

self.ComboBoxs.Bind(wx.EVT_TEXT, self.ComboChange, self.ComboBoxs)


问:
How to determine if google auth2.signIn() window was closed by the user?
Im implementing auth using this and am currently showing a loading icon in React when a user clicks the button to sign in and the auth2 account selection/login window shows.

However if a user closes the window, there doesnt seem to be any event fired i.e the signIn() function which returns a promise never resolves, I would have thought google would return an error for this promise if the window is closed. As a result there is no way for me to stop showing the loader icon and reshow the login menu.

I was wondering if anyone had a solution for this?

答:
I try to modifiy my code that call Google OAuth 2.0 window.

You only have to add extra AJAX method that cover what is Google OAuth error result.

```<code>gapi.auth2.getAuthInstance().signIn()
</code>```

Change it to this one,

```<code>gapi.auth2.getAuthInstance().signIn().then(function(response){
    //If Google OAuth 2 works fine
    console.log(response);
}, function(error){
    //If Google OAuth 2 occured error
    console.log(error);
    if(error.error === 'popup_closed_by_user'){
        alert('Oh Dude, Why you close authentication user window...!');
    }
});
</code>```

That's it...

For more detail about Google OAuth 2.0 information, you can visit this link.

https://developers.google.com/api-client-library/javascript/samples/samples#authorizing-and-making-authorized-requests

Sample code on JavaScript:

https://github.com/google/google-api-javascript-client/blob/master/samples/authSample.html

Body:
I try to modifiy my code that call Google OAuth 2.0 window.

You only have to add extra AJAX method that cover what is Google OAuth error result.

gapi.auth2.getAuthInstance().signIn()

Change it to this one,

gapi.auth2.getAuthInstance().signIn().then(function(response){
    //If Google OAuth 2 works fine
    console.log(response);
}, function(error){
    //If Google OAuth 2 occured error
    console.log(error);
    if(error.error === 'popup_closed_by_user'){
        alert('Oh Dude, Why you close authentication user window...!');
    }
});

That's it...

For more detail about Google OAuth 2.0 information, you can visit this link.

https://developers.google.com/api-client-library/javascript/samples/samples#authorizing-and-making-authorized-requests

Sample code on JavaScript:

https://github.com/google/google-api-javascript-client/blob/master/samples/authSample.html


答:
It's kind of weird that you need to do this. So I warn you that you might be doing something wrong.

Anyway, here's a solution that uses regex:

```<code>var match = Regex.Match(yourSQLString, "^.+@(\\w+) .+$");
var result = match.Groups[1].Value;
</code>```

Title: How to get the character between a character and a space

Body:
It's kind of weird that you need to do this. So I warn you that you might be doing something wrong.

Anyway, here's a solution that uses regex:

var match = Regex.Match(yourSQLString, "^.+@(\\w+) .+$");
var result = match.Groups[1].Value;


问:
Show "duplicate Number" when number is not found in range
```<code>If MoneyTextBox.Value = range("H:H").Find(MoneyTextBox.Value) Then
    MsgBox "Duplicate number"
EndIf
</code>```

答:
Use this instead:</p>

```<code>If Not IsError(Application.Match(CLng(MoneyTextBox.Value), Range("H:H"), 0)) Then
    MsgBox "Duplicate number"
EndIf
</code>```

Body:
Use this instead:

If Not IsError(Application.Match(CLng(MoneyTextBox.Value), Range("H:H"), 0)) Then
    MsgBox "Duplicate number"
EndIf


问:
Duplicated Rows with UNIQUE INDEX MySQL and NULL Columns
Table Sufix:
id, name

```<code>(3, 'com')
</code>```

Table DomainName:
id, name

```<code>(2, 'microsoft')
</code>```

Table Domain:
id, name_code, sufix

```<code>(1, 2, 3)    -- microsoft.com
</code>```

Table SubDomainName:

```<code>(4, 'windows')
</code>```

Table SubDomain:
id, name_code, domain

```<code>(7, 4, 1)     -- windows.microsoft.com
</code>```

Table Email:
id, name, atserver

```<code>(3, 'myemail', 7)    -- myemail@windows.microsoft.com
(4, 'other', 1)      -- other@microsoft.com
</code>```

Here is a problem of foreign key constraints. How can I resolve domains and subdomains to create emails correctly? I'm having problems with Unique INDEX with NULL values, for example, a solution maybe:

Table Email:
id, name, subdomain, domain

```<code>(3, 'myemail', 7, NULL)  -- myemail@windows.microsoft.com
(4, 'other', NULL, 1)    -- other@microsoft.com
</code>```

BUT

```<code>(5, 'newemail', NULL, NULL)  -- will duplicated values in the table
(6, 'newemail', NULL, NULL)
(7, 'newemail', NULL, NULL)
(8, 'newemail', NULL, NULL)
</code>```

AND

```<code>(**3**, 'myemail', 7, 1)   -- myemail@windows.microsoft.com and myemail@microsoft.com
</code>```

答:
Unique in MySQL does only check non-NULL values to be unique.
So if you don't like to have more than one of theese lines:

```<code>(6, 'newemail', NULL, NULL)
</code>```

You have to put a unique index over theese last two fields and put values other than NULL (i.e. 0) in them

```<code>(6, 'newemail', 0, 0)
</code>```

Then MySQL will prevent multiple entries.

Body:
Table Sufix:
id, name

(3, 'com')

Table DomainName:
id, name

(2, 'microsoft')

Table Domain:
id, name_code, sufix

(1, 2, 3)    -- microsoft.com

Table SubDomainName:

(4, 'windows')

Table SubDomain:
id, name_code, domain

(7, 4, 1)     -- windows.microsoft.com

Table Email:
id, name, atserver

(3, 'myemail', 7)    -- myemail@windows.microsoft.com
(4, 'other', 1)      -- other@microsoft.com

Here is a problem of foreign key constraints. How can I resolve domains and subdomains to create emails correctly? I'm having problems with Unique INDEX with NULL values, for example, a solution maybe:

Table Email:
id, name, subdomain, domain

(3, 'myemail', 7, NULL)  -- myemail@windows.microsoft.com
(4, 'other', NULL, 1)    -- other@microsoft.com

BUT

(5, 'newemail', NULL, NULL)  -- will duplicated values in the table
(6, 'newemail', NULL, NULL)
(7, 'newemail', NULL, NULL)
(8, 'newemail', NULL, NULL)

AND

(**3**, 'myemail', 7, 1)   -- myemail@windows.microsoft.com and myemail@microsoft.com

Body:
Unique in MySQL does only check non-NULL values to be unique.
So if you don't like to have more than one of theese lines:

(6, 'newemail', NULL, NULL)

You have to put a unique index over theese last two fields and put values other than NULL (i.e. 0) in them

(6, 'newemail', 0, 0)

Then MySQL will prevent multiple entries.


问:
Recommender System (SVD) with TensorFlow
I'm trying to create a collaborative filtering algorithm to suggest products to certain users.

I started shortly and started working with TensorFlow (I thought it was sufficiently effective and flexible).
I found this code that does what I'm interested in, creates the model and train the user IDs, products, and ratings: https://github.com/songgc/TF-recomm

I launched the code and trained the model.

After training the model I would need to make the predictions, that is, get suggestions for each user so that they can be saved in a DB from which I access with a NODE.js application.

How do I retrieve this list of suggestions for each user when the training is done?

```<code>if __name__ == '__main__':
    df_train, df_test=get_data()
    svd(df_train, df_test)
    print("Done!")
</code>```

答:
You need to modify the prediction part of your code to output top K recommended products. The current code where the prediction is made is :

```<code> embd_user = tf.nn.embedding_lookup(w_user, user_batch, name="embedding_user")
 embd_item = tf.nn.embedding_lookup(w_item, item_batch, name="embedding_item")
 infer = tf.reduce_sum(tf.multiply(embd_user, embd_item), 1)
</code>```

Here the embed_user is the user embeddings of a particular user and embd_item is for the particular item. So instead of comparing a particular user with a particular item, you need to change it to compare it to all items. The matrix w_item is the embeddings of all items. This can be done by:

```<code> embd_user = tf.nn.embedding_lookup(w_user, user_batch, name="embedding_user")
 # Multiply user embedding of shape: [1 x dim]
 # with every item embeddings of shape: [item_num, dim],
 # to produce rank of all items of shape: [item_num]
 predict = tf.matmul(embd_user, w_item, transpose_b=True)
</code>```

Then you can select the top k index of the maximum in the predicted output.

Body:
I'm trying to create a collaborative filtering algorithm to suggest products to certain users.

I started shortly and started working with TensorFlow (I thought it was sufficiently effective and flexible).
I found this code that does what I'm interested in, creates the model and train the user IDs, products, and ratings: https://github.com/songgc/TF-recomm

I launched the code and trained the model.

After training the model I would need to make the predictions, that is, get suggestions for each user so that they can be saved in a DB from which I access with a NODE.js application.

How do I retrieve this list of suggestions for each user when the training is done?

if __name__ == '__main__':
    df_train, df_test=get_data()
    svd(df_train, df_test)
    print("Done!")

Body:
You need to modify the prediction part of your code to output top K recommended products. The current code where the prediction is made is :

 embd_user = tf.nn.embedding_lookup(w_user, user_batch, name="embedding_user")
 embd_item = tf.nn.embedding_lookup(w_item, item_batch, name="embedding_item")
 infer = tf.reduce_sum(tf.multiply(embd_user, embd_item), 1)

Here the embed_user is the user embeddings of a particular user and embd_item is for the particular item. So instead of comparing a particular user with a particular item, you need to change it to compare it to all items. The matrix w_item is the embeddings of all items. This can be done by:

 embd_user = tf.nn.embedding_lookup(w_user, user_batch, name="embedding_user")
 # Multiply user embedding of shape: [1 x dim]
 # with every item embeddings of shape: [item_num, dim],
 # to produce rank of all items of shape: [item_num]
 predict = tf.matmul(embd_user, w_item, transpose_b=True)

Then you can select the top k index of the maximum in the predicted output.


问:
AppAuth oidc invalid State error when authenticating against identity server
I've configured  an identity server 3 as an IdP for a project, we have 3 clients: MVC web, IOS and Android.
everything is good for MVC app, using Hybrid flow.

for IOS and Android, using the native oidc client (AppAuth IOS and AppAuth android) is not working, even though I configured the flow as Hybrid with PKCE.

now when I try to make a POC on android using Xamarin, and using IdentityModel.oidcClient everything works as expected, getting access, refresh and id tokens.
when using the AppAuth for IOS and android I am getting the following error:

```<code>{"type":0,"code":9,"errorDescription":"Response state param did not match request state"}
</code>```

any idea what is missing ?

I am suspecting that those two native oidc clients aren't asking for shared secret of the clients, so the flow is corrupted because of that.

答:
The data should be the same in the mobile app and in the Identity Server,

On The Server :

```<code>new Client
        {
            ClientId = "myClientId",
            ClientName = "myClientName",
            AllowedGrantTypes = GrantTypes.CodeAndClientCredentials,
            RequireConsent = false,

            ClientSecrets =
            {
                new Secret("myClientSecret".Sha256())
            },

            RedirectUris = { "myRedirectUri://callback" },

            AllowedScopes =
            {
                IdentityServerConstants.StandardScopes.OpenId,
                IdentityServerConstants.StandardScopes.Profile,
                IdentityServerConstants.StandardScopes.Email,
                IdentityServerConstants.StandardScopes.Phone,
            },

            AllowOfflineAccess = true
        }
</code>```

On click login in android :

```<code>    AuthManager authManager = AuthManager.getInstance(this);
    AuthorizationService authService = authManager.getAuthService();
    Auth auth = authManager.getAuth();

    AuthorizationRequest authRequest = new AuthorizationRequest
        .Builder(
        authManager.getAuthConfig(),
        auth.getClientId(),
        auth.getResponseType(),
        Uri.parse(auth.getRedirectUri()))
        .setScope(auth.getScope())
        .build();

    Intent authIntent = new Intent(this, LoginAuthActivity.class);
    PendingIntent pendingIntent = PendingIntent.getActivity(this, authRequest.hashCode(), authIntent, 0);

    authService.performAuthorizationRequest(
        authRequest,
        pendingIntent);
</code>```

Ask for the token :

```<code>    final AuthorizationResponse resp = AuthorizationResponse.fromIntent(getIntent());
    AuthorizationException ex = AuthorizationException.fromIntent(getIntent());

    final AuthManager authManager = AuthManager.getInstance(this);
    authManager.setAuthState(resp,ex);

    if (resp != null) {

        ClientSecretPost clientSecretPost = new ClientSecretPost(authManager.getAuth().getClientSecret());
        TokenRequest tokenRequest = new TokenRequest
            .Builder(authManager.getAuthConfig(), authManager.getAuth().getClientId())
            .setAuthorizationCode(resp.authorizationCode)
            .setRedirectUri(Uri.parse(authManager.getAuth().getRedirectUri()))
            .build();

        mAuthService = authManager.getAuthService();

        mAuthService.performTokenRequest(tokenRequest, clientSecretPost, new AuthorizationService.TokenResponseCallback() {
            @Override public void onTokenRequestCompleted(@Nullable TokenResponse response, @Nullable AuthorizationException ex) {
                if(ex == null) {
                    authManager.updateAuthState(response,ex);
                    MyApp.Token = authManager.getAuthState().getIdToken();
                    startService(new Intent(LoginAuthActivity.this, TokenService.class));
                    Intent mainIntent = new Intent(LoginAuthActivity.this, MainActivity.class);
                    startActivity(mainIntent);
                    finish();
                }
                else{
                    Intent loginIntent = new Intent(LoginAuthActivity.this, LoginActivity.class);
                    startActivity(loginIntent);
                    finish();
                }
            }
        });

        // authorization completed
    } else {
        // authorization failed, check ex for more details
        Intent loginIntent = new Intent(LoginAuthActivity.this, LoginActivity.class);
        startActivity(loginIntent);
        finish();
    }
</code>```

The AuthManager Class :

```<code>public class AuthManager {
private static AuthManager instance;
private AuthState mAuthState;
private Auth mAuth;
private AuthorizationServiceConfiguration mAuthConfig;
private SharedPreferencesRepository mSharedPrefRep;
private AuthorizationService mAuthService;

public static AuthManager getInstance(Context context) {
    if (instance == null) {
        instance = new AuthManager(context);
    }
    return instance;
}

private AuthManager(Context context){
    mSharedPrefRep = new SharedPreferencesRepository(context);
    setAuthData();
    mAuthConfig = new AuthorizationServiceConfiguration(
            Uri.parse(mAuth.getAuthorizationEndpointUri()),
            Uri.parse(mAuth.getTokenEndpointUri()),
            null);
    mAuthState = mSharedPrefRep.getAuthState();

    mAuthService = new AuthorizationService(context);
}

public AuthorizationServiceConfiguration getAuthConfig() {
    return mAuthConfig;
}

public Auth getAuth() {
    if(mAuth == null){
       setAuthData();
    }

    return mAuth;
}

public AuthState getAuthState(){
    return mAuthState;
}

public void updateAuthState(TokenResponse response, AuthorizationException ex){
    mAuthState.update(response,ex);
    mSharedPrefRep.saveAuthState(mAuthState);
}

public void setAuthState(AuthorizationResponse response, AuthorizationException ex){
    if(mAuthState == null)
        mAuthState = new AuthState(response,ex);

    mSharedPrefRep.saveAuthState(mAuthState);
}

public AuthorizationService getAuthService(){
    return mAuthService;
}

private void setAuthData(){
    mAuth = new Auth();
    mAuth.setClientId(BuildConfig.CLIENT_ID);
    mAuth.setAuthorizationEndpointUri(BuildConfig.AUTHORIZSTION_END_POINT_URI);
    mAuth.setClientSecret(BuildConfig.CLIENT_SECRET);
    mAuth.setRedirectUri(BuildConfig.REDIRECT_URI);
    mAuth.setScope(BuildConfig.SCOPE);
    mAuth.setTokenEndpointUri(BuildConfig.TOKEN_END_POINT_URI);
    mAuth.setResponseType(BuildConfig.RESPONSE_TYPE);
}
}
</code>```

The Service here will ask for the refresh token.

I have made a sample using Identity Server 4 with AppAuth-Android you can check it here

Body:
I've configured  an identity server 3 as an IdP for a project, we have 3 clients: MVC web, IOS and Android.
everything is good for MVC app, using Hybrid flow.

for IOS and Android, using the native oidc client (AppAuth IOS and AppAuth android) is not working, even though I configured the flow as Hybrid with PKCE.

now when I try to make a POC on android using Xamarin, and using IdentityModel.oidcClient everything works as expected, getting access, refresh and id tokens.
when using the AppAuth for IOS and android I am getting the following error:

{"type":0,"code":9,"errorDescription":"Response state param did not match request state"}

any idea what is missing ?

I am suspecting that those two native oidc clients aren't asking for shared secret of the clients, so the flow is corrupted because of that.

Body:
The data should be the same in the mobile app and in the Identity Server,

On The Server :

new Client
        {
            ClientId = "myClientId",
            ClientName = "myClientName",
            AllowedGrantTypes = GrantTypes.CodeAndClientCredentials,
            RequireConsent = false,

            ClientSecrets =
            {
                new Secret("myClientSecret".Sha256())
            },

            RedirectUris = { "myRedirectUri://callback" },

            AllowedScopes =
            {
                IdentityServerConstants.StandardScopes.OpenId,
                IdentityServerConstants.StandardScopes.Profile,
                IdentityServerConstants.StandardScopes.Email,
                IdentityServerConstants.StandardScopes.Phone,
            },

            AllowOfflineAccess = true
        }

On click login in android :

    AuthManager authManager = AuthManager.getInstance(this);
    AuthorizationService authService = authManager.getAuthService();
    Auth auth = authManager.getAuth();

    AuthorizationRequest authRequest = new AuthorizationRequest
        .Builder(
        authManager.getAuthConfig(),
        auth.getClientId(),
        auth.getResponseType(),
        Uri.parse(auth.getRedirectUri()))
        .setScope(auth.getScope())
        .build();

    Intent authIntent = new Intent(this, LoginAuthActivity.class);
    PendingIntent pendingIntent = PendingIntent.getActivity(this, authRequest.hashCode(), authIntent, 0);

    authService.performAuthorizationRequest(
        authRequest,
        pendingIntent);

Ask for the token :

    final AuthorizationResponse resp = AuthorizationResponse.fromIntent(getIntent());
    AuthorizationException ex = AuthorizationException.fromIntent(getIntent());

    final AuthManager authManager = AuthManager.getInstance(this);
    authManager.setAuthState(resp,ex);

    if (resp != null) {

        ClientSecretPost clientSecretPost = new ClientSecretPost(authManager.getAuth().getClientSecret());
        TokenRequest tokenRequest = new TokenRequest
            .Builder(authManager.getAuthConfig(), authManager.getAuth().getClientId())
            .setAuthorizationCode(resp.authorizationCode)
            .setRedirectUri(Uri.parse(authManager.getAuth().getRedirectUri()))
            .build();

        mAuthService = authManager.getAuthService();

        mAuthService.performTokenRequest(tokenRequest, clientSecretPost, new AuthorizationService.TokenResponseCallback() {
            @Override public void onTokenRequestCompleted(@Nullable TokenResponse response, @Nullable AuthorizationException ex) {
                if(ex == null) {
                    authManager.updateAuthState(response,ex);
                    MyApp.Token = authManager.getAuthState().getIdToken();
                    startService(new Intent(LoginAuthActivity.this, TokenService.class));
                    Intent mainIntent = new Intent(LoginAuthActivity.this, MainActivity.class);
                    startActivity(mainIntent);
                    finish();
                }
                else{
                    Intent loginIntent = new Intent(LoginAuthActivity.this, LoginActivity.class);
                    startActivity(loginIntent);
                    finish();
                }
            }
        });

        // authorization completed
    } else {
        // authorization failed, check ex for more details
        Intent loginIntent = new Intent(LoginAuthActivity.this, LoginActivity.class);
        startActivity(loginIntent);
        finish();
    }

The AuthManager Class :

public class AuthManager {
private static AuthManager instance;
private AuthState mAuthState;
private Auth mAuth;
private AuthorizationServiceConfiguration mAuthConfig;
private SharedPreferencesRepository mSharedPrefRep;
private AuthorizationService mAuthService;

public static AuthManager getInstance(Context context) {
    if (instance == null) {
        instance = new AuthManager(context);
    }
    return instance;
}

private AuthManager(Context context){
    mSharedPrefRep = new SharedPreferencesRepository(context);
    setAuthData();
    mAuthConfig = new AuthorizationServiceConfiguration(
            Uri.parse(mAuth.getAuthorizationEndpointUri()),
            Uri.parse(mAuth.getTokenEndpointUri()),
            null);
    mAuthState = mSharedPrefRep.getAuthState();

    mAuthService = new AuthorizationService(context);
}

public AuthorizationServiceConfiguration getAuthConfig() {
    return mAuthConfig;
}

public Auth getAuth() {
    if(mAuth == null){
       setAuthData();
    }

    return mAuth;
}

public AuthState getAuthState(){
    return mAuthState;
}

public void updateAuthState(TokenResponse response, AuthorizationException ex){
    mAuthState.update(response,ex);
    mSharedPrefRep.saveAuthState(mAuthState);
}

public void setAuthState(AuthorizationResponse response, AuthorizationException ex){
    if(mAuthState == null)
        mAuthState = new AuthState(response,ex);

    mSharedPrefRep.saveAuthState(mAuthState);
}

public AuthorizationService getAuthService(){
    return mAuthService;
}

private void setAuthData(){
    mAuth = new Auth();
    mAuth.setClientId(BuildConfig.CLIENT_ID);
    mAuth.setAuthorizationEndpointUri(BuildConfig.AUTHORIZSTION_END_POINT_URI);
    mAuth.setClientSecret(BuildConfig.CLIENT_SECRET);
    mAuth.setRedirectUri(BuildConfig.REDIRECT_URI);
    mAuth.setScope(BuildConfig.SCOPE);
    mAuth.setTokenEndpointUri(BuildConfig.TOKEN_END_POINT_URI);
    mAuth.setResponseType(BuildConfig.RESPONSE_TYPE);
}
}

The Service here will ask for the refresh token.

I have made a sample using Identity Server 4 with AppAuth-Android you can check it here


问:
Value too long exception while changing the datatype size
Iam trying to changing the column size but getting exception like below. actually the column size is 64 bytes but trying changing to 2 bytes.

ALTER TABLE table1 ALTER COLUMN column1  type VARCHAR(2);
ERROR:  value too long for type character varying(2)

I had verified existing data also the size is less than 2 bytes.

Can anyone help me to fix this.

Thanks
Ramesh

答:
Even if the data size is less than 2 bytes, postgre won't allow you to do that.

You must manually 'limit' the size of your varchar. You can do so with doing substrings of your data. Of course if your column is already 2 bytes long, there won't be any side effect, else it will trim the variables to 2 characters.

```<code>ALTER TABLE table1 ALTER COLUMN column1 type VARCHAR(2) USING substr(column1, 1, 2)
</code>```

Note that if you want to change the column size to a bigger one, there will be no problems at all.

Body:
Even if the data size is less than 2 bytes, postgre won't allow you to do that.

You must manually 'limit' the size of your varchar. You can do so with doing substrings of your data. Of course if your column is already 2 bytes long, there won't be any side effect, else it will trim the variables to 2 characters.

ALTER TABLE table1 ALTER COLUMN column1 type VARCHAR(2) USING substr(column1, 1, 2)

Note that if you want to change the column size to a bigger one, there will be no problems at all.


问:
ReactJS: Unable to send JSON data and PDF file in one POST call
I am working on GRAILS-ReactJs based project which involves a scenario where I need to send the RESUME and the JSON data in one POST call.
However, I am able to send file in one call but the data I am getting is null.
I am using Grails-3 at my server side and receiving the POST request as multipart file. I want both JSON and Multipart file object to be combined in one object to send to the server and want to receive the file and the JSON data both at the server side.
I have tried changing the content type of the header but ut doesn't work.

答:
You can't post JSON data along with the file or any other attachment. You can post it as form data to your back end. The form data is passed as a multi-part data to the server with relevant boundaries. Here's a sample code for your reference. You may pass json data along with the formData as key, value pairs.

```<code>export function postAttachment (fileData, fileName) {
  let formData = new FormData()
  formData.append('prop1', 'value1')
  formData.append('prop2', 'value2')
  formData.append('upload', fileData, fileName)
  return fetch('/your/endpoint', {
    headers: {
      'Accept': 'application/json',
      'header1': 'headerValue1'
    },
    method: 'POST',
    body: formData
  })
}
</code>```

Hope this helps. Happy Coding !

Body:
You can't post JSON data along with the file or any other attachment. You can post it as form data to your back end. The form data is passed as a multi-part data to the server with relevant boundaries. Here's a sample code for your reference. You may pass json data along with the formData as key, value pairs.

export function postAttachment (fileData, fileName) {
  let formData = new FormData()
  formData.append('prop1', 'value1')
  formData.append('prop2', 'value2')
  formData.append('upload', fileData, fileName)
  return fetch('/your/endpoint', {
    headers: {
      'Accept': 'application/json',
      'header1': 'headerValue1'
    },
    method: 'POST',
    body: formData
  })
}

Hope this helps. Happy Coding !