2015年06月

Fade in and out using display property



function myFunction() {
document.getElementById("myDIV").style.display = "block";
document.getElementById("second").style.display = "none";
}

function myFunction2() {
document.getElementById("second").style.display ="block";
document.getElementById("myDIV").style.display = "none";
}

#myDIV {
width: 500px;
height: 500px;
background-color: lightblue;
display: none;
}

#second {
width: 500px;
height: 500px;
background-color: lightblue;
display: none;
}

<button onclick="myFunction()">Try it</button>
<button onclick="myFunction2()">Try this now</button>
<div id="myDIV">
This is my DIV element.
</div>
<div id="second">
This is my DIV2 element.
</div>


Answers

Use jQuery for event handling and fade animations:



HTML:



<button id="button1">Try it</button>
<button id="button2">Try this now</button>


Javascript:



$('#button1').on('click', function () {
$('#second').fadeOut(2000, function () {
$('#myDIV').fadeIn(2000);
});
});


$('#button2').on('click', function () {
$('#myDIV').fadeOut(2000, function () {
$('#second').fadeIn(2000);
});
});


Demo: http://jsfiddle.net/tusharj/rLvpqcLb/



Answers

You can do it with css3 no jquery required, instead of display none use opacity 0



<!DOCTYPE html>
<html>

<head>
<style>
#myDIV {
width: 500px;
height: 500px;
background-color: lightblue;
opacity: 0;
transition: all 2s linear;
}

#second {
width: 500px;
height: 500px;
background-color: lightblue;
display: none;
}
</style>
</head>

<body>

<button onclick="myFunction()">Try it</button>
<button onclick="myFunction2()">Try this now</button>
<div id="myDIV">
This is my DIV element.
</div>
<div id="second">
This is my DIV2 element.
</div>

<script>
function myFunction() {
document.getElementById("myDIV").style.opacity = "1";
document.getElementById("second").style.display = "none";
}
</script>




Give names to Key and Value in C# Dictionary to improve code readability

In C# struct, we can know clearly the purpose of a variable by it's name. For example,



public struct Book
{
public string title;
public string author;
}


Then, i know b.title is a type of string and it's referring to title.



However in C# dictionary, we can only specify the type



Dictionary<string,string> d


How can i make the code more readable such that the key of the dictionary is type of string and it is referring to title, and the value is type of string and it is referring to author? That means, other people can easily know that d["J.R.R. Tolkien"] is a wrong use of the dictionary when reading the code.



EDIT
@mike z suggested to use a variable name titleToAuthor to help readability. But my real issue is that in the code there are nested dictionary. E.g.



Dictionary<string, Dictionary<string, string>>, 
or even 3 levels
Dictionary<string, Dictionary<string , Dictionary< string , string[] >>>.


We want to keep to convenience of using Dictionary without creating our own class but at the same time we need some way to improve the readability



Answers

What you can't solve without fighting the language, I'd suggest solving with documentation. Identifiers are included in that category as a form of self-documentation.



So to add self-documentation to a type of this sort:



using TitleToAuthor = System.Collections.Generic.Dictionary<
string, // title
string // author
>;


To add self-documentation to instances of that type:



TitleToAuthor title_to_author = new TitleToAuthor();


Unfortunately you cannot nest using directives as generic type parameters, so using a solution like this will make your using directives at the top of the file butt-ugly, but at least that butt-ugly code, written once, will then create a very readable alias to the left of it (showing exactly what it's for) that you can refer to throughout the rest of the code without actually creating new data types.



Another way is to simply create new data types, inheriting from Dictionary, e.g. I'd suggest this route if you have more you can do with the new type than simply getting a more readable type name, like adding methods that are specifically useful for that collection or if that collection is used in many source files (since then you'd have to repeat the same using directives a lot).



