问:
gulp: Could not find an option named "sourcemap"
it's the fifth day when I'm fighting this and I'm almost ready to give up (but I can't). I picked up a project from someone else and I'm trying to make gulp work.

I ended up with "could not find an option named "sourcemap".

```<code>Starting 'watch'...
[11:48:54] Finished 'watch' after 2.75 s
[11:49:32] Starting 'styles'...
[11:49:33] Could not find an option named "sourcemap".
Usage: dart-sass <input>
</code>```

in gulpfile.js I've got this:

```<code>gulp.task('styles', () => {
    return sass(['_/sass/main.scss', '_/sass/editor.scss', '_/sass/career-form.scss'], {
    sourcemap: true, style: "compact"
    })
})
</code>```

even when I delete the sourcemap: true part, the error is still there. Gulp works with js files, but not with CSS. not sure if that matter.

I use gulp-ruby-sass and I tried everything there were related to the issue, but no luck. (The guy that worked before on that is not helpful - "I don't know, go Google the error").

I already tried to rebuild node_modules, five times, maybe more, checked different versions of gulp-ruby-sass and gulp-sourcemaps. Looked for another usage of sourcemap but no luck.

答:
From the gulp-ruby-sass sourcemap option documentation it looks like if you use the sourcemap option than you must also use gulp-sourcemaps.

sourcemap

                Type: boolean
  Default: false

Initialize and pass Sass sourcemaps to gulp-sourcemaps.

So their code:

```<code>const gulp = require('gulp');
const sass = require('gulp-ruby-sass');
const sourcemaps = require('gulp-sourcemaps');

gulp.task('sass', () =>
    sass('source/file.scss', {sourcemap: true})
        .on('error', sass.logError)
        // for inline sourcemaps
        .pipe(sourcemaps.write())
        // for file sourcemaps
        .pipe(sourcemaps.write('maps', {
            includeContent: false,
            sourceRoot: 'source'
        }))
        .pipe(gulp.dest('result'))
);
</code>```

So try them together.  [Why you still get an error message if you remove the sourcemap option is strange.]

Body:
it's the fifth day when I'm fighting this and I'm almost ready to give up (but I can't). I picked up a project from someone else and I'm trying to make gulp work.

I ended up with "could not find an option named "sourcemap".

Starting 'watch'...
[11:48:54] Finished 'watch' after 2.75 s
[11:49:32] Starting 'styles'...
[11:49:33] Could not find an option named "sourcemap".
Usage: dart-sass <input>

in gulpfile.js I've got this:

gulp.task('styles', () => {
    return sass(['_/sass/main.scss', '_/sass/editor.scss', '_/sass/career-form.scss'], {
    sourcemap: true, style: "compact"
    })
})

even when I delete the sourcemap: true part, the error is still there. Gulp works with js files, but not with CSS. not sure if that matter.

I use gulp-ruby-sass and I tried everything there were related to the issue, but no luck. (The guy that worked before on that is not helpful - "I don't know, go Google the error").

I already tried to rebuild node_modules, five times, maybe more, checked different versions of gulp-ruby-sass and gulp-sourcemaps. Looked for another usage of sourcemap but no luck.

Body:
From the gulp-ruby-sass sourcemap option documentation it looks like if you use the sourcemap option than you must also use gulp-sourcemaps.

sourcemap

                Type: boolean
  Default: false

Initialize and pass Sass sourcemaps to gulp-sourcemaps.

So their code:

const gulp = require('gulp');
const sass = require('gulp-ruby-sass');
const sourcemaps = require('gulp-sourcemaps');

gulp.task('sass', () =>
    sass('source/file.scss', {sourcemap: true})
        .on('error', sass.logError)
        // for inline sourcemaps
        .pipe(sourcemaps.write())
        // for file sourcemaps
        .pipe(sourcemaps.write('maps', {
            includeContent: false,
            sourceRoot: 'source'
        }))
        .pipe(gulp.dest('result'))
);

So try them together.  [Why you still get an error message if you remove the sourcemap option is strange.]


来源: stackexchange

问:
Passing value as key in Firebase database rule
I have a database where family has members.

Family member database.

```<code>// Family 1 has user 1, user 2, user 3.
// Family 2 has user 4, user 5.
// family_id_x is uniquely generated by firebase.
// uid is uniquely generated by firebase on registration. (auth.uid)
// database 'family-member'
'family-member':[
  'family_id_1': 'uid_1',
  'family_id_1': 'uid_2',
  'family_id_1': 'uid_3'
  'family_id_2': 'uid_4'
  'family_id_2': 'uid_5'
]
</code>```

Furniture database

```<code>// A family member can create furniture for the family.
// database 'furniture'
'furniture':[
  'furniture_id_1': {
    'furnitureName': "Mahogany Dining Table",
    'familyKey': 'family_id_1'
  }
]
</code>```

So I created a database rule to see if the user is able to make a new furniture.
I've logged in with uid_1.
Then I tried the following.

```<code>// database rule for furniture.
"furniture": {
   ".write": "auth != null && (root.child('family-member').child(
   newData.child(familyKey).val() // Problem!
   ).child(auth.uid).exists())
}
</code>```

This fails. I suspected the underlined part is the cause. So I hard coded.

```<code>"furniture": {
   ".write": "auth != null && (root.child('family-member').child(
   'family_id_1' // HardCode! Now works.
   ).child(auth.uid).exists())
}
</code>```

It works.

Please let me know what I should do in order to solve this problem.

Edit: product => furniture, Miscellaneous syntax errors

答:
It was a simple typo.

I needed to put quotation around the key

```<code>newData.child(familyKey).val() // Problem!

newData.child('familyKey').val() // Solution!
</code>```

Closing.

ContentLicense: CC BY-SA 3.0

Body:
I have a database where family has members.

Family member database.

// Family 1 has user 1, user 2, user 3.
// Family 2 has user 4, user 5.
// family_id_x is uniquely generated by firebase.
// uid is uniquely generated by firebase on registration. (auth.uid)
// database 'family-member'
'family-member':[
  'family_id_1': 'uid_1',
  'family_id_1': 'uid_2',
  'family_id_1': 'uid_3'
  'family_id_2': 'uid_4'
  'family_id_2': 'uid_5'
]

Furniture database

// A family member can create furniture for the family.
// database 'furniture'
'furniture':[
  'furniture_id_1': {
    'furnitureName': "Mahogany Dining Table",
    'familyKey': 'family_id_1'
  }
]

So I created a database rule to see if the user is able to make a new furniture.
I've logged in with uid_1.
Then I tried the following.

// database rule for furniture.
"furniture": {
   ".write": "auth != null && (root.child('family-member').child(
   newData.child(familyKey).val() // Problem!
   ).child(auth.uid).exists())
}

This fails. I suspected the underlined part is the cause. So I hard coded.

"furniture": {
   ".write": "auth != null && (root.child('family-member').child(
   'family_id_1' // HardCode! Now works.
   ).child(auth.uid).exists())
}

It works.

Please let me know what I should do in order to solve this problem.

Edit: product => furniture, Miscellaneous syntax errors

Body:
It was a simple typo.

I needed to put quotation around the key

newData.child(familyKey).val() // Problem!

newData.child('familyKey').val() // Solution!

Closing.


问:
Custom exception type
Can I define custom types for user-defined exceptions in JavaScript?  If so, how would I do it?</p>

答:
```<code>function MyError(message) {
 this.message = message;
}

MyError.prototype = new Error;
</code>```

This allows for usage like..

```<code>try {
  something();
 } catch(e) {
  if(e instanceof MyError)
   doSomethingElse();
  else if(e instanceof Error)
   andNowForSomethingCompletelyDifferent();
}
</code>```

OwnerDisplayName: Manki

ContentLicense: CC BY-SA 4.0

Title: Custom exception type

Body:
function MyError(message) {
 this.message = message;
}

MyError.prototype = new Error;

This allows for usage like..

try {
  something();
 } catch(e) {
  if(e instanceof MyError)
   doSomethingElse();
  else if(e instanceof Error)
   andNowForSomethingCompletelyDifferent();
}

ContentLicense: CC BY-SA 2.5


问:
Error installing tizen studio on windows 10
No matter which of the three tizen studio 2.0 installers I try they all don't work as they won't accept any path. The CLI installer gives the most detailed description:

** The directory you specify is not allowed to install the Tizen Studio. Some tools of the Tizen Studio will not properly work in the directory with administrator privilege or read-only access rights for your account.=> path

I have tried starting the installer with admin rights and owning the destination folders. Additionally, I switched from JDK 9 to 8.

Still, there seems no way to get the installer running. Any ideas what the reason could be? Thanks!

答:
I had this problem as well (on my Windows 8.1 machine), and ended up using the previous version of Tizen Studio Installer (version 1.3)

https://download.tizen.org/sdk/Installer/tizen-studio_1.3/


问:
I am getting error while only using "Data" class library reference in my ASPNet core 1.0 Project Visual studio 2017
Severity    Code    Description Project File    Line    Suppression State

Error CS1705  Assembly 'Data' with identity 'Data, Version=1.0.0.0,
  Culture=neutral, PublicKeyToken=null' uses 'System.Runtime,
  Version=4.1.2.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a'
  which has a higher version than referenced assembly 'System.Runtime'
  with identity 'System.Runtime, Version=4.1.0.0, Culture=neutral,
  PublicKeyToken=b03f5f7f11d50a3a'  "Project"   C:\Users\Sit\source\repos\WebApplication8\WebApplication8\Controllers\Login\LoginController.cs  29  Active

答:
First, this is an absolute awful question. For future reference, please refer to How do I ask a good question?

That said, I can parse enough from what little you gave to tell you that the issue is that your Data project is referencing a different version of System.Runtime than the application you're referencing it in, specifically a higher version. You cannot do that. Any shared references must be the same. In other words, you either need to downgrade System.Runtime in your Data project or upgrade it in your other project.


问:
How to get Git to exclude a local directory from PUSH to remote, but still part of local repo
Using git, I would like to be able to keep a certain folder as part of my local project (feature it in branches, etc) yet I don't want this directory getting pushed up to the public git server.

The folder in question has some CLI Java stuff that the project does not need, but I would like to keep in in sync with the branch work that will go live.

Is this possible?

答:
If you don't need to track those files at all...

... you can make git ignore them.

If you want to track them locally...

... but not have them in the remote repo I can only give you some hints/ideas to thing I never tried, but you will probably end up having different repositories and things might get a little nasty.

I would have a look at (from maybe ok to probably quite messy and a bad idea):

Nested repositories

Subtrees, Submodules, git-repo, git-subrepo or similar

Nest repositories manually: Make git ignore the subfolder, set up an own repository, make sure commits somehow align

