问:
SQL Server: many-to-many relation
So I am having a brain meltdown when trying to figure this one out. What I have is a few database's like:

tblGenre

```<code>genreID
genreName
</code>```

tblArtist

```<code>artistID
artistName
genreID
</code>```

tblAlbum

```<code>albumID
albumName
artistID
</code>```

Everything is all well and good, and working fine. Ok, now with the question...

What I am trying to figure out is how to link an artist who has multiple names. I.e. the artist 'Prince'. I have albums from him, who I would catalog under 3 different bands; Prince (artistID=5), Prince and the new power generation (artistID=17, and "Symbol" (artistID=43)...

So, When I lookup the artist "Prince", who has a artistID of 5, how can I link the other 2 bands up to this one? Would I create a seperate database the has a comma-separated values of each artistID (i.e. 5,17,43) or is there an easier way to do this?

I don't want to go as far as the album level, of who played on every album in my database. I just want to create a link of artists who have been with multiple bands. Just a few more examples of how I would want "hooked together"...

Tom Petty (Classic Rock)

Tom Petty & the Heartbreakers (Classic Rock)

Tom Petty & the Heartbreakers (Soundtrack)

Prince (Funk)

Prince & the New Power Generation (Funk)

Mark Knopfler (Classic Rock)

Mark Knopfler (Soundtrack)

Dire Straits (Classic Rock)

Thanks for the input.

答:
I would create a table like tblRelatedArtists which has two columns: .artistID and .relatedArtistID.

When you query the database, you could inner join the tblArtist
where .artistID is in (select relatedArtistID from tblRelatedArtists as innerArtists where innerArtists.artistID = outerArtists.artistID).

Title: SQL Server: many-to-many relation

Body:
So I am having a brain meltdown when trying to figure this one out. What I have is a few database's like:

tblGenre

genreID
genreName

tblArtist

artistID
artistName
genreID

tblAlbum

albumID
albumName
artistID

Everything is all well and good, and working fine. Ok, now with the question...

What I am trying to figure out is how to link an artist who has multiple names. I.e. the artist 'Prince'. I have albums from him, who I would catalog under 3 different bands; Prince (artistID=5), Prince and the new power generation (artistID=17, and "Symbol" (artistID=43)...

So, When I lookup the artist "Prince", who has a artistID of 5, how can I link the other 2 bands up to this one? Would I create a seperate database the has a comma-separated values of each artistID (i.e. 5,17,43) or is there an easier way to do this?

I don't want to go as far as the album level, of who played on every album in my database. I just want to create a link of artists who have been with multiple bands. Just a few more examples of how I would want "hooked together"...

Tom Petty (Classic Rock)

Tom Petty & the Heartbreakers (Classic Rock)

Tom Petty & the Heartbreakers (Soundtrack)

Prince (Funk)

Prince & the New Power Generation (Funk)

Mark Knopfler (Classic Rock)

Mark Knopfler (Soundtrack)

Dire Straits (Classic Rock)

Thanks for the input.


来源: stackexchange

问:
Raspberry Pi crashes when building OpenFrameWorks project in Eclipse CDT
I'm working on a Raspberry Pi 3 with OS Raspbian Jessie. I'm using Eclipse CDT (for C/C++) and am trying to learn about OpenFrameWorks:
http://openframeworks.cc/

I installed everything according to the guides and imported everything to Eclipse. I thought it seemed to work out, but when I try to run some test-code I get the error "Unable to launch, binary not found." I look it up and find a potential solution, that I have to build the actual project first.

This is my problem, when I try to build the project Eclipse gets to about 20% and then the entire Raspberry freezes, forcing me to force a restart. How can I continue from here on out? I don't know if I still should try to build the project through Eclipse or if there is another way to actually run some test code for OpenFrameWorks.

I don't know if this is the best place to ask about this, but I'm thankful for all answers.

答:
Eclipse is super slow on Raspberry Pi.
I recommend using the provided setup scripts to install dependencies. After you compile OF, use make files to compile projects.

In terms of editing code, I recommend using a light weight text editor (geany for example). I've tried CodeBlocks and Qt Creator, which are faster/less resource intensive than eclipse, but still pretty heavy for a system with limited resources.

Another option is to combine your computer the RPi:

Use projectGenerator to generate a project for both Raspberry Pi and your computer/IDE

Edit/test/iterate on your computer

When ready to run on RPi, sync the project using your preferred method(e.g. SSH/SFTP/git/etc.), then use make -j4(to use all 4 cores) in the RPi project folder.

The pro is you the quick compile/feedback times you're used to on your computer.
The con is this method won't work for RPi specific code (e.g. accessing GPIO, PiCamera, etc.)

Another option is to setup cross compilation, but getting everything ready is a bit laborious. (Although, once it's done, it saves time on the long run).

ContentLicense: CC BY-SA 3.0


问:
RewriteCond scope in htaccess
I want to redirect non-existing files with versioned filename to the current version. There are two target files depending on a pattern in the requested filename.

For example the current file is setup-win-3-1-0.exe
A request for setup-win-2-7-1.exe (non existent) would redirect to the previous one. (And setup-mac-2-7-1.dmg would go to setup-mac-3-1-0.dmg)

```<code>RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^setup-win-[^.]+\.exe$ setup-win-%{ENV:DOWNLWIN}.exe [L,R=301,NC]
RewriteRule ^setup-mac-[^.]+\.dmg$ setup-mac-%{ENV:DOWNLMAC}.dmg [L,R=301,NC]
</code>```

(The ENV:DOWNL is set before, omited for clarity)

I've been searching the web and I find some contradictions, I've seen that RewriteCond applies only to the next RewriteRule and in other places that it applies until it fins a RweriteRule with Last flag.

Would that RewriteCond apply to both lines?

If so, when does stop that RewriteCond? (if I have more Rules following, would they still be in the scope of the Cond?)

答:
Would that RewriteCond apply to both lines?

Answer is No. RewriteCond is only applicable to the nearest RewriteRule. It is never applied to more than one rules defined using RewriteRule directive.

Alternative Approach: If you don't to want RewriteCond over and over again before all the rules then have a separate **skip-all* rule using opposite of the RewriteCond. Consider below example:

```<code>RewriteEngine

# skip all the rules *below* of comdition is met
RewriteCond %{REQUEST_FILENAME} -f
RewriteRule ^ - [L]

RewriteRule ^setup-win-[^.]+\.exe$ setup-win-%{ENV:DOWNLWIN}.exe [L,R=301,NC]

RewriteRule ^setup-mac-[^.]+\.dmg$ setup-mac-%{ENV:DOWNLMAC}.dmg [L,R=301,NC]
</code>```

Title: RewriteCond scope in htaccess

Body:
I want to redirect non-existing files with versioned filename to the current version. There are two target files depending on a pattern in the requested filename.

For example the current file is setup-win-3-1-0.exe
A request for setup-win-2-7-1.exe (non existent) would redirect to the previous one. (And setup-mac-2-7-1.dmg would go to setup-mac-3-1-0.dmg)

RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^setup-win-[^.]+\.exe$ setup-win-%{ENV:DOWNLWIN}.exe [L,R=301,NC]
RewriteRule ^setup-mac-[^.]+\.dmg$ setup-mac-%{ENV:DOWNLMAC}.dmg [L,R=301,NC]

(The ENV:DOWNL is set before, omited for clarity)

I've been searching the web and I find some contradictions, I've seen that RewriteCond applies only to the next RewriteRule and in other places that it applies until it fins a RweriteRule with Last flag.

Would that RewriteCond apply to both lines?

If so, when does stop that RewriteCond? (if I have more Rules following, would they still be in the scope of the Cond?)

Body:
Would that RewriteCond apply to both lines?

Answer is No. RewriteCond is only applicable to the nearest RewriteRule. It is never applied to more than one rules defined using RewriteRule directive.

Alternative Approach: If you don't to want RewriteCond over and over again before all the rules then have a separate **skip-all* rule using opposite of the RewriteCond. Consider below example:

RewriteEngine

# skip all the rules *below* of comdition is met
RewriteCond %{REQUEST_FILENAME} -f
RewriteRule ^ - [L]

RewriteRule ^setup-win-[^.]+\.exe$ setup-win-%{ENV:DOWNLWIN}.exe [L,R=301,NC]

RewriteRule ^setup-mac-[^.]+\.dmg$ setup-mac-%{ENV:DOWNLMAC}.dmg [L,R=301,NC]


问:
What is the difference between JavaScript promises and async await?
I have been using ECMAScript 6 and ECMAScript 7 features already (thanks to Babel) in my applications - both mobile and web.

The first step obviously was to ECMAScript 6 levels. I learnt many async patterns, the promises (which are really promising), generators (not sure why the * symbol), etc.
Out of these, promises suited my purpose pretty well. And I have been using them in my applications quite a lot.

Here is an example/pseudocode of how I have implemented a basic promise-

```<code>var myPromise = new Promise(
    function (resolve,reject) {
      var x = MyDataStore(myObj);
      resolve(x);
    });

myPromise.then(
  function (x) {
    init(x);
});
</code>```

As time passed, I came across ECMAScript 7 features, and one of them being ASYNC and AWAIT keywords/functions. These in conjunction do great wonders. I have started to replace some of my promises with async & await. They seem to add great value to programming style.

Again, here is a pseudocode of how my async, await function looks like-

```<code>async function myAsyncFunction (myObj) {
    var x = new MyDataStore(myObj);
    return await x.init();
}
var returnVal = await myAsyncFunction(obj);
</code>```

Keeping the syntax errors (if any) aside, both of them do the exact same thing is what I feel. I have almost been able to replace most of my promises with async,awaits.

Why is async,await needed when promises do a similar job?

Does async,await solve a bigger problem? Or was it just a different solution to callback hell?

As I said earlier, I am able to use promises and async,await to solve the same problem. Is there anything specific that async await solved?

Additional notes:

I have been using async,awaits and promises in my React projects and Node.js modules extensively.
React especially have been an early bird and adopted a lot of ECMAScript 6 and ECMAScript 7 features.

答:
Async/await can help make your code cleaner and more readable in cases where you need complicated control flow. It also produces more debug-friendly code. And makes it possible to handle both synchronous and asynchronous errors with just try/catch.

I recently wrote this post showing the advantages of async/await over promises in some common use cases with code examples: 6 Reasons Why JavaScript Async/Await Blows Promises Away (Tutorial)

ContentLicense: CC BY-SA 4.0

Body:
I have been using ECMAScript 6 and ECMAScript 7 features already (thanks to Babel) in my applications - both mobile and web.

The first step obviously was to ECMAScript 6 levels. I learnt many async patterns, the promises (which are really promising), generators (not sure why the * symbol), etc.
Out of these, promises suited my purpose pretty well. And I have been using them in my applications quite a lot.

Here is an example/pseudocode of how I have implemented a basic promise-

var myPromise = new Promise(
    function (resolve,reject) {
      var x = MyDataStore(myObj);
      resolve(x);
    });

myPromise.then(
  function (x) {
    init(x);
});

As time passed, I came across ECMAScript 7 features, and one of them being ASYNC and AWAIT keywords/functions. These in conjunction do great wonders. I have started to replace some of my promises with async & await. They seem to add great value to programming style.

Again, here is a pseudocode of how my async, await function looks like-

async function myAsyncFunction (myObj) {
    var x = new MyDataStore(myObj);
    return await x.init();
}
var returnVal = await myAsyncFunction(obj);

Keeping the syntax errors (if any) aside, both of them do the exact same thing is what I feel. I have almost been able to replace most of my promises with async,awaits.

Why is async,await needed when promises do a similar job?

Does async,await solve a bigger problem? Or was it just a different solution to callback hell?

As I said earlier, I am able to use promises and async,await to solve the same problem. Is there anything specific that async await solved?

Additional notes:

I have been using async,awaits and promises in my React projects and Node.js modules extensively.
React especially have been an early bird and adopted a lot of ECMAScript 6 and ECMAScript 7 features.


问:
Java 2d Array print out index at certain element
Lets say i got this :

```<code>int b[][];
b = new int[4][4];
for (int i = 0; i < b.length; i++) {
    for (int j = 0; j < b[i].length; j++) {
        b[i][j] = (Math.random() * 10);
    }
}
</code>```

And i want to print out at which [i][j] the value is < 5, how would i do this?

答:
You should to cast the value to int, because Math.random() return a double and not an int, and you have to use if to check if your value is < 5 or not, You can use this, :

```<code>...
for (int j = 0; j < b[i].length; j++) {
    b[i][j] = (int) (Math.random() * 10);
    if(b[i][j] < 5){
        System.out.println(b[i][j]);
    }
}
...
</code>```

Or you can use :

```<code>if ((b[i][j] = (int) (Math.random() * 10)) < 5) {...}
//--^--Initialization and test in one shot-^---------
</code>```

Body:
Lets say i got this :

int b[][];
b = new int[4][4];
for (int i = 0; i < b.length; i++) {
    for (int j = 0; j < b[i].length; j++) {
        b[i][j] = (Math.random() * 10);
    }
}

And i want to print out at which [i][j] the value is < 5, how would i do this?

Body:
You should to cast the value to int, because Math.random() return a double and not an int, and you have to use if to check if your value is < 5 or not, You can use this, :

...
for (int j = 0; j < b[i].length; j++) {
    b[i][j] = (int) (Math.random() * 10);
    if(b[i][j] < 5){
        System.out.println(b[i][j]);
    }
}
...

Or you can use :

if ((b[i][j] = (int) (Math.random() * 10)) < 5) {...}
//--^--Initialization and test in one shot-^---------


问:
Is there a shortcut to move between header and source file in VC++?
This is a feature I have grown accustomed to in Eclipse (Ctrl+Tab). Is there an equivalent in Visual C++?

答:
Try Visual Assist, which sports this very feature (amongst others):

http://www.wholetomato.com/

The code browsing functionality -- of which the header/cpp swap is one part -- are really good.

(I also really rated its intellisense and refactoring features, but not everybody I've spoken to has agreed with me.)

EDIT: just remembered, the Nifty Solution Plugin also does this -- plus another handly Visual Assist-like thing, though nothing else -- and they're free:

http://code.google.com/p/niftyplugins/

(The guy's perforce plugin is great, too. Much better than the default VSSCC rubbish.)

OwnerDisplayName: please delete me

ContentLicense: CC BY-SA 2.5


问:
Server returned HTTP response code: 415 Unsupported media type
I have a rest web service like below.

```<code>@POST
@Path("/startProcess")
@Produces(MediaType.TEXT_PLAIN)
@Consumes(MediaType.APPLICATION_JSON)
public String startProcess(InputParams inputParams, @Context HttpServletRequest request, @Context HttpServletResponse response) {
   ProjectBean projBean = new ProjectBean();
   Helper.loadProjectBean(inputParams, projBean);
   return "1";
}
</code>```

Now I am trying to consume it with below main program.

```<code>public static void main(String[] args) throws Exception {
    StringBuffer response = new StringBuffer();
    String taigaServiceUrl = "http://localhost:8181/restServer/rest/TestWebService/startProcess/";
    URL url = new URL(taigaServiceUrl);
    HttpURLConnection conn = (HttpURLConnection) url.openConnection();
    conn.setRequestMethod("POST");
    conn.setDoOutput(true);
    conn.setRequestProperty("Content-Type", "application/json");
    String userpass = "admin" + ":" + "admin";
    String basicAuth = "Basic " + new String(new Base64().encode(userpass.getBytes()));
    conn.setRequestProperty("Authorization", basicAuth);
    InputParams inputParams = new InputParams();
    inputParams.setXXX("xxxx");
    inputParams.setYYYY("123456");
    inputParams.setZZZZ("ZZZZ");
    String json = new Gson().toJson(inputParams);
    DataOutputStream os = new DataOutputStream (conn.getOutputStream());
    os.write(json.getBytes());
    os.flush();
    BufferedReader br = new BufferedReader(new InputStreamReader((conn.getInputStream())));
    String inputLine;
    while ((inputLine = br.readLine()) != null) {
        response.append(inputLine);
    }
    br.close();
}
</code>```

But every time I am getting below error.

```<code>Exception in thread "main" java.io.IOException: Server returned HTTP response code: 415 for URL: http://localhost:8181/restServer/rest/TestWebService/startProcess/
at sun.net.www.protocol.http.HttpURLConnection.getInputStream0(Unknown Source)
at sun.net.www.protocol.http.HttpURLConnection.getInputStream(Unknown Source)
at scm.controllers.Test.main(Test.java:64)
</code>```

As per error the media type is unsupported. In my rest webservice I am consuming JSON and in my main program I am sending JSON. Then where it is breaking?

答:
Well after lot of debugging I found solution of my problem. I needed to add below jars in classpath. Actually Jersey was not able to bind JSON object to the rest service. </p>

```<code>jackson-annotations-2.5.4.jar
jackson-core-2.5.4.jar
jackson-databind-2.5.4.jar
jackson-jaxrs-base-2.5.4.jar
jackson-jaxrs-json-provider-2.5.4.jar
jersey-entity-filtering-2.22.2.jar
jersey-media-json-jackson-2.22.2.jar
</code>```

Body:
I have a rest web service like below.

@POST
@Path("/startProcess")
@Produces(MediaType.TEXT_PLAIN)
@Consumes(MediaType.APPLICATION_JSON)
public String startProcess(InputParams inputParams, @Context HttpServletRequest request, @Context HttpServletResponse response) {
   ProjectBean projBean = new ProjectBean();
   Helper.loadProjectBean(inputParams, projBean);
   return "1";
}

Now I am trying to consume it with below main program.

public static void main(String[] args) throws Exception {
    StringBuffer response = new StringBuffer();
    String taigaServiceUrl = "http://localhost:8181/restServer/rest/TestWebService/startProcess/";
    URL url = new URL(taigaServiceUrl);
    HttpURLConnection conn = (HttpURLConnection) url.openConnection();
    conn.setRequestMethod("POST");
    conn.setDoOutput(true);
    conn.setRequestProperty("Content-Type", "application/json");
    String userpass = "admin" + ":" + "admin";
    String basicAuth = "Basic " + new String(new Base64().encode(userpass.getBytes()));
    conn.setRequestProperty("Authorization", basicAuth);
    InputParams inputParams = new InputParams();
    inputParams.setXXX("xxxx");
    inputParams.setYYYY("123456");
    inputParams.setZZZZ("ZZZZ");
    String json = new Gson().toJson(inputParams);
    DataOutputStream os = new DataOutputStream (conn.getOutputStream());
    os.write(json.getBytes());
    os.flush();
    BufferedReader br = new BufferedReader(new InputStreamReader((conn.getInputStream())));
    String inputLine;
    while ((inputLine = br.readLine()) != null) {
        response.append(inputLine);
    }
    br.close();
}

But every time I am getting below error.

Exception in thread "main" java.io.IOException: Server returned HTTP response code: 415 for URL: http://localhost:8181/restServer/rest/TestWebService/startProcess/
at sun.net.www.protocol.http.HttpURLConnection.getInputStream0(Unknown Source)
at sun.net.www.protocol.http.HttpURLConnection.getInputStream(Unknown Source)
at scm.controllers.Test.main(Test.java:64)

As per error the media type is unsupported. In my rest webservice I am consuming JSON and in my main program I am sending JSON. Then where it is breaking?

Body:
Well after lot of debugging I found solution of my problem. I needed to add below jars in classpath. Actually Jersey was not able to bind JSON object to the rest service.

jackson-annotations-2.5.4.jar
jackson-core-2.5.4.jar
jackson-databind-2.5.4.jar
jackson-jaxrs-base-2.5.4.jar
jackson-jaxrs-json-provider-2.5.4.jar
jersey-entity-filtering-2.22.2.jar
jersey-media-json-jackson-2.22.2.jar


问:
Calculate 64bit jmp for code cave in c#
i cannot solve my problem. Any help appreciated.
I want to create a jmp to my allocated memory.
If i check my calculation with cheat engine allocated memory it is fine.
Cause Cheat Engine allocates memory in a higher region.
My allocated memory is e.g: 0x870000 and the adress where i want to create the jmp is at: 7FFDE65F5184.

```<code>Console.WriteLine("toWrite: {0:x}", toWrite.ToInt64()); /*toWrite: 7FFDE65F5184*/
IntPtr allocation = VirtualAllocEx(openproc, IntPtr.Zero , 0x1024, AllocationType.Commit | AllocationType.Reserve, MemoryProtection.ExecuteReadWrite);

Console.WriteLine("allocation: {0:x}", allocation.ToInt64()); /* allocation: 870000*/

IntPtr jmp = new IntPtr((toWrite.ToInt64() - (allocation.ToInt64() + 5)));

byte[] bytes1 = BitConverter.GetBytes(jmp.ToInt64());

byte[] bytes2 = { 0, 0, 0, 0, 0, 0, 0, 0, 0, };
bytes2[0] = 233;
bytes2[1] = bytes1[0];
bytes2[2] = bytes1[1];
bytes2[3] = bytes1[2];
bytes2[4] = bytes1[3];
/*nops*/
bytes2[5] = 144;
bytes2[6] = 144;
bytes2[7] = 144;
bytes2[8] = 144;
UIntPtr written = new UIntPtr();
WriteProcessMemory(openproc, toWrite, bytes2, 9, out written);
</code>```

50% of the result is correct. anyone can help?

This is my result:

```<code>7FFDE65F5184 - E9 77AE271A           - jmp 7FFE00870000
</code>```

Why is there 7FFE00 in front of my needed jmp adress ?
if i choose another value than IntPtr.Zero in VirtualAllocEx the return value is 0 - dont know why! i know it is not well coded, but first of all i want to understand what is my problem and how i can solve this issue.

Thanks so much guys!

答: Wow guys! You ve inspired me and i got my solution ... MEM_TOP_DOWN did the job! Thanks so much!</p>

Title: Calculate 64bit jmp for code cave in c#

Body:
i cannot solve my problem. Any help appreciated.
I want to create a jmp to my allocated memory.
If i check my calculation with cheat engine allocated memory it is fine.
Cause Cheat Engine allocates memory in a higher region.
My allocated memory is e.g: 0x870000 and the adress where i want to create the jmp is at: 7FFDE65F5184.

Console.WriteLine("toWrite: {0:x}", toWrite.ToInt64()); /*toWrite: 7FFDE65F5184*/
IntPtr allocation = VirtualAllocEx(openproc, IntPtr.Zero , 0x1024, AllocationType.Commit | AllocationType.Reserve, MemoryProtection.ExecuteReadWrite);

Console.WriteLine("allocation: {0:x}", allocation.ToInt64()); /* allocation: 870000*/

IntPtr jmp = new IntPtr((toWrite.ToInt64() - (allocation.ToInt64() + 5)));

byte[] bytes1 = BitConverter.GetBytes(jmp.ToInt64());

byte[] bytes2 = { 0, 0, 0, 0, 0, 0, 0, 0, 0, };
bytes2[0] = 233;
bytes2[1] = bytes1[0];
bytes2[2] = bytes1[1];
bytes2[3] = bytes1[2];
bytes2[4] = bytes1[3];
/*nops*/
bytes2[5] = 144;
bytes2[6] = 144;
bytes2[7] = 144;
bytes2[8] = 144;
UIntPtr written = new UIntPtr();
WriteProcessMemory(openproc, toWrite, bytes2, 9, out written);

50% of the result is correct. anyone can help?

This is my result:

7FFDE65F5184 - E9 77AE271A           - jmp 7FFE00870000

Why is there 7FFE00 in front of my needed jmp adress ?
if i choose another value than IntPtr.Zero in VirtualAllocEx the return value is 0 - dont know why! i know it is not well coded, but first of all i want to understand what is my problem and how i can solve this issue.

Thanks so much guys!


问:
Change a while loop to foreach?
I'm about to change a code to "WordPress-customized code" (using $wpdb). And with $wpdb->get_results() I get an array that need to be outputted with a foreach loop. But the problem is that my current while-loop has a "$initial_hidden statement" in it that I don't know how to do with the new foreach.

Here is my current code:

```<code>while (($initial_hidden == true) || ($r = mysql_fetch_assoc($q))) {

...

}
</code>```

So, how do I get the "initial hidden" to this:

```<code>foreach ($q as $r) {

...

}
</code>```

答: Please use this line of code: $r = mysql_fetch_assoc($q); if(($initial_hidden) || (mysql_num_rows($q) > 0)) { foreach($r as $key => $value) { //result } }</p>

Title: Change a while loop to foreach?

Body:
I'm about to change a code to "WordPress-customized code" (using $wpdb). And with $wpdb->get_results() I get an array that need to be outputted with a foreach loop. But the problem is that my current while-loop has a "$initial_hidden statement" in it that I don't know how to do with the new foreach.

Here is my current code:

while (($initial_hidden == true) || ($r = mysql_fetch_assoc($q))) {

...

}

So, how do I get the "initial hidden" to this:

foreach ($q as $r) {

...

}


问:
Cast Enumeration Value to Integer in Delphi
Is it possible to cast/convert an Enumeration Value to Integer in Delphi?

If yes, then how?

答: You can use the Ord() function for this.  For clarity it may be better to write a pair of IntToEnum() and EnumToInt() functions though.</p>


问:
Laravel 5.4 Eloquent relationship sorting
I have two database tables called deliverables, and deliverable_version.

Deliverable hasMany Deliverable_Version.

Deliverable has id column, and the model has a function to get the most recent version:

```<code>public function getRecentVersion()
    {
        $deliverable_version_max = $this->versions()->max('version');

        $deliverable_version = DeliverableVersion::where([
            'version'=>$deliverable_version_max,
            'deliverable_ID'=>$this->id,
        ])->first();

        return $deliverable_version;
    }
</code>```

Deliverable_version table has id, deliverable_ID, title, message, deadline, version, created_at, updated_at.

How I would perform an operation where I can:

Get all deliverables and the most recent version associated with the deliverable.

Sort the deliverables by it by the columns of the deliverable_version table (updated_at)

Paginate the result?

Here is my attempt at it, which isn't working because it selects all the versions when I join the tables, not just the recent version:

```<code>$deliverables = Accounts::find($owner_account_ID)->deliverables();
    $deliverables = $deliverables->join('deliverable_version', 'deliverable.id', '=', 'deliverable_version.deliverable_ID');
    $deliverables = $deliverables->search($search);
    $deliverables = $deliverables->orderBy('deliverable_version.updated_at', 'desc');
    $deliverables = $deliverables->paginate(4);
</code>```

Any help is appreciated. Thanks.

答:
```<code>in Accounts module add:

 public function deliverable_version(){
        return $this->hasMany('App\deliverable_version');
    }

in controller:

    enter code here

$deliverables = Accounts::find($owner_account_ID)->deliverables()>with('deliverable_version');
foreach($deliverables as $deliverable){
// last version
$deliverable = $deliverables->deliverable_version->last();
</code>```

<p>}</p>

Body:
I have two database tables called deliverables, and deliverable_version.

Deliverable hasMany Deliverable_Version.

Deliverable has id column, and the model has a function to get the most recent version:

public function getRecentVersion()
    {
        $deliverable_version_max = $this->versions()->max('version');

        $deliverable_version = DeliverableVersion::where([
            'version'=>$deliverable_version_max,
            'deliverable_ID'=>$this->id,
        ])->first();

        return $deliverable_version;
    }

Deliverable_version table has id, deliverable_ID, title, message, deadline, version, created_at, updated_at.

How I would perform an operation where I can:

Get all deliverables and the most recent version associated with the deliverable.

Sort the deliverables by it by the columns of the deliverable_version table (updated_at)

Paginate the result?

Here is my attempt at it, which isn't working because it selects all the versions when I join the tables, not just the recent version:

$deliverables = Accounts::find($owner_account_ID)->deliverables();
    $deliverables = $deliverables->join('deliverable_version', 'deliverable.id', '=', 'deliverable_version.deliverable_ID');
    $deliverables = $deliverables->search($search);
    $deliverables = $deliverables->orderBy('deliverable_version.updated_at', 'desc');
    $deliverables = $deliverables->paginate(4);

Any help is appreciated. Thanks.

Body:
in Accounts module add:

 public function deliverable_version(){
        return $this->hasMany('App\deliverable_version');
    }

in controller:

    enter code here

$deliverables = Accounts::find($owner_account_ID)->deliverables()>with('deliverable_version');
foreach($deliverables as $deliverable){
// last version
$deliverable = $deliverables->deliverable_version->last();

}


答:
```<code>DECLARE @MyTable TABLE (Reference INT, ModifiedDate DATETIME)
INSERT INTO @MyTable VALUES

(1023175, '2017-03-03 16:02:01.723'),
(1023175, '2017-03-07 07:59:49.283'),
(1023175, '2017-03-12 11:14:40.230');

SELECT
    T1.Reference,
    T1. ModifiedDate AS Start_Date,
    COALESCE(MIN(T2.ModifiedDate),CAST('31/12/9999' AS DATETIME))  as EndDate
FROM @MyTable T1
    LEFT JOIN @MyTable T2
ON T1.reference = T2.reference AND T1.ModifiedDate < T2.ModifiedDate
GROUP BY
    T1.Reference,
    T1. ModifiedDate
</code>```

Title: Complex SQL transformation

Body:
This is my source table

Reference   ModifiedDate
------------------------------------
1023175     2017-03-03 16:02:01.723
1023175     2017-03-07 07:59:49.283
1023175     2017-03-12 11:14:40.230

Ineed the following output

Reference   StartDate                 EndDate
---------------------------------------------
1023175   2017-03-03 16:02:01.723     2017-03-07 07:59:49.283
1023175   2017-03-07 07:59:49.283     2017-03-12 11:14:40.230
1023175   2017-03-12 11:14:40.230     9999-12-31 00:00:00.000 (last record should have this value)

Any suggestions on how this can be achieved?


问:
How can I access tomcat log files from Java web application deployed on it?
How can I access tomcat log files from Java web application deployed on it?
Is that possible?</p>

答:
Okay, it is possible. I used something like:</p>

```<code>    public static String readLogFile () {
        StringBuilder sb = new StringBuilder();
        try(BufferedReader br = new BufferedReader(new FileReader("/var/log/tomcat8/catalina.out"))) {
            String line = br.readLine();
            while (line != null) {
                sb.append(line);
                sb.append(System.lineSeparator());
                line = br.readLine();
            }
        } catch (IOException e) {
            // exception handling
        }
        return sb.toString();
    }
</code>```

Body:
Okay, it is possible. I used something like:

    public static String readLogFile () {
        StringBuilder sb = new StringBuilder();
        try(BufferedReader br = new BufferedReader(new FileReader("/var/log/tomcat8/catalina.out"))) {
            String line = br.readLine();
            while (line != null) {
                sb.append(line);
                sb.append(System.lineSeparator());
                line = br.readLine();
            }
        } catch (IOException e) {
            // exception handling
        }
        return sb.toString();
    }


问:
Is the --group option deprecated from kafka-console-consumer tool? if so, how can I set the consumer group using kafka-console-consumer.
I am trying to run multiple consumer for the same topic under different group name using the command line tool - kafka-console-consumer.sh. When I set --group option, it fails with error 'group is not a recognized option'. This was working fine until I upgraded to the latest kafka version (kafka_2.11-0.8.2.2).    </p>

答:
--group is not available for bin/kafka-console-consumer.sh in new API.

By default all consumers uses config/consumer.properties where group.id=test-consumer-group.
Create one property file anywhere, and put group.id=<your-group-name>.

And when you run your console-consumer, just add one new parameter as --consumer.config <your-newly-created-property-file>

$KAFKA_HOME/bin/kafka-console-consumer.sh --topic <topic-name> --zookeeper <zk-server>:<zk-port> --consumer.config <new-property-file>


问:
Convert CSV to RDD and read with Spark/Scala
I tried to read a file (csv) and print its schema. My problem is that my file has not header to query like SQL.
I tried with this code:

```<code>val logFile = "../resouces/cells.csv"

val dfCells = spark.read
 .format("csv")
 .option("header", "false")
 .option("mode", "DROPMALFORMED")
 .option("delimiter", "|")
 .csv(logFile)

dfCell.printSchema;
</code>```

The file input is:

```<code>ES|15032017|25100|54600||3G|FIBRE|OUTDOOR|COMPANY|MAST|MACRO||47001|DU|41.651834|-4.728534||||||||||||||||
ES|15032017|25101|54601||3G|FIBRE|OUTDOOR|COMPANY|ROOFTOP|MACRO||47001|DU|41.651994|-4.724693||||||||||||||||
ES|15032017|25102|54602||4G|FIBRE|OUTDOOR|COMPANY|ROOFTOP|MICRO||47001|U|41.650912|-4.720648||||||||||||||||
ES|15032017|25103|54603||3G|MICROWAVES|OUTDOOR|COMPANY|ROOFTOP|MACRO||47001|U|41.647312|-4.717118||||||||||||||||
</code>```

The output is:

```<code>|
|
|
</code>```

Body:
I tried to read a file (csv) and print its schema. My problem is that my file has not header to query like SQL.
I tried with this code:

val logFile = "../resouces/cells.csv"

val dfCells = spark.read
 .format("csv")
 .option("header", "false")
 .option("mode", "DROPMALFORMED")
 .option("delimiter", "|")
 .csv(logFile)

dfCell.printSchema;

The file input is:

ES|15032017|25100|54600||3G|FIBRE|OUTDOOR|COMPANY|MAST|MACRO||47001|DU|41.651834|-4.728534||||||||||||||||
ES|15032017|25101|54601||3G|FIBRE|OUTDOOR|COMPANY|ROOFTOP|MACRO||47001|DU|41.651994|-4.724693||||||||||||||||
ES|15032017|25102|54602||4G|FIBRE|OUTDOOR|COMPANY|ROOFTOP|MICRO||47001|U|41.650912|-4.720648||||||||||||||||
ES|15032017|25103|54603||3G|MICROWAVES|OUTDOOR|COMPANY|ROOFTOP|MACRO||47001|U|41.647312|-4.717118||||||||||||||||

The output is:

|
|
|

Body:
I use Spark 1.5.0 with load function instead of csv.

val logFile = "../input.csv"

val dfCells = sqlContext.read
                        .format("csv")
                        .option("header", "false")
                        .option("mode", "DROPMALFORMED")
                        .option("delimiter", "|")
                        .load(logFile)

dfCells.show()
+---+--------+-----+-----+---+---+----------+-------+-------+-------+-----+---+-----+---+---------+---------+---+---+---+---+---+---+---+---+---+---+---+---+---+---+---+---+
| C0|      C1|   C2|   C3| C4| C5|        C6|     C7|     C8|     C9|  C10|C11|  C12|C13|      C14|      C15|C16|C17|C18|C19|C20|C21|C22|C23|C24|C25|C26|C27|C28|C29|C30|C31|
+---+--------+-----+-----+---+---+----------+-------+-------+-------+-----+---+-----+---+---------+---------+---+---+---+---+---+---+---+---+---+---+---+---+---+---+---+---+
| ES|15032017|25100|54600|   | 3G|     FIBRE|OUTDOOR|COMPANY|   MAST|MACRO|   |47001| DU|41.651834|-4.728534|   |   |   |   |   |   |   |   |   |   |   |   |   |   |   |   |
| ES|15032017|25101|54601|   | 3G|     FIBRE|OUTDOOR|COMPANY|ROOFTOP|MACRO|   |47001| DU|41.651994|-4.724693|   |   |   |   |   |   |   |   |   |   |   |   |   |   |   |   |
| ES|15032017|25102|54602|   | 4G|     FIBRE|OUTDOOR|COMPANY|ROOFTOP|MICRO|   |47001|  U|41.650912|-4.720648|   |   |   |   |   |   |   |   |   |   |   |   |   |   |   |   |
| ES|15032017|25103|54603|   | 3G|MICROWAVES|OUTDOOR|COMPANY|ROOFTOP|MACRO|   |47001|  U|41.647312|-4.717118|   |   |   |   |   |   |   |   |   |   |   |   |   |   |   |   |
+---+--------+-----+-----+---+---+----------+-------+-------+-------+-----+---+-----+---+---------+---------+---+---+---+---+---+---+---+---+---+---+---+---+---+---+---+---+

and the schema is:

dfCells.printSchema()
root
 |-- C0: string (nullable = true)
 |-- C1: string (nullable = true)
 |-- C2: string (nullable = true)
 |-- C3: string (nullable = true)
 |-- C4: string (nullable = true)
 |-- C5: string (nullable = true)
 |-- C6: string (nullable = true)
 |-- C7: string (nullable = true)
 |-- C8: string (nullable = true)
 |-- C9: string (nullable = true)
 |-- C10: string (nullable = true)
 |-- C11: string (nullable = true)
 |-- C12: string (nullable = true)
 |-- C13: string (nullable = true)
 |-- C14: string (nullable = true)
 |-- C15: string (nullable = true)
 |-- C16: string (nullable = true)
 |-- C17: string (nullable = true)
 |-- C18: string (nullable = true)
 |-- C19: string (nullable = true)
 |-- C20: string (nullable = true)
 |-- C21: string (nullable = true)
 |-- C22: string (nullable = true)
 |-- C23: string (nullable = true)
 |-- C24: string (nullable = true)
 |-- C25: string (nullable = true)
 |-- C26: string (nullable = true)
 |-- C27: string (nullable = true)
 |-- C28: string (nullable = true)
 |-- C29: string (nullable = true)
 |-- C30: string (nullable = true)
 |-- C31: string (nullable = true)


问:
C# function that return instance with unknown generic type
I am now implementing a function Register() which invoking other function ApiReturnFactory() inside.

```<code>    public ???? Register(string username)
    {
        var result = new AccountProcess().CreateAccount(username);
        return ApiReturnFactory.CreateInstance(result);
    }
</code>```

new AccountProcess().CreateAccount(username) returns me an object like obj<WhateverType>.

ApiReturnFactory.CreateInstance(obj) returns me an object like obj2<SameTypeWithWhateverType>.

My question is the compiler have already know what type I will return in ApiReturnFactory.CreateInstance(obj) (IntelliSense do), but what should I state in the return type ???? of Register(string username)?

I don't want to specific a generic type for obj like obj<string>, this is not reasonable since the generic type may not always be a string. What I want is something like obj<T>.

Thanks in advance.

答:
Create an interface and inherit your generic types from that interface and return that interface object back or a base class whatever is suitable in your use-case:

```<code>public interface IObject
{

}

public class GenericClass<SomeType> : IObject
{

}
</code>```

and then you can return the interface object :

```<code>public IObject Register(string username)
{
    var obj = new AccountProcess().CreateAccount(username);
    return ApiReturnFactory.CreateInstance(obj);
}
</code>```

Body:
I am now implementing a function Register() which invoking other function ApiReturnFactory() inside.

    public ???? Register(string username)
    {
        var result = new AccountProcess().CreateAccount(username);
        return ApiReturnFactory.CreateInstance(result);
    }

new AccountProcess().CreateAccount(username) returns me an object like obj<WhateverType>.

ApiReturnFactory.CreateInstance(obj) returns me an object like obj2<SameTypeWithWhateverType>.

My question is the compiler have already know what type I will return in ApiReturnFactory.CreateInstance(obj) (IntelliSense do), but what should I state in the return type ???? of Register(string username)?

I don't want to specific a generic type for obj like obj<string>, this is not reasonable since the generic type may not always be a string. What I want is something like obj<T>.

Thanks in advance.

Body:
Create an interface and inherit your generic types from that interface and return that interface object back or a base class whatever is suitable in your use-case:

public interface IObject
{

}

public class GenericClass<SomeType> : IObject
{

}

and then you can return the interface object :

public IObject Register(string username)
{
    var obj = new AccountProcess().CreateAccount(username);
    return ApiReturnFactory.CreateInstance(obj);
}


问:
Sign up django with cbv and AbstractUser model image error
i tried using class based views for signup but when i try to add images to the form fields, i keep getting this field is required the problem is with the image file
this is the forms.py file
`

```<code>from django import forms
from .models import User

class USerForm(forms.ModelForm):
    password = forms.CharField(widget=forms.PasswordInput())

    class Meta:
        model = User
        fields = ['username', 'email', 'password', 'company', 'description', 'logo']
</code>```

`
and the views.py file

```<code>from django.shortcuts import render, redirect
from django.views.generic import View, TemplateView
from .forms import USerForm
from django.contrib.auth import authenticate, login, logout
from django.http import HttpResponseRedirect
from django.contrib.auth.decorators import login_required
from django.contrib import messages
from django.views.generic.edit import UpdateView

# Create your views here.

@login_required(login_url="/jembe/login/")
def index(request):
    return render(request, 'base.html')

class SignUp(View):
    form_class = USerForm
    template_name = 'signup.html'

    def get(self, request):
        form = self.form_class(None)
        return render(request, self.template_name, {'form': form})

    def post(self, request):
        form = self.form_class(request.POST, request.FILES)
        if form.is_valid():
            user = form.save(commit=False)

            username = form.cleaned_data['username']
            password = form.cleaned_data['password']
            user.set_password(password)
            user.save()
            user = authenticate(username=username, password=password)

            if user is not None:
                if user.is_active:
                    login(request, user)
                    return redirect('invoice:index')
        return render(request, self.template_name, {'form': form})

class LogoutView(View):
    def get(self, request):
        logout(request)
        return HttpResponseRedirect('/jembe/login')

class AboutView(TemplateView):
    template_name = "about.html"
</code>```

models.py file

```<code>`from django.db import models
from django.contrib.auth.models import AbstractUser

# Create your models here.

class User(AbstractUser):
    company = models.CharField(max_length=300)
    description = models.TextField(blank=True)
    website = models.URLField()
    logo = models.ImageField(upload_to='../media/')

`
</code>```

register.html

```<code>    {% load staticfiles %}
{% load i18n widget_tweaks %}

<!DOCTYPE html>
<html lang="en">

<head>
        <meta charset="utf-8">
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
        <meta name="description" content="">
        <meta name="author" content="">

        <link rel="shortcut icon" href="img/favicon_1.ico">

        <title>{% block title %} Signup {% endblock %} |Jims</title>
 ""

        <!-- Bootstrap core CSS -->
        <link href="{% static 'login/css/bootstrap.min.css' %}" rel="stylesheet">
        <link href="{% static 'login/css/bootstrap-reset.css' %}" rel="stylesheet">

        <!--Animation css-->
        <link href="{% static 'login/css/animate.css' %}" rel="stylesheet">

        <!--Icon-fonts css-->
        <link href="{% static 'login/assets/font-awesome/css/font-awesome.css' %}" rel="stylesheet" />
        <link href="{% static 'login/assets/ionicon/css/ionicons.min.css' %}" rel="stylesheet" />

        <!--Morris Chart CSS -->
        <link rel="stylesheet" href="{% static 'login/assets/morris/morris.css">

        <!-- Custom styles for this template -->
        <link href="{% static 'login/css/style.css' %}" rel="stylesheet">
        <link href="{% static 'login/css/helper.css' %}" rel="stylesheet">
        <link href="{% static 'css/style.css' %}" rel="stylesheet">
        <link href="{% static 'css/bootstrap.css' %}" rel="stylesheet">
        <link href="{% static 'css/main.css' %}" rel="stylesheet">

        <link rel='stylesheet prefetch' href='http://fonts.googleapis.com/css?family=Roboto:400,100,300,500,700,900|RobotoDraft:400,100,300,500,700,900'>
        <link rel='stylesheet prefetch' href='http://maxcdn.bootstrapcdn.com/font-awesome/4.3.0/css/font-awesome.min.css'>

        <!-- HTML5 shim and Respond.js IE8 support of HTML5 tooltipss and media queries -->
        <!--[if lt IE 9]>
          <script src="js/html5shiv.js"></script>
          <script src="js/respond.min.js"></script>
        <![endif]-->

        <script>
          (function(i,s,o,g,r,a,m){i['GoogleAnalyticsObject']=r;i[r]=i[r]||function(){
          (i[r].q=i[r].q||[]).push(arguments)},i[r].l=1*new Date();a=s.createElement(o),
          m=s.getElementsByTagName(o)[0];a.async=1;a.src=g;m.parentNode.insertBefore(a,m)
          })(window,document,'script','../../../www.google-analytics.com/analytics.js','ga');

          ga('create', 'UA-62751496-1', 'auto');
          ga('send', 'pageview');

        </script>

    </head>

    <body>
        <div class="navbar navbar-default navbar-fixed-top">
      <div class="container">
        <div class="navbar-header">
          <button type="button" class="navbar-toggle" data-toggle="collapse" data-target=".navbar-collapse">
            <span class="icon-bar"></span>
            <span class="icon-bar"></span>
            <span class="icon-bar"></span>
          </button>
          <a class="navbar-brand" href=""><div class="logo">
                <a href="" class="logo-expanded">
                    <i class="ion-compose"></i>
                    <span class="nav-label">Jigs</span>
                </a>
            </div></a>
        </div>
        <div class="navbar-collapse collapse">
          <ul class="nav navbar-nav navbar-right">
            <li><a href=""><strong>About</strong></a></li>
            <li><a href=""><strong>Login</strong></a></li>
            <li><a href=""><strong>Register</strong></a></li>

          </ul>
        </div><!--/.nav-collapse -->
      </div>
    </div>
        <div class="wrapper-page animated fadeInDown">
            <div class="panel panel-color panel-primary">
                <div class="panel-heading">
                   <h3 class="text-center m-t-10"> Create a new Account </h3>
                </div>

                {# error logic #}
                {% if form.errors %}
                {% for field in form %}
                {% for error in field.errors %}
                <div class="alert alert-danger">
                    <strong>{{ error | escape }}</strong>
                </div>
                {% endfor %}
                {% for error in form.non_field_errors %}
                <div class="alert alert-danger">
                    <strong> {{ error | escape }}</strong>
                </div>
                {% endfor %}
                {% endfor %}
                {% endif %}
                {# end error logic #}
                <form class="form-horizontal m-t-40" action="" method="post">
                    {% csrf_token %}

                    {% for field in form %}
                    <div class="form-group">
                        <div class="col-xs-12">
                            <label> {{ field.label }} </label>
                               {{ field|attr:"class:form-control" }}
                        </div>
                    </div>
                    {% endfor %}
                    <div class="form-group ">
                        <div class="col-xs-12">
                            <label class="cr-styled">
                                <input type="checkbox" checked>
                                <i class="fa"></i>
                                 I accept <strong><a href="#">Terms and Conditions</a></strong>
                            </label>
                        </div>
                    </div>

                    <div class="form-group text-right">
                        <div class="col-xs-12">
                            <button class="btn btn-purple w-md" type="submit">Register</button>
                        </div>
                    </div>

                    <div class="form-group m-t-30">
                        <div class="col-sm-12 text-center">
                            <a href="{% url 'invoice:login' %}">Already have account?</a>
                        </div>
                    </div>
                </form>

            </div>
        </div>

        <!-- js placed at the end of the document so the pages load faster -->
        <script src="{% static 'login/js/jquery.js' %}"></script>
        <script src="{% static 'login/js/bootstrap.min.js' %}"></script>
        <script src="{% static 'login/js/pace.min.js' %}"></script>
        <script src="{% static 'login/js/wow.min.js' %}"></script>
        <script src="{% static 'login/js/jquery.nicescroll.js' %}" type="text/javascript"></script>

        <!--common script for all pages-->
        <script src="{% static 'login/js/jquery.app.js' %}"></script>

     <hr/>
           <center><h3 class="text text-success"> Jembe™ © 2017</h3></center>
    </body>

</html>
</code>```

答:
You have forgotten to set enctype in your form. It should be:

```<code><form class="form-horizontal m-t-40" action="" method="post" enctype="multipart/form-data">
</code>```

See the Django docs on file uploads for more info.

Body:
i tried using class based views for signup but when i try to add images to the form fields, i keep getting this field is required the problem is with the image file
this is the forms.py file
`

from django import forms
from .models import User

class USerForm(forms.ModelForm):
    password = forms.CharField(widget=forms.PasswordInput())

    class Meta:
        model = User
        fields = ['username', 'email', 'password', 'company', 'description', 'logo']

`
and the views.py file

from django.shortcuts import render, redirect
from django.views.generic import View, TemplateView
from .forms import USerForm
from django.contrib.auth import authenticate, login, logout
from django.http import HttpResponseRedirect
from django.contrib.auth.decorators import login_required
from django.contrib import messages
from django.views.generic.edit import UpdateView

# Create your views here.

@login_required(login_url="/jembe/login/")
def index(request):
    return render(request, 'base.html')

class SignUp(View):
    form_class = USerForm
    template_name = 'signup.html'

    def get(self, request):
        form = self.form_class(None)
        return render(request, self.template_name, {'form': form})

    def post(self, request):
        form = self.form_class(request.POST, request.FILES)
        if form.is_valid():
            user = form.save(commit=False)

            username = form.cleaned_data['username']
            password = form.cleaned_data['password']
            user.set_password(password)
            user.save()
            user = authenticate(username=username, password=password)

            if user is not None:
                if user.is_active:
                    login(request, user)
                    return redirect('invoice:index')
        return render(request, self.template_name, {'form': form})

class LogoutView(View):
    def get(self, request):
        logout(request)
        return HttpResponseRedirect('/jembe/login')

class AboutView(TemplateView):
    template_name = "about.html"

models.py file

`from django.db import models
from django.contrib.auth.models import AbstractUser

# Create your models here.

class User(AbstractUser):
    company = models.CharField(max_length=300)
    description = models.TextField(blank=True)
    website = models.URLField()
    logo = models.ImageField(upload_to='../media/')

`

register.html

    {% load staticfiles %}
{% load i18n widget_tweaks %}

<!DOCTYPE html>

        <meta charset="utf-8">
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
        <meta name="description" content="">
        <meta name="author" content="">

        <link rel="shortcut icon" href="img/favicon_1.ico">

        <title>{% block title %} Signup {% endblock %} |Jims</title>
 ""

        <link href="{% static 'login/css/bootstrap.min.css' %}" rel="stylesheet">
        <link href="{% static 'login/css/bootstrap-reset.css' %}" rel="stylesheet">

        <link href="{% static 'login/css/animate.css' %}" rel="stylesheet">

        <link href="{% static 'login/assets/font-awesome/css/font-awesome.css' %}" rel="stylesheet" />
        <link href="{% static 'login/assets/ionicon/css/ionicons.min.css' %}" rel="stylesheet" />

        <link rel="stylesheet" href="{% static 'login/assets/morris/morris.css">

        <link href="{% static 'login/css/style.css' %}" rel="stylesheet">
        <link href="{% static 'login/css/helper.css' %}" rel="stylesheet">
        <link href="{% static 'css/style.css' %}" rel="stylesheet">
        <link href="{% static 'css/bootstrap.css' %}" rel="stylesheet">
        <link href="{% static 'css/main.css' %}" rel="stylesheet">

        <link rel='stylesheet prefetch' href='http://fonts.googleapis.com/css?family=Roboto:400,100,300,500,700,900|RobotoDraft:400,100,300,500,700,900'>
        <link rel='stylesheet prefetch' href='http://maxcdn.bootstrapcdn.com/font-awesome/4.3.0/css/font-awesome.min.css'>

          <button type="button" class="navbar-toggle" data-toggle="collapse" data-target=".navbar-collapse">

          </button>

                    Jigs

About

Login

Register

 Create a new Account

                {# error logic #}
                {% if form.errors %}
                {% for field in form %}
                {% for error in field.errors %}

                    {{ error | escape }}

                {% endfor %}
                {% for error in form.non_field_errors %}

                     {{ error | escape }}

                {% endfor %}
                {% endfor %}
                {% endif %}
                {# end error logic #}
                <form class="form-horizontal m-t-40" action="" method="post">
                    {% csrf_token %}

                    {% for field in form %}

                             {{ field.label }}
                               {{ field|attr:"class:form-control" }}

                    {% endfor %}

                                <input type="checkbox" checked>

                                 I accept Terms and Conditions

                            <button class="btn btn-purple w-md" type="submit">Register</button>

                            Already have account?

                </form>

 Jembe™ © 2017

Body:
You have forgotten to set enctype in your form. It should be:

<form class="form-horizontal m-t-40" action="" method="post" enctype="multipart/form-data">

See the Django docs on file uploads for more info.


问:
Validation of file extension before uploading file
I am uploading images to a servlet. The validation whether the uploaded file is an image is done in server side only, by checking the magic numbers in the file header. Is there any way to validate the extensions in client side before submitting the form to servlet? As soon as I hit enter it starts uploading.

I am using Javascript and jQuery in client side.

Update:
I was finally ended up with server side validation which reads bytes & rejects the upload if it is not an image.

答:
[TypeScript]</p>

```<code>uploadFileAcceptFormats: string[] = ['image/jpeg', 'image/gif', 'image/png', 'image/svg+xml'];

// if you find the element type in the allowed types array, then read the file
isAccepted = this.uploadFileAcceptFormats.find(val => {
    return val === uploadedFileType;
});
</code>```

Body:
[TypeScript]

uploadFileAcceptFormats: string[] = ['image/jpeg', 'image/gif', 'image/png', 'image/svg+xml'];

// if you find the element type in the allowed types array, then read the file
isAccepted = this.uploadFileAcceptFormats.find(val => {
    return val === uploadedFileType;
});


问:
read property 'setState' of undefined
I am trying to get data from a sample api, I keep getting the error:

```<code>Cannot read property 'setState' of undefined.
</code>```

Can anyone please tell me why I get the undefined error, do I need to bind to this?

```<code>import React, { Component } from 'react';
import axios from 'axios';
import logo from './logo.svg';
import './App.css';
import '../node_modules/bootstrap/dist/css/bootstrap.css';
import '../node_modules/bootstrap/dist/css/bootstrap-theme.css';

import Users from './components/Users.js';

class App extends Component {

constructor(props) {
    super(props);
    this.state = {users: []};
}

getUsers(){
     axios.get('http://jsonplaceholder.typicode.com/users')
.then(function (response) {
     this.setState({ users: response.data });
})
.catch(function (error) {
  console.log(error);
  });
}

componentDidMount(){
     this.getUsers();
}

render() {
return (
  <div className="App">
    <div className="App-header">
      <img src={logo} className="App-logo" alt="logo" />
      <h2>Welcome to React</h2>
    </div>

      <Users data={this.state.users} />

  </div>
);
   }
  }

export default App;
</code>```

答:
This happens because this is a different object inside the scope of the callback. That's why it complains that setState() doesn't exist - it's the wrong object.

The easiest solution is a so-called arrow function. The reason this solves your issue is because arrow functions, unlike the traditional functions, do not bind the this object. As such, the this object inside the callback is the "correct" one and you can call setState().

This is what the MDN documentation says on arrow functions:

An arrow function expression has a shorter syntax than a function expression and does not bind its own this, arguments, super, or new.target. These function expressions are best suited for non-method functions, and they cannot be used as constructors.

and

An arrow function does not create its own this context, so this has its original meaning from the enclosing context.

So your function would become:

```<code>getUsers(){
  axios.get('http://jsonplaceholder.typicode.com/users')
  .then((response) => {
     this.setState({ users: response.data });
  })
  .catch((error) => {
    console.log(error);
  });
}
</code>```

The catch doesn't need changing since you are only logging to the console and don't use the this object - but I changed it anyway for consistency.

Title: read property 'setState' of undefined

Body:
I am trying to get data from a sample api, I keep getting the error:

Cannot read property 'setState' of undefined.

Can anyone please tell me why I get the undefined error, do I need to bind to this?

import React, { Component } from 'react';
import axios from 'axios';
import logo from './logo.svg';
import './App.css';
import '../node_modules/bootstrap/dist/css/bootstrap.css';
import '../node_modules/bootstrap/dist/css/bootstrap-theme.css';

import Users from './components/Users.js';

class App extends Component {

constructor(props) {
    super(props);
    this.state = {users: []};
}

getUsers(){
     axios.get('http://jsonplaceholder.typicode.com/users')
.then(function (response) {
     this.setState({ users: response.data });
})
.catch(function (error) {
  console.log(error);
  });
}

componentDidMount(){
     this.getUsers();
}

render() {
return (

Welcome to React

      <Users data={this.state.users} />

);
   }
  }

export default App;

Body:
This happens because this is a different object inside the scope of the callback. That's why it complains that setState() doesn't exist - it's the wrong object.

The easiest solution is a so-called arrow function. The reason this solves your issue is because arrow functions, unlike the traditional functions, do not bind the this object. As such, the this object inside the callback is the "correct" one and you can call setState().

This is what the MDN documentation says on arrow functions:

An arrow function expression has a shorter syntax than a function expression and does not bind its own this, arguments, super, or new.target. These function expressions are best suited for non-method functions, and they cannot be used as constructors.

and

An arrow function does not create its own this context, so this has its original meaning from the enclosing context.

So your function would become:

getUsers(){
  axios.get('http://jsonplaceholder.typicode.com/users')
  .then((response) => {
     this.setState({ users: response.data });
  })
  .catch((error) => {
    console.log(error);
  });
}

The catch doesn't need changing since you are only logging to the console and don't use the this object - but I changed it anyway for consistency.


问:
Running Different Macros Based on Values in Range
Im busy trying to write code that calls different macros based on the value of a cell across an entire range on VBA.

So for the example I have a range S20:S21.

When the value in cell S20 is equal to 1, I want to call macro1.
When the value in cell S21 is equal to 2, I want to call macro2.

When there is no match I have a time that it will test it in the next 5 seconds again where it will start from the top checking if cell S20 is 1 or of S20 is 2.

This is currently the code I have.

```<code>    Dim TimeToRun

Sub auto_open()
    Call ScheduleCopyPriceOver
End Sub

Sub ScheduleCopyPriceOver()
    TimeToRun = Now + TimeValue("00:00:05")
    Application.OnTime TimeToRun, "CopyPriceOver"
End Sub

Sub CopyPriceOver()
Application.ScreenUpdating = False

    Number = Range("S20:S22").Value

    If Number = 1 Then

    Call Macro1
    Call ScheduleCopyPriceOver

    ElseIf Number = 2 Then

    Call Macro2
    Call ScheduleCopyPriceOver

    Else

    Call ScheduleCopyPriceOver
    End If

End Sub

Sub auto_close()
    On Error Resume Next
    Application.OnTime TimeToRun, "CopyPriceOver", , False
End Sub
</code>```

答:
use the below code</p>

```<code>If range("S20") = 1 Then

Call Macro1
Call ScheduleCopyPriceOver

ElseIf range("S21") = 2 Then

Call Macro2
Call ScheduleCopyPriceOver

Else
Call ScheduleCopyPriceOver
End If
</code>```

Body:
Im busy trying to write code that calls different macros based on the value of a cell across an entire range on VBA.

So for the example I have a range S20:S21.

When the value in cell S20 is equal to 1, I want to call macro1.
When the value in cell S21 is equal to 2, I want to call macro2.

When there is no match I have a time that it will test it in the next 5 seconds again where it will start from the top checking if cell S20 is 1 or of S20 is 2.

This is currently the code I have.

    Dim TimeToRun

Sub auto_open()
    Call ScheduleCopyPriceOver
End Sub

Sub ScheduleCopyPriceOver()
    TimeToRun = Now + TimeValue("00:00:05")
    Application.OnTime TimeToRun, "CopyPriceOver"
End Sub

Sub CopyPriceOver()
Application.ScreenUpdating = False

    Number = Range("S20:S22").Value

    If Number = 1 Then

    Call Macro1
    Call ScheduleCopyPriceOver

    ElseIf Number = 2 Then

    Call Macro2
    Call ScheduleCopyPriceOver

    Else

    Call ScheduleCopyPriceOver
    End If

End Sub

Sub auto_close()
    On Error Resume Next
    Application.OnTime TimeToRun, "CopyPriceOver", , False
End Sub

Body:
use the below code

If range("S20") = 1 Then

Call Macro1
Call ScheduleCopyPriceOver

ElseIf range("S21") = 2 Then

Call Macro2
Call ScheduleCopyPriceOver

Else
Call ScheduleCopyPriceOver
End If


问:
Embedded Scala REPL inherits parent classpath
As asked in this thread on the Scala mailing list, how can I create an embedded Scala REPL that inherits the classpath of the parent program? Suppose the parent Scala program is launched using scala -cp <classpath> ...; can <classpath> be accessed as a string and used to initialize the embedded REPL? (The Java classpath, available via System.getProperty("java.class.path"), appears to differ from the Scala classpath.)

Alternatively, perhaps the embedded Scala REPL can inherit or construct its ClassLoader from the parent process (Michael Dürig's ScalaDays 2010 talk might be relevant). Is this the recommended approach?

答:
There does not seem to be an easy way to access the "Scala classpath" from within a running Scala program (in contrast, the "Java classpath" is available through the java.class.path system property). One would like to access, e.g., the field Calculated.userClasspath in the instance of scala.tools.PathResolver, but the latter does not seem accessible. Perhaps the easiest work-around is to modify the scala launch script to store the -classpath parameter string in an environment variable.

Assuming the desired Scala classpath can be determined, it can be passed to the embedded Scala interpreter via:
settings.classpath.value = ...

Update: although the Scala classpath string may not be directly attainable from the Scala runtime, @Eugene points out that it can be extracted from the context classloader. Thanks.


问:
How to specify encoding while process csv file in PHP?
```<code><?php
$row = 1;
$handle = fopen ("test.csv","r");
while ($data = fgetcsv ($handle, 1000, ",")) {
    $num = count ($data);
    print "<p> $num fields in line $row: <br>\n";
    $row++;
    for ($c=0; $c < $num; $c++) {
        print $data[$c] . "<br>\n";
    }
}
fclose ($handle);
?>
</code>```

The above comes from php manual,but I didn't see where to specify the encoding(like utf8 or so)

答:
try this:</p>

```<code><?php
$handle = fopen ("specialchars.csv","r");
echo '<table border="1"><tr><td>First name</td><td>Last name</td></tr><tr>';
while ($data = fgetcsv ($handle, 1000, ";")) {
        $data = array_map("utf8_encode", $data); //added
        $num = count ($data);
        for ($c=0; $c < $num; $c++) {
            // output data
            echo "<td>$data[$c]</td>";
        }
        echo "</tr><tr>";
}
?>
</code>```

Body:
<?php
$row = 1;
$handle = fopen ("test.csv","r");
while ($data = fgetcsv ($handle, 1000, ",")) {
    $num = count ($data);
    print "
 $num fields in line $row:
\n";
    $row++;
    for ($c=0; $c < $num; $c++) {
        print $data[$c] . "
\n";
    }
}
fclose ($handle);
?>

The above comes from php manual,but I didn't see where to specify the encoding(like utf8 or so)

Body:
try this:

<?php
$handle = fopen ("specialchars.csv","r");
echo '<table border="1"><tr><td>First name</td><td>Last name</td></tr><tr>';
while ($data = fgetcsv ($handle, 1000, ";")) {
        $data = array_map("utf8_encode", $data); //added
        $num = count ($data);
        for ($c=0; $c < $num; $c++) {
            // output data
            echo "<td>$data[$c]</td>";
        }
        echo "</tr><tr>";
}
?>


问:
Is it safe to render Html that was uploaded as Markdown and converted serverside to Html?
I have a webform that allows users to upload text as Markdown.

The Markdown is converted to Html on the server(using Markdig) and also stored.

When displaying the converted Html that the user uploaded, should I @Html.Encode the content - the project is in c#, MVC 5/razor with request validation on.

答:
No, it isn't.

I just trivially tested the following:

```<code><a href="javascript:evil()">hello</a>
</code>```

and markdig lets it through:

See online example.

Although I haven't looked into it too deeply, the Microsoft AntiXSS library might be useful here:

```<code>var safeHtml = Microsoft.Security.Application.Sanitizer
    .GetSafeHtmlFragment("<a href='javascript:evil()'>hello</a>");
</code>```

gives:

```<code><a href="">hello</a>
</code>```

but

```<code>var safeHtml = Microsoft.Security.Application.Sanitizer
    .GetSafeHtmlFragment("<a href='http://stackoverflow.com'>hello</a>");
</code>```

gives:

```<code><a href="http://stackoverflow.com">hello</a>
</code>```

Body:
No, it isn't.

I just trivially tested the following:

<a href="javascript:evil()">hello</a>

and markdig lets it through:

See online example.

Although I haven't looked into it too deeply, the Microsoft AntiXSS library might be useful here:

var safeHtml = Microsoft.Security.Application.Sanitizer
    .GetSafeHtmlFragment("<a href='javascript:evil()'>hello</a>");

gives:

<a href="">hello</a>

but

var safeHtml = Microsoft.Security.Application.Sanitizer
    .GetSafeHtmlFragment("<a href='http://stackoverflow.com'>hello</a>");

gives:

<a href="http://stackoverflow.com">hello</a>


问:
Go to activity without starting it upon clicking on notification
Following the Android tutorial on Notification https://developer.android.com/guide/topics/ui/notifiers/notifications.html I'm able to display a Notification.
What I do want, which is not explain in the article, is how to go to the activity without starting it.
In fact I have an application with a couple of Activities. As soon as I enter one of those activities, a permanent Notification is shown which only disappears when the user leaves that activity.
If the user then clicks on the Notification while my application is not on screen, I want the activity to be resumed without restarting it. The activity runs a counter. That's why it shouldn't be restarted.

Best regards

答:
This is how I manage to solve the problem.
In the manifest.xml file set android:launchMode="singleTop" for that activity. And then you build the notification as follows:

```<code>NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(context)
            .setSmallIcon(R.drawable.ic_directions_run_white_24dp).setContentTitle("My " +
                    "notification").setContentText("Hello World!");
    // Creates an explicit intent for an Activity in your app
    Intent resultIntent = new Intent(context, PlayActivity.class);
    resultIntent.setFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP);
    PendingIntent resultPendingIntent = PendingIntent.getActivity(context, 0, resultIntent,
            PendingIntent.FLAG_UPDATE_CURRENT);

    mBuilder.setContentIntent(resultPendingIntent);
    NotificationManager notificationManager = (NotificationManager) context.getSystemService
            (Context.NOTIFICATION_SERVICE);
    // mId allows you to update the notification later on.
    notificationManager.notify(NOTIFICATION_ID, mBuilder.build());
</code>```

I haven't gone with using the SharedPreferences because the whole process of retrieving the counter value and restarting the activity could hold the counter for some time which may make lose its accuracy.

Body:
This is how I manage to solve the problem.
In the manifest.xml file set android:launchMode="singleTop" for that activity. And then you build the notification as follows:

NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(context)
            .setSmallIcon(R.drawable.ic_directions_run_white_24dp).setContentTitle("My " +
                    "notification").setContentText("Hello World!");
    // Creates an explicit intent for an Activity in your app
    Intent resultIntent = new Intent(context, PlayActivity.class);
    resultIntent.setFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP);
    PendingIntent resultPendingIntent = PendingIntent.getActivity(context, 0, resultIntent,
            PendingIntent.FLAG_UPDATE_CURRENT);

    mBuilder.setContentIntent(resultPendingIntent);
    NotificationManager notificationManager = (NotificationManager) context.getSystemService
            (Context.NOTIFICATION_SERVICE);
    // mId allows you to update the notification later on.
    notificationManager.notify(NOTIFICATION_ID, mBuilder.build());

I haven't gone with using the SharedPreferences because the whole process of retrieving the counter value and restarting the activity could hold the counter for some time which may make lose its accuracy.


问:
How do I combine Result and State in Elm?
I am struggling with Elm's lack of monads. A library implementing the state monad for Elm (http://package.elm-lang.org/packages/folkertdev/elm-state/latest/State) has helped me quite a bit.

The problem is that I have now run into a situation where I have alternately nested Result and State types, when I only want to have one of each.

I tried to write a function with the following signature, but it seems impossible, because the inner Result is only known once the outer State is evaluated.

```<code>join : Result a (State s (Result a (State s x))) -> Result a (State s x)
</code>```

Maybe it would work if I put the Result inside the State in the return value, but that would generate a dummy State in case the outer Result is Err.

I think the right idea would be to make something that is both Result and State. Can someone who is familiar with Haskell monad transformers explain how they solve this kind of problem or suggest an alternative solution?

Here is a rough version of one place where the problem arises:

```<code>  generateConstraints environment value
  |> Result.map (State.map (\(value, valueC) ->
    Result.map
      (State.map2 (\this (body, bodyC) ->
        ( this
        , valueC ++ bodyC ++ [(this, body)]
        ))
      freshTypevar)
      (generateConstraints (extend environment name value) body))
  )
</code>```

答:
I ended up writing a monad that is both. I had to sacrifice the ability to fail before State is touched, because I need to be able to fail after.</p>

```<code>type alias Infer a = State Int (Result String a)

infer : a -> Infer a
infer x =
  State.state (Ok x)

map : (a -> value) -> Infer a -> Infer value
map f x =
  State.map (Result.map f) x

andThen : (a -> Infer b) -> Infer a -> Infer b
andThen f x =
  State.andThen
    (\r -> case r of
      Ok v -> f v
      Err e -> State.state <| Err e
    )
    x

andMap : Infer y -> Infer (y -> z) -> Infer z
andMap y =
  andThen (\g -> map g y)

map2 : (a -> b -> c) -> Infer a -> Infer b -> Infer c
map2 f x y =
  map f x
  |> andMap y

map3 : (a -> b -> c -> d) -> Infer a -> Infer b -> Infer c -> Infer d
map3 f a b c =
  map2 f a b
  |> andMap c

map4 : (a -> b -> c -> d -> e) -> Infer a -> Infer b -> Infer c -> Infer d -> Infer e
map4 f a b c d =
  map3 f a b c
  |> andMap d
</code>```

Body:
I am struggling with Elm's lack of monads. A library implementing the state monad for Elm (http://package.elm-lang.org/packages/folkertdev/elm-state/latest/State) has helped me quite a bit.

The problem is that I have now run into a situation where I have alternately nested Result and State types, when I only want to have one of each.

I tried to write a function with the following signature, but it seems impossible, because the inner Result is only known once the outer State is evaluated.

join : Result a (State s (Result a (State s x))) -> Result a (State s x)

Maybe it would work if I put the Result inside the State in the return value, but that would generate a dummy State in case the outer Result is Err.

I think the right idea would be to make something that is both Result and State. Can someone who is familiar with Haskell monad transformers explain how they solve this kind of problem or suggest an alternative solution?

Here is a rough version of one place where the problem arises:

  generateConstraints environment value
  |> Result.map (State.map (\(value, valueC) ->
    Result.map
      (State.map2 (\this (body, bodyC) ->
        ( this
        , valueC ++ bodyC ++ [(this, body)]
        ))
      freshTypevar)
      (generateConstraints (extend environment name value) body))
  )

Body:
I ended up writing a monad that is both. I had to sacrifice the ability to fail before State is touched, because I need to be able to fail after.

type alias Infer a = State Int (Result String a)

infer : a -> Infer a
infer x =
  State.state (Ok x)

map : (a -> value) -> Infer a -> Infer value
map f x =
  State.map (Result.map f) x

andThen : (a -> Infer b) -> Infer a -> Infer b
andThen f x =
  State.andThen
    (\r -> case r of
      Ok v -> f v
      Err e -> State.state <| Err e
    )
    x

andMap : Infer y -> Infer (y -> z) -> Infer z
andMap y =
  andThen (\g -> map g y)

map2 : (a -> b -> c) -> Infer a -> Infer b -> Infer c
map2 f x y =
  map f x
  |> andMap y

map3 : (a -> b -> c -> d) -> Infer a -> Infer b -> Infer c -> Infer d
map3 f a b c =
  map2 f a b
  |> andMap c

map4 : (a -> b -> c -> d -> e) -> Infer a -> Infer b -> Infer c -> Infer d -> Infer e
map4 f a b c d =
  map3 f a b c
  |> andMap d


问:
How to format cells so they only accept numbers
How do I make a cell only accept numbers? I.e. you can't enter text, it will only allow numeric values to be entered based on the criteria of dropdown from another cell.

If A is BYB, then only numbers should be entered in B.
If A is with any other data, only text should be entered in B.

答:
use data validation custom formula on your cell

select your cell (ex cell B1 [selected] and constraint of type is on A1)

select custom validation in: main tab / data / data validation /data validation

enter formula: =(type(B1)=A1)

type() function return the value 1 for integer, 2 for string. So for number only, set A1 to 1.

Adapt the formula according your need (ex for same format as A1 =(type(b1)=type(a1)), ...)


问:
SVG, forming lines into an image
I'm forming an image in SVG from a bitmap using svgwrite and python where each line is rotated by theta around a common origin into a fan like-pattern. Currently this image is running around 10 MB for 128 lines largely because the excessive amount of floating point retained in the 79000+ line segments (one line segment per pixel).

I'd like to get the image size down significantly by drawing a single line from the origin out to the end-point and then stretch one line 'image' over that SVG line. Is this possible using SVG? Beyond that, I'm open to any suggestion that might get the size down significantly and so I later I can animate the lines in place.

答:
How about this solution (see fiddle):

Slice the image up  in the number of strips you need. For the example in the linked fiddle, I used ImageMagick as follows to cut up a 128x128 PNG image into 128 vertical strips:

convert image.png -crop 1x128 +repage +adjoin strip-%d.png

Convert all the image strips to data URI format and embed them in the SVG. I used this bash one-liner:

for i in strip-*.png; do echo "data:image/png;base64,$(openssl base64 < $i | tr -d '\n')"; done > data-uris.txt

In the SVG, use the transform() attribute on the image strip elements to rotate them to the required degree.

For a 128x128 PNG icon of 16.4KB, I end up with an SVG file of 128.1KB. Most of that is the base64-encoded image data (the total size of the 128 PNG strips is already 85.1KB). It could be further reduced a little by rounding of some floats, but I don't think there's a whole lot to be gained.

There might be another approach possible where you embed the image as a whole, and reference another clipped section of the same image over and over, but I couldn't get that to work.

Title: SVG, forming lines into an image


问:
Normalizing a variety of properties with similar data types
I'm working on setting up a database to house properties related to a game, for example whether or not it supports multiplayer, what genres it is, release dates, etc.

It seems like creating two additional tables (genres, genres_data for example) for each category type isn't nearly as dynamic as it could be. My initial thought was to set it up one of two ways...

Have a games table with skeletal information, then a properties table to list all the properties, and a third table to contain all the data related to the game, where essentially only the columns related to each property are used:

```<code>games
-----------
game_id
... relevant data

properties
-----------
property_id
title
type
category

properties_data
---------------
game_id
property_id
bool
min
max
date
text(max255)
longtext
</code>```

Or, have the games table the same, and have properties include a column name then use columns in the third table:

```<code>properties
--------------
property_id
title
type
category
column_name

properties_data
----------------
game_id
title
description
release_date_au
release_date_jp
genre_rpg
genre_fps
platform_360
platform_ps3
platform_pc
has_leaderboards
has_downloadable_content
... etc
</code>```

What's the practical approach in this sort of scenario where you have a half dozen or so types of data related to a row, but a large number of categories and supporting properties in each category? It doesn't seem efficient to make a table for each property type or category (to me).

答:
This appears to be a typical Supertype-subtype cluster of tables. Except you have not identified it as such.  So, identify it formally, and normalise the data.

place common columns in the Supertype (parent)

place all columns specific to each Subtype in a separate child table

so that you end up with no optional columns

if you do, then you need another level of sub-table.

If you go for "dynamically" populated tables, you lose all the control of static tables in a db with the busienss rules defined in DDL (not code).  In that case, be aware that these loosely defined tables are famous for ending up as a mess with no data integrity.  Read this recent answer to get some context.

Link to Related Answer

The point is, if you do that "dynamic" stuff, do it properly.

But I do not believe you need to go that far.  With an ordinary Rdb, you can maintain full relational power and flexibility.  More tables are the nature of an Rdb, nothing to be scared of.  Done properly, you will have full control, and speed.  Which takes me back to the first para.

Body:
I'm working on setting up a database to house properties related to a game, for example whether or not it supports multiplayer, what genres it is, release dates, etc.

It seems like creating two additional tables (genres, genres_data for example) for each category type isn't nearly as dynamic as it could be. My initial thought was to set it up one of two ways...

Have a games table with skeletal information, then a properties table to list all the properties, and a third table to contain all the data related to the game, where essentially only the columns related to each property are used:

games
-----------
game_id
... relevant data

properties
-----------
property_id
title
type
category

properties_data
---------------
game_id
property_id
bool
min
max
date
text(max255)
longtext

Or, have the games table the same, and have properties include a column name then use columns in the third table:

properties
--------------
property_id
title
type
category
column_name

properties_data
----------------
game_id
title
description
release_date_au
release_date_jp
genre_rpg
genre_fps
platform_360
platform_ps3
platform_pc
has_leaderboards
has_downloadable_content
... etc

What's the practical approach in this sort of scenario where you have a half dozen or so types of data related to a row, but a large number of categories and supporting properties in each category? It doesn't seem efficient to make a table for each property type or category (to me).


问:
Linq Group by to column
I have a list of items with a property code and I want to group by eventId and create a table representation where code values are transformed to columns.
Every triple (event, code,amount) is unique.

I want to transform this

```<code>eventId code  amount
  1      A     100
  1      B     101
  1      C     102
  2      A     103
  2      C     104
  3      B     105
  ....
</code>```

to this

```<code>eventId  A    B   C
 1      100  101 102
 2      103   0  104
 3       0   105  0
 ...

var table=from x in list
    group x by x.eventId into gr
    select new
           {
              eventId=gr.Key,
              ....
           }
</code>```

答:
It's actually quite neat to use a lookup:

```<code>var table =
    from x in list
    group x by x.eventId into gr
    let lookup = gr.ToLookup(y => y.code, y => y.amount)
    select new
    {
        eventId = gr.Key,
        A = lookup["A"].Sum(),
        B = lookup["B"].Sum(),
        C = lookup["C"].Sum(),
    };
</code>```

I get this result:

Title: Linq Group by to column

Body:
I have a list of items with a property code and I want to group by eventId and create a table representation where code values are transformed to columns.
Every triple (event, code,amount) is unique.

I want to transform this

eventId code  amount
  1      A     100
  1      B     101
  1      C     102
  2      A     103
  2      C     104
  3      B     105
  ....

to this

eventId  A    B   C
 1      100  101 102
 2      103   0  104
 3       0   105  0
 ...

var table=from x in list
    group x by x.eventId into gr
    select new
           {
              eventId=gr.Key,
              ....
           }

Body:
It's actually quite neat to use a lookup:

var table =
    from x in list
    group x by x.eventId into gr
    let lookup = gr.ToLookup(y => y.code, y => y.amount)
    select new
    {
        eventId = gr.Key,
        A = lookup["A"].Sum(),
        B = lookup["B"].Sum(),
        C = lookup["C"].Sum(),
    };

I get this result:


问:
Android: OpenGraph Stories sharing in Facebook with SDK 4.0
I am trying to implement achievements for sharing to facebook when the player unlocks a badge. Have made an object using the object browser in facebook developer console. I made Action-types and object-types and made a custom story. Now i am stuck trying to share the story to facebook. The documentation given by facebook is inadequate. Even the sample code given by facebook uses v3.x

Sample code given by facebook is given below. Couldnt find any good documentation.

Code for Object

```<code>Bundle params = new Bundle();
Request request = new Request(
    Session.getActiveSession(),
    "me/objects/enguru_app:badge",
    params,
    HttpMethod.POST
);
Response response = request.executeAndWait();
// handle the response
</code>```

Code for Action

```<code>Bundle params = new Bundle();
params.putString("badge", "http://samples.ogp.me/1114467558579559");
Request request = new Request(
    Session.getActiveSession(),
    "me/enguru_app:unlocked",
    params,
    HttpMethod.POST
);
Response response = request.executeAndWait();
// handle the response
</code>```

答:
If you are looking for how to share without using ShareDialog:

```<code>ShareApi shareApi = new ShareApi(content);
shareApi.share(new FacebookCallback<Sharer.Result>() {
        @Override
        public void onSuccess(Sharer.Result result) {

        }

        @Override
        public void onCancel() {

        }

        @Override
        public void onError(FacebookException error) {

        }
});
</code>```

Also you probably want to check shareApi.canShare()

Body:
I am trying to implement achievements for sharing to facebook when the player unlocks a badge. Have made an object using the object browser in facebook developer console. I made Action-types and object-types and made a custom story. Now i am stuck trying to share the story to facebook. The documentation given by facebook is inadequate. Even the sample code given by facebook uses v3.x

Sample code given by facebook is given below. Couldnt find any good documentation.

Code for Object

Bundle params = new Bundle();
Request request = new Request(
    Session.getActiveSession(),
    "me/objects/enguru_app:badge",
    params,
    HttpMethod.POST
);
Response response = request.executeAndWait();
// handle the response

Code for Action

Bundle params = new Bundle();
params.putString("badge", "http://samples.ogp.me/1114467558579559");
Request request = new Request(
    Session.getActiveSession(),
    "me/enguru_app:unlocked",
    params,
    HttpMethod.POST
);
Response response = request.executeAndWait();
// handle the response

Body:
If you are looking for how to share without using ShareDialog:

ShareApi shareApi = new ShareApi(content);
shareApi.share(new FacebookCallback<Sharer.Result>() {
        @Override
        public void onSuccess(Sharer.Result result) {

        }

        @Override
        public void onCancel() {

        }

        @Override
        public void onError(FacebookException error) {

        }
});

Also you probably want to check shareApi.canShare()


问:
How to create a library
I have some code which I want to organize into a class or library for other developers to use more easily on their website.

The way I use the class now is to instantiate an instance of it and start calling the functions I need as I need them.

```<code>$class_object = new MyClass();
$class_object->myFunction();
</code>```

Is this basically all I need to make a library, or do I need to make further changes to turn this into a library?

答:
It depends on what exactly your library is. A class is a good solution if you are describing an object which can have properties and methods, and all the actions are related to that object.

If you only have a collection of functions and you can assume users will have PHP 5.3+, then you might just define them under a namespace.

Title: How to create a library

Body:
I have some code which I want to organize into a class or library for other developers to use more easily on their website.

The way I use the class now is to instantiate an instance of it and start calling the functions I need as I need them.

$class_object = new MyClass();
$class_object->myFunction();

Is this basically all I need to make a library, or do I need to make further changes to turn this into a library?


问:
Hibernate, SINGLE_TABLE Inheritance with abstract class in the middle of the hierarchy
Consider the following entity hierarchy tree:

```<code>-  Parameter (abstract)
-- ConstantParameter
-- GenerableParameter (abstract)
--- AnalogParameter
--- DigitalParameter
</code>```

On the db side, there is a parameters table with a discriminator column category that can take the following values constant, analog or digital.

Parameter abstract root entity and leaf entities can easily be mapped using SINGLE_TABLE inheritance and using category column as discriminator column.

Now, an abstract entity GenerableParameter has been added on the tree between Parameter and (AnalogParameter & DigitalParameter) to denote a specific behaviour which applies only to theses two leaf entities.

How can i map this intermediary abstract entity GenerableParameter in order to be able to query on it (in my case it means create a Repository using Spring data jpa) ?

Thanks.

答:
Ok so i answer myself because i have found the solution.

In fact it works out of the box (have not tested before ask the question because i wanted some lightning about implementation).

The GenerableParameter abstract entity only needs @Entity. I am able to query on it. The results are as expected: ConstantParameter records are discarded.

Body:
Consider the following entity hierarchy tree:

-  Parameter (abstract)
-- ConstantParameter
-- GenerableParameter (abstract)
--- AnalogParameter
--- DigitalParameter

On the db side, there is a parameters table with a discriminator column category that can take the following values constant, analog or digital.

Parameter abstract root entity and leaf entities can easily be mapped using SINGLE_TABLE inheritance and using category column as discriminator column.

Now, an abstract entity GenerableParameter has been added on the tree between Parameter and (AnalogParameter & DigitalParameter) to denote a specific behaviour which applies only to theses two leaf entities.

How can i map this intermediary abstract entity GenerableParameter in order to be able to query on it (in my case it means create a Repository using Spring data jpa) ?

Thanks.


问:
Lombok annotations vs code coverage in Cobertura or similar tool
Configure cobertura to ignore certain blocks of code

From what I have read from above question, there's no way in Cobertura to exclude given code part from being tested versus having coverage in tests.

Is that true? /  Is it possible in any simmilar tool?

I'm usuing Lombok annotations @Getter, @Setter and so on, which are great, but they result in being 'red' in coverage report, even if I'm testing getter and setter methods. - I would like to do something with that... Is there any way to fix this?

答:
Lombok adds a @javax.annotation.Generated annotation (1). But this annotation has source retention, i.e. your coverage tool can't see it any more :-(

Lombok 1.16.14 just fixed issue-1014 by adding an option to generate a @lombok.Generated annotation instead; just configure lombok.addLombokGeneratedAnnotation(2).

Cobertura can be configured to skip methods with some annotation, so most of the generated code won't count against your coverage.

JaCoCo doesn't provide a configuration mechanism to skip on certain annotations. Issue-15 tries to fix this (and much more) without requiring any configuration.

(1) If not disabled with lombok.addGeneratedAnnotation which is now deprecated and should be replaced with lombok.addJavaxGeneratedAnnotation

(2) see lombok config

(3) see this comment


问:
How change size of imageView(SubView) in Cell in CollectionView
I have a problem with image in cell. More precisely image in assets are bigger than cell. How i can transform image to smaller size? </p>

<p>`   var photos = ["IMG_3814","IMG_3803"]</p>

```<code>override func viewDidLoad() {
    super.viewDidLoad()

    // Do any additional setup after loading the view.
}

func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
    return photos.count
}

func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {

    let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "cellID", for: indexPath)
    let img = photos[indexPath.row]
    let imageView: UIImageView = UIImageView(image: UIImage(named: img))

    cell.contentView.addSubview(imageView)

    return cell
}`
</code>```

答:
Try this </p>

```<code> let img = UIImage(named: photos[indexPath.row])
 let imageView: UIImageView = UIImageView(frame: cell.frame)
 imageView.image = img
 imageView.contentMode = .scaleAspectFit
 imageView.clipsToBounds = true
 cell.contentView.addSubview(imageView)
</code>```

Body:
I have a problem with image in cell. More precisely image in assets are bigger than cell. How i can transform image to smaller size?

`   var photos = ["IMG_3814","IMG_3803"]

override func viewDidLoad() {
    super.viewDidLoad()

    // Do any additional setup after loading the view.
}

func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
    return photos.count
}

func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {

    let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "cellID", for: indexPath)
    let img = photos[indexPath.row]
    let imageView: UIImageView = UIImageView(image: UIImage(named: img))

    cell.contentView.addSubview(imageView)

    return cell
}`

Body:
Try this

 let img = UIImage(named: photos[indexPath.row])
 let imageView: UIImageView = UIImageView(frame: cell.frame)
 imageView.image = img
 imageView.contentMode = .scaleAspectFit
 imageView.clipsToBounds = true
 cell.contentView.addSubview(imageView)


问:
Deleting a value at a time by it's location which is separated by a comma in column of a mysql table
This is table that has all the skills which candidate can add to their profile in candidate table

And this is where candidate has added desired skills which is separated by comma,

Now i am stuck , problem is how can i delete those skills which i dont want anymore to be in my profile. This is separated by a comma that's why i am finding it delete individualy

```<code>$sql_r = "select expert_skills, inter_skills, beginner_skills
            from user_personal_details
            WHERE upd_user_id = '". $_SESSION["user_id"] ."'";

$skills_render = $this->model->execute_query_all($sql_r);

$arr1=explode(",",$skills_render['0']['expert_skills']);

$ty = array_keys($arr1);
$ty1 = array_values($arr1);

$location = $_POST['skill_location'];

echo $location;
</code>```

$location variable i.e skill id, i am taking from front end, how can i delete by location

答: You can use array_diff( [3, 2, 1, 5], [2] ) will result in [3, 1, 5] </p>

Body:
This is table that has all the skills which candidate can add to their profile in candidate table

And this is where candidate has added desired skills which is separated by comma,

Now i am stuck , problem is how can i delete those skills which i dont want anymore to be in my profile. This is separated by a comma that's why i am finding it delete individualy

$sql_r = "select expert_skills, inter_skills, beginner_skills
            from user_personal_details
            WHERE upd_user_id = '". $_SESSION["user_id"] ."'";

$skills_render = $this->model->execute_query_all($sql_r);

$arr1=explode(",",$skills_render['0']['expert_skills']);

$ty = array_keys($arr1);
$ty1 = array_values($arr1);

$location = $_POST['skill_location'];

echo $location;

$location variable i.e skill id, i am taking from front end, how can i delete by location


问:
CSS: Can I use the classes of nested elements to narrow css down?
Here is an example of what I have:

```<code><div class="node node-blog">
  <div class="field-item even">
    <img src="image.png"/>
  </div>
</div>
</code>```

What I would like to do is apply a style to the img element only when inside the node-blog and field-item divs, but this does not work:

```<code>.node-blog .field-item img {float:right;}
</code>```

Sure I am doing something wrong.

Thanks.

答: All else being equal, it should work. The problem is in a piece of code you aren't sharing with us.</p>

Body:
Here is an example of what I have:

What I would like to do is apply a style to the img element only when inside the node-blog and field-item divs, but this does not work:

.node-blog .field-item img {float:right;}

Sure I am doing something wrong.

Thanks.