text:
    <title>Week 12</title>

    JavaScript is required to view this page's content.

Alice's Evidence

      <canvas id="webgl-canvas" width="384" height="384">

	HTML5 is required to view this page's content.

	    'Here!' cried Alice, quite forgetting in the flurry of the moment how
	    large she had grown in the last few minutes, and she jumped up in such a
	    hurry that she tipped over the jury-box with the edge of her skirt,
	    upsetting all the jurymen on to the heads of the crowd below, and there
	    they lay sprawling about, reminding her very much of a globe of goldfish
	    she had accidentally upset the week before.

	    'Oh, I beg your pardon!' she exclaimed in a tone of great dismay, and
	    began picking them up again as quickly as she could, for the accident of
	    the goldfish kept running in her head, and she had a vague sort of idea
	    that they must be collected at once and put back into the jury-box, or
	    they would die.

	    'The trial cannot proceed,' said the King in a very grave voice, 'until
	    all the jurymen are back in their proper places—all,' he repeated
	    with great emphasis, looking hard at Alice as he said do.

	    Alice looked at the jury-box, and saw that, in her haste, she had put the
	    Lizard in head downwards, and the poor little thing was waving its tail
	    about in a melancholy way, being quite unable to move. She soon got it out
	    again, and put it right; 'not that it signifies much,' she said to
	    herself; 'I should think it would be quite as much use in the trial one
	    way up as the other.'

	    As soon as the jury had a little recovered from the shock of being upset,
	    and their slates and pencils had been found and handed back to them, they
	    set to work very diligently to write out a history of the accident, all
	    except the Lizard, who seemed too much overcome to do anything but sit
	    with its mouth open, gazing up into the roof of the court.

	    'What do you know about this business?' the King said to Alice.

	    'Nothing,' said Alice.

	    'Nothing whatever?' persisted the King.

	    'Nothing whatever,' said Alice.

	    'That's very important,' the King said, turning to the jury. They were
	    just beginning to write this down on their slates, when the White Rabbit
	    interrupted: 'Unimportant, your Majesty means, of course,' he said in a
	    very respectful tone, but frowning and making faces at him as he spoke.

	    'Unimportant, of course, I meant,' the King hastily said, and went on to
	    himself in an undertone,

	    'important—unimportant—unimportant—important—' as
	    if he were trying which word sounded best.

	    Some of the jury wrote it down 'important,' and some 'unimportant.' Alice
	    could see this, as she was near enough to look over their slates; 'but it
	    doesn't matter a bit,' she thought to herself.

	    At this moment the King, who had been for some time busily writing in his
	    note-book, cackled out 'Silence!' and read out from his book, 'Rule
	    Forty-two. All persons more than a mile high to leave the court.'

	    Everybody looked at Alice.

	    'I'm not a mile high,' said Alice.

	    'You are,' said the King.

	    'Nearly two miles high,' added the Queen.

	    'Well, I shan't go, at any rate,' said Alice: 'besides, that's not a
	    regular rule: you invented it just now.'

	    'It's the oldest rule in the book,' said the King.

	    'Then it ought to be Number One,' said Alice.

	    The King turned pale, and shut his note-book hastily. 'Consider your
	    verdict,' he said to the jury, in a low, trembling voice.

	    'There's more evidence to come yet, please your Majesty,' said the White
	    Rabbit, jumping up in a great hurry; 'this paper has just been picked up.'

	    'What's in it?' said the Queen.

	    'I haven't opened it yet,' said the White Rabbit, 'but it seems to be a
	    letter, written by the prisoner to—to somebody.'

	    'It must have been that,' said the King, 'unless it was written to nobody,
	    which isn't usual, you know.'

	    'Who is it directed to?' said one of the jurymen.

	    'It isn't directed at all,' said the White Rabbit; 'in fact, there's
	    nothing written on the outside.' He unfolded the paper as he spoke, and
	    added 'It isn't a letter, after all: it's a set of verses.'

	    'Are they in the prisoner's handwriting?' asked another of the jurymen.

	    'No, they're not,' said the White Rabbit, 'and that's the queerest thing
	    about it.' (The jury all looked puzzled.)

	    'He must have imitated somebody else's hand,' said the King. (The jury all
	    brightened up again.)

	    'Please your Majesty,' said the Knave, 'I didn't write it, and they can't
	    prove I did: there's no name signed at the end.'

	    'If you didn't sign it,' said the King, 'that only makes the matter worse.
	    You must have meant some mischief, or else you'd have signed your name
	    like an honest man.'

	    There was a general clapping of hands at this: it was the first really
	    clever thing the King had said that day.

	    'That proves his guilt,' said the Queen.

	    'It proves nothing of the sort!' said Alice. 'Why, you don't even know
	    what they're about!'

	    'Read them,' said the King.

	    The White Rabbit put on his spectacles. 'Where shall I begin, please your
	    Majesty?' he asked.

	    'Begin at the beginning,' the King said gravely, 'and go on till you come
	    to the end: then stop.'

	    These were the verses the White Rabbit read:—

	    'They told me you had been to her,
	    And mentioned me to him:
	    She gave me a good character,
	    But said I could not swim.

	    He sent them word I had not gone
	    (We know it to be true):
	    If she should push the matter on,
	    What would become of you?

	    I gave her one, they gave him two,
	    You gave us three or more;
	    They all returned from him to you,
	    Though they were mine before.

	    If I or she should chance to be
	    Involved in this affair,
	    He trusts to you to set them free,
	    Exactly as we were.

	    My notion was that you had been
	    (Before she had this fit)
	    An obstacle that came between
	    Him, and ourselves, and it.

	    Don't let him know she liked them best,
	    For this must ever be
	    A secret, kept from all the rest,
	    Between yourself and me.'

	    'That's the most important piece of evidence we've heard yet,' said the
	    King, rubbing his hands; 'so now let the jury—'

	    'If any one of them can explain it,' said Alice, (she had grown so large
	    in the last few minutes that she wasn't a bit afraid of interrupting him,)
	    'I'll give him sixpence. I don't believe there's an atom of meaning
	    in it.'

	    The jury all wrote down on their slates, 'She doesn't believe there's an
	    atom of meaning in it,' but none of them attempted to explain the paper.

	    'If there's no meaning in it,' said the King, 'that saves a world of
	    trouble, you know, as we needn't try to find any. And yet I don't know,'
	    he went on, spreading out the verses on his knee, and looking at them with
	          one eye; 'I seem to see some meaning in them, after all. "—said I
	      could not swim—" you can't swim, can you?' he added, turning to the
	    Knave.

	    The Knave shook his head sadly. 'Do I look like it?' he said. (Which he
	    certainly did not, being made entirely of cardboard.)

	    'All right, so far,' said the King, and he went on muttering over the
	    verses to himself: '"We know it to be true—" that's the jury, of
	    course—"I gave her one, they gave him two—" why, that must be
	    what he did with the tarts, you know—'

	    'But, it goes on "they all returned from him to you,"' said Alice.

	    'Why, there they are!' said the King triumphantly, pointing to the tarts
	          on the table. 'Nothing can be clearer than that. Then again—"before
	      she had this fit—" you never had fits, my dear, I think?' he said to
	    the Queen.

	    'Never!' said the Queen furiously, throwing an inkstand at the Lizard as
	    she spoke. (The unfortunate little Bill had left off writing on his slate
	    with one finger, as he found it made no mark; but he now hastily began
	    again, using the ink, that was trickling down his face, as long as it
	    lasted.)

	    'Then the words don't fit you,' said the King, looking round the court
	    with a smile. There was a dead silence.

	    'It's a pun!' the King added in an offended tone, and everybody laughed,
	    'Let the jury consider their verdict,' the King said, for about the
	    twentieth time that day.

	    'No, no!' said the Queen. 'Sentence first—verdict afterwards.'

	    'Stuff and nonsense!' said Alice loudly. 'The idea of having the sentence
	    first!'

	    'Hold your tongue!' said the Queen, turning purple.

	    'I won't!' said Alice.

	    'Off with her head!' the Queen shouted at the top of her voice. Nobody
	    moved.

	    'Who cares for you?' said Alice, (she had grown to her full size by this
	    time.) 'You're nothing but a pack of cards!'

	    At this the whole pack rose up into the air, and came flying down upon
	    her: she gave a little scream, half of fright and half of anger, and tried
	    to beat them off, and found herself lying on the bank, with her head in
	    the lap of her sister, who was gently brushing away some dead leaves that
	    had fluttered down from the trees upon her face.

	    'Wake up, Alice dear!' said her sister; 'Why, what a long sleep you've
	    had!'

	    'Oh, I've had such a curious dream!' said Alice, and she told her sister,
	    as well as she could remember them, all these strange Adventures of hers
	    that you have just been reading about; and when she had finished, her
	    sister kissed her, and said, 'It was a curious dream, dear, certainly: but
	    now run in to your tea; it's getting late.' So Alice got up and ran off,
	    thinking while she ran, as well she might, what a wonderful dream it had
	    been.

	    But her sister sat still just as she left her, leaning her head on her
	    hand, watching the setting sun, and thinking of little Alice and all her
	    wonderful Adventures, till she too began dreaming after a fashion, and
	    this was her dream:—

	    First, she dreamed of little Alice herself, and once again the tiny hands
	    were clasped upon her knee, and the bright eager eyes were looking up into
	    hers—she could hear the very tones of her voice, and see that queer
	    little toss of her head to keep back the wandering hair that would always
	    get into her eyes—and still as she listened, or seemed to listen,
	    the whole place around her became alive with the strange creatures of her
	    little sister's dream.

	    The long grass rustled at her feet as the White Rabbit hurried by—the
	    frightened Mouse splashed his way through the neighbouring pool—she
	    could hear the rattle of the teacups as the March Hare and his friends
	    shared their never-ending meal, and the shrill voice of the Queen ordering
	    off her unfortunate guests to execution—once more the pig-baby was
	    sneezing on the Duchess's knee, while plates and dishes crashed around it—once
	    more the shriek of the Gryphon, the squeaking of the Lizard's
	    slate-pencil, and the choking of the suppressed guinea-pigs, filled the
	    air, mixed up with the distant sobs of the miserable Mock Turtle.

	    So she sat on, with closed eyes, and half believed herself in Wonderland,
	    though she knew she had but to open them again, and all would change to
	    dull reality—the grass would be only rustling in the wind, and the
	    pool rippling to the waving of the reeds—the rattling teacups would
	    change to tinkling sheep-bells, and the Queen's shrill cries to the voice
	    of the shepherd boy—and the sneeze of the baby, the shriek of the
	    Gryphon, and all the other queer noises, would change (she knew) to the
	    confused clamour of the busy farm-yard—while the lowing of the
	    cattle in the distance would take the place of the Mock Turtle's heavy
	    sobs.

	    Lastly, she pictured to herself how this same little sister of hers would,
	    in the after-time, be herself a grown woman; and how she would keep,
	    through all her riper years, the simple and loving heart of her childhood:
	    and how she would gather about her other little children, and make their
	    eyes bright and eager with many a strange tale, perhaps even with the
	    dream of Wonderland of long ago: and how she would feel with all their
	    simple sorrows, and find a pleasure in all their simple joys, remembering
	    her own child-life, and the happy summer days.

	    THE END

      </canvas>

	Select Texture :

	  <select id="select_texture" onchange="select_texture(this.value)">
	    <option value="0" selected>Checkerboard</option>
	    <option value="1">Moon</option>
	  </select>

	Background Color :

	  <input type="color" id="bg_color"
		 onchange="set_bgcolor(this.value)" value="#000000"/>

	Mapping :

	  <select id="mapping" onchange="select_mapping(this.value)">
	    <option value="0" selected>Regular</option>
	    <option value="1">Planar</option>
	  </select>

	Ambient Color :

	  <input type="color" id="ambient_color"
		 onchange="set_ambientcolor(this.value)" value="#ffffff"/>

	Translate X :

	  <input type="range" id="translate_x"
		 min="-16" max="16" value="0" step="0.1"
		 onchange="translate_x(this.value)"
		 oninput="translate_x(this.value)"/>

	Rotate X :

	  <input type="range" id="rotate_x"
		 min="-180" max="180" value="0" step="1"
		 onchange="rotate_x(this.value)"
		 oninput="rotate_x(this.value)"/>

	Scale Height :

	  <input type="range" id="scale_y"
		 min="0.1" max="4.0" value="1.0" step="0.1"
		 onchange="scale_y(this.value)"
		 oninput="scale_y(this.value)"/>

	Diffuse Color :

	  <input type="color" id="diffuse_color"
		 onchange="set_diffusecolor(this.value)" value="#ffffff"/>

	Translate Y :

	  <input type="range" id="translate_y"
		 min="-16" max="16" value="0" step="0.1"
		 onchange="translate_y(this.value)"
		 oninput="translate_y(this.value)"/>

	Rotate Y :

	  <input type="range" id="rotate_y"
		 min="-180" max="180" value="0" step="1"
		 onchange="rotate_y(this.value)"
		 oninput="rotate_y(this.value)"/>

	Scale Width :

	  <input type="range" id="scale_x"
		 min="0.1" max="4.0" value="1.0" step="0.1"
		 onchange="scale_x(this.value)"
		 oninput="scale_x(this.value)"/>

	Specular Color :

	  <input type="color" id="specula_color"
		 onchange="set_speculacolor(this.value)" value="#ffffff"/>

	Translate Z :

	  <input type="range" id="translate_z"
		 min="-50" max="2" value="0" step="0.1"
		 onchange="translate_z(this.value)"
		 oninput="translate_z(this.value)"/>

	Rotate Z :

	  <input type="range" id="rotate_z"
		 min="-180" max="180" value="0" step="1"
		 onchange="rotate_z(this.value)"
		 oninput="rotate_z(this.value)"/>

	Shininess :

	  <input type="range" id="shininess"
		 min="1" max="200" value="20" step="1"
		 onchange="shininess(this.value)"
		 oninput="shininess(this.value)"/>

	Ambient Light :

	  <input type="color" id="ambient_light"
		 onchange="set_ambientlight(this.value)" value="#ffffff"/>

	Light X :

	  <input type="range" id="light_x"
		 min="-8" max="8" value="0" step="0.1"
		 onchange="light_x(this.value)"
		 oninput="light_x(this.value)"/>

	Diffuse Light :

	  <input type="color" id="diffuse_light"
		 onchange="set_diffuselight(this.value)" value="#ffffff"/>

	Light Y :

	  <input type="range" id="light_y"
		 min="-8" max="8" value="2" step="0.1"
		 onchange="light_y(this.value)"
		 oninput="light_y(this.value)"/>

	Specular Light :

	  <input type="color" id="specula_light"
		 onchange="set_speculalight(this.value)" value="#ffffff"/>

	Light Z :

	  <input type="range" id="light_z"
		 min="-90" max="3" value="-5" step="0.1"
		 onchange="light_z(this.value)"
		 oninput="light_z(this.value)"/>


text:
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE html
  PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
<meta name="copyright" content="(C) Copyright 2005"/>
<meta name="DC.rights.owner" content="(C) Copyright 2005"/>
<meta name="DC.Type" content="reference"/>
<meta name="DC.Title" content="cxxStructDeclarationFileLineEnd"/>
<meta name="abstract" content="The <cxxStructDeclarationFileLineEnd> element specifies the end of the struct declaration."/>
<meta name="description" content="The <cxxStructDeclarationFileLineEnd> element specifies the end of the struct declaration."/>
<meta name="DC.Relation" scheme="URI" content="../cxxStruct/cxxStruct_module.html"/>
<meta name="DC.Format" content="XHTML"/>
<meta name="DC.Identifier" content="cxxStructDeclarationFileLineEnd"/>
<meta name="DC.Language" content="en-us"/>
<link rel="stylesheet" type="text/css" href="../commonltr.css"/>
<title>cxxStructDeclarationFileLineEnd</title>
<link rel="stylesheet" type="text/css" href="../nokiacxxref.css"/>

cxxStructDeclarationFileLineEnd

The <cxxStructDeclarationFileLineEnd> element specifies the end of the struct declaration.

Description

The <cxxStructDeclarationFileLineEnd> element is defined within <cxxStructAPIItemLocation>.
            It contains the line number that the struct declaration ends on. The element is empty but for the required attributes name
            and value. The attribute name must be set to "lineNumber". The attribute value is set to the line number
            the struct declaration ends on.

Example

<cxxStructDefinition>
    <cxxStructAccessSpecifier value="public" />
    <cxxStructAPIItemLocation>
         <cxxStructDeclarationFile name="filePath" value="s:/sf/os/commsfw/commsconfig/commsdatabaseshim/commdbshim/SCDB/CDBTABLE.CPP" />
        <cxxStructDeclarationFileLineStart name="lineNumber" value="36" />
        <cxxStructDeclarationFileLineEnd name="lineNumber" value="41" />
    </cxxStructAPIItemLocation>
</cxxStructDefinition>

Contained by

cxxStructAPIItemLocation

Contains

Content Model

No content.

Inheritance

 topic/state reference/state apiRef/apiQualifier apiStructifier/apiQualifier cxxStruct/cxxStructDeclarationFileLineEnd

Parent topic: cxxStruct module

redpajama_set_name: RedPajamaGithub


text:
package com.google.javascript.rhino;

import static com.google.common.truth.Truth.assertThat;
import static com.google.javascript.rhino.testing.Asserts.assertThrows;

import com.google.common.collect.Iterables;
import com.google.common.collect.ListMultimap;
import com.google.common.collect.MultimapBuilder;
import com.google.javascript.rhino.PMap.Reconciler;
import java.util.Objects;
import java.util.TreeSet;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.JUnit4;

/** Tests for {@link HamtPMap}. */
@RunWith(JUnit4.class)
public class HamtPMapTest {
  @Test
  public void testEmpty() {
    PMap<String, Integer> map = HamtPMap.empty();
    assertThat(map.get("foo")).isNull();
    assertThat(map.values()).isEmpty();
    assertThat(map.isEmpty()).isTrue();
  }

  @Test
  public void testPlus() {
    PMap<String, Integer> empty = HamtPMap.empty();
    PMap<String, Integer> map = empty.plus("foo", 42);
    assertThat(map.get("foo")).isEqualTo(42);
    assertThat(map.values()).containsExactly(42);
    assertThat(map.isEmpty()).isFalse();
  }

  @Test
  public void testPlus_alreadyExistsReturnsSame() {
    PMap<String, Integer> empty = HamtPMap.empty();
    PMap<String, Integer> map = empty.plus("foo", 42);
    assertThat(map.plus("foo", 42)).isSameInstanceAs(map);
  }

  @Test
  public void testPlus_updatesExistingKey() {
    PMap<String, Integer> empty = HamtPMap.empty();
    PMap<String, Integer> map = empty.plus("foo", 42).plus("foo", 23);
    assertThat(map.get("foo")).isEqualTo(23);
    assertThat(map.values()).containsExactly(23);
    assertThat(map.isEmpty()).isFalse();
  }

  @Test
  public void testMinus() {
    PMap<String, Integer> map = HamtPMap.<String, Integer>empty().plus("foo", 42);
    PMap<String, Integer> empty = map.minus("foo");
    assertThat(empty.get("foo")).isNull();
    assertThat(empty.values()).isEmpty();
    assertThat(empty.isEmpty()).isTrue();
  }

  @Test
  public void testMinus_nonexistentKeyReturnsSame() {
    PMap<String, Integer> empty = HamtPMap.empty();
    PMap<String, Integer> map = empty.plus("foo", 42);
    assertThat(map.minus("bar")).isSameInstanceAs(map);
  }

  @Test
  public void testPlusAndMinus() {
    PMap<String, Integer> empty = HamtPMap.empty();
    PMap<String, Integer> map = empty.plus("foo", 42).plus("bar", 19).plus("baz", 12);
    assertThat(map.get("foo")).isEqualTo(42);
    assertThat(map.get("bar")).isEqualTo(19);
    assertThat(map.get("baz")).isEqualTo(12);
    assertThat(map.values()).containsExactly(12, 19, 42);
    assertThat(map.isEmpty()).isFalse();

    map = map.minus("bar");
    assertThat(map.get("foo")).isEqualTo(42);
    assertThat(map.get("bar")).isNull();
    assertThat(map.get("baz")).isEqualTo(12);
    assertThat(map.values()).containsExactly(12, 42);
    assertThat(map.isEmpty()).isFalse();

    map = map.minus("baz");
    assertThat(map.get("foo")).isEqualTo(42);
    assertThat(map.get("baz")).isNull();
    assertThat(map.values()).containsExactly(42);
    assertThat(map.isEmpty()).isFalse();

    map = map.minus("foo");
    assertThat(map.get("foo")).isNull();
    assertThat(map.values()).isEmpty();
    assertThat(map.isEmpty()).isTrue();
  }

  @Test
  public void testReconcile_customJoiner() {
    PMap<Integer, String> empty = HamtPMap.<Integer, String>empty();
    PMap<Integer, String> left =
        empty.plus(1, "1").plus(3, "3").plus(5, "5").plus(7, "7").plus(9, "9");
    PMap<Integer, String> right =
        empty.plus(3, "C").plus(4, "D").plus(5, "5").plus(6, "F").plus(7, "G");

    JoinExpectations<Integer, String> expectations =
        new JoinExpectations<Integer, String>()
            .expect(1, "1", null, "1")
            .expect(3, "3", "C", "c")
            .expect(4, null, "D", "D")
            .expect(6, null, "F", "F")
            .expect(7, "7", "G", "g")
            .expect(9, "9", null, "9");

    PMap<Integer, String> joined = left.reconcile(right, expectations);

    assertThat(joined.values()).containsExactly("1", "c", "D", "5", "F", "g", "9");
    expectations.verify();
  }

  @Test
  public void testReconcile_emptyMaps() {
    PMap<Integer, String> empty = HamtPMap.<Integer, String>empty();
    PMap<Integer, String> map =
        empty.plus(1, "1").plus(3, "3").plus(5, "5").plus(7, "7").plus(9, "9");

    PMap<Integer, String> joined =
        map.reconcile(
            empty,
            (k, a, b) -> {
              assertThat(b).isNull();
              return a;
            });
    assertThat(joined.equivalent(map, Objects::equals)).isTrue();

    joined =
        empty.reconcile(
            map,
            (k, a, b) -> {
              assertThat(a).isNull();
              return b;
            });
    assertThat(joined.equivalent(map, Objects::equals)).isTrue();
  }

  @Test
  public void testReconcile_differentSizes() {
    PMap<Integer, Integer> left = build(1, 6, 2, 19, 4, 23, 5, 8, 42, 12, 18, 33);
    PMap<Integer, Integer> right =
        build().plus(3, 1).plus(4, 1).plus(8, 1).plus(19, 1).plus(25, 1).plus(42, 1);
    PMap<Integer, Integer> expected =
        left.plus(3, 1).plus(4, 5).plus(8, 9).plus(19, 20).plus(25, 1).plus(42, 43);

    PMap<Integer, Integer> joined =
        left.reconcile(right, (k, a, b) -> a == null ? b : b == null ? a : a + b);
    assertThat(joined.equivalent(expected, Objects::equals)).isTrue();
  }

  @Test
  public void testReconcile_rejectsNullResult() {
    PMap<Integer, Integer> left = build(1, 3, 5, 7);
    PMap<Integer, Integer> right = build(2, 4, 6, 8);

    assertThrows(Exception.class, () -> left.reconcile(right, (k, a, b) -> null));
  }

  @Test
  public void testEquivalent_equivalent() {
    PMap<Integer, Integer> left = build(1, 2, 4, 8, 16, 32, 64, 128, 256, 512, 1024);
    PMap<Integer, Integer> right = build(2, 512, 32, 8, 1024, 1, 64, 4, 16, 256, 128);

    assertThat(left.equivalent(right, Objects::equals)).isTrue();
    assertThat(right.equivalent(left, Objects::equals)).isTrue();
  }

  @Test
  public void testEquivalent_oneDifferentValue() {
    // Insertion order doesn't matter
    PMap<Integer, Integer> left1 = build(1, 3, 5, 7);
    PMap<Integer, Integer> left2 = build(7, 3, 5, 1);
    PMap<Integer, Integer> right1 = build().plus(1, 2).plus(3, 3).plus(5, 5).plus(7, 7);
    PMap<Integer, Integer> right2 = build(1, 3, 5).plus(7, 8);

    assertThat(left1.equivalent(right1, Objects::equals)).isFalse();
    assertThat(right1.equivalent(left1, Objects::equals)).isFalse();
    assertThat(left2.equivalent(right1, Objects::equals)).isFalse();
    assertThat(right1.equivalent(left2, Objects::equals)).isFalse();
    assertThat(left1.equivalent(right2, Objects::equals)).isFalse();
    assertThat(right2.equivalent(left1, Objects::equals)).isFalse();
    assertThat(left2.equivalent(right2, Objects::equals)).isFalse();
    assertThat(right2.equivalent(left2, Objects::equals)).isFalse();
  }

  @Test
  public void testEquivalent_oneDifferentKey() {
    PMap<Integer, Integer> left1 = build().plus(2, 1).plus(3, 3).plus(5, 5).plus(7, 7);
    PMap<Integer, Integer> left2 = build(1, 3, 5).plus(7, 8);
    PMap<Integer, Integer> right = build(1, 3, 5, 7);

    assertThat(left1.equivalent(right, Objects::equals)).isFalse();
    assertThat(right.equivalent(left1, Objects::equals)).isFalse();
    assertThat(left2.equivalent(right, Objects::equals)).isFalse();
    assertThat(right.equivalent(left2, Objects::equals)).isFalse();
  }

  @Test
  public void testEquivalent_oneMissingKey() {
    PMap<Integer, Integer> left = build(1, 5, 4, 3, 9);
    PMap<Integer, Integer> right = build(1, 5, 3, 9);

    assertThat(left.equivalent(right, Objects::equals)).isFalse();
    assertThat(right.equivalent(left, Objects::equals)).isFalse();
  }

  @Test
  public void testEquivalent_equalsWithCustomEquivalence() {
    PMap<String, String> empty = HamtPMap.empty();
    PMap<String, String> left = empty.plus("abc", "AAa").plus("def", "Ddd").plus("ghi", "ggG");
    PMap<String, String> right = empty.plus("abc", "aAA").plus("def", "ddD").plus("ghi", "GGG");

    assertThat(left.equivalent(right, (l, r) -> l.toLowerCase().equals(r.toLowerCase()))).isTrue();
  }

  @Test
  public void testEquivalent_notEquivalentShortCircuits() {
    PMap<Integer, String> empty = HamtPMap.empty();
    PMap<Integer, String> left = empty.plus(1, "1").plus(2, "2");
    PMap<Integer, String> right = empty.plus(1, "3").plus(2, "4");

    int[] calls = new int[] { 0 };
    assertThat(
            left.equivalent(
                right,
                (l, r) -> {
                  calls[0]++;
                  return false;
                }))
        .isFalse();
    assertThat(calls[0]).isEqualTo(1);
  }

  @Test
  public void testKeys_containsExactlyKeys() {
    PMap<Integer, String> empty = HamtPMap.empty();
    PMap<Integer, String> actual =
        empty.plus(1, "a").plus(2, "b").plus(100, "x").plus(-847, "h").minus(2);

    assertThat(actual.keys()).containsExactly(1, 100, -847);
  }

  @Test
  public void testValues_containsExactlyValues() {
    PMap<Integer, String> empty = HamtPMap.empty();
    PMap<Integer, String> actual =
        empty.plus(1, "a").plus(2, "b").plus(3, "kkdmw").plus(4, ":::").minus(1);

    assertThat(actual.values()).containsExactly("b", "kkdmw", ":::");
  }

  private static class JoinExpectations<K, V> implements Reconciler<K, V> {
    private final ListMultimap<K, V> expectations =
        MultimapBuilder.linkedHashKeys().arrayListValues().build();

    @Override
    public V merge(K key, V left, V right) {
      assertThat(this.expectations).containsKey(key);
      assertThat(this.expectations.get(key).get(0)).isEqualTo(left);
      assertThat(this.expectations.get(key).get(1)).isEqualTo(right);
      return this.expectations.removeAll(key).get(2);
    }

    JoinExpectations<K, V> expect(K key, V left, V right, V result) {
      assertThat(this.expectations).doesNotContainKey(key);
      this.expectations.put(key, left);
      this.expectations.put(key, right);
      this.expectations.put(key, result);
      return this;
    }

    void verify() {
      assertThat(this.expectations).isEmpty();
    }
  }

  @Test
  public void testIntegration() {
    TreeSet<Integer> ref = new TreeSet<>();
    PMap<Integer, String> map = HamtPMap.empty();

    // Note: multiplying by 43 produces every nonzero integer mod 127.
    for (int i = 17; ref.add(i); i = (i * 43) % 127) {
      map = map.plus(i, String.valueOf(i));
      ((HamtPMap<?, ?>) map).assertCorrectStructure();
      assertThat(map.isEmpty()).isEqualTo(ref.isEmpty());
      for (int j = 1; j < 127; j++) {
        assertThat(map.get(j)).isEqualTo(ref.contains(j) ? String.valueOf(j) : null);
        if (ref.contains(j)) {
          assertThat(map.plus(j, String.valueOf(j))).isSameInstanceAs(map);
        } else {
          assertThat(map.minus(j)).isSameInstanceAs(map);
        }
      }
      assertThat(map.values()).containsExactlyElementsIn(Iterables.transform(ref, String::valueOf));
    }
    assertThat(ref).hasSize(126); // (quick check that we actually did add everything)

    // Note: multiplying by 39 produces every nonzero integer mod 127 in a different order.
    for (int i = 12; ref.remove(i); i = (i * 39) % 127) {
      map = map.minus(i);
      ((HamtPMap<?, ?>) map).assertCorrectStructure();
      assertThat(map.isEmpty()).isEqualTo(ref.isEmpty());
      for (int j = 1; j < 127; j++) {
        assertThat(map.get(j)).isEqualTo(ref.contains(j) ? String.valueOf(j) : null);
        if (ref.contains(j)) {
          assertThat(map.plus(j, String.valueOf(j))).isSameInstanceAs(map);
        } else {
          assertThat(map.minus(j)).isSameInstanceAs(map);
        }
      }
      assertThat(map.values()).containsExactlyElementsIn(Iterables.transform(ref, String::valueOf));
    }
    assertThat(ref).isEmpty();
    assertThat(map).isSameInstanceAs(HamtPMap.empty());
  }

  private PMap<Integer, Integer> build(int... values) {
    PMap<Integer, Integer> map = HamtPMap.<Integer, Integer>empty();
    for (int value : values) {
      map = map.plus(value, value);
      ((HamtPMap<?, ?>) map).assertCorrectStructure();
    }
    return map;
  }
}


text:
package soundgates.simulation;

import org.eclipse.jface.preference.BooleanFieldEditor;
import org.eclipse.jface.preference.FieldEditorPreferencePage;
import org.eclipse.jface.preference.FileFieldEditor;
import org.eclipse.jface.preference.StringFieldEditor;
import org.eclipse.ui.IWorkbench;
import org.eclipse.ui.IWorkbenchPreferencePage;

public class PdPreferencePage extends FieldEditorPreferencePage implements
		IWorkbenchPreferencePage {

	public static final String PD_EXECUTABLE = "PD_EXEC";
	public static final String PD_ARGUMENTS = "PD_PARAMS";
	public static final String PD_NOGUI = "PD_NOGUI";

	@Override
	public void init(IWorkbench workbench) {
		setPreferenceStore(Activator.getDefault().getPreferenceStore());
		setDescription("Soundgates simulation settings");
	}

	@Override
	protected void createFieldEditors() {
		addField(new FileFieldEditor(PD_EXECUTABLE, "Pure data executable", getFieldEditorParent()));
		addField(new StringFieldEditor(PD_ARGUMENTS, "Parameters (separated by %)", getFieldEditorParent()));
		addField(new BooleanFieldEditor(PD_NOGUI, "Start PD without gui", getFieldEditorParent()));
	}

}


text:
require "kittikrb/cursor"

cursor = KittikRb::Cursor.create.reset_tty!
height, width = $stdout.winsize

COLORS = KittikRb::Cursor::Colors::COLORS.keys

0.upto height do |y|
  0.upto width do |x|
    cursor.move_to(x, y)
      .background(COLORS[(y + x) % (COLORS.size - 1)]).write(" ")
  end
end

cursor.flush


text:
require "cgi"
class User < ActiveRecord::Base
	def self.create_with_omniauth(auth)
		create! do |user|
			puts "creating new user"
			user.provider = CGI::escapeHTML(auth["provider"].force_encoding(Encoding::UTF_8))
			user.uid = auth["uid"]
			user.name = CGI::escapeHTML(auth["info"]["name"].force_encoding(Encoding::UTF_8))
		end
	end

	def self.update_with_omniauth(user, auth)
		name = CGI::escapeHTML(auth["info"]["name"].force_encoding(Encoding::UTF_8))
		user.update(name: name)
	end

end


text:
#include "mitkPluginActivator.h"
#include "QmitkDataStorageViewerTestView.h"

namespace mitk
{
  void DataStorageViewerTestActivator::start(ctkPluginContext *context)
  {
    BERRY_REGISTER_EXTENSION_CLASS(QmitkDataStorageViewerTestView, context)
  }

  void DataStorageViewerTestActivator::stop(ctkPluginContext *context) { Q_UNUSED(context) }
}


text:
require 'generators/factory_girl'

module FactoryGirl
  module Generators
    class ModelGenerator < Base
      argument :attributes, :type => :array, :default => [], :banner => "field:type field:type"
      class_option :dir, :type => :string, :default => "test/factories", :desc => "The directory where the factories should go"

      def create_fixture_file
        template 'fixtures.rb', File.join(options[:dir], "#{table_name}.rb")
      end
    end
  end
end


text:
'''
The 'forecast' module contains class definitions for
retreiving forecasted data from UNIDATA Thredd servers.
'''
from netCDF4 import num2date
import numpy as np
import pandas as pd
from requests.exceptions import HTTPError
from xml.etree.ElementTree import ParseError

from pvlib.location import Location
from pvlib.irradiance import campbell_norman, get_extra_radiation, disc
from pvlib.irradiance import _liujordan
from siphon.catalog import TDSCatalog
from siphon.ncss import NCSS

import warnings
from pvlib._deprecation import deprecated

warnings.warn(
    'The forecast module algorithms and features are highly experimental. '
    'The API may change, the functionality may be consolidated into an io '
    'module, or the module may be separated into its own package.')

_forecast_deprecated = deprecated(
    since='0.9.1',
    removal='a future release',
    addendum='For details, see https://pvlib-python.readthedocs.io/en/stable/user_guide/forecasts.html'  # noqa: E501
)

# don't decorate the base class to prevent the subclasses from showing
# duplicate warnings:
# @_forecast_deprecated
class ForecastModel:
    """
    An object for querying and holding forecast model information for
    use within the pvlib library.

    Simplifies use of siphon library on a THREDDS server.

    Parameters
    ----------
    model_type: string
        UNIDATA category in which the model is located.
    model_name: string
        Name of the UNIDATA forecast model.
    set_type: string
        Model dataset type.

    Attributes
    ----------
    access_url: string
        URL specifying the dataset from data will be retrieved.
    base_tds_url : string
        The top level server address
    catalog_url : string
        The url path of the catalog to parse.
    data: pd.DataFrame
        Data returned from the query.
    data_format: string
        Format of the forecast data being requested from UNIDATA.
    dataset: Dataset
        Object containing information used to access forecast data.
    dataframe_variables: list
        Model variables that are present in the data.
    datasets_list: list
        List of all available datasets.
    fm_models: Dataset
        TDSCatalog object containing all available
        forecast models from UNIDATA.
    fm_models_list: list
        List of all available forecast models from UNIDATA.
    latitude: list
        A list of floats containing latitude values.
    location: Location
        A pvlib Location object containing geographic quantities.
    longitude: list
        A list of floats containing longitude values.
    lbox: boolean
        Indicates the use of a location bounding box.
    ncss: NCSS object
        NCSS
    model_name: string
        Name of the UNIDATA forecast model.
    model: Dataset
        A dictionary of Dataset object, whose keys are the name of the
        dataset's name.
    model_url: string
        The url path of the dataset to parse.
    modelvariables: list
        Common variable names that correspond to queryvariables.
    query: NCSS query object
        NCSS object used to complete the forecast data retrival.
    queryvariables: list
        Variables that are used to query the THREDDS Data Server.
    time: DatetimeIndex
        Time range.
    variables: dict
        Defines the variables to obtain from the weather
        model and how they should be renamed to common variable names.
    units: dict
        Dictionary containing the units of the standard variables
        and the model specific variables.
    vert_level: float or integer
        Vertical altitude for query data.
    """

    access_url_key = 'NetcdfSubset'
    catalog_url = 'https://thredds.ucar.edu/thredds/catalog.xml'
    base_tds_url = catalog_url.split('/thredds/')[0]
    data_format = 'netcdf'

    units = {
        'temp_air': 'C',
        'wind_speed': 'm/s',
        'ghi': 'W/m^2',
        'ghi_raw': 'W/m^2',
        'dni': 'W/m^2',
        'dhi': 'W/m^2',
        'total_clouds': '%',
        'low_clouds': '%',
        'mid_clouds': '%',
        'high_clouds': '%'}

    def __init__(self, model_type, model_name, set_type, vert_level=None):
        self.model_type = model_type
        self.model_name = model_name
        self.set_type = set_type
        self.connected = False
        self.vert_level = vert_level

    def connect_to_catalog(self):
        self.catalog = TDSCatalog(self.catalog_url)
        self.fm_models = TDSCatalog(
            self.catalog.catalog_refs[self.model_type].href)
        self.fm_models_list = sorted(list(self.fm_models.catalog_refs.keys()))

        try:
            model_url = self.fm_models.catalog_refs[self.model_name].href
        except ParseError:
            raise ParseError(self.model_name + ' model may be unavailable.')

        try:
            self.model = TDSCatalog(model_url)
        except HTTPError:
            try:
                self.model = TDSCatalog(model_url)
            except HTTPError:
                raise HTTPError(self.model_name + ' model may be unavailable.')

        self.datasets_list = list(self.model.datasets.keys())
        self.set_dataset()
        self.connected = True

    def __repr__(self):
        return f'{self.model_name}, {self.set_type}'

    def set_dataset(self):
        '''
        Retrieves the designated dataset, creates NCSS object, and
        creates a NCSS query object.
        '''

        keys = list(self.model.datasets.keys())
        labels = [item.split()[0].lower() for item in keys]
        if self.set_type == 'best':
            self.dataset = self.model.datasets[keys[labels.index('best')]]
        elif self.set_type == 'latest':
            self.dataset = self.model.datasets[keys[labels.index('latest')]]
        elif self.set_type == 'full':
            self.dataset = self.model.datasets[keys[labels.index('full')]]

        self.access_url = self.dataset.access_urls[self.access_url_key]
        self.ncss = NCSS(self.access_url)
        self.query = self.ncss.query()

    def set_query_time_range(self, start, end):
        """
        Parameters
        ----------
        start : datetime.datetime, pandas.Timestamp
            Must be tz-localized.
        end : datetime.datetime, pandas.Timestamp
            Must be tz-localized.

        Notes
        -----
        Assigns ``self.start``, ``self.end``. Modifies ``self.query``
        """
        self.start = pd.Timestamp(start)
        self.end = pd.Timestamp(end)
        if self.start.tz is None or self.end.tz is None:
            raise TypeError('start and end must be tz-localized')
        # don't assume that siphon or the server can handle anything other
        # than UTC
        self.query.time_range(
            self.start.tz_convert('UTC'),
            self.end.tz_convert('UTC')
        )

    def set_query_latlon(self):
        '''
        Sets the NCSS query location latitude and longitude.
        '''

        if (isinstance(self.longitude, list) and
                isinstance(self.latitude, list)):
            self.lbox = True
            # west, east, south, north
            self.query.lonlat_box(self.longitude[0], self.longitude[1],
                                  self.latitude[0], self.latitude[1])
        else:
            self.lbox = False
            self.query.lonlat_point(self.longitude, self.latitude)

    def set_location(self, tz, latitude, longitude):
        '''
        Sets the location for the query.

        Parameters
        ----------
        tz: tzinfo
            Timezone of the query
        latitude: float
            Latitude of the query
        longitude: float
            Longitude of the query

        Notes
        -----
        Assigns ``self.location``.
        '''
        self.location = Location(latitude, longitude, tz=tz)

    def get_data(self, latitude, longitude, start, end,
                 vert_level=None, query_variables=None,
                 close_netcdf_data=True, **kwargs):
        """
        Submits a query to the UNIDATA servers using Siphon NCSS and
        converts the netcdf data to a pandas DataFrame.

        Parameters
        ----------
        latitude: float
            The latitude value.
        longitude: float
            The longitude value.
        start: datetime or timestamp
            The start time.
        end: datetime or timestamp
            The end time.
        vert_level: None, float or integer, default None
            Vertical altitude of interest.
        query_variables: None or list, default None
            If None, uses self.variables.
        close_netcdf_data: bool, default True
            Controls if the temporary netcdf data file should be closed.
            Set to False to access the raw data.
        **kwargs:
            Additional keyword arguments are silently ignored.

        Returns
        -------
        forecast_data : DataFrame
            column names are the weather model's variable names.
        """

        if not self.connected:
            self.connect_to_catalog()

        if vert_level is not None:
            self.vert_level = vert_level

        if query_variables is None:
            self.query_variables = list(self.variables.values())
        else:
            self.query_variables = query_variables

        self.set_query_time_range(start, end)

        self.latitude = latitude
        self.longitude = longitude
        self.set_query_latlon()  # modifies self.query
        self.set_location(self.start.tz, latitude, longitude)

        if self.vert_level is not None:
            self.query.vertical_level(self.vert_level)

        self.query.variables(*self.query_variables)
        self.query.accept(self.data_format)

        self.netcdf_data = self.ncss.get_data(self.query)

        # might be better to go to xarray here so that we can handle
        # higher dimensional data for more advanced applications
        self.data = self._netcdf2pandas(self.netcdf_data, self.query_variables,
                                        self.start, self.end)

        if close_netcdf_data:
            self.netcdf_data.close()

        return self.data

    def process_data(self, data, **kwargs):
        """
        Defines the steps needed to convert raw forecast data
        into processed forecast data. Most forecast models implement
        their own version of this method which also call this one.

        Parameters
        ----------
        data: DataFrame
            Raw forecast data

        Returns
        -------
        data: DataFrame
            Processed forecast data.
        """
        data = self.rename(data)
        return data

    def get_processed_data(self, *args, **kwargs):
        """
        Get and process forecast data.

        Parameters
        ----------
        *args: positional arguments
            Passed to get_data
        **kwargs: keyword arguments
            Passed to get_data and process_data

        Returns
        -------
        data: DataFrame
            Processed forecast data
        """
        return self.process_data(self.get_data(*args, **kwargs), **kwargs)

    def rename(self, data, variables=None):
        """
        Renames the columns according the variable mapping.

        Parameters
        ----------
        data: DataFrame
        variables: None or dict, default None
            If None, uses self.variables

        Returns
        -------
        data: DataFrame
            Renamed data.
        """
        if variables is None:
            variables = self.variables
        return data.rename(columns={y: x for x, y in variables.items()})

    def _netcdf2pandas(self, netcdf_data, query_variables, start, end):
        """
        Transforms data from netcdf to pandas DataFrame.

        Parameters
        ----------
        data: netcdf
            Data returned from UNIDATA NCSS query.
        query_variables: list
            The variables requested.
        start: Timestamp
            The start time
        end: Timestamp
            The end time

        Returns
        -------
        pd.DataFrame
        """
        # set self.time
        try:
            time_var = 'time'
            self.set_time(netcdf_data.variables[time_var])
        except KeyError:
            # which model does this dumb thing?
            time_var = 'time1'
            self.set_time(netcdf_data.variables[time_var])

        data_dict = {}
        for key, data in netcdf_data.variables.items():
            # if accounts for possibility of extra variable returned
            if key not in query_variables:
                continue
            squeezed = data[:].squeeze()

            # If the data is big endian, swap the byte order to make it
            # little endian
            if squeezed.dtype.byteorder == '>':
                squeezed = squeezed.byteswap().newbyteorder()
            if squeezed.ndim == 1:
                data_dict[key] = squeezed
            elif squeezed.ndim == 2:
                for num, data_level in enumerate(squeezed.T):
                    data_dict[key + '_' + str(num)] = data_level
            else:
                raise ValueError('cannot parse ndim > 2')

        data = pd.DataFrame(data_dict, index=self.time)
        # sometimes data is returned as hours since T0
        # where T0 is before start. Then the hours between
        # T0 and start are added *after* end. So sort and slice
        # to remove the garbage
        data = data.sort_index().loc[start:end]
        return data

    def set_time(self, time):
        '''
        Converts time data into a pandas date object.

        Parameters
        ----------
        time: netcdf
            Contains time information.

        Returns
        -------
        pandas.DatetimeIndex
        '''
        # np.masked_array with elements like real_datetime(2021, 8, 17, 16, 0)
        # and dtype=object
        times = num2date(time[:].squeeze(), time.units,
                         only_use_cftime_datetimes=False,
                         only_use_python_datetimes=True)
        # convert to pandas, localize to UTC, convert to desired timezone
        self.time = pd.DatetimeIndex(
            times, tz='UTC').tz_convert(self.location.tz)

    def cloud_cover_to_ghi_linear(self, cloud_cover, ghi_clear, offset=35,
                                  **kwargs):
        """
        Convert cloud cover to GHI using a linear relationship.

        0% cloud cover returns ghi_clear.

        100% cloud cover returns offset*ghi_clear.

        Parameters
        ----------
        cloud_cover: numeric
            Cloud cover in %.
        ghi_clear: numeric
            GHI under clear sky conditions.
        offset: numeric, default 35
            Determines the minimum GHI.
        kwargs
            Not used.

        Returns
        -------
        ghi: numeric
            Estimated GHI.

        References
        ----------
        Larson et. al. "Day-ahead forecasting of solar power output from
        photovoltaic plants in the American Southwest" Renewable Energy
        91, 11-20 (2016).
        """

        offset = offset / 100.
        cloud_cover = cloud_cover / 100.
        ghi = (offset + (1 - offset) * (1 - cloud_cover)) * ghi_clear
        return ghi

    def cloud_cover_to_irradiance_clearsky_scaling(self, cloud_cover,
                                                   method='linear',
                                                   **kwargs):
        """
        Estimates irradiance from cloud cover in the following steps:

        1. Determine clear sky GHI using Ineichen model and
           climatological turbidity.
        2. Estimate cloudy sky GHI using a function of
           cloud_cover e.g.
           :py:meth:`~ForecastModel.cloud_cover_to_ghi_linear`
        3. Estimate cloudy sky DNI using the DISC model.
        4. Calculate DHI from DNI and GHI.

        Parameters
        ----------
        cloud_cover : Series
            Cloud cover in %.
        method : str, default 'linear'
            Method for converting cloud cover to GHI.
            'linear' is currently the only option.
        **kwargs
            Passed to the method that does the conversion

        Returns
        -------
        irrads : DataFrame
            Estimated GHI, DNI, and DHI.
        """
        solpos = self.location.get_solarposition(cloud_cover.index)
        cs = self.location.get_clearsky(cloud_cover.index, model='ineichen',
                                        solar_position=solpos)

        method = method.lower()
        if method == 'linear':
            ghi = self.cloud_cover_to_ghi_linear(cloud_cover, cs['ghi'],
                                                 **kwargs)
        else:
            raise ValueError('invalid method argument')

        dni = disc(ghi, solpos['zenith'], cloud_cover.index)['dni']
        dhi = ghi - dni * np.cos(np.radians(solpos['zenith']))

        irrads = pd.DataFrame({'ghi': ghi, 'dni': dni, 'dhi': dhi}).fillna(0)
        return irrads

    def cloud_cover_to_transmittance_linear(self, cloud_cover, offset=0.75,
                                            **kwargs):
        """
        Convert cloud cover (percentage) to atmospheric transmittance
        using a linear model.

        0% cloud cover returns "offset".

        100% cloud cover returns 0.

        Parameters
        ----------
        cloud_cover : numeric
            Cloud cover in %.
        offset : numeric, default 0.75
            Determines the maximum transmittance. [unitless]
        kwargs
            Not used.

        Returns
        -------
        transmittance : numeric
            The fraction of extraterrestrial irradiance that reaches
            the ground. [unitless]
        """
        transmittance = ((100.0 - cloud_cover) / 100.0) * offset

        return transmittance

    def cloud_cover_to_irradiance_campbell_norman(self, cloud_cover, **kwargs):
        """
        Estimates irradiance from cloud cover in the following steps:

        1. Determine transmittance using a function of cloud cover e.g.
           :py:meth:`~ForecastModel.cloud_cover_to_transmittance_linear`
        2. Calculate GHI, DNI, DHI using the
           :py:func:`pvlib.irradiance.campbell_norman` model

        Parameters
        ----------
        cloud_cover : Series

        Returns
        -------
        irradiance : DataFrame
            Columns include ghi, dni, dhi
        """
        # in principle, get_solarposition could use the forecast
        # pressure, temp, etc., but the cloud cover forecast is not
        # accurate enough to justify using these minor corrections
        solar_position = self.location.get_solarposition(cloud_cover.index)
        dni_extra = get_extra_radiation(cloud_cover.index)

        transmittance = self.cloud_cover_to_transmittance_linear(cloud_cover,
                                                                 **kwargs)

        irrads = campbell_norman(solar_position['apparent_zenith'],
                                 transmittance, dni_extra=dni_extra)
        irrads = irrads.fillna(0)

        return irrads

    def cloud_cover_to_irradiance(self, cloud_cover, how='clearsky_scaling',
                                  **kwargs):
        """
        Convert cloud cover to irradiance. A wrapper method.

        Parameters
        ----------
        cloud_cover : Series
        how : str, default 'clearsky_scaling'
            Selects the method for conversion. Can be one of
            clearsky_scaling or campbell_norman. Method liujordan is
            deprecated.
        **kwargs
            Passed to the selected method.

        Returns
        -------
        irradiance : DataFrame
            Columns include ghi, dni, dhi
        """

        how = how.lower()
        if how == 'clearsky_scaling':
            irrads = self.cloud_cover_to_irradiance_clearsky_scaling(
                cloud_cover, **kwargs)
        elif how == 'campbell_norman':
            irrads = self.cloud_cover_to_irradiance_campbell_norman(
                cloud_cover, **kwargs)
        else:
            raise ValueError('invalid how argument')

        return irrads

    def kelvin_to_celsius(self, temperature):
        """
        Converts Kelvin to celsius.

        Parameters
        ----------
        temperature: numeric

        Returns
        -------
        temperature: numeric
        """
        return temperature - 273.15

    def isobaric_to_ambient_temperature(self, data):
        """
        Calculates temperature from isobaric temperature.

        Parameters
        ----------
        data: DataFrame
            Must contain columns pressure, temperature_iso,
            temperature_dew_iso. Input temperature in K.

        Returns
        -------
        temperature : Series
            Temperature in K
        """

        P = data['pressure'] / 100.0                            # noqa: N806
        Tiso = data['temperature_iso']                          # noqa: N806
        Td = data['temperature_dew_iso'] - 273.15               # noqa: N806

        # saturation water vapor pressure
        e = 6.11 * 10**((7.5 * Td) / (Td + 273.3))

        # saturation water vapor mixing ratio
        w = 0.622 * (e / (P - e))

        temperature = Tiso - ((2.501 * 10.**6) / 1005.7) * w

        return temperature

    def uv_to_speed(self, data):
        """
        Computes wind speed from wind components.

        Parameters
        ----------
        data : DataFrame
            Must contain the columns 'wind_speed_u' and 'wind_speed_v'.

        Returns
        -------
        wind_speed : Series
        """
        wind_speed = np.sqrt(data['wind_speed_u']**2 + data['wind_speed_v']**2)

        return wind_speed

    def gust_to_speed(self, data, scaling=1/1.4):
        """
        Computes standard wind speed from gust.
        Very approximate and location dependent.

        Parameters
        ----------
        data : DataFrame
            Must contain the column 'wind_speed_gust'.

        Returns
        -------
        wind_speed : Series
        """
        wind_speed = data['wind_speed_gust'] * scaling

        return wind_speed

@_forecast_deprecated
class GFS(ForecastModel):
    """
    Subclass of the ForecastModel class representing GFS
    forecast model.

    Model data corresponds to 0.25 degree resolution forecasts.

    Parameters
    ----------
    resolution: string, default 'half'
        Resolution of the model, either 'half' or 'quarter' degree.
    set_type: string, default 'best'
        Type of model to pull data from.

    Attributes
    ----------
    dataframe_variables: list
        Common variables present in the final set of data.
    model: string
        Name of the UNIDATA forecast model.
    model_type: string
        UNIDATA category in which the model is located.
    variables: dict
        Defines the variables to obtain from the weather
        model and how they should be renamed to common variable names.
    units: dict
        Dictionary containing the units of the standard variables
        and the model specific variables.
    """

    _resolutions = ['Half', 'Quarter']

    def __init__(self, resolution='half', set_type='best'):
        model_type = 'Forecast Model Data'

        resolution = resolution.title()
        if resolution not in self._resolutions:
            raise ValueError(f'resolution must in {self._resolutions}')

        model = f'GFS {resolution} Degree Forecast'

        # isobaric variables will require a vert_level to prevent
        # excessive data downloads
        self.variables = {
            'temp_air': 'Temperature_surface',
            'wind_speed_gust': 'Wind_speed_gust_surface',
            'wind_speed_u': 'u-component_of_wind_isobaric',
            'wind_speed_v': 'v-component_of_wind_isobaric',
            'total_clouds':
                'Total_cloud_cover_entire_atmosphere_Mixed_intervals_Average',
            'low_clouds':
                'Low_cloud_cover_low_cloud_Mixed_intervals_Average',
            'mid_clouds':
                'Medium_cloud_cover_middle_cloud_Mixed_intervals_Average',
            'high_clouds':
                'High_cloud_cover_high_cloud_Mixed_intervals_Average',
            'boundary_clouds': ('Total_cloud_cover_boundary_layer_cloud_'
                                'Mixed_intervals_Average'),
            'convect_clouds': 'Total_cloud_cover_convective_cloud',
            'ghi_raw': ('Downward_Short-Wave_Radiation_Flux_'
                        'surface_Mixed_intervals_Average')}

        self.output_variables = [
            'temp_air',
            'wind_speed',
            'ghi',
            'dni',
            'dhi',
            'total_clouds',
            'low_clouds',
            'mid_clouds',
            'high_clouds']

        super().__init__(model_type, model, set_type,
                                  vert_level=100000)

    def process_data(self, data, cloud_cover='total_clouds', **kwargs):
        """
        Defines the steps needed to convert raw forecast data
        into processed forecast data.

        Parameters
        ----------
        data: DataFrame
            Raw forecast data
        cloud_cover: str, default 'total_clouds'
            The type of cloud cover used to infer the irradiance.

        Returns
        -------
        data: DataFrame
            Processed forecast data.
        """
        data = super().process_data(data, **kwargs)
        data['temp_air'] = self.kelvin_to_celsius(data['temp_air'])
        data['wind_speed'] = self.uv_to_speed(data)
        irrads = self.cloud_cover_to_irradiance(data[cloud_cover], **kwargs)
        data = data.join(irrads, how='outer')
        return data[self.output_variables]

@_forecast_deprecated
class HRRR_ESRL(ForecastModel):                                 # noqa: N801
    """
    Subclass of the ForecastModel class representing
    NOAA/GSD/ESRL's HRRR forecast model.
    This is not an operational product.

    Model data corresponds to NOAA/GSD/ESRL HRRR CONUS 3km resolution
    surface forecasts.

    Parameters
    ----------
    set_type: string, default 'best'
        Type of model to pull data from.

    Attributes
    ----------
    dataframe_variables: list
        Common variables present in the final set of data.
    model: string
        Name of the UNIDATA forecast model.
    model_type: string
        UNIDATA category in which the model is located.
    variables: dict
        Defines the variables to obtain from the weather
        model and how they should be renamed to common variable names.
    units: dict
        Dictionary containing the units of the standard variables
        and the model specific variables.
    """

    def __init__(self, set_type='best'):
        warnings.warn('HRRR_ESRL is an experimental model and is not '
                      'always available.')

        model_type = 'Forecast Model Data'
        model = 'GSD HRRR CONUS 3km surface'

        self.variables = {
            'temp_air': 'Temperature_surface',
            'wind_speed_gust': 'Wind_speed_gust_surface',
            # 'temp_air': 'Temperature_height_above_ground',  # GH 702
            # 'wind_speed_u': 'u-component_of_wind_height_above_ground',
            # 'wind_speed_v': 'v-component_of_wind_height_above_ground',
            'total_clouds': 'Total_cloud_cover_entire_atmosphere',
            'low_clouds': 'Low_cloud_cover_UnknownLevelType-214',
            'mid_clouds': 'Medium_cloud_cover_UnknownLevelType-224',
            'high_clouds': 'High_cloud_cover_UnknownLevelType-234',
            'ghi_raw': 'Downward_short-wave_radiation_flux_surface', }

        self.output_variables = [
            'temp_air',
            'wind_speed',
            'ghi_raw',
            'ghi',
            'dni',
            'dhi',
            'total_clouds',
            'low_clouds',
            'mid_clouds',
            'high_clouds']

        super().__init__(model_type, model, set_type)

    def process_data(self, data, cloud_cover='total_clouds', **kwargs):
        """
        Defines the steps needed to convert raw forecast data
        into processed forecast data.

        Parameters
        ----------
        data: DataFrame
            Raw forecast data
        cloud_cover: str, default 'total_clouds'
            The type of cloud cover used to infer the irradiance.

        Returns
        -------
        data: DataFrame
            Processed forecast data.
        """

        data = super().process_data(data, **kwargs)
        data['temp_air'] = self.kelvin_to_celsius(data['temp_air'])
        data['wind_speed'] = self.gust_to_speed(data)
        # data['wind_speed'] = self.uv_to_speed(data)  # GH 702
        irrads = self.cloud_cover_to_irradiance(data[cloud_cover], **kwargs)
        data = data.join(irrads, how='outer')
        return data[self.output_variables]

@_forecast_deprecated
class NAM(ForecastModel):
    """
    Subclass of the ForecastModel class representing NAM
    forecast model.

    Model data corresponds to NAM CONUS 12km resolution forecasts
    from CONDUIT.

    Parameters
    ----------
    set_type: string, default 'best'
        Type of model to pull data from.

    Attributes
    ----------
    dataframe_variables: list
        Common variables present in the final set of data.
    model: string
        Name of the UNIDATA forecast model.
    model_type: string
        UNIDATA category in which the model is located.
    variables: dict
        Defines the variables to obtain from the weather
        model and how they should be renamed to common variable names.
    units: dict
        Dictionary containing the units of the standard variables
        and the model specific variables.
    """

    def __init__(self, set_type='best'):
        model_type = 'Forecast Model Data'
        model = 'NAM CONUS 12km from CONDUIT'

        self.variables = {
            'temp_air': 'Temperature_surface',
            'wind_speed_gust': 'Wind_speed_gust_surface',
            'total_clouds': 'Total_cloud_cover_entire_atmosphere_single_layer',
            'low_clouds': 'Low_cloud_cover_low_cloud',
            'mid_clouds': 'Medium_cloud_cover_middle_cloud',
            'high_clouds': 'High_cloud_cover_high_cloud',
            'ghi_raw': 'Downward_Short-Wave_Radiation_Flux_surface', }

        self.output_variables = [
            'temp_air',
            'wind_speed',
            'ghi',
            'dni',
            'dhi',
            'total_clouds',
            'low_clouds',
            'mid_clouds',
            'high_clouds']

        super().__init__(model_type, model, set_type)

    def process_data(self, data, cloud_cover='total_clouds', **kwargs):
        """
        Defines the steps needed to convert raw forecast data
        into processed forecast data.

        Parameters
        ----------
        data: DataFrame
            Raw forecast data
        cloud_cover: str, default 'total_clouds'
            The type of cloud cover used to infer the irradiance.

        Returns
        -------
        data: DataFrame
            Processed forecast data.
        """

        data = super().process_data(data, **kwargs)
        data['temp_air'] = self.kelvin_to_celsius(data['temp_air'])
        data['wind_speed'] = self.gust_to_speed(data)
        irrads = self.cloud_cover_to_irradiance(data[cloud_cover], **kwargs)
        data = data.join(irrads, how='outer')
        return data[self.output_variables]

@_forecast_deprecated
class HRRR(ForecastModel):
    """
    Subclass of the ForecastModel class representing HRRR
    forecast model.

    Model data corresponds to NCEP HRRR CONUS 2.5km resolution
    forecasts.

    Parameters
    ----------
    set_type: string, default 'best'
        Type of model to pull data from.

    Attributes
    ----------
    dataframe_variables: list
        Common variables present in the final set of data.
    model: string
        Name of the UNIDATA forecast model.
    model_type: string
        UNIDATA category in which the model is located.
    variables: dict
        Defines the variables to obtain from the weather
        model and how they should be renamed to common variable names.
    units: dict
        Dictionary containing the units of the standard variables
        and the model specific variables.
    """

    def __init__(self, set_type='best'):
        model_type = 'Forecast Model Data'
        model = 'HRRR CONUS 2.5km Forecasts'

        self.variables = {
            'temp_air': 'Temperature_height_above_ground',
            'pressure': 'Pressure_surface',
            'wind_speed_gust': 'Wind_speed_gust_surface',
            'wind_speed_u': 'u-component_of_wind_height_above_ground',
            'wind_speed_v': 'v-component_of_wind_height_above_ground',
            'total_clouds': 'Total_cloud_cover_entire_atmosphere',
            'low_clouds': 'Low_cloud_cover_low_cloud',
            'mid_clouds': 'Medium_cloud_cover_middle_cloud',
            'high_clouds': 'High_cloud_cover_high_cloud'}

        self.output_variables = [
            'temp_air',
            'wind_speed',
            'ghi',
            'dni',
            'dhi',
            'total_clouds',
            'low_clouds',
            'mid_clouds',
            'high_clouds', ]

        super().__init__(model_type, model, set_type)

    def process_data(self, data, cloud_cover='total_clouds', **kwargs):
        """
        Defines the steps needed to convert raw forecast data
        into processed forecast data.

        Parameters
        ----------
        data: DataFrame
            Raw forecast data
        cloud_cover: str, default 'total_clouds'
            The type of cloud cover used to infer the irradiance.

        Returns
        -------
        data: DataFrame
            Processed forecast data.
        """
        data = super().process_data(data, **kwargs)
        wind_mapping = {
            'wind_speed_u': 'u-component_of_wind_height_above_ground_0',
            'wind_speed_v': 'v-component_of_wind_height_above_ground_0',
        }
        data = self.rename(data, variables=wind_mapping)
        data['temp_air'] = self.kelvin_to_celsius(data['temp_air'])
        data['wind_speed'] = self.uv_to_speed(data)
        irrads = self.cloud_cover_to_irradiance(data[cloud_cover], **kwargs)
        data = data.join(irrads, how='outer')
        data = data.iloc[:-1, :]  # issue with last point
        return data[self.output_variables]

@_forecast_deprecated
class NDFD(ForecastModel):
    """
    Subclass of the ForecastModel class representing NDFD forecast
    model.

    Model data corresponds to NWS CONUS CONDUIT forecasts.

    Parameters
    ----------
    set_type: string, default 'best'
        Type of model to pull data from.

    Attributes
    ----------
    dataframe_variables: list
        Common variables present in the final set of data.
    model: string
        Name of the UNIDATA forecast model.
    model_type: string
        UNIDATA category in which the model is located.
    variables: dict
        Defines the variables to obtain from the weather
        model and how they should be renamed to common variable names.
    units: dict
        Dictionary containing the units of the standard variables
        and the model specific variables.
    """

    def __init__(self, set_type='best'):
        model_type = 'Forecast Products and Analyses'
        model = 'National Weather Service CONUS Forecast Grids (CONDUIT)'
        self.variables = {
            'temp_air': 'Temperature_height_above_ground',
            'wind_speed': 'Wind_speed_height_above_ground',
            'total_clouds': 'Total_cloud_cover_surface', }
        self.output_variables = [
            'temp_air',
            'wind_speed',
            'ghi',
            'dni',
            'dhi',
            'total_clouds', ]
        super().__init__(model_type, model, set_type)

    def process_data(self, data, **kwargs):
        """
        Defines the steps needed to convert raw forecast data
        into processed forecast data.

        Parameters
        ----------
        data: DataFrame
            Raw forecast data

        Returns
        -------
        data: DataFrame
            Processed forecast data.
        """

        cloud_cover = 'total_clouds'
        data = super().process_data(data, **kwargs)
        data['temp_air'] = self.kelvin_to_celsius(data['temp_air'])
        irrads = self.cloud_cover_to_irradiance(data[cloud_cover], **kwargs)
        data = data.join(irrads, how='outer')
        return data[self.output_variables]

@_forecast_deprecated
class RAP(ForecastModel):
    """
    Subclass of the ForecastModel class representing RAP forecast model.

    Model data corresponds to Rapid Refresh CONUS 20km resolution
    forecasts.

    Parameters
    ----------
    resolution: string or int, default '20'
        The model resolution, either '20' or '40' (km)
    set_type: string, default 'best'
        Type of model to pull data from.

    Attributes
    ----------
    dataframe_variables: list
        Common variables present in the final set of data.
    model: string
        Name of the UNIDATA forecast model.
    model_type: string
        UNIDATA category in which the model is located.
    variables: dict
        Defines the variables to obtain from the weather
        model and how they should be renamed to common variable names.
    units: dict
        Dictionary containing the units of the standard variables
        and the model specific variables.
    """

    _resolutions = ['20', '40']

    def __init__(self, resolution='20', set_type='best'):

        resolution = str(resolution)
        if resolution not in self._resolutions:
            raise ValueError(f'resolution must in {self._resolutions}')

        model_type = 'Forecast Model Data'
        model = f'Rapid Refresh CONUS {resolution}km'
        self.variables = {
            'temp_air': 'Temperature_surface',
            'wind_speed_gust': 'Wind_speed_gust_surface',
            'total_clouds': 'Total_cloud_cover_entire_atmosphere',
            'low_clouds': 'Low_cloud_cover_low_cloud',
            'mid_clouds': 'Medium_cloud_cover_middle_cloud',
            'high_clouds': 'High_cloud_cover_high_cloud', }
        self.output_variables = [
            'temp_air',
            'wind_speed',
            'ghi',
            'dni',
            'dhi',
            'total_clouds',
            'low_clouds',
            'mid_clouds',
            'high_clouds', ]
        super().__init__(model_type, model, set_type)

    def process_data(self, data, cloud_cover='total_clouds', **kwargs):
        """
        Defines the steps needed to convert raw forecast data
        into processed forecast data.

        Parameters
        ----------
        data: DataFrame
            Raw forecast data
        cloud_cover: str, default 'total_clouds'
            The type of cloud cover used to infer the irradiance.

        Returns
        -------
        data: DataFrame
            Processed forecast data.
        """

        data = super().process_data(data, **kwargs)
        data['temp_air'] = self.kelvin_to_celsius(data['temp_air'])
        data['wind_speed'] = self.gust_to_speed(data)
        irrads = self.cloud_cover_to_irradiance(data[cloud_cover], **kwargs)
        data = data.join(irrads, how='outer')
        return data[self.output_variables]


text:
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>InteractiveSphere</title>
    <link rel="icon" href="oldtrafford.jpg">
    <style>
    /* Basic */
    body {
        margin: 0;
        font-family: "Consolas", RalewayBold, monospace;
        background: url(oldtraffordspheric.jpg) no-repeat center;
        background-size: 100%;
    }
    canvas {
    width: 100%;
    height: 100%;
    opacity: 0.8;
    }
    .btn{
        position: absolute;
        background-color: lightcoral;
        z-index: 4;
        color: white;
        font-size: 16px;
        font-weight: 800;
        width: 120px;
        height: 40px;
        border: none;
        border-radius: 12px;
        -webkit-border-radius: 12px;
        -moz-border-radius: 12px;
        text-align: center;
        text-decoration: none;
        padding-top: 6px;
    }
    </style>
</head>
<body>
<script src="three.js-master/build/three.js"></script>
<script>
    var camera, scene, renderer;
    var cube, sphere, torus, material;
    var count = 0, cubeCamera1, cubeCamera2;
    var lon = 0, lat = 0;
    var phi = 0, theta = 0;
    var textureLoader = new THREE.TextureLoader();
    textureLoader.load( 'oldtrafford.jpg', function ( texture ) {
        texture.mapping = THREE.UVMapping;
        init( texture );
        animate();
    } );

    function init( texture ) {
        camera = new THREE.PerspectiveCamera( 60, window.innerWidth / window.innerHeight, 1, 1000 );
        scene = new THREE.Scene();
        var mesh = new THREE.Mesh( new THREE.SphereBufferGeometry( 500, 42, 16 ), new THREE.MeshBasicMaterial( { map: texture } ) );
        mesh.scale.x = -1;
        scene.add( mesh );
        renderer = new THREE.WebGLRenderer( { antialias: true } );
        renderer.setPixelRatio( window.devicePixelRatio );
        renderer.setSize( window.innerWidth, window.innerHeight );
        cubeCamera1 = new THREE.CubeCamera( 1, 1000, 256 );
        cubeCamera1.renderTarget.texture.minFilter = THREE.LinearMipMapLinearFilter;
        scene.add( cubeCamera1 );
        cubeCamera2 = new THREE.CubeCamera( 1, 1000, 256 );
        cubeCamera2.renderTarget.texture.minFilter = THREE.LinearMipMapLinearFilter;
        scene.add( cubeCamera2 );
        document.body.appendChild( renderer.domElement );
        material = new THREE.MeshBasicMaterial( {
            envMap: cubeCamera2.renderTarget.texture
        } );
        sphere = new THREE.Mesh( new THREE.IcosahedronBufferGeometry( 20, 3, 60 ), material );
        scene.add( sphere );
        cube = new THREE.Mesh( new THREE.BoxBufferGeometry( 20, 20, 20 ), material );
        scene.add( cube );
        torus = new THREE.Mesh( new THREE.TorusKnotBufferGeometry( 10, 5, 60, 25 ), material );
        scene.add( torus );

        document.addEventListener( 'mousedown', onDocumentMouseDown, true );
        document.addEventListener( 'wheel', onDocumentMouseWheel, false );
        window.addEventListener( 'resize', onWindowResized, false );
    }

    function onWindowResized( event ) {
        renderer.setSize( window.innerWidth, window.innerHeight );
        camera.aspect = window.innerWidth / window.innerHeight;
        camera.updateProjectionMatrix();
    }

    function onDocumentMouseDown( event ) {
        event.preventDefault();
        onPointerDownPointerX = event.clientX;
        onPointerDownPointerY = event.clientY;
        onPointerDownLon = lon;
        onPointerDownLat = lat;
        document.addEventListener( 'mousemove', onDocumentMouseMove, false );
        document.addEventListener( 'mouseup', onDocumentMouseUp, false );
    }

    function onDocumentMouseMove( event ) {
        lon = ( event.clientX - onPointerDownPointerX ) * 0.1 + onPointerDownLon;
        lat = ( event.clientY - onPointerDownPointerY ) * 0.1 + onPointerDownLat;
    }

    function onDocumentMouseUp( event ) {
        document.removeEventListener( 'mousemove', onDocumentMouseMove, false );
        document.removeEventListener( 'mouseup', onDocumentMouseUp, false );
    }

    function onDocumentMouseWheel( event ) {
        camera.fov += ( event.deltaY * 0.05 );
        camera.updateProjectionMatrix();
    }

    function animate() {
        requestAnimationFrame( animate );
        render();
    }

    function render() {
        var time = Date.now();
        lon += .15;
        lat = Math.max( - 85, Math.min( 85, lat ) );
        phi = THREE.Math.degToRad( 90 - lat );
        theta = THREE.Math.degToRad( lon );
        cube.position.x = Math.cos( time * 0.001 ) * 30;
        cube.position.y = Math.sin( time * 0.001 ) * 30;
        cube.position.z = Math.sin( time * 0.001 ) * 30;
        cube.rotation.x += 0.02;
        cube.rotation.y += 0.03;
        torus.position.x = Math.cos( time * 0.001 + 10 ) * 30;
        torus.position.y = Math.sin( time * 0.001 + 10 ) * 30;
        torus.position.z = Math.sin( time * 0.001 + 10 ) * 30;
        torus.rotation.x += 0.02;
        torus.rotation.y += 0.03;
        camera.position.x = 100 * Math.sin( phi ) * Math.cos( theta );
        camera.position.y = 100 * Math.cos( phi );
        camera.position.z = 100 * Math.sin( phi ) * Math.sin( theta );
        camera.lookAt( scene.position );
        sphere.visible = false;

        if ( count % 2 === 0 ) {
            material.envMap = cubeCamera1.renderTarget.texture;
            cubeCamera2.updateCubeMap( renderer, scene );
        } else {
            material.envMap = cubeCamera2.renderTarget.texture;
            cubeCamera1.updateCubeMap( renderer, scene );
        }

        count ++;
        sphere.visible = true;
        renderer.render( scene, camera );
    }
</script>
</body>
</html>


text:
<?php

namespace Smacme\Commit;

class EmojiUsage
{
    /** @var string The directory used to store emoji usage data */
    private $workingDir;
    /** @var  string Filename to store usage data */
    private $usageFilename = '.emoji_usage';

    public function __construct($workingDir)
    {
        $this->workingDir = realpath($workingDir);
    }

    public function sortByUsage($emojii)
    {
        uksort($emojii, function ($a, $b) use ($emojii) {
            $aCount = $this->getCount($a);
            $bCount = $this->getCount($b);

            if ($aCount == $bCount) {
                return $emojii[$a] > $emojii[$b];
            }

            return $aCount > $bCount ? -1 : 1;
        });

        return $emojii;
    }

    public function useEmojii($emojii)
    {
        $usage = $this->get();
        foreach ($emojii as $emoji) {
            if (!array_key_exists($emoji, $usage)) {
                $usage[$emoji] = 0;
            }

            $usage[$emoji]++;
        }

        $this->save($usage);
    }

    private function getCount($emoji)
    {
        $usage = $this->get();
        return array_key_exists($emoji, $usage)
            ? $usage[$emoji]
            : 0;
    }

    private function get()
    {
        $filename = $this->getFilename();
        if (!file_exists($filename)) {
            file_put_contents($filename, json_encode([]));
        }

        return json_decode(file_get_contents($filename), true);
    }

    private function save($usage)
    {
        file_put_contents($this->getFilename(), json_encode($usage, JSON_PRETTY_PRINT));
    }

    private function getFilename()
    {
        return $this->workingDir . DIRECTORY_SEPARATOR . $this->usageFilename;
    }
}


text:
#region License

#endregion

#region Imports

using System.Collections.Generic;
using System.Xml;

using NUnit.Framework;

using Spring.Core.IO;
using Spring.Objects;
using Spring.Objects.Factory;
using Spring.Objects.Factory.Config;
using Spring.Objects.Factory.Xml;
using Spring.Validation.Actions;
using Spring.Validation.Config;

#endregion

namespace Spring.Validation
{
    /// <summary>
    /// Unit tests for the ValidationNamespaceParser class.
    /// </summary>
    /// <author>Rick Evans</author>
    [TestFixture]
    public sealed class ValidationNamespaceParserTests
    {
        [Test]
        public void WhenConfigFileIsValid()
        {
            XmlDocument doc = GetValidatedXmlResource("_WhenConfigFileIsValid.xml");

            MockObjectDefinitionRegistry registry = new MockObjectDefinitionRegistry();

            XmlReaderContext readerContext = new XmlReaderContext(null, new XmlObjectDefinitionReader(registry));
            ObjectDefinitionParserHelper helper = new ObjectDefinitionParserHelper(readerContext);
            helper.InitDefaults(doc.DocumentElement);
            ParserContext parserContext = new ParserContext(helper);

            ValidationNamespaceParser parser = new ValidationNamespaceParser();
            foreach (XmlElement element in doc.DocumentElement.ChildNodes)
            {
                if (element.NamespaceURI == "http://www.springframework.net/validation")
                {
                    parser.ParseElement(element, parserContext);
                }
            }
            IList<IObjectDefinition> defs = registry.GetObjectDefinitions();
            Assert.AreEqual(9, defs.Count);

            IObjectDefinition def = registry.GetObjectDefinition("destinationAirportValidator");
            Assert.IsTrue(def.IsSingleton);
            Assert.IsTrue(def.IsLazyInit);
            Assert.IsTrue(typeof(IValidator).IsAssignableFrom(def.ObjectType));

            PropertyValue fastValidateProperty = def.PropertyValues.GetPropertyValue("FastValidate");
            Assert.IsNotNull(fastValidateProperty);
            Assert.AreEqual("true", fastValidateProperty.Value);

            PropertyValue validatorsProperty = def.PropertyValues.GetPropertyValue("Validators");
            Assert.IsNotNull(validatorsProperty);
            object validatorsObject = validatorsProperty.Value;
            Assert.AreEqual(typeof(ManagedList), validatorsObject.GetType());
            ManagedList validators = (ManagedList)validatorsObject;
            Assert.AreEqual(4, validators.Count);

            def = (IObjectDefinition)validators[3];
            Assert.IsTrue(def.IsSingleton);
            Assert.IsTrue(def.IsLazyInit);
            Assert.AreEqual(typeof(RegularExpressionValidator), def.ObjectType);
            Assert.AreEqual("[A-Z]*", def.PropertyValues.GetPropertyValue("Expression").Value);

            def = registry.GetObjectDefinition("simpleAirportValidator");
            Assert.IsTrue(def.IsSingleton);
            Assert.IsTrue(def.IsLazyInit);
            Assert.IsTrue(typeof(IValidator).IsAssignableFrom(def.ObjectType));
            PropertyValue actionsProperty = def.PropertyValues.GetPropertyValue("Actions");
            Assert.IsNotNull(actionsProperty);
            object actionsObject = actionsProperty.Value;
            Assert.AreEqual(typeof(ManagedList), actionsObject.GetType());
            ManagedList actions = (ManagedList)actionsObject;
            Assert.AreEqual(1, actions.Count);

            IObjectDefinition exceptionActionDefinition = (IObjectDefinition)actions[0];
            Assert.AreEqual(typeof(ExceptionAction), exceptionActionDefinition.ObjectType);
            Assert.AreEqual("'new System.InvalidOperationException(\"invalid\")' []", exceptionActionDefinition.ConstructorArgumentValues.GenericArgumentValues[0].ToString());
            //

            def = registry.GetObjectDefinition("airportCodeValidator");
            Assert.IsTrue(def.IsSingleton);
            Assert.IsTrue(def.IsLazyInit);
            Assert.IsTrue(typeof(IValidator).IsAssignableFrom(def.ObjectType));
            actionsProperty = def.PropertyValues.GetPropertyValue("Actions");
            Assert.IsNotNull(actionsProperty);
            actionsObject = actionsProperty.Value;
            Assert.AreEqual(typeof(ManagedList), actionsObject.GetType());
            actions = (ManagedList)actionsObject;
            Assert.AreEqual(4, actions.Count);

            IObjectDefinition messageDefinition = (IObjectDefinition)actions[1];
            Assert.AreEqual(typeof(ErrorMessageAction), messageDefinition.ObjectType);

            IObjectDefinition actionDefinition = (IObjectDefinition)actions[2];
            Assert.AreEqual(typeof(ExpressionAction), actionDefinition.ObjectType);
            Assert.AreEqual("#now = DateTime.Now", actionDefinition.PropertyValues.GetPropertyValue("Valid").Value);

            def = registry.GetObjectDefinition("regex");
            Assert.IsTrue(def.IsSingleton);
            Assert.IsTrue(def.IsLazyInit);
            Assert.IsTrue(typeof(IValidator).IsAssignableFrom(def.ObjectType));
            PropertyValue expressionProperty = def.PropertyValues.GetPropertyValue("Expression");
            Assert.IsNotNull(expressionProperty);
            Assert.AreEqual("RegExp", expressionProperty.Value);
        }

        private XmlDocument GetValidatedXmlResource(string resourceExtension)
        {
            AssemblyResource validationSchema = new AssemblyResource("assembly://Spring.Core/Spring.Validation.Config/spring-validation-1.3.xsd");
            AssemblyResource objectsSchema = new AssemblyResource("assembly://Spring.Core/Spring.Objects.Factory.Xml/spring-objects-1.3.xsd");

            return TestResourceLoader.GetXmlValidated(this, resourceExtension, objectsSchema, validationSchema);
        }

        [Test]
        public void WhenConfigFileIsNotValid()
        {
//            const string xml = @"<?xml version='1.0' encoding='UTF-8' ?>
//<objects xmlns='http://www.springframework.net' xmlns:v='http://www.springframework.net/validation'>
//    <v:required test='#this'>
//        <v:message id='error.airportCode.required' providers='summary'/>
//        <v:action type='Spring.Validation.Actions.ExpressionAction, Spring.Core' when='true'/>
//    </v:required>
//</objects>
//";
            XmlDocument doc = GetValidatedXmlResource("_WhenConfigFileIsNotValid.xml");

            MockObjectDefinitionRegistry registry = new MockObjectDefinitionRegistry();

            XmlReaderContext readerContext = new XmlReaderContext(null, new XmlObjectDefinitionReader(registry));
            ObjectDefinitionParserHelper helper = new ObjectDefinitionParserHelper(readerContext);
            helper.InitDefaults(doc.DocumentElement);
            ParserContext parserContext = new ParserContext(helper);

            ValidationNamespaceParser parser = new ValidationNamespaceParser();
            Assert.Throws<ObjectDefinitionStoreException>(() =>
            {
                foreach (XmlElement element in doc.DocumentElement.ChildNodes)
                {
                    if (element.NamespaceURI == "http://www.springframework.net/validation")
                    {
                        parser.ParseElement(element, parserContext);
                    }
                }
            });
        }
    }
}


text:
'use strict'
/*global describe, it, before, after, beforeEach */

var should = require('should')
var thunk = require('thunks')()
var redis = require('../index')

module.exports = function () {
  describe('commands:Script', function () {
    var client

    before(function () {
      client = redis.createClient({
        database: 0
      })
      client.on('error', function (error) {
        console.error('redis client:', error)
      })
    })

    beforeEach(function (done) {
      client.flushdb()(function (error, res) {
        should(error).be.equal(null)
        should(res).be.equal('OK')
      })(done)
    })

    after(function () {
      client.clientEnd()
    })

    it('client.eval', function (done) {
      client.eval('return {KEYS[1],KEYS[2],ARGV[1],ARGV[2]}', 2, 'key1', 'key2', 'first', 'second')(function (error, res) {
        should(error).be.equal(null)
        should(res).be.eql(['key1', 'key2', 'first', 'second'])
        return this.eval('return redis.call("set",KEYS[1],"bar")', 1, 'foo')
      })(function (error, res) {
        should(error).be.equal(null)
        should(res).be.equal('OK')
        return thunk.all(this.get('foo'), this.eval('return redis.call("get","foo")', 0))
      })(function (error, res) {
        should(error).be.equal(null)
        should(res).be.eql(['bar', 'bar'])
        return thunk.all(this.lpush('list', 123), this.eval('return redis.call("get", "list")', 0))
      })(function (error, res) {
        should(error).be.instanceOf(Error)
        return this.eval('return redis.pcall("get", "list")', 0)
      })(function (error, res) {
        should(error).be.instanceOf(Error)
      })(done)
    })

    it('client.script, client.evalsha', function (done) {
      var sha = null

      client.script('load', 'return "hello thunk-redis"')(function (error, res) {
        should(error).be.equal(null)
        sha = res
        return this.evalsha(res, 0)
      })(function (error, res) {
        should(error).be.equal(null)
        should(res).be.equal('hello thunk-redis')
        return this.script('exists', sha)
      })(function (error, res) {
        should(error).be.equal(null)
        should(res).be.eql([1])
        return thunk.all(this.script('flush'), this.script('exists', sha))
      })(function (error, res) {
        should(error).be.equal(null)
        should(res).be.eql(['OK', [0]])
        return this.script('kill')
      })(function (error, res) {
        should(error).be.instanceOf(Error)
      })(done)
    })

  })
}


text:
require "minitest/autorun"
require "<%= @underscored_name %>"

class <%= @constant_name %>Test < Minitest::Test
  def test_fails
    flunk "Gotta write a test!"
  end
end