Remove on push: (Drawback: You probably won't be able to properly diff as histories only match for the temporary repository. You could of course somehow also hack your diffing, making the setup even messier.)

Steps:

Before pushing clone the repository to a temporary folder

Remove your subfolder from the entire history inside the newly created clone (getting another repository with different commit hashes)

Push the newly created repository

Options: Trigger:

pre-push Hook

Manually do the above instead of using git push

Options: Removal:

Tool like BFG-Repo-Cleaner

git-filter-branch by hand

Again: I didn't use either of them and don't know their drawbacks, pitfalls etc. but to me it seems subtrees are by far the best solution from the above.

Most of the rest does seem quite messy to me but at the end of the day the only thing that matters is what works for you.

Ship lousy stuff, but ship.

...be it in Wasabi


问:
How can the Ctrl+0 through Ctrl+9 key bindings be mapped in Vim?
Why can’t I map—using any of the *map commands (nmap, imap, etc.)—the Ctrl+0 through Ctrl+9 key strokes? In fact, it appears that some of them, like Ctrl+3, are bound to ^[ at the X Window level. How can I make Vim override those default bindings?

That is, if I do imap <C-3> fancystuffhere, typing Ctrl+3 in Insert mode puts me into Normal mode, instead of inserting 'fancystuffhere'.

I’m using X11 on Linux.

答:
Both Vim and gVim use byte queue instead of keypress event queue, so that values from 0x40 (@) to 0x5F (_), including the 0x41–0x5A (A–Z) range) have corresponding control characters (you can get their codes by subtracting 0x40 from their value). Because of this, no characters above and beyond this range can be used together with C- (Ctrl).

It is also the reason why C-S- (Ctrl+Shift) for alphanumeric keys does not work even in gVim—functional keys generate more then one byte, so <C-S-F1> may work. Replacing <C-3> with <Esc> is done by terminal; you can try mapping it in almost any GUI application and see that <Esc> does not get mapped.


问:
How can I Dump() a Newtonsoft JObject in LinqPad?
In LinqPad, trying to call .Dump() on a Newtonsoft JSON.Net JObject yields an exception:

RuntimeBinderException: 'Newtonsoft.Json.Linq.JObject' does not contain a definition for 'Dump'.

This works for almost everything else in LinqPad.  I'd like to figure out a method that will Dump out a Newtonsoft JObject, just like other objects, showing property names, values, etc.

I've already figured out how to get it to dump the JSON string, but I'd like to see an object get output rather than just a text string.

答:
Using LINQPad's new ToDump you can .Dump() a Newtonsoft JSON.Net JObject directly.

Add this snippet to LINQPad's My Extensions query

```<code>static Object ToDump(Object input)
{
    var json = input as JObject;
    if (json != null)
        return json.ToObject<ExpandoObject>();
    return input;
}
</code>```

You will also need to add a reference to Netwonsoft.Json the same as you did for your main query

Body:
Using LINQPad's new ToDump you can .Dump() a Newtonsoft JSON.Net JObject directly.

Add this snippet to LINQPad's My Extensions query

static Object ToDump(Object input)
{
    var json = input as JObject;
    if (json != null)
        return json.ToObject<ExpandoObject>();
    return input;
}

You will also need to add a reference to Netwonsoft.Json the same as you did for your main query


问:
Class path must be set or restored default
I was doing a Hibernate project while creating pojo I am getting this error "Class path must be set or restored default"  while doing console configuration I have all the jars which are working with other projects please help me with this</p>

答:
This error mainly appears when some jars or sql drivers is missing. You said that you have added all the jars, but try to check it again carefully. If your jars is placed not in your project so you need to check if they still exist in specified path. It's recommended to copy them to the project folder first and then add them by 'add jar' (if you using eclipse).

I hope it helps. But you can give more details to understand what real problem is.


问:
GitHub pages custom domain infinite redirect loop
I'm having an absolute nightmare trying to setup a custom TLD domain with github pages.
For some reason http://www is redirecting to http:// and then back to http://www over and over in an infinite redirect loop.

My settings with 123-reg are:

```<code>DNS ENTRY   TYPE        TARGET/DESTINATION
@           A           204.232.175.78
www         CNAME       scottyv.me.
</code>```

And i have a CNAME file setup correctly in my repo.
Can someone please tell me what i'm doing wrong?

答: I had a similar problem.  In my case, my DNS was correct (Network Solutions), but I had left out the "www" in my CNAME file.  I had "yoursite.com" instead of "www.yoursite.com".  Once I added the "www", the infinite redirects were fixed.</p>

Body:
I'm having an absolute nightmare trying to setup a custom TLD domain with github pages.
For some reason http://www is redirecting to http:// and then back to http://www over and over in an infinite redirect loop.

My settings with 123-reg are:

DNS ENTRY   TYPE        TARGET/DESTINATION
@           A           204.232.175.78
www         CNAME       scottyv.me.

And i have a CNAME file setup correctly in my repo.
Can someone please tell me what i'm doing wrong?


问:
powershell ConvertTo-Html add class
My script is pulling information from server, than it converts to HTML and send the report by email.
Snippet:

```<code>$sourceFile = "log.log"
$targetFile = "log.html"
$file = Get-Content $sourceFile
$fileLine = @()
foreach ($Line in $file) {
  $MyObject = New-Object -TypeName PSObject
  Add-Member -InputObject $MyObject -Type NoteProperty -Name Load -Value $Line
  $fileLine += $MyObject
}
$fileLine | ConvertTo-Html -Property Load -head '<style> .tdclass{color:red;} </style>' | Out-File $target
</code>```

Current HTML report snippet:

```<code><table>
<colgroup><col/></colgroup>
<tr><th>Load on servers</th></tr>
<tr><td>Server1 load is 2442</td></tr>
<tr><td>Server2 load is 6126</td></tr>
<tr><td>Server3 load is 6443</td></tr>
<tr><td> </td></tr>
<tr><td>Higher than 4000:</td></tr>
<tr><td>6126</td></tr>
<tr><td>6443</td></tr>
</table>
</code>```

This will generate an HTML report containing a table with tr and td.
Is there any method to make it generate td with classes, so I can insert the class name into the -head property with styles and make it red for the Higher than 4000: tds ?

答:
You can use the Get-Help ConvertTo-Html command you will get all parameters for the ConvertTo-Html command. Below is output:

```<code>ConvertTo-Html [[-Property] <Object[]>] [[-Head] <String[]>] [[-Title] <String>] [[-Body] <String[]>] [-As<String>] [-CssUri <Uri>] [-InputObject <PSObject>] [-PostContent <String[]>] [-PreContent <String[]>][<CommonParameters>]
</code>```

You can create an external CSS file and give the CSS file path in the [-CssUri] parameter.

Title: powershell ConvertTo-Html add class

Body:
My script is pulling information from server, than it converts to HTML and send the report by email.
Snippet:

$sourceFile = "log.log"
$targetFile = "log.html"
$file = Get-Content $sourceFile
$fileLine = @()
foreach ($Line in $file) {
  $MyObject = New-Object -TypeName PSObject
  Add-Member -InputObject $MyObject -Type NoteProperty -Name Load -Value $Line
  $fileLine += $MyObject
}
$fileLine | ConvertTo-Html -Property Load -head '' | Out-File $target

Current HTML report snippet:

<colgroup><col/></colgroup>

Load on servers

Server1 load is 2442

Server2 load is 6126

Server3 load is 6443

Higher than 4000:

6126

6443

This will generate an HTML report containing a table with tr and td.
Is there any method to make it generate td with classes, so I can insert the class name into the -head property with styles and make it red for the Higher than 4000: tds ?

Body:
You can use the Get-Help ConvertTo-Html command you will get all parameters for the ConvertTo-Html command. Below is output:

ConvertTo-Html [[-Property] <Object[]>] [[-Head] <String[]>] [[-Title] <String>] [[-Body] <String[]>] [-As<String>] [-CssUri <Uri>] [-InputObject <PSObject>] [-PostContent <String[]>] [-PreContent <String[]>][<CommonParameters>]

You can create an external CSS file and give the CSS file path in the [-CssUri] parameter.


问:
PHP: Converting Image to TIFF with imagemagick
I am trying to convert and image to a tiff using imagemagick but am running into a problem when trying to write the file. I get an error that says:

Unable to open image...
  error/blob.c/OpenBlob/2584'

This is the code I am using:

```<code>$im2 = new Imagick($image);
$im2->setImageFormat("tiff");
$im2->setImageColorSpace(5);
$im2->writeImage("test.tiff");
</code>```

$image is just a url I am passing to an image file. I am just running a simple test function to get it to work and put a test.tiff in the same folder.  What could I be doing wrong here? Having trouble finding much documentation on this.

答:
The argument of the Imagick constructor is to load a local image file. To load a remote image file, you should instantiate an Imagick object without arguments and either:

download the image content and pass it to the readImageBlob method, or

fopen the URL and pass it to the readImageFile method.

For example:

```<code>// assuming $image is an URL or path to a local file
$handle = fopen($image, 'rb');
$im2 = new Imagick();
$im2->readImageFile($handle);
$im2->setImageFormat("tiff");
$im2->setImageColorSpace(5);
$im2->writeImage("test.tiff");
fclose($handle);
$im2->destroy();
</code>```

Body:
I am trying to convert and image to a tiff using imagemagick but am running into a problem when trying to write the file. I get an error that says:

Unable to open image...
  error/blob.c/OpenBlob/2584'

This is the code I am using:

$im2 = new Imagick($image);
$im2->setImageFormat("tiff");
$im2->setImageColorSpace(5);
$im2->writeImage("test.tiff");

$image is just a url I am passing to an image file. I am just running a simple test function to get it to work and put a test.tiff in the same folder.  What could I be doing wrong here? Having trouble finding much documentation on this.

Body:
The argument of the Imagick constructor is to load a local image file. To load a remote image file, you should instantiate an Imagick object without arguments and either:

download the image content and pass it to the readImageBlob method, or

fopen the URL and pass it to the readImageFile method.

For example:

// assuming $image is an URL or path to a local file
$handle = fopen($image, 'rb');
$im2 = new Imagick();
$im2->readImageFile($handle);
$im2->setImageFormat("tiff");
$im2->setImageColorSpace(5);
$im2->writeImage("test.tiff");
fclose($handle);
$im2->destroy();


问:
How can one use JQuery to validate email addresses?
How can one use JQuery to validate email addresses?</p>

答:
You can use jQuery Validation and, in a single HTML line, you can validate the email and the email validation message: type="email" required data-msg-email="Enter a valid email account!"

You can use the data-msg-email parameter to place a personalized message or otherwise do not place this parameter and the default message will be displayed: "Please enter a valid email address."

Full example:

<form class="cmxform" id="commentForm" method="get" action="">
  <fieldset>

      E-Mail (required)
      <input id="cemail" type="email" name="email" required data-msg-email="Enter a valid email account!">

      <input class="submit" type="submit" value="Submit">

  </fieldset>
</form>

```

Body:
You can use jQuery Validation and, in a single HTML line, you can validate the email and the email validation message: type="email" required data-msg-email="Enter a valid email account!"

You can use the data-msg-email parameter to place a personalized message or otherwise do not place this parameter and the default message will be displayed: "Please enter a valid email address."

Full example:

<form class="cmxform" id="commentForm" method="get" action="">
  <fieldset>
    <p>
      <label for="cemail">E-Mail (required)</label>
      <input id="cemail" type="email" name="email" required data-msg-email="Enter a valid email account!">
    </p>
    <p>
      <input class="submit" type="submit" value="Submit">
    </p>
  </fieldset>
</form>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script type="text/javascript" src="https://cdn.jsdelivr.net/npm/jquery-validation@1.17.0/dist/jquery.validate.js"></script>
<script>
$("#commentForm").validate();
</script>


问:
Pandas DataFrame GroupBy sum/count to new DataFrame
My DataFrame is

```<code>State|City|Year|Budget|Income
S1|C1|2000|1000|1
S1|C2|2000|1200|2
S2|C3|2000|5500|3
</code>```

I need to get a new DataFrame with columns:

```<code>State, Year, Count, Sum_Budget, Sum_Income:
</code>```

That is,

```<code>State|Year|Count|Sum_Budget|Sum_Income
S1|2000|2|2200|3
S2|2000|1|5500|3
</code>```

In C# the code would be:

```<code>    dataframe
       .GroupBy(x => new { x.State, x.City})
       .Select(x => new {
          x.Key.State,
          x.Key.City,
          Count = x.Count(),
          Sum_Budget = x.Sum(y => y.Budget),
          Sum_Income= x.Sum(y => y.Income)
       }
}).ToArray();
</code>```

How do I do so with Pandas?

答:
Use agg:

```<code>d = {'Income':'Sum_Income','Budget':'Sum_Budget','City':'Count'}
agg_d = {'Budget':'sum', 'Income':'sum', 'City':'size'}
df = df.groupby(['State', 'Year'], as_index=False).agg(agg_d).rename(columns=d)