In such a case, composition might be better than inheritance (storing dictionary as a member) since then you could create a smaller, subset interface tailored to your needs (and perhaps with fewer ways to misuse it by only providing higher-level functions that make total sense for the specific container type) instead of just a full-blown dictionary's interface + more methods. In such a case, you'd be turning that somewhat hard-to-read, generic, general-purpose dictionary into a hidden implementation detail of something that not only reads better with respect to its type name, but also provides a smaller, tailored (less general) interface that more specifically handles your needs. For a simple example, it might be an error to allow empty strings to be specified for the key or the value. A dictionary doesn't impose such assertions, but an interface of your own design that uses dictionary as a private implementation detail can.



If you're tripping up over the readability of the key/value parameters of a dictionary, perhaps the problem is not really in the readability of the dictionary, but in the amount of public exposure that specific dictionary has. If you have a dictionary instance or even type with very public visibility that gets referred to all over the place, then you might be concerned with not only the readability of such code but also the flexibility that allows those accessing it to do anything they want that's allowed in a full-blown dictionary (including things you might not want to allow to happen at a broader scope). After all, even a type like float tells you very little about what it's supposed to do, but we tend to write code in a way where floats are either implementation details of a class/function or just function parameters/return types that are rather obvious in terms of what they do. So perhaps it would be better to seek to make such dictionaries less visible and more into private implementation details, since the clarity and readability of implementation details generally doesn't matter nearly as much as the more publicly-visible parts of an interface that are going to be accessed throughout your codebase.



Answers

By design, a dictionary is a key-value pair, and the exposed collections are called as such. If you want something more explicit, you can derive your own custom dictionary or implement the appropriate dictionary interfaces on your own class. You could also look at implementing this as a keyed collection, where you provide a lambda expression to derive the key from your data.



Answers

As suggested by @ScottDorman you could define a new Type TitleAuthorDictionary that derives from Dictionary<string, string>, like so:



public class TitleAuthorDictionary : Dictionary<string, string>
{
public new void Add(string title, string author)
{
base.Add(title, author);
}

public new string this[string title]
{
get { return base[title]; }
set { base[title] = value; }
}
}


You could then use the more readable Dictionary Collection, like this:



TitleAuthorDictionary dictionary = new TitleAuthorDictionary();
dictionary.Add("Title1", "Author1");
dictionary.Add(title: "Title2", author: "Author2");
dictionary["Title2"] = "Author3";




One icon is missing in font awesome in Windows

I'm currently using a Windows 7 VM to test my website in IE11. My website uses font awesome and glyphicons. All icons are loaded as expected except for a single one.



<button type="submit">
<i class="fa fa-cart-plus fa-2x"></i>
</button>


Testing in Firefox and Chrome in my Linux Mint machine, all icons render correctly. But both IE and Firefox in Windows show this single icon as a box.





I noticed that in Linux, the .woff2 file was being used while the .woff version was used in Windows. Font Awesome CSS and fonts are being served locally, not from a CDN. Could this make any difference? This missing icon shows correctly on font awesome"s website.



I found a few similar answers in Stack Overflow, most are old and I couldn't fix this because I don't even know where to start. How can I fix this missing icon?



Answers