print (df)
   State  Year  Sum_Income  Sum_Budget  Count
0    S1  2000           3        2200      2
1    S2  2000           3        5500      1
</code>```

Body:
My DataFrame is

State|City|Year|Budget|Income
S1|C1|2000|1000|1
S1|C2|2000|1200|2
S2|C3|2000|5500|3

I need to get a new DataFrame with columns:

State, Year, Count, Sum_Budget, Sum_Income:

That is,

State|Year|Count|Sum_Budget|Sum_Income
S1|2000|2|2200|3
S2|2000|1|5500|3

In C# the code would be:

    dataframe
       .GroupBy(x => new { x.State, x.City})
       .Select(x => new {
          x.Key.State,
          x.Key.City,
          Count = x.Count(),
          Sum_Budget = x.Sum(y => y.Budget),
          Sum_Income= x.Sum(y => y.Income)
       }
}).ToArray();

How do I do so with Pandas?

Body:
Use agg:

d = {'Income':'Sum_Income','Budget':'Sum_Budget','City':'Count'}
agg_d = {'Budget':'sum', 'Income':'sum', 'City':'size'}
df = df.groupby(['State', 'Year'], as_index=False).agg(agg_d).rename(columns=d)

print (df)
   State  Year  Sum_Income  Sum_Budget  Count
0    S1  2000           3        2200      2
1    S2  2000           3        5500      1


问:
SQL improvement - UNION?
I have 2 tables: "packages" and "items".

"packages" has the following columns: pack_id | item_id

"items" has the following columns.......:    item_id | type

One package can have multiple items.

UPDATE:

Sample Data and Expected Results:

```<code>pack_id | item_id
1           1
1           2
1           3
2           2
2           1
3           4
3           5
3           6

item_id | type
1           C
2           F
3           Z
4           Z
5           Z
6           Z
</code>```

Expected result:

```<code>pack_id | pack_type
1           Mixed
2           Cool
3           Not Cool
</code>```

My question is:

Is there a better way to query these 2 tables, in order to get a 3rd one, having as columns: "pack_id" and the new column "pack_type"? Those UNIONs seem to add a huge amount of time to the run time.

```<code>    SELECT pack_id, pack_type
    FROM (
      -- CASE 1 - pack_type is 'Cool' - type 'C' or 'F', but not 'Z'
      SELECT  Distinct q1.pack_id, 'Cool' AS pack_type
        FROM (
            SELECT  Distinct p.pack_id, i.type
            FROM packages p
            INNER JOIN items i
                ON p.item_id = i.item_id
            WHERE i.type <> 'Z') q1
        WHERE q1.type IN ('C','F')

      UNION

      -- CASE 2 - pack_type is 'Not-Cool' - type 'Z', but not 'C' or 'F'
      SELECT  Distinct q2.pack_id, 'Not-Cool' AS pack_type
        FROM (
            SELECT  Distinct p.pack_id, i.type
            FROM packages p
            INNER JOIN items i
                ON p.item_id = i.item_id
            WHERE i.type = 'Z') q2
        WHERE q2.type NOT IN ('C','F')

      UNION

     -- CASE 3 - pack_type is 'Mixed' - type 'Z' and ('C' or 'F')
     SELECT  Distinct q3.pack_id, 'Mixed' AS pack_type
        FROM (
            SELECT  Distinct p.pack_id, i.type
            FROM packages p
            INNER JOIN items i
                ON p.item_id = i.item_id
            WHERE i.type = 'Z') q3
        WHERE q3.type IN ('C','F')
    ) m
</code>```

NOTE: some explication for the multiple comments that point to "A type cannot be Z and also C or F".

I also thought that, but the way I understand the behavior of the query is that if u say "type IN ('C','F')", it will look at each item of type 'C' or 'F' and get the package id that has that item. BUT, a package that has items of type 'C' or 'F' can also have items of type 'Z', hence the inner select, dealing with items of type 'Z' first.

答:
Even when isnt explain on the question I guess your package type is derived from the combination of items on it. So you need group the items on each package

SQL DEMO

```<code>WITH cte as (
     SELECT pack_id,
            COUNT(CASE WHEN i.type IN ('C','F') THEN 1 END) as total_CF,
            COUNT(CASE WHEN i.type = 'Z' THEN 1 END) as total_Z
     FROM packages p
     INNER JOIN items i
        ON p.item_id = i.item_id
     GROUP BY pack_id
)
SELECT pack_id,
       CASE WHEN total_CF > 0 and total_Z = 0 THEN 'Cool'
            WHEN total_CF = 0 and total_Z > 0 THEN 'Not Cool'
            WHEN total_CF > 0 and total_Z > 0 THEN 'Mixed'
         -- ELSE 'NOT determinated'
       END as type
FROM cte
</code>```

OUTPUT

Title: SQL improvement - UNION?

Body:
I have 2 tables: "packages" and "items".

"packages" has the following columns: pack_id | item_id

"items" has the following columns.......:    item_id | type

One package can have multiple items.

UPDATE:

Sample Data and Expected Results:

pack_id | item_id
1           1
1           2
1           3
2           2
2           1
3           4
3           5
3           6

item_id | type
1           C
2           F
3           Z
4           Z
5           Z
6           Z

Expected result:

pack_id | pack_type
1           Mixed
2           Cool
3           Not Cool

My question is:

Is there a better way to query these 2 tables, in order to get a 3rd one, having as columns: "pack_id" and the new column "pack_type"? Those UNIONs seem to add a huge amount of time to the run time.

    SELECT pack_id, pack_type
    FROM (
      -- CASE 1 - pack_type is 'Cool' - type 'C' or 'F', but not 'Z'
      SELECT  Distinct q1.pack_id, 'Cool' AS pack_type
        FROM (
            SELECT  Distinct p.pack_id, i.type
            FROM packages p
            INNER JOIN items i
                ON p.item_id = i.item_id
            WHERE i.type <> 'Z') q1
        WHERE q1.type IN ('C','F')

      UNION

      -- CASE 2 - pack_type is 'Not-Cool' - type 'Z', but not 'C' or 'F'
      SELECT  Distinct q2.pack_id, 'Not-Cool' AS pack_type
        FROM (
            SELECT  Distinct p.pack_id, i.type
            FROM packages p
            INNER JOIN items i
                ON p.item_id = i.item_id
            WHERE i.type = 'Z') q2
        WHERE q2.type NOT IN ('C','F')

      UNION

     -- CASE 3 - pack_type is 'Mixed' - type 'Z' and ('C' or 'F')
     SELECT  Distinct q3.pack_id, 'Mixed' AS pack_type
        FROM (
            SELECT  Distinct p.pack_id, i.type
            FROM packages p
            INNER JOIN items i
                ON p.item_id = i.item_id
            WHERE i.type = 'Z') q3
        WHERE q3.type IN ('C','F')
    ) m

NOTE: some explication for the multiple comments that point to "A type cannot be Z and also C or F".

I also thought that, but the way I understand the behavior of the query is that if u say "type IN ('C','F')", it will look at each item of type 'C' or 'F' and get the package id that has that item. BUT, a package that has items of type 'C' or 'F' can also have items of type 'Z', hence the inner select, dealing with items of type 'Z' first.

Body:
Even when isnt explain on the question I guess your package type is derived from the combination of items on it. So you need group the items on each package

SQL DEMO

WITH cte as (
     SELECT pack_id,
            COUNT(CASE WHEN i.type IN ('C','F') THEN 1 END) as total_CF,
            COUNT(CASE WHEN i.type = 'Z' THEN 1 END) as total_Z
     FROM packages p
     INNER JOIN items i
        ON p.item_id = i.item_id
     GROUP BY pack_id
)
SELECT pack_id,
       CASE WHEN total_CF > 0 and total_Z = 0 THEN 'Cool'
            WHEN total_CF = 0 and total_Z > 0 THEN 'Not Cool'
            WHEN total_CF > 0 and total_Z > 0 THEN 'Mixed'
         -- ELSE 'NOT determinated'
       END as type
FROM cte

OUTPUT


问:
Localizing a website
Which should you rather use for a medium-sized web site (I don't know the exact number of pages, words, and so on yet):

A) PHP files with static resources:

en.php

```<code>    $lang_welcome = 'Welcome';
</code>```

de.php

```<code>    $lang_welcome = 'Willkommen';
</code>```

B) MySQL table containing translations:

```<code>+------+-----------+---------+-------------+
| lang |   path    |  term   | translation |
+------+-----------+---------+-------------+
|  en  | index.php | welcome |   Welcome   |
+------+-----------+---------+-------------+
|  de  | index.php | welcome |  Willkommen |
+------+-----------+---------+-------------+
|  en  |           |  cancel |   Cancel    |
+------+-----------+---------+-------------+
|  de  |           |  cancel |  Abbrechen  |
+------+-----------+---------+-------------+
</code>```

(The only solution I could think of off the top of my head right now.)

C.) Some other solution.

答: Use Gettext for static content, and your database schema for dynamic content.</p>

Title: Localizing a website

Body:
Which should you rather use for a medium-sized web site (I don't know the exact number of pages, words, and so on yet):

A) PHP files with static resources:

en.php

    $lang_welcome = 'Welcome';

de.php

    $lang_welcome = 'Willkommen';

B) MySQL table containing translations:

+------+-----------+---------+-------------+
| lang |   path    |  term   | translation |
+------+-----------+---------+-------------+
|  en  | index.php | welcome |   Welcome   |
+------+-----------+---------+-------------+
|  de  | index.php | welcome |  Willkommen |
+------+-----------+---------+-------------+
|  en  |           |  cancel |   Cancel    |
+------+-----------+---------+-------------+
|  de  |           |  cancel |  Abbrechen  |
+------+-----------+---------+-------------+

(The only solution I could think of off the top of my head right now.)

C.) Some other solution.


问:
Modern C++: initialize constexpr tables
Suppose I have a class X, which functionality requires a lot of constant table values, say an array A[1024]. I have a recurrent function f that computes its values, smth like

```<code>A[x] = f(A[x - 1]);
</code>```

Suppose that A[0] is a known constant, therefore the rest of the array is constant too. What is the best way to calculate these values beforehand, using features of modern C++, and without storaging file with hardcoded values of this array? My workaround was a const static dummy variable:

```<code>const bool X::dummy = X::SetupTables();

bool X::SetupTables() {
    A[0] = 1;
    for (size_t i = 1; i <= A.size(); ++i)
        A[i] = f(A[i - 1]);
}
</code>```

But I believe, it’s not the most beautiful way to go.
Note: I emphasize that array is rather big and I want to avoid monstrosity of the code.

答:
Since C++14, for loops are allowed in constexpr functions. Moreover, since C++17, std::array::operator[] is constexpr too.

So you can write something like this:

```<code>template<class T, size_t N, class F>
constexpr auto make_table(F func, T first)
{
    std::array<T, N> a {first};
    for (size_t i = 1; i < N; ++i)
    {
        a[i] = func(a[i - 1]);
    }
    return a;
}
</code>```

Example: https://godbolt.org/g/irrfr2

Title: Modern C++: initialize constexpr tables

Body:
Suppose I have a class X, which functionality requires a lot of constant table values, say an array A[1024]. I have a recurrent function f that computes its values, smth like

A[x] = f(A[x - 1]);

Suppose that A[0] is a known constant, therefore the rest of the array is constant too. What is the best way to calculate these values beforehand, using features of modern C++, and without storaging file with hardcoded values of this array? My workaround was a const static dummy variable:

const bool X::dummy = X::SetupTables();

bool X::SetupTables() {
    A[0] = 1;
    for (size_t i = 1; i <= A.size(); ++i)
        A[i] = f(A[i - 1]);
}

But I believe, it’s not the most beautiful way to go.
Note: I emphasize that array is rather big and I want to avoid monstrosity of the code.

Body:
Since C++14, for loops are allowed in constexpr functions. Moreover, since C++17, std::array::operator[] is constexpr too.

So you can write something like this:

template<class T, size_t N, class F>
constexpr auto make_table(F func, T first)
{
    std::array<T, N> a {first};
    for (size_t i = 1; i < N; ++i)
    {
        a[i] = func(a[i - 1]);
    }
    return a;
}

Example: https://godbolt.org/g/irrfr2


问:
Powershell 5 Get-ChildItem LiteralPath doesn't work with Include anymore
Right now I updated to Windows 10 TH2 Build 10586 with PowerShell 5.0.10586.0

Now I got a problem with Get-ChildItem

```<code>$files = Get-ChildItem -LiteralPath $path -Force -Recurse -Include *.txt
</code>```

This returns ALL files in $path even they are not .txt.
This was working before the update.
When I change it to

```<code>$files = Get-ChildItem -Path $path -Force -Recurse -Include *.txt
</code>```

it works again. But that's not what I want.
Is this a bug or am I doing something wrong?

答:
Note that -Filter does not seem to have this issue. This works:

```<code>$files = Get-ChildItem -LiteralPath $path -Force -Recurse -Filter *.txt
</code>```

Filter is also more efficient, because it is used by the underlying provider (as opposed to Include which is applied by PowerShell itself, much like a where clause added by your code).

However Filter only accepts one pattern parameter, whereas Include supports multiple patterns.

Body:
Right now I updated to Windows 10 TH2 Build 10586 with PowerShell 5.0.10586.0

Now I got a problem with Get-ChildItem

$files = Get-ChildItem -LiteralPath $path -Force -Recurse -Include *.txt

This returns ALL files in $path even they are not .txt.
This was working before the update.
When I change it to

$files = Get-ChildItem -Path $path -Force -Recurse -Include *.txt

it works again. But that's not what I want.
Is this a bug or am I doing something wrong?

Body:
Note that -Filter does not seem to have this issue. This works:

$files = Get-ChildItem -LiteralPath $path -Force -Recurse -Filter *.txt

Filter is also more efficient, because it is used by the underlying provider (as opposed to Include which is applied by PowerShell itself, much like a where clause added by your code).

However Filter only accepts one pattern parameter, whereas Include supports multiple patterns.


问:
JavaFX Dialogs remove header decoration
Is there a quick way to remove a Dialog header in JavaFX? Or should i just go and create my own dialog?

```<code>TextInputDialog dialog = new TextInputDialog();
dialog.setTitle("create DATABASE");
dialog.setHeaderText("create DATABASE");
dialog.setContentText("Ingrese un nombre:");
dialog.showAndWait().ifPresent(name -> getCodeArea().setTemplateInjump("create database "+name+";\n\nuse "+name+";\n\n"));
</code>```

答:
Yes, you can achieve this by setting the graphic and header text to null:  </p>

```<code>dialog.setHeaderText(null);
dialog.setGraphic(null);
</code>```

Title: JavaFX Dialogs remove header decoration

Body:
Is there a quick way to remove a Dialog header in JavaFX? Or should i just go and create my own dialog?

TextInputDialog dialog = new TextInputDialog();
dialog.setTitle("create DATABASE");
dialog.setHeaderText("create DATABASE");
dialog.setContentText("Ingrese un nombre:");
dialog.showAndWait().ifPresent(name -> getCodeArea().setTemplateInjump("create database "+name+";\n\nuse "+name+";\n\n"));

Body:
Yes, you can achieve this by setting the graphic and header text to null:

dialog.setHeaderText(null);
dialog.setGraphic(null);


问:
Foreign Key Not Outputting Query Data
```<code>try {
    Statement s = conn.createStatement();
    ResultSet result2 = s.executeQuery("Select Distinct * From Poem p,Recording r Where r.PoemTitle = p.PoemTitle AND r.poemTitle = 'poem1'");
    System.out.print("Result (Select with Join): ");
    while (result2.next()) {
        System.out.println(result2.getString(1)+ " " + result2.getString(2)+ result2.getString(3));
    }
} catch(Exception e) {
    System.out.print(e.getMessage());
}
</code>```

I am trying to output the poemtitle and the date it was recorded. When this runs it outputs the poemtitle and then gives the date the poem was created instead of recorded? Is this because of the relationship?

答:
Most likely it's because of the * in the SELECT list.

Specify the columns that you want returned, in the order you want them returned.

We're just guessing at the name of the column that contains "date recorded" and which table it's in:

```<code>SELECT p.PoemTitle
     , r.dateRecorded
     , r.readBy
  FROM Poem p
  JOIN Recording r
    ON r.PoemTitle = p.PoemTitle
 WHERE r.poemTitle = 'poem1'
 GROUP
    BY p.PoemTitle
     , r.dateRecorded
     , r.readBy
 ORDER
    BY p.PoemTitle
     , r.dateRecorded DESC
     , r.readBy
</code>```

Notes:

Ditch the old-school comma syntax for the join operation and use the JOIN keyword instead, and relocate the join predicates from the WHERE clause to an ON clause.

Avoid using * in the SELECT list. Explicitly list the columns/expressions to be returned. When we read the code, and that SQL statement, we don't know how many columns are being returned, what order the columns are in, or what the datatypes are. (We'd have to go look at the table definitions.)

Explicitly listing the columns/expressions being returned only takes a little bit of work. If code was only ever written, then it would be fine, save the time writing. But code is READ ten times more than it is written. (And the SQL statement with the * makes the SQL statement virtually indecipherable in terms of which column is being referenced by getString(1).

Listing the columns columns can also make it more efficient on the database, to prepare a resultset with a few columns vs a resultset of dozens of columns, and we also transfer a smaller resultset from the database to the client. With a subset of columns, its more likely we can use a covering index for the query.

Title: Foreign Key Not Outputting Query Data

Body:
try {
    Statement s = conn.createStatement();
    ResultSet result2 = s.executeQuery("Select Distinct * From Poem p,Recording r Where r.PoemTitle = p.PoemTitle AND r.poemTitle = 'poem1'");
    System.out.print("Result (Select with Join): ");
    while (result2.next()) {
        System.out.println(result2.getString(1)+ " " + result2.getString(2)+ result2.getString(3));
    }
} catch(Exception e) {
    System.out.print(e.getMessage());
}

I am trying to output the poemtitle and the date it was recorded. When this runs it outputs the poemtitle and then gives the date the poem was created instead of recorded? Is this because of the relationship?

Body:
Most likely it's because of the * in the SELECT list.

Specify the columns that you want returned, in the order you want them returned.

We're just guessing at the name of the column that contains "date recorded" and which table it's in:

SELECT p.PoemTitle
     , r.dateRecorded
     , r.readBy
  FROM Poem p
  JOIN Recording r
    ON r.PoemTitle = p.PoemTitle
 WHERE r.poemTitle = 'poem1'
 GROUP
    BY p.PoemTitle
     , r.dateRecorded
     , r.readBy
 ORDER
    BY p.PoemTitle
     , r.dateRecorded DESC
     , r.readBy

Notes:

Ditch the old-school comma syntax for the join operation and use the JOIN keyword instead, and relocate the join predicates from the WHERE clause to an ON clause.

Avoid using * in the SELECT list. Explicitly list the columns/expressions to be returned. When we read the code, and that SQL statement, we don't know how many columns are being returned, what order the columns are in, or what the datatypes are. (We'd have to go look at the table definitions.)

Explicitly listing the columns/expressions being returned only takes a little bit of work. If code was only ever written, then it would be fine, save the time writing. But code is READ ten times more than it is written. (And the SQL statement with the * makes the SQL statement virtually indecipherable in terms of which column is being referenced by getString(1).

Listing the columns columns can also make it more efficient on the database, to prepare a resultset with a few columns vs a resultset of dozens of columns, and we also transfer a smaller resultset from the database to the client. With a subset of columns, its more likely we can use a covering index for the query.


问:
VBA Message box to work through a filtered selection of data
I'm trying to create a macro that I can run on a worksheet that uses autofilters. In an ideal world my macro should display a message box that gives me three options:

1) Run a specific set of VBA instructions (in the code below it is to colour cell B2) on the first visible row (ignoring the header) then move to the next visible row and display the message box again.

2) Skip this row, find the next visible row and display the message box again.

3) Quit the macro.

I have the bare bones of the macro below however I feel I'm missing some clever way of displaying the message box again after the first two buttons are pressed. Also I'm not convinced by my code to end the macro.

FYI: The reason for the message box rather than a flat out looped macro is that the filters regularly change and I'm looking to reduce the need to rewrite the code based on the necessary filters.

```<code>Sub Msg_exe()
    Dim Option_Menu As Integer
    Dim strMsg As String
    Dim strTitle As String

    Range("B2").Select
    strMsg = "Continue with this row"
    strTitle = "Alert"

    Option_Menu = MsgBox(strMsg, vbYesNoCancel + vbQuestion, strTitle)

    Select Case Option_Menu
        Case 6 'code to colour the cell goes here
            Selection.Font.ColorIndex = 25
            Selection.Interior.ColorIndex = 33
            ActiveCell.Offset(1, 0).Activate
            Do While ActiveCell.EntireRow.Hidden = True
                ActiveCell.Offset(1, 0).Activate
            Loop
            'I need some code to show the message box again ready for the next row

        Case 7 'code to skip to the next visable line goes here
            ActiveCell.Offset(1, 0).Activate
            Do While ActiveCell.EntireRow.Hidden = True
                ActiveCell.Offset(1, 0).Activate
            Loop
            'I need some code to show the message box again ready for the next row

        Case 2 'the code to end the macro goes here (I hope this is correct)
            End
    End Select
End Sub
</code>```

答:
You could loop through the rows, beginning at whichever row you decide, and ascertain if the calculation is required thereafter (I haven't tested so please check this matches your requirements first):</p>

```<code>Sub Msg_exe()

    Dim cur_row as long
    Dim Option_Menu As Integer
    Dim strMsg As String
    Dim strTitle As String

    For cur_row = 2 to Range("A65000").End(xlUp).Row 'Modify this row referenced to suit

        if not Range("B" & cur_row).EntireRow.Hidden then

            Range("B" & cur_row).Select
            strMsg = "Continue with this row"
            strTitle = "Alert"

            Option_Menu = MsgBox(strMsg, vbYesNoCancel + vbQuestion, strTitle)

            Select Case Option_Menu
                Case 6 'code to colour the cell goes here
                    Selection.Font.ColorIndex = 25
                    Selection.Interior.ColorIndex = 33
                Case 7 'code to skip to the next visible line goes here
                Case 2 'the code to end the macro goes here (I hope this is correct)
                    Exit Sub
            End Select

        End If

    Next