Also having this issue with Chrome in a local environment (Probably more than that but can't be bothered to fully test) - I suspect the latest release has gotten messed up.



I've built a version using the fa-stack method below, just needs a little css for positioning but works fine:



HTML



<a role="button" class="btn btn-primary">
<span class="fa-stack">
<i class="fa fa-shopping-cart fa-stack-2x"></i>
<i class="fa fa-plus fa-stack-1x fa-primary"></i>
</span> New</a>


CSS



.fa-primary{
position: relative;
color: #1a9dff;
font-size: 0.5em !important;
top:-4px;
left:2px !important;
}


Edit: I've had to tweak the css for use with the CDN version of FontAwesome - Further suspect the download package and the CDN do not match



See this codepen example



This will overlay a plus icon of the colour of your choosing over the shopping cart icon. (Edit: Apologies for my poor indentation, first time answering!)



I'll point out that something similar happened with Bootstrap a few months ago, I updated the core files from 3.1.1 to 3.3.4 (or something) and it completely destroyed my layouts, though using the CDN used on bootstrap's homepage everything was fine, just not the downloadable package.



Basically, hang about for a bit and I'm sure they'll sort it, even the pros make mistakes - Use the same source as on working examples until the download package gets fixed if you're desperate to use it.



Answers

You're serving an older version of font awesome font files on Linux vs your Windows machine. This icon (fa-cart-plus) is only available starting in v4.3 (http://fortawesome.github.io/Font-Awesome/icon/cart-plus/). Make sure both machines are being served fontawesome 4.3 font files and it'll work fine.



CDN is always helpful to use, but it's not going to show you the root cause of your problem.



Answers

you can use this CSS in your webpage



<link href="http://netdna.bootstrapcdn.com/font-awesome/4.0.3/css/font-awesome.css" rel="stylesheet">




$httpBackend.expect vs. $httpBackend.when

After reading the AngularJS document fo $httpBackend, I am still not very clear what the difference between $httpBackend.expect and $httpBackend.when as both are functions for mocking http requests.



Could someone help explain the difference between these two functions? And also when shall I use $httpBackend.when instead of $httpBackend.expect?



Answers

The answer is fairly clear in the documentation, however, here is the main difference:



$httpBackend.when will return you a fake http response, but not fail the test if the URL declared is never called.



$httpBackend.expect will return you a fake http response. but fail the test if the URL declared is never called.



So, expect sets up an test expectation that the test must call the URL that is set up.





Compare adjacent list items

I'm writing a duplicate file detector. To determine if two files are duplicates I calculate a CRC32 checksum. Since this can be an expensive operation, I only want to calculate checksums for files that have another file with matching size. I have sorted my list of files by size, and am looping through to compare each element to the ones above and below it. Unfortunately, there is an issue at the beginning and end since there will be no previous or next file, respectively. I can fix this using if statements, but it feels clunky. Here is my code:



    public void GetCRCs(List<DupInfo> dupInfos)
{
var crc = new Crc32();
for (int i = 0; i < dupInfos.Count(); i++)
{
if (dupInfos[i].Size == dupInfos[i - 1].Size || dupInfos[i].Size == dupInfos[i + 1].Size)
{
dupInfos[i].CheckSum = crc.ComputeChecksum(File.ReadAllBytes(dupInfos[i].FullName));
}
}
}


My question is:




How can I compare each entry to its neighbors without the out of bounds error?


Should I be using a loop for this, or is there a better LINQ or other function?




Note: I did not include the rest of my code to avoid clutter. If you want to see it, I can include it.



Answers

I have sorted my list of files by size, and am looping through to
compare each element to the ones above and below it.




The next logical step is to actually group your files by size. Comparing consecutive files will not always be sufficient if you have more than two files of the same size. Instead, you will need to compare every file to every other same-sized file.



I suggest taking this approach




Use LINQ's .GroupBy to create a collection of files sizes. Then .Where to only keep the groups with more than one file.


Within those groups, calculate the CRC32 checksum and add it to a collection of known checksums. Compare with previously calculated checksums. If you need to know which files specifically are duplicates you could use a dictionary keyed by this checksum (you can achieve this with another GroupBy. Otherwise a simple list will suffice to detect any duplicates.




The code might look something like this:



var filesSetsWithPossibleDupes = files.GroupBy(f => f.Length)
.Where(group => group.Count() > 1);

foreach (var grp in filesSetsWithPossibleDupes)
{
var checksums = new List<CRC32CheckSum>(); //or whatever type
foreach (var file in grp)
{
var currentCheckSum = crc.ComputeChecksum(file);
if (checksums.Contains(currentCheckSum))
{
//Found a duplicate
}
else
{
checksums.Add(currentCheckSum);
}
}
}


Or if you need the specific objects that could be duplicates, the inner foreach loop might look like



var filesSetsWithPossibleDupes = files.GroupBy(f => f.FileSize)
.Where(grp => grp.Count() > 1);

var masterDuplicateDict = new Dictionary<DupStats, IEnumerable<DupInfo>>();
//A dictionary keyed by the basic duplicate stats
//, and whose value is a collection of the possible duplicates

foreach (var grp in filesSetsWithPossibleDupes)
{
var likelyDuplicates = grp.GroupBy(dup => dup.Checksum)
.Where(g => g.Count() > 1);
//Same GroupBy logic, but applied to the checksum (instead of file size)

foreach(var dupGrp in likelyDuplicates)
{
//Create the key for the dictionary (your code is likely different)
var sample = dupGrp.First();
var key = new DupStats() {FileSize = sample.FileSize, Checksum = sample.Checksum};
masterDuplicateDict.Add(key, dupGrp);
}
}


A demo of this idea.



Answers

Compute the Crcs first:



// It is assumed that DupInfo.CheckSum is nullable
public void GetCRCs(List<DupInfo> dupInfos)
{
dupInfos[0].CheckSum = null ;
for (int i = 1; i < dupInfos.Count(); i++)
{
dupInfos[i].CheckSum = null ;
if (dupInfos[i].Size == dupInfos[i - 1].Size)
{
if (dupInfos[i-1].Checksum==null) dupInfos[i-1].CheckSum = crc.ComputeChecksum(File.ReadAllBytes(dupInfos[i-1].FullName));
dupInfos[i].CheckSum = crc.ComputeChecksum(File.ReadAllBytes(dupInfos[i].FullName));
}
}
}


After having sorted your files by size and crc, identify duplicates:



public void GetDuplicates(List<DupInfo> dupInfos) 
{
for (int i = dupInfos.Count();i>0 i++)
{ // loop is inverted to allow list items deletion
if (dupInfos[i].Size == dupInfos[i - 1].Size &&
dupInfos[i].CheckSum != null &&
dupInfos[i].CheckSum == dupInfos[i - 1].Checksum)
{ // i is duplicated with i-1
... // your code here
... // eventually, dupInfos.RemoveAt(i) ;
}
}
}


Answers

I think the for loop should be : for (int i = 1; i < dupInfos.Count()-1; i++)



var grps= dupInfos.GroupBy(d=>d.Size);
grps.Where(g=>g.Count>1).ToList().ForEach(g=>
{
...
});


Answers

Can you do a union between your two lists? If you have a list of filenames and do a union it should result in only a list of the overlapping files. I can write out an example if you want but this link should give you the general idea.



http://stackoverflow.com/a/13505715/1856992



Edit: Sorry for some reason I thought you were comparing file name not size.



So here is an actual answer for you.



using System;
using System.Collections.Generic;
using System.Linq;


public class ObjectWithSize
{
public int Size {get; set;}
public ObjectWithSize(int size)
{
Size = size;
}
}

public class Program
{
public static void Main()
{
Console.WriteLine("start");
var list = new List<ObjectWithSize>();
list.Add(new ObjectWithSize(12));
list.Add(new ObjectWithSize(13));
list.Add(new ObjectWithSize(14));
list.Add(new ObjectWithSize(14));
list.Add(new ObjectWithSize(18));
list.Add(new ObjectWithSize(15));
list.Add(new ObjectWithSize(15));
var duplicates = list.GroupBy(x=>x.Size)
.Where(g=>g.Count()>1);
foreach (var dup in duplicates)
foreach (var objWithSize in dup)
Console.WriteLine(objWithSize.Size);
}
}


This will print out



14
14
15
15


Here is a netFiddle for that.
https://dotnetfiddle.net/0ub6Bs



Final note. I actually think your answer looks better and will run faster. This was just an implementation in Linq.





↑このページのトップヘ