End Sub
</code>```

Body:
I'm trying to create a macro that I can run on a worksheet that uses autofilters. In an ideal world my macro should display a message box that gives me three options:

1) Run a specific set of VBA instructions (in the code below it is to colour cell B2) on the first visible row (ignoring the header) then move to the next visible row and display the message box again.

2) Skip this row, find the next visible row and display the message box again.

3) Quit the macro.

I have the bare bones of the macro below however I feel I'm missing some clever way of displaying the message box again after the first two buttons are pressed. Also I'm not convinced by my code to end the macro.

FYI: The reason for the message box rather than a flat out looped macro is that the filters regularly change and I'm looking to reduce the need to rewrite the code based on the necessary filters.

Sub Msg_exe()
    Dim Option_Menu As Integer
    Dim strMsg As String
    Dim strTitle As String

    Range("B2").Select
    strMsg = "Continue with this row"
    strTitle = "Alert"

    Option_Menu = MsgBox(strMsg, vbYesNoCancel + vbQuestion, strTitle)

    Select Case Option_Menu
        Case 6 'code to colour the cell goes here
            Selection.Font.ColorIndex = 25
            Selection.Interior.ColorIndex = 33
            ActiveCell.Offset(1, 0).Activate
            Do While ActiveCell.EntireRow.Hidden = True
                ActiveCell.Offset(1, 0).Activate
            Loop
            'I need some code to show the message box again ready for the next row

        Case 7 'code to skip to the next visable line goes here
            ActiveCell.Offset(1, 0).Activate
            Do While ActiveCell.EntireRow.Hidden = True
                ActiveCell.Offset(1, 0).Activate
            Loop
            'I need some code to show the message box again ready for the next row

        Case 2 'the code to end the macro goes here (I hope this is correct)
            End
    End Select
End Sub

Body:
You could loop through the rows, beginning at whichever row you decide, and ascertain if the calculation is required thereafter (I haven't tested so please check this matches your requirements first):

Sub Msg_exe()

    Dim cur_row as long
    Dim Option_Menu As Integer
    Dim strMsg As String
    Dim strTitle As String

    For cur_row = 2 to Range("A65000").End(xlUp).Row 'Modify this row referenced to suit

        if not Range("B" & cur_row).EntireRow.Hidden then

            Range("B" & cur_row).Select
            strMsg = "Continue with this row"
            strTitle = "Alert"

            Option_Menu = MsgBox(strMsg, vbYesNoCancel + vbQuestion, strTitle)

            Select Case Option_Menu
                Case 6 'code to colour the cell goes here
                    Selection.Font.ColorIndex = 25
                    Selection.Interior.ColorIndex = 33
                Case 7 'code to skip to the next visible line goes here
                Case 2 'the code to end the macro goes here (I hope this is correct)
                    Exit Sub
            End Select

        End If

    Next

End Sub


问:
deleting certain lines out of a urllib url
```<code>import csv
import urllib.request
from pylab import *

eventurl = "http://data.hisparc.nl/show/source/eventtime/501/2017/1/1/"
data = urllib.request.urlopen(eventurl)
print(data.read())
</code>```

When I run the code and the data from the eventurl is printed, this is what terminal shows:

```<code>b"# HiSPARC eventtime histogram source\n#\n# Station: 501\n# Data from 2017-1-1\n#\n# HiSPARC data is licensed under Creative Commons Attribution-ShareAlike 4.0.\n#\n#\n# Please note: the 'bin' is the left bin edge. The width of the bin is 1\n# hour.  So bin 0 means between 0:00 and 1:00. Value means the number of\n# events which were measured during 1 hour.\n#\n# This data contains the following columns:\n#\n# bin:   time [hour of day]\n# value: number of events [counts]\n#\n#\n# bin\tvalue\n0\t2265\n1\t2354\n2\t2302\n3\t2353\n4\t2369\n5\t2378\n6\t2280\n7\t2411\n8\t2340\n9\t2431\n10\t2353\n11\t2394\n12\t2412\n13\t2470\n14\t2404\n15\t2540\n16\t2492\n17\t2390\n18\t2454\n19\t2404\n20\t2451\n21\t2467\n22\t2471\n23\t2371\n\n"
</code>```

what we want to have, is just two rows with the bins and the values. Is there a code that can help us get rid of the rest and make it easy to use the numbers for a histogram?

Body:
import csv
import urllib.request
from pylab import *

eventurl = "http://data.hisparc.nl/show/source/eventtime/501/2017/1/1/"
data = urllib.request.urlopen(eventurl)
print(data.read())

When I run the code and the data from the eventurl is printed, this is what terminal shows:

b"# HiSPARC eventtime histogram source\n#\n# Station: 501\n# Data from 2017-1-1\n#\n# HiSPARC data is licensed under Creative Commons Attribution-ShareAlike 4.0.\n#\n#\n# Please note: the 'bin' is the left bin edge. The width of the bin is 1\n# hour.  So bin 0 means between 0:00 and 1:00. Value means the number of\n# events which were measured during 1 hour.\n#\n# This data contains the following columns:\n#\n# bin:   time [hour of day]\n# value: number of events [counts]\n#\n#\n# bin\tvalue\n0\t2265\n1\t2354\n2\t2302\n3\t2353\n4\t2369\n5\t2378\n6\t2280\n7\t2411\n8\t2340\n9\t2431\n10\t2353\n11\t2394\n12\t2412\n13\t2470\n14\t2404\n15\t2540\n16\t2492\n17\t2390\n18\t2454\n19\t2404\n20\t2451\n21\t2467\n22\t2471\n23\t2371\n\n"

what we want to have, is just two rows with the bins and the values. Is there a code that can help us get rid of the rest and make it easy to use the numbers for a histogram?

Body:
data = data.read().decode()
values = data.split("# bin  value")

result = [d.split("\t")[1] for d in values[1].strip().split("\n")]
print(result)

Output:

['2265', '2354', '2302', '2353', ...., '2471', '2371']


问:
Rapid text recognition from Android or iOS video camera
Are any of the current text capture APIs (e.g. Google's Text API) fast enough to capture text from a phone's video feed, and draw a box that stays on the text even as the camera moves?

I don't need fast enough to do full OCR per-frame (though that would be amazing!). I'm just looking for fast enough to recognize blocks of text and keep the bounding box displayed in sync with the live image.

答:
There are two major options for good results. They are both C++ but there are wrappers. I've personally played with OpenCV for face recognition and the results were promising. Below links with small tutorials and demos.

OpenCV

Tessaract by Google


问:
How to exclude an annotation processor dependency from ProGuard
I received a ProGuard warning when attempting to create a release of my Android project that prevents the build from completing successfully.

Warning: library class com.google.googlejavaformat.java.filer.FormattingJavaFileObject$1$1 extends or implements program class com.google.common.io.CharSink

After a little digging and running gradlew :app:dependencies, I discovered that google-java-format has been included because it is used by AutoFactory, which was recently added to the project.

```<code>+--- com.google.auto.factory:auto-factory:1.0-beta5
|    +--- com.google.auto:auto-common:0.6 (*)
|    +--- com.google.auto.value:auto-value:1.1 -> 1.3
|    +--- com.google.googlejavaformat:google-java-format:1.1
</code>```

AutoFactory is only included in my build.gradle file as an annotationProcessor, so I don't understand why it is even being processed by ProGuard.

```<code>provided "com.google.auto.factory:auto-factory:1.0-beta5"
annotationProcessor "com.google.auto.factory:auto-factory:1.0-beta5"
</code>```

I tried adding a -dontwarn com.google.gooogleformat.** to my ProGuard configuration file figuring that the library is only used during code generation and isn't actually required for the release. This had no effect.

I also looked at the online help, but I'm not clear on how to specify this dependency as a -libraryjars file as suggested.

How do I configure the app's ProGuard configuration file or its build.gradle file to prevent ProGuard from choking on this library? If it matters, I'm simply using ProGuard to remove unused code and not performing any obfuscation.

答:
We revisited this issue after upgrading to Android Studio 3.0 with the Android 3.0.0 Gradle plugin and Gradle 4.1. It now appears that adding the following to proguard-rules.pro resolves the problem:

```<code>-dontwarn com.google.googlejavaformat.**
-dontwarn com.google.common.**
</code>```

Looking at my original question, it appears that we likely mistyped the namespace for com.google.googlejavaformat when originally trying to solve this problem.

Body:
I received a ProGuard warning when attempting to create a release of my Android project that prevents the build from completing successfully.

Warning: library class com.google.googlejavaformat.java.filer.FormattingJavaFileObject$1$1 extends or implements program class com.google.common.io.CharSink

After a little digging and running gradlew :app:dependencies, I discovered that google-java-format has been included because it is used by AutoFactory, which was recently added to the project.

+--- com.google.auto.factory:auto-factory:1.0-beta5
|    +--- com.google.auto:auto-common:0.6 (*)
|    +--- com.google.auto.value:auto-value:1.1 -> 1.3
|    +--- com.google.googlejavaformat:google-java-format:1.1

AutoFactory is only included in my build.gradle file as an annotationProcessor, so I don't understand why it is even being processed by ProGuard.

provided "com.google.auto.factory:auto-factory:1.0-beta5"
annotationProcessor "com.google.auto.factory:auto-factory:1.0-beta5"

I tried adding a -dontwarn com.google.gooogleformat.** to my ProGuard configuration file figuring that the library is only used during code generation and isn't actually required for the release. This had no effect.

I also looked at the online help, but I'm not clear on how to specify this dependency as a -libraryjars file as suggested.

How do I configure the app's ProGuard configuration file or its build.gradle file to prevent ProGuard from choking on this library? If it matters, I'm simply using ProGuard to remove unused code and not performing any obfuscation.

Body:
We revisited this issue after upgrading to Android Studio 3.0 with the Android 3.0.0 Gradle plugin and Gradle 4.1. It now appears that adding the following to proguard-rules.pro resolves the problem:

-dontwarn com.google.googlejavaformat.**
-dontwarn com.google.common.**

Looking at my original question, it appears that we likely mistyped the namespace for com.google.googlejavaformat when originally trying to solve this problem.


问:
How to make a smooth image rotation in Android?
I'm using a RotateAnimation to rotate an image that I'm using as a custom cyclical spinner in Android.  Here's my rotate_indefinitely.xml file, which I placed in res/anim/:

```<code><?xml version="1.0" encoding="UTF-8"?>
<rotate
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:fromDegrees="0"
    android:toDegrees="360"
    android:pivotX="50%"
    android:pivotY="50%"
    android:repeatCount="infinite"
    android:duration="1200" />
</code>```

When I apply this to my ImageView using AndroidUtils.loadAnimation(), it works great!

```<code>spinner.startAnimation(
    AnimationUtils.loadAnimation(activity, R.anim.rotate_indefinitely) );
</code>```

The one problem is that the image rotation seems to pause at the top of every cycle.

In other words, the image rotates 360 degrees, pauses briefly, then rotates 360 degrees again, etc.

I suspect that the problem is that the animation is using a default interpolator like android:iterpolator="@android:anim/accelerate_interpolator" (AccelerateInterpolator), but I don't know how to tell it not to interpolate the animation.

How can I turn off interpolation (if that is indeed the problem) to make my animation cycle smoothly?

答:
Try to use more than 360 to avoid restarting.

I use 3600 insted of 360 and this works fine for me:

```<code><rotate xmlns:android="http://schemas.android.com/apk/res/android"
    android:fromDegrees="0"
    android:toDegrees="3600"
    android:interpolator="@android:anim/linear_interpolator"
    android:repeatCount="infinite"
    android:duration="8000"
    android:pivotX="50%"
    android:pivotY="50%" />
</code>```

Body:
I'm using a RotateAnimation to rotate an image that I'm using as a custom cyclical spinner in Android.  Here's my rotate_indefinitely.xml file, which I placed in res/anim/:

<?xml version="1.0" encoding="UTF-8"?>
<rotate
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:fromDegrees="0"
    android:toDegrees="360"
    android:pivotX="50%"
    android:pivotY="50%"
    android:repeatCount="infinite"
    android:duration="1200" />

When I apply this to my ImageView using AndroidUtils.loadAnimation(), it works great!

spinner.startAnimation(
    AnimationUtils.loadAnimation(activity, R.anim.rotate_indefinitely) );

The one problem is that the image rotation seems to pause at the top of every cycle.

In other words, the image rotates 360 degrees, pauses briefly, then rotates 360 degrees again, etc.

I suspect that the problem is that the animation is using a default interpolator like android:iterpolator="@android:anim/accelerate_interpolator" (AccelerateInterpolator), but I don't know how to tell it not to interpolate the animation.

How can I turn off interpolation (if that is indeed the problem) to make my animation cycle smoothly?

Body:
Try to use more than 360 to avoid restarting.

I use 3600 insted of 360 and this works fine for me:

<rotate xmlns:android="http://schemas.android.com/apk/res/android"
    android:fromDegrees="0"
    android:toDegrees="3600"
    android:interpolator="@android:anim/linear_interpolator"
    android:repeatCount="infinite"
    android:duration="8000"
    android:pivotX="50%"
    android:pivotY="50%" />


答:
It's very simple set dialog.setHeaderText(null) and it will remove the header.
For more information have a look here

Title: JavaFX Dialogs remove header decoration


问:
starting with react example, in constructors this.method = this.method.bind(this) , why?
I'm starting with react and the first thing I did is to go to the main page where I see some examples, e.g.:

```<code>class MarkdownEditor extends React.Component {
  constructor(props) {
    super(props);
    this.handleChange = this.handleChange.bind(this);
    this.state = { value: 'Type some *markdown* here!' };
  }

  handleChange(e) {
    this.setState({ value: e.target.value });
  }

  getRawMarkup() {
    const md = new Remarkable();
    return { __html: md.render(this.state.value) };
  }

  render() {
    return (
      <div className="MarkdownEditor">
        <h3>Input</h3>
        <textarea
          onChange={this.handleChange}
          defaultValue={this.state.value}
        />
        <h3>Output</h3>
        <div
          className="content"
          dangerouslySetInnerHTML={this.getRawMarkup()}
        />
      </div>
    );
  }
}

ReactDOM.render(<MarkdownEditor />, mountNode);
</code>```

...
I see that in the constructor is done:

```<code>this.handleChange = this.handleChange.bind(this);
</code>```

What is the reason behind that? Talking with colleagues they think some possible reasons like something special behind the render() method, or something related with non supported feature of ES6.

Do someone have a specific explainment to that?

In a first look, it seems unnecessary for me as shown in this simple example:

```<code>class A {
  constructor(){
      this.a = 1;
  }
  do(){
      console.log('A', this.a);
 }
}

class B extends A {
  constructor(){
    super();
    this.a = 2;
  }

 do(){
      console.log('B', this.a);
  }
}
console.log ((new B()).do())
</code>```

答:
this.handleChange.bind(this) returns a new function, in which references to this will refer to the actual context (your React component).

When you don't bind this and pass the method to a Child component, for example. this will refer to that Child component instead of the Parent. We normally don't want to do that. That's why we bind it.

Note that arrow functions don't need that because they capture this value of the enclosing context.

Body:
I'm starting with react and the first thing I did is to go to the main page where I see some examples, e.g.:

class MarkdownEditor extends React.Component {
  constructor(props) {
    super(props);
    this.handleChange = this.handleChange.bind(this);
    this.state = { value: 'Type some *markdown* here!' };
  }

  handleChange(e) {
    this.setState({ value: e.target.value });
  }

  getRawMarkup() {
    const md = new Remarkable();
    return { __html: md.render(this.state.value) };
  }

  render() {
    return (

Input

        <textarea
          onChange={this.handleChange}
          defaultValue={this.state.value}
        />

Output

    );
  }
}

ReactDOM.render(<MarkdownEditor />, mountNode);

...
I see that in the constructor is done:

this.handleChange = this.handleChange.bind(this);

What is the reason behind that? Talking with colleagues they think some possible reasons like something special behind the render() method, or something related with non supported feature of ES6.

Do someone have a specific explainment to that?

In a first look, it seems unnecessary for me as shown in this simple example:

class A {
  constructor(){
      this.a = 1;
  }
  do(){
      console.log('A', this.a);
 }
}

class B extends A {
  constructor(){
    super();
    this.a = 2;
  }

 do(){
      console.log('B', this.a);
  }
}
console.log ((new B()).do())


答:
You can upload your source code using a zip file. I added two additional tasks to my build definition: 1 to archive the source files into a zip file and 1 to upload the zip file to Code Dx:

The Archive file to create parameter of your archive task becomes the Files to upload parameter in your Code Dx task.

Archive task

Code Dx task

Title: How to setup CodeDX plugin for Visual Studio Team Services?

Body:
I have a CodeDx sever running at http://******:82/codedx

This is how my build task looks in VSTS.

And these are the logs for the build:
2017-11-13T22:17:14.6911243Z ==============================================================================
2017-11-13T22:17:14.6911243Z Task         : Code Dx - Upload Files
2017-11-13T22:17:14.6911243Z Description  : Upload files to Code Dx
2017-11-13T22:17:14.6911243Z Version      : 0.1.18
2017-11-13T22:17:14.6911243Z Author       : CodeDx
2017-11-13T22:17:14.6911243Z Help         :
2017-11-13T22:17:14.6911243Z ==============================================================================
2017-11-13T22:17:14.7536277Z Preparing task execution handler.
2017-11-13T22:17:15.8474356Z Executing the powershell script: C:\agent\_work\_tasks\CodeDxUploadFilse_7a5fadd7-438e-4e37-bba4-aac9d265893c\0.1.18\UploadSourceToCodeDx.ps1
2017-11-13T22:17:15.8630563Z Code Dx URL: http://*******:82/codedx
2017-11-13T22:17:15.8630563Z
2017-11-13T22:17:15.8630563Z
2017-11-13T22:17:15.8630563Z Project ID: 1
2017-11-13T22:17:15.8630563Z
2017-11-13T22:17:15.8630563Z
2017-11-13T22:17:15.8630563Z API key: **********
2017-11-13T22:17:15.8630563Z
2017-11-13T22:17:15.8630563Z
2017-11-13T22:17:15.8630563Z Paths: C:\agent\_work\4\s\***\****\Controllers\AccountController.cs
2017-11-13T22:17:15.8630563Z
2017-11-13T22:17:15.8630563Z
2017-11-13T22:17:15.8630563Z Source/binaries filenames:
2017-11-13T22:17:15.8630563Z
2017-11-13T22:17:15.8630563Z
2017-11-13T22:17:15.8630563Z Full URL: http://********:82/codedx/api/projects/1/analysis
2017-11-13T22:17:15.8630563Z
2017-11-13T22:17:15.8630563Z
2017-11-13T22:17:15.8630563Z Processing C:\agent\_work\4\s\****\****\Controllers\AccountController.cs as file1...
2017-11-13T22:17:15.8630563Z
2017-11-13T22:17:15.8630563Z
2017-11-13T22:17:15.8630563Z Reading contents of AccountController.cs...
2017-11-13T22:17:15.8630563Z
2017-11-13T22:17:15.8630563Z
2017-11-13T22:17:15.8630563Z Content size: 45983 bytes
2017-11-13T22:17:15.8630563Z
2017-11-13T22:17:15.8630563Z
2017-11-13T22:17:15.8630563Z Building HTTP content...
2017-11-13T22:17:15.8630563Z
2017-11-13T22:17:15.8630563Z
2017-11-13T22:17:15.8630563Z Building request message...
2017-11-13T22:17:15.8630563Z
2017-11-13T22:17:15.8630563Z
2017-11-13T22:17:15.8630563Z Sending source to Code Dx...
2017-11-13T22:17:15.8630563Z
2017-11-13T22:17:15.8630563Z
2017-11-13T22:17:15.8942973Z Reading response...
2017-11-13T22:17:15.8942973Z
2017-11-13T22:17:15.8942973Z

2017-11-13T22:17:15.8942973Z Response: {"error":"No appropriate role for file AccountController.cs - it should be removed"}

2017-11-13T22:17:15.8942973Z
2017-11-13T22:17:15.8942973Z
2017-11-13T22:17:15.9411717Z ##[section]Finishing: Code Dx

How do I specify to scan all my files under a project to CodeDx?


问:
Scala nested Lists
I’m trying to fetch a value from a nested list in Scala but somehow I’m not able to find a solution.

I’ve created a list as:

```<code>var list3 = List((1,2,3),(4,5,6),(7,8),(9,10,11,12))
</code>```

I require 7 as the output.

In Python, for the same thing, I’m creating list as

```<code>list3 = [[1,2,3],[4,5,6],[7,8],[9,10,11,12]]
</code>```

To get the output as 7, I’m using

```<code>list3[len(list3) -2][len(list3) -4]
</code>```

Please suggest me how to achieve the same in Scala.

Thanks in advance.

答:
list3 isn't a list-of-lists, it's a list of tuples. You can create a list-of-lists as follows:

```<code>var list3 = List(List(1,2,3),List(4,5,6),List(7,8),List(9,10,11,12))
</code>```

Then, the Scala version of your python code would work:

```<code>scala> list3(list3.size - 2)(list3.size - 4)
res3: Int = 7
</code>```

Title: Scala nested Lists

Body:
I’m trying to fetch a value from a nested list in Scala but somehow I’m not able to find a solution.

I’ve created a list as:

var list3 = List((1,2,3),(4,5,6),(7,8),(9,10,11,12))

I require 7 as the output.

In Python, for the same thing, I’m creating list as

list3 = [[1,2,3],[4,5,6],[7,8],[9,10,11,12]]

To get the output as 7, I’m using

list3[len(list3) -2][len(list3) -4]

Please suggest me how to achieve the same in Scala.

Thanks in advance.

Body:
list3 isn't a list-of-lists, it's a list of tuples. You can create a list-of-lists as follows:

var list3 = List(List(1,2,3),List(4,5,6),List(7,8),List(9,10,11,12))

Then, the Scala version of your python code would work:

scala> list3(list3.size - 2)(list3.size - 4)
res3: Int = 7


问:
How to validate non breaking space in CKEditor
Well i have the ckeditor in my page when the user keep entering spaces only, then the empty validation meant that it is not empty because it contains the   inside the

 so the editor content is not empty but when we see that content in html it will display nothing because its non breaking spaces.

Now issue is that how validate that inside the editor no one can put like spaces like that.

答:
You can use 'trim' to remove all whitespace from the beginning and end of the input

https://api.jquery.com/jquery.trim/

you can then add some logic to see if the trimmed string is empty or not, before it is passed to whatever you use to save/display the data.
Use .text() to remove tags first.

e.g.

```<code>if($(myContent).text().trim() != "") //process myContent
else //throw error
</code>```

Fiddle: http://jsfiddle.net/gLzoL81u/

Body:
You can use 'trim' to remove all whitespace from the beginning and end of the input

https://api.jquery.com/jquery.trim/

you can then add some logic to see if the trimmed string is empty or not, before it is passed to whatever you use to save/display the data.
Use .text() to remove tags first.

e.g.

if($(myContent).text().trim() != "") //process myContent
else //throw error

Fiddle: http://jsfiddle.net/gLzoL81u/


问:
Date transformation in Oracle database
What is the easier way to compare dates in a different format in Oracle?
Example:
In the first table, I have a date the format: "2017/09/15 03:14:13".
The second table contains data with the format: "15-SEP-17"

I would like to compare these dates like Table1.column>Table2.column

One way is a well-known solution with to_date(to_char()), but I am curious if there is any simpler way. Any thought?

答:
In Oracle date have no format at all. If you wish to compare dates you may use something like date1 < date2, date1 between date2 and date3 and so on.

You cannot have 'date with format' into the table. If you think so, it means you have varchar field which represents a date. If you wish to compare it, you should convert it to date using to_date function.

Title: Date transformation in Oracle database


问:
Monte Carlo simulation in R: For loop value return NA
Monte Carlo simulation: The code is meant to simulate a demand of 260 and calculate the amount of 2nd shift required. However, I encounter NA in value after the 10th run.
I am trying to achieve this: The first column start from 'B'
enter image description here</p>

```<code>        set.seed(1234)
        n = 260
        demand = runif(260, min = 80, max = 130)
        production_capacity = 100
        begining_inventory[] = 100
        post_inventory[] = 0
        counter = 0
        for(i in 1:n){
          if (i == 1){
            begining_inventory[i] = 100
            ending_inventory[i] = begining_inventory[i] + production_capacity - demand [i]
            ending_inventory[i]
            post_inventory[i] = ending_inventory[i]

          }
          else{
            post_inventory[i] = ending_inventory[i]
            begining_inventory[i] = post_inventory[i-1]
            ending_inventory[i] = begining_inventory[i] + production_capacity - demand [i]
          }
          if(ending_inventory[i] <= 50){
            counter = counter + 1
          }
         print(ending_inventory[i])
         P.first_shift = (1-counter/n)
         P.second_shift = 1-P.first_shift
        }
</code>```

答:
Figured it out:</p>

```<code>set.seed(1234)
n = 260
demand = runif(n, min = 80, max = 130)
production_capacity = 100
begining_inventory = 100

counter = 0
second_shift = rep(0,n)
ending_inventory = rep(0,n)

second_shift_production = rep(0,n)
post_second = rep(0,n)

for(i in 1:n){

  ending_inventory[i] = begining_inventory + production_capacity - demand[i]

  if(ending_inventory[i] < 50){
    print(ending_inventory[i])
    second_shift[i] = 1
    counter = counter + 1
  }else{
    second_shift[i] = 0
  }
  second_shift_production[i] = second_shift[i]*100
  post_second[i] = second_shift_production[i] + ending_inventory[i]

  if(i > 1){
    begining_inventory = post_second[i-1]
  }

}
hist(ending_inventory)
abline(v = 50, col = "red")

P.first_shift = (1-counter/n)
P.second_shift = 1-P.first_shift

print(paste("Probabiity Only first shift = ", (1-counter/n)*100, "%", sep = " "))
print(paste("Probabiity second shift = ", 100-(1-counter/n)*100, "%", sep = " "))
</code>```

Body:
Monte Carlo simulation: The code is meant to simulate a demand of 260 and calculate the amount of 2nd shift required. However, I encounter NA in value after the 10th run.
I am trying to achieve this: The first column start from 'B'
enter image description here

        set.seed(1234)
        n = 260
        demand = runif(260, min = 80, max = 130)
        production_capacity = 100
        begining_inventory[] = 100
        post_inventory[] = 0
        counter = 0
        for(i in 1:n){
          if (i == 1){
            begining_inventory[i] = 100
            ending_inventory[i] = begining_inventory[i] + production_capacity - demand [i]
            ending_inventory[i]
            post_inventory[i] = ending_inventory[i]

          }
          else{
            post_inventory[i] = ending_inventory[i]
            begining_inventory[i] = post_inventory[i-1]
            ending_inventory[i] = begining_inventory[i] + production_capacity - demand [i]
          }
          if(ending_inventory[i] <= 50){
            counter = counter + 1
          }
         print(ending_inventory[i])
         P.first_shift = (1-counter/n)
         P.second_shift = 1-P.first_shift
        }

Body:
Figured it out:

set.seed(1234)
n = 260
demand = runif(n, min = 80, max = 130)
production_capacity = 100
begining_inventory = 100

counter = 0
second_shift = rep(0,n)
ending_inventory = rep(0,n)

second_shift_production = rep(0,n)
post_second = rep(0,n)

for(i in 1:n){

  ending_inventory[i] = begining_inventory + production_capacity - demand[i]

  if(ending_inventory[i] < 50){
    print(ending_inventory[i])
    second_shift[i] = 1
    counter = counter + 1
  }else{
    second_shift[i] = 0
  }
  second_shift_production[i] = second_shift[i]*100
  post_second[i] = second_shift_production[i] + ending_inventory[i]

  if(i > 1){
    begining_inventory = post_second[i-1]
  }

}
hist(ending_inventory)
abline(v = 50, col = "red")

P.first_shift = (1-counter/n)
P.second_shift = 1-P.first_shift

print(paste("Probabiity Only first shift = ", (1-counter/n)*100, "%", sep = " "))
print(paste("Probabiity second shift = ", 100-(1-counter/n)*100, "%", sep = " "))


问:
Comparing two collections for equality irrespective of the order of items in them
I would like to compare two collections (in C#), but I'm not sure of the best way to implement this efficiently.

I've read the other thread about Enumerable.SequenceEqual, but it's not exactly what I'm looking for.

In my case, two collections would be equal if they both contain the same items (no matter the order).

Example:

```<code>collection1 = {1, 2, 3, 4};
collection2 = {2, 4, 1, 3};

collection1 == collection2; // true
</code>```

What I usually do is to loop through each item of one collection and see if it exists in the other collection, then loop through each item of the other collection and see if it exists in the first collection. (I start by comparing the lengths).

```<code>if (collection1.Count != collection2.Count)
    return false; // the collections are not equal

foreach (Item item in collection1)
{
    if (!collection2.Contains(item))
        return false; // the collections are not equal
}

foreach (Item item in collection2)
{
    if (!collection1.Contains(item))
        return false; // the collections are not equal
}

return true; // the collections are equal
</code>```

However, this is not entirely correct, and it's probably not the most efficient way to do compare two collections for equality.

An example I can think of that would be wrong is:

```<code>collection1 = {1, 2, 3, 3, 4}
collection2 = {1, 2, 2, 3, 4}
</code>```

Which would be equal with my implementation. Should I just count the number of times each item is found and make sure the counts are equal in both collections?

The examples are in some sort of C# (let's call it pseudo-C#), but give your answer in whatever language you wish, it does not matter.

Note: I used integers in the examples for simplicity, but I want to be able to use reference-type objects too (they do not behave correctly as keys because only the reference of the object is compared, not the content).

答:
If you use Shouldly, you can use ShouldAllBe with Contains.

```<code>collection1 = {1, 2, 3, 4};
collection2 = {2, 4, 1, 3};

collection1.ShouldAllBe(item=>collection2.Contains(item)); // true
</code>```

And finally, you can write an extension.

```<code>public static class ShouldlyIEnumerableExtensions
{
    public static void ShouldEquivalentTo<T>(this IEnumerable<T> list, IEnumerable<T> equivalent)
    {
        list.ShouldAllBe(l => equivalent.Contains(l));
    }
}
</code>```

UPDATE

A optional parameter exists on ShouldBe method.

collection1.ShouldBe(collection2, ignoreOrder: true); // true
```

OwnerDisplayName: Mono

Body:
I would like to compare two collections (in C#), but I'm not sure of the best way to implement this efficiently.

I've read the other thread about Enumerable.SequenceEqual, but it's not exactly what I'm looking for.

In my case, two collections would be equal if they both contain the same items (no matter the order).

Example:

collection1 = {1, 2, 3, 4};
collection2 = {2, 4, 1, 3};

collection1 == collection2; // true

What I usually do is to loop through each item of one collection and see if it exists in the other collection, then loop through each item of the other collection and see if it exists in the first collection. (I start by comparing the lengths).

if (collection1.Count != collection2.Count)
    return false; // the collections are not equal

foreach (Item item in collection1)
{
    if (!collection2.Contains(item))
        return false; // the collections are not equal
}

foreach (Item item in collection2)
{
    if (!collection1.Contains(item))
        return false; // the collections are not equal
}

return true; // the collections are equal

However, this is not entirely correct, and it's probably not the most efficient way to do compare two collections for equality.

An example I can think of that would be wrong is:

collection1 = {1, 2, 3, 3, 4}
collection2 = {1, 2, 2, 3, 4}

Which would be equal with my implementation. Should I just count the number of times each item is found and make sure the counts are equal in both collections?

The examples are in some sort of C# (let's call it pseudo-C#), but give your answer in whatever language you wish, it does not matter.

Note: I used integers in the examples for simplicity, but I want to be able to use reference-type objects too (they do not behave correctly as keys because only the reference of the object is compared, not the content).

LastEditorDisplayName: Mono

Body:
If you use Shouldly, you can use ShouldAllBe with Contains.

collection1 = {1, 2, 3, 4};
collection2 = {2, 4, 1, 3};

collection1.ShouldAllBe(item=>collection2.Contains(item)); // true

And finally, you can write an extension.

public static class ShouldlyIEnumerableExtensions
{
    public static void ShouldEquivalentTo<T>(this IEnumerable<T> list, IEnumerable<T> equivalent)
    {
        list.ShouldAllBe(l => equivalent.Contains(l));
    }
}

UPDATE

A optional parameter exists on ShouldBe method.

collection1.ShouldBe(collection2, ignoreOrder: true); // true


问:
How to do i18n translation in Angular 4 for dynamic value?
I have one html template which has display labels which are coming from .ts file dynamically, if I want to translate it dynamically, how can I achieve this?

html

```<code><div class="container" *ng-for="let diplaylbl of array">
    <div class="name">{{diplaylbl.firstname}}</div>
</div>
</code>```

from .ts

```<code>export public array = [{firstname:"potato"}, {firstname:"tomato"}]
</code>```

答:
Angular has a useful built-in translate function. You just need to create the i18n folder and files with the translations, I would recommend to group them to keep it ordered: I use different folders for each language (Spanish, English) and inside each, a folder for each section (management), and inside I separate all kinds of strings (ui, alert, instructions, tooltip, etc...), then just a name to recognize it later on.
Add this on the element/container you want translated:

translate="management.ui.accept"

Hope that helps

Body:
I have one html template which has display labels which are coming from .ts file dynamically, if I want to translate it dynamically, how can I achieve this?

html

{{diplaylbl.firstname}}

from .ts

export public array = [{firstname:"potato"}, {firstname:"tomato"}]


问:
repeating-linear-gradient is not rendering evenly in safari
I'm having problems with my background in Safari.

body {
  background-color: #161619;
  /* For browsers that do not support gradients */
  background-image: radial-gradient(rgba(240, 240, 255, .1), rgba(20, 20, 30, .1) 60%), repeating-linear-gradient(40deg, #222, #222, 3px, #252525 3px, #252525 6px);
}```
</div>
</div>
</p>

<p>All other browsers (incl. Chrome) give me a nice striped background:
<img src="https://i.stack.imgur.com/oaMwi.png" alt="a nice striped background"></p>

<p>But Safari (Version 11.0.1) made it soft stripes in different sizes:
<img src="https://i.stack.imgur.com/bmeRV.png" alt="soft stripes in different sizes"></p>

<p>So I tried prefixes – but safari doesn't use the right one.
(I tried a colour-change)</p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-css lang-css prettyprint-override"><code>body {
  background-color: #161619;
  /* For browsers that do not support gradients */
  background-image: -webkit-radial-gradient(rgba(240, 240, 255, .1), rgba(20, 20, 30, .1) 60%), -webkit-repeating-linear-gradient(40deg, #222, #222, 3px, #500000 3px, #500000 6px);
  background-image: -o-radial-gradient(rgba(240, 240, 255, .1), rgba(20, 20, 30, .1) 60%), -o-repeating-linear-gradient(40deg, #222, #222, 3px, #252525 3px, #252525 6px);
  background-image: radial-gradient(rgba(240, 240, 255, .1), rgba(20, 20, 30, .1) 60%), repeating-linear-gradient(40deg, #222, #222, 3px, #252525 3px, #252525 6px);
}</code>```

I've been trying a lot of stuff now. But nothing works.

Anyone any ideas?

答:
Webkit seems to have issues when rendering gradients at certain degrees and with low contrast. At times, the results are completely unpredictable.

Problem is exacerbated when these snippets are run in full screen.

45deg angle gives the best results.

Heavy contrast:

html {
 height: 100%;
 background:
  repeating-linear-gradient(
   45deg,
   #fff, /* heavy contrast */
   #fff 0.5em,
   #252525 0.5em,
   #252525 1em)
}```
</div>
</div>
</p>

<p>Lower contrast:</p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-css lang-css prettyprint-override"><code>html {
 height: 100%;
 background:
  repeating-linear-gradient(
   45deg,
   #111, /* heavy contrast */
   #111 0.5em,
   #252525 0.5em,
   #252525 1em)
}</code>```

I also noted that the results are better when using responsive units, such as em used above. With pixels things get even more wonky.

Very low contrast with pixel units, 40deg angle:

html {
 height: 100%;
 background:
  repeating-linear-gradient(
   40deg,
   #111,
   #111 3px,
   #252525 3px,
   #252525 6px)
}```
</div>
</div>
</p>

<p>Very low contrast with pixel units but larger size, <code>40deg</code> angle:</p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-css lang-css prettyprint-override"><code>html {
 height: 100%;
 background:
  repeating-linear-gradient(
   30deg,
   #222, /* heavy contrast */
   #222 20px,
   #252525 20px,
   #252525 40px)
}</code>```

Body:
I'm having problems with my background in Safari.

body {
  background-color: #161619;
  /* For browsers that do not support gradients */
  background-image: radial-gradient(rgba(240, 240, 255, .1), rgba(20, 20, 30, .1) 60%), repeating-linear-gradient(40deg, #222, #222, 3px, #252525 3px, #252525 6px);
}

All other browsers (incl. Chrome) give me a nice striped background:

But Safari (Version 11.0.1) made it soft stripes in different sizes:

So I tried prefixes – but safari doesn't use the right one.
(I tried a colour-change)

body {
  background-color: #161619;
  /* For browsers that do not support gradients */
  background-image: -webkit-radial-gradient(rgba(240, 240, 255, .1), rgba(20, 20, 30, .1) 60%), -webkit-repeating-linear-gradient(40deg, #222, #222, 3px, #500000 3px, #500000 6px);
  background-image: -o-radial-gradient(rgba(240, 240, 255, .1), rgba(20, 20, 30, .1) 60%), -o-repeating-linear-gradient(40deg, #222, #222, 3px, #252525 3px, #252525 6px);
  background-image: radial-gradient(rgba(240, 240, 255, .1), rgba(20, 20, 30, .1) 60%), repeating-linear-gradient(40deg, #222, #222, 3px, #252525 3px, #252525 6px);
}

I've been trying a lot of stuff now. But nothing works.

Anyone any ideas?

Body:
Webkit seems to have issues when rendering gradients at certain degrees and with low contrast. At times, the results are completely unpredictable.

Problem is exacerbated when these snippets are run in full screen.

45deg angle gives the best results.

Heavy contrast:

html {
 height: 100%;
 background:
  repeating-linear-gradient(
   45deg,
   #fff, /* heavy contrast */
   #fff 0.5em,
   #252525 0.5em,
   #252525 1em)
}

Lower contrast:

html {
 height: 100%;
 background:
  repeating-linear-gradient(
   45deg,
   #111, /* heavy contrast */
   #111 0.5em,
   #252525 0.5em,
   #252525 1em)
}

I also noted that the results are better when using responsive units, such as em used above. With pixels things get even more wonky.

Very low contrast with pixel units, 40deg angle:

html {
 height: 100%;
 background:
  repeating-linear-gradient(
   40deg,
   #111,
   #111 3px,
   #252525 3px,
   #252525 6px)
}

Very low contrast with pixel units but larger size, 40deg angle:

html {
 height: 100%;
 background:
  repeating-linear-gradient(
   30deg,
   #222, /* heavy contrast */
   #222 20px,
   #252525 20px,
   #252525 40px)
}


问:
In matlab, how to get all edges of a polygon whose indices are labelled by integers using sets
To put the problem in context: I have a 3D polygon, whose vertices are all labelled by integers 1,...,N, and I have a n*3 matrix faces each of whose rows indicates one of its triangular faces. E.g.

```<code>faces =

     1     3     5
     2     4     6
     1     3     6
     2     4     5
     1     4     5
     2     3     6
     1     4     6
     2     3     5
</code>```

So the first row [1 3 5] denotes the face formed by vertices 1 3 5 and so on. Now I want to get all the edges of these faces.

So I want to use the concept of a set (non-ordered, unique elements). For each row of faces there are three edges, corresponding to three sets, say, {1, 3}, {1, 5}, {3, 5} (here I'm borrowing notations from Python). And I want to create a set of all these sets for all rows. How to do it in Matlab?

In Python it seems I simply can't do a set of sets, since sets are unhashable. In Matlab, it seems everything is a matrix, so I may have to still use a 1x2 matrix to represent each edge, which is fine, but what I want is I don't get duplicated edges. For example, [1 2] and [2 1] are one same edge so I have to make sure one and only one of them is retained in the final dataset.

答:
First search your matrix and extract each vector.
After that you can store that in another matrix.</p>

```<code>edges =

 1     3
 3     5
 1     3
 3     4
 5     1
 1     4
 4     4
 4     3

A = unique(edges,'rows')
</code>```

Body:
To put the problem in context: I have a 3D polygon, whose vertices are all labelled by integers 1,...,N, and I have a n*3 matrix faces each of whose rows indicates one of its triangular faces. E.g.

faces =

     1     3     5
     2     4     6
     1     3     6
     2     4     5
     1     4     5
     2     3     6
     1     4     6
     2     3     5

So the first row [1 3 5] denotes the face formed by vertices 1 3 5 and so on. Now I want to get all the edges of these faces.

So I want to use the concept of a set (non-ordered, unique elements). For each row of faces there are three edges, corresponding to three sets, say, {1, 3}, {1, 5}, {3, 5} (here I'm borrowing notations from Python). And I want to create a set of all these sets for all rows. How to do it in Matlab?

In Python it seems I simply can't do a set of sets, since sets are unhashable. In Matlab, it seems everything is a matrix, so I may have to still use a 1x2 matrix to represent each edge, which is fine, but what I want is I don't get duplicated edges. For example, [1 2] and [2 1] are one same edge so I have to make sure one and only one of them is retained in the final dataset.

Body:
First search your matrix and extract each vector.
After that you can store that in another matrix.

edges =

 1     3
 3     5
 1     3
 3     4
 5     1
 1     4
 4     4
 4     3

A = unique(edges,'rows')


问:
How to click at an element by the CSS code using Protractor?
I've been trying to click at the element using CSS Selector but it doesn't work:

```<code><button _ngcontent-c16="" class="btn btn-flat btn-no-text btn-kebab-view">
         <i _ngcontent-c16="" class="zmdi zmdi-more-vert"></i>
</button>
</code>```

I'm trying:

```<code>element.all(by.css('.btn .btn-flat .btn-no-text .btn-kebab-view')).first().click();
</code>```

Protractor gives me error:

Failed: Index out of bound. Trying to access element at index: 0, but
  there are only 0 elements that match locator By(css selector, .btn
  .btn-flat .btn-no-text .btn-kebab-view)

答: You should use the following CSS Selector: .btn.btn-flat.btn-no-text.btn-kebab-view.

Body:
I've been trying to click at the element using CSS Selector but it doesn't work:

<button _ngcontent-c16="" class="btn btn-flat btn-no-text btn-kebab-view">

</button>

I'm trying:

element.all(by.css('.btn .btn-flat .btn-no-text .btn-kebab-view')).first().click();

Protractor gives me error:

Failed: Index out of bound. Trying to access element at index: 0, but
  there are only 0 elements that match locator By(css selector, .btn
  .btn-flat .btn-no-text .btn-kebab-view)


问:
Keeping pages inside an iframe
I am trying to put a website inside an iframe, but this code on the site keeps changing the window of the page. Is there anyway I can get around this? Or better yet, can I disable javascript in an iframe?</p>

```<code>if(top!=self){
  if(top.location)
    top.location=self.location;
  else
    top.location='http://example.com/not_subframe.html';
}
</code>```

答: Nope, can't be done.  Not to mention it's usually a bad practice.</p>

Title: Keeping pages inside an iframe

Body:
I am trying to put a website inside an iframe, but this code on the site keeps changing the window of the page. Is there anyway I can get around this? Or better yet, can I disable javascript in an iframe?

if(top!=self){
  if(top.location)
    top.location=self.location;
  else
    top.location='http://example.com/not_subframe.html';
}


问:
Closing input tag issue in xhtml
I have closed all the possible tags here in my xhtml document that also includes few scripting part and yet I'm receiving the close input tag issue. Here's my code :

```<code><!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
    <title>Assignment3</title>
</head>
<body>
    <input type="checkbox" name="check" value="tick" onclick="addCostApple()"/>apple<br/><br/>
    <input type="checkbox" name="check" value="tick" onclick="addCostOrange()"/>banana<br/><br/>
    <input type="checkbox" name="check" value="tick" onclick="addCostBanana()"/>cherry<br/><br/>
    <input type="button" value="Submit" onclick="displayCost()">
    <script type="text/javascript">
        var total=0;
        function addCostApple()
        {
             total = total + 59;
        }
        function addCostOrange()
        {
             total = total + 49;
        }
        function addCostBanana()
        {
             total = total + 39;
        }
        function displayCost()
        {
            var tax = (0.05*total)/100;
            alert("Cost : $ "+(total/100)+"\nTax : $"+tax+"\nTotal : $"+(total+tax)/100);
        }
    </script>
</body>
</html>
</code>```

And this is the error I'm getting :

```<code>    XML Parsing Error: mismatched tag. Expected: </input>. Location:
file:///home/aravind/aravind/Sessions/Web%20programming/JavaScript
/day2/Assignment3.xhtml Line Number 35, Column 3:
</code>```

答:
In XHTML you have to close all HTML tags. The browser will translate it as HTML without <input> close tag.

Check here the syntax XHTML rules.

Title: Closing input tag issue in xhtml

Body:
I have closed all the possible tags here in my xhtml document that also includes few scripting part and yet I'm receiving the close input tag issue. Here's my code :

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

    <title>Assignment3</title>

    <input type="checkbox" name="check" value="tick" onclick="addCostApple()"/>apple

    <input type="checkbox" name="check" value="tick" onclick="addCostOrange()"/>banana

    <input type="checkbox" name="check" value="tick" onclick="addCostBanana()"/>cherry

    <input type="button" value="Submit" onclick="displayCost()">

And this is the error I'm getting :

    XML Parsing Error: mismatched tag. Expected: </input>. Location:
file:///home/aravind/aravind/Sessions/Web%20programming/JavaScript
/day2/Assignment3.xhtml Line Number 35, Column 3: