repo_name stringlengths 4 116 | path stringlengths 4 379 | size stringlengths 1 7 | content stringlengths 3 1.05M | license stringclasses 15
values |
|---|---|---|---|---|
depcheck/depcheck | test/fake_modules/webpack_inline_loader/index.ts | 81 | import 'script-loader!slickity-slick';
require('script-loader!slickity-slick');
| mit |
danglauber/FW2 | public/js/site.js | 462 | (function($){
$(document).ready(function(){
// Cache the elements we'll need
var menu = $('#cssmenu');
var menuList = menu.find('ul:first');
var listItems = menu.find('li').not('#responsive-tab');
// Create responsive trigger
menuList.prepend('<li id="responsive-tab"><a href="#">Menu</a></li>');
// Toggle menu visibility
menu.on('click', '#responsive-tab', function(){
listItems.slideToggle('fast');
listItems.addClass('collapsed');
});
});
})(jQuery);
| mit |
sinkpoint/research-mri-db | patientdb/patientdb/migrations/0002_mris_subject.py | 449 | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import models, migrations
class Migration(migrations.Migration):
dependencies = [
('patientdb', '0001_initial'),
]
operations = [
migrations.AddField(
model_name='mris',
name='subject',
field=models.ForeignKey(default=-1, to='patientdb.Patients'),
preserve_default=False,
),
]
| mit |
jacob-keller/git-plugin | src/test/java/jenkins/plugins/git/AbstractGitSCMSourceTest.java | 43578 | package jenkins.plugins.git;
import edu.umd.cs.findbugs.annotations.NonNull;
import hudson.FilePath;
import hudson.Launcher;
import hudson.model.Action;
import hudson.model.Actionable;
import hudson.model.Run;
import hudson.model.TaskListener;
import hudson.plugins.git.UserRemoteConfig;
import hudson.plugins.git.extensions.impl.IgnoreNotifyCommit;
import hudson.scm.SCMRevisionState;
import hudson.plugins.git.GitSCM;
import hudson.plugins.git.extensions.GitSCMExtension;
import hudson.plugins.git.extensions.impl.BuildChooserSetting;
import hudson.plugins.git.extensions.impl.LocalBranch;
import hudson.util.StreamTaskListener;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.TreeMap;
import java.util.UUID;
import jenkins.plugins.git.traits.BranchDiscoveryTrait;
import jenkins.plugins.git.traits.DiscoverOtherRefsTrait;
import jenkins.plugins.git.traits.IgnoreOnPushNotificationTrait;
import jenkins.plugins.git.traits.RefSpecsSCMSourceTrait;
import jenkins.plugins.git.traits.TagDiscoveryTrait;
import jenkins.scm.api.SCMHead;
import jenkins.scm.api.SCMHeadObserver;
import jenkins.scm.api.SCMRevision;
import jenkins.scm.api.SCMSource;
import static org.hamcrest.Matchers.*;
import jenkins.scm.api.SCMSourceCriteria;
import jenkins.scm.api.SCMSourceOwner;
import jenkins.scm.api.metadata.PrimaryInstanceMetadataAction;
import jenkins.scm.api.trait.SCMSourceTrait;
import org.junit.Ignore;
import org.junit.Rule;
import org.junit.Test;
import org.jvnet.hudson.test.Issue;
import org.jvnet.hudson.test.JenkinsRule;
import org.mockito.Mockito;
import static org.junit.Assert.*;
import static org.mockito.Mockito.when;
/**
* Tests for {@link AbstractGitSCMSource}
*/
public class AbstractGitSCMSourceTest {
static final String GitBranchSCMHead_DEV_MASTER = "[GitBranchSCMHead{name='dev', ref='refs/heads/dev'}, GitBranchSCMHead{name='master', ref='refs/heads/master'}]";
static final String GitBranchSCMHead_DEV_DEV2_MASTER = "[GitBranchSCMHead{name='dev', ref='refs/heads/dev'}, GitBranchSCMHead{name='dev2', ref='refs/heads/dev2'}, GitBranchSCMHead{name='master', ref='refs/heads/master'}]";
@Rule
public JenkinsRule r = new JenkinsRule();
@Rule
public GitSampleRepoRule sampleRepo = new GitSampleRepoRule();
@Rule
public GitSampleRepoRule sampleRepo2 = new GitSampleRepoRule();
// TODO AbstractGitSCMSourceRetrieveHeadsTest *sounds* like it would be the right place, but it does not in fact retrieve any heads!
@Issue("JENKINS-37482")
@Test
public void retrieveHeads() throws Exception {
sampleRepo.init();
sampleRepo.git("checkout", "-b", "dev");
sampleRepo.write("file", "modified");
sampleRepo.git("commit", "--all", "--message=dev");
SCMSource source = new GitSCMSource(null, sampleRepo.toString(), "", "*", "", true);
TaskListener listener = StreamTaskListener.fromStderr();
// SCMHeadObserver.Collector.result is a TreeMap so order is predictable:
assertEquals(GitBranchSCMHead_DEV_MASTER, source.fetch(listener).toString());
// And reuse cache:
assertEquals(GitBranchSCMHead_DEV_MASTER, source.fetch(listener).toString());
sampleRepo.git("checkout", "-b", "dev2");
sampleRepo.write("file", "modified again");
sampleRepo.git("commit", "--all", "--message=dev2");
// After changing data:
assertEquals(GitBranchSCMHead_DEV_DEV2_MASTER, source.fetch(listener).toString());
}
@Test
public void retrieveHeadsRequiresBranchDiscovery() throws Exception {
sampleRepo.init();
sampleRepo.git("checkout", "-b", "dev");
sampleRepo.write("file", "modified");
sampleRepo.git("commit", "--all", "--message=dev");
GitSCMSource source = new GitSCMSource(sampleRepo.toString());
TaskListener listener = StreamTaskListener.fromStderr();
// SCMHeadObserver.Collector.result is a TreeMap so order is predictable:
assertEquals("[]", source.fetch(listener).toString());
source.setTraits(Collections.<SCMSourceTrait>singletonList(new BranchDiscoveryTrait()));
assertEquals(GitBranchSCMHead_DEV_MASTER, source.fetch(listener).toString());
// And reuse cache:
assertEquals(GitBranchSCMHead_DEV_MASTER, source.fetch(listener).toString());
sampleRepo.git("checkout", "-b", "dev2");
sampleRepo.write("file", "modified again");
sampleRepo.git("commit", "--all", "--message=dev2");
// After changing data:
assertEquals(GitBranchSCMHead_DEV_DEV2_MASTER, source.fetch(listener).toString());
}
@Issue("JENKINS-46207")
@Test
public void retrieveHeadsSupportsTagDiscovery_ignoreTagsWithoutTagDiscoveryTrait() throws Exception {
sampleRepo.init();
sampleRepo.git("checkout", "-b", "dev");
sampleRepo.write("file", "modified");
sampleRepo.git("commit", "--all", "--message=dev");
sampleRepo.git("tag", "lightweight");
sampleRepo.write("file", "modified2");
sampleRepo.git("commit", "--all", "--message=dev2");
sampleRepo.git("tag", "-a", "annotated", "-m", "annotated");
sampleRepo.write("file", "modified3");
sampleRepo.git("commit", "--all", "--message=dev3");
GitSCMSource source = new GitSCMSource(sampleRepo.toString());
TaskListener listener = StreamTaskListener.fromStderr();
// SCMHeadObserver.Collector.result is a TreeMap so order is predictable:
assertEquals("[]", source.fetch(listener).toString());
source.setTraits(Collections.<SCMSourceTrait>singletonList(new BranchDiscoveryTrait()));
assertEquals(GitBranchSCMHead_DEV_MASTER, source.fetch(listener).toString());
// And reuse cache:
assertEquals(GitBranchSCMHead_DEV_MASTER, source.fetch(listener).toString());
sampleRepo.git("checkout", "-b", "dev2");
sampleRepo.write("file", "modified again");
sampleRepo.git("commit", "--all", "--message=dev2");
// After changing data:
assertEquals(GitBranchSCMHead_DEV_DEV2_MASTER, source.fetch(listener).toString());
}
@Issue("JENKINS-46207")
@Test
public void retrieveHeadsSupportsTagDiscovery_findTagsWithTagDiscoveryTrait() throws Exception {
sampleRepo.init();
sampleRepo.git("checkout", "-b", "dev");
sampleRepo.write("file", "modified");
sampleRepo.git("commit", "--all", "--message=dev-commit-message");
long beforeLightweightTag = System.currentTimeMillis();
sampleRepo.git("tag", "lightweight");
long afterLightweightTag = System.currentTimeMillis();
sampleRepo.write("file", "modified2");
sampleRepo.git("commit", "--all", "--message=dev2-commit-message");
long beforeAnnotatedTag = System.currentTimeMillis();
sampleRepo.git("tag", "-a", "annotated", "-m", "annotated");
long afterAnnotatedTag = System.currentTimeMillis();
sampleRepo.write("file", "modified3");
sampleRepo.git("commit", "--all", "--message=dev3-commit-message");
GitSCMSource source = new GitSCMSource(sampleRepo.toString());
source.setTraits(new ArrayList<SCMSourceTrait>());
TaskListener listener = StreamTaskListener.fromStderr();
// SCMHeadObserver.Collector.result is a TreeMap so order is predictable:
assertEquals("[]", source.fetch(listener).toString());
source.setTraits(Arrays.asList(new BranchDiscoveryTrait(), new TagDiscoveryTrait()));
Set<SCMHead> scmHeadSet = source.fetch(listener);
long now = System.currentTimeMillis();
for (SCMHead scmHead : scmHeadSet) {
if (scmHead instanceof GitTagSCMHead) {
GitTagSCMHead tagHead = (GitTagSCMHead) scmHead;
// FAT file system time stamps only resolve to 2 second boundary
// EXT3 file system time stamps only resolve to 1 second boundary
long fileTimeStampFuzz = isWindows() ? 2000L : 1000L;
if (scmHead.getName().equals("lightweight")) {
long timeStampDelta = afterLightweightTag - tagHead.getTimestamp();
assertThat(timeStampDelta, is(both(greaterThanOrEqualTo(0L)).and(lessThanOrEqualTo(afterLightweightTag - beforeLightweightTag + fileTimeStampFuzz))));
} else if (scmHead.getName().equals("annotated")) {
long timeStampDelta = afterAnnotatedTag - tagHead.getTimestamp();
assertThat(timeStampDelta, is(both(greaterThanOrEqualTo(0L)).and(lessThanOrEqualTo(afterAnnotatedTag - beforeAnnotatedTag + fileTimeStampFuzz))));
} else {
fail("Unexpected tag head '" + scmHead.getName() + "'");
}
}
}
String expected = "[SCMHead{'annotated'}, GitBranchSCMHead{name='dev', ref='refs/heads/dev'}, SCMHead{'lightweight'}, GitBranchSCMHead{name='master', ref='refs/heads/master'}]";
assertEquals(expected, scmHeadSet.toString());
// And reuse cache:
assertEquals(expected, source.fetch(listener).toString());
sampleRepo.git("checkout", "-b", "dev2");
sampleRepo.write("file", "modified again");
sampleRepo.git("commit", "--all", "--message=dev2");
// After changing data:
expected = "[SCMHead{'annotated'}, GitBranchSCMHead{name='dev', ref='refs/heads/dev'}, GitBranchSCMHead{name='dev2', ref='refs/heads/dev2'}, SCMHead{'lightweight'}, GitBranchSCMHead{name='master', ref='refs/heads/master'}]";
assertEquals(expected, source.fetch(listener).toString());
}
@Issue("JENKINS-46207")
@Test
public void retrieveHeadsSupportsTagDiscovery_onlyTagsWithoutBranchDiscoveryTrait() throws Exception {
sampleRepo.init();
sampleRepo.git("checkout", "-b", "dev");
sampleRepo.write("file", "modified");
sampleRepo.git("commit", "--all", "--message=dev");
sampleRepo.git("tag", "lightweight");
sampleRepo.write("file", "modified2");
sampleRepo.git("commit", "--all", "--message=dev2");
sampleRepo.git("tag", "-a", "annotated", "-m", "annotated");
sampleRepo.write("file", "modified3");
sampleRepo.git("commit", "--all", "--message=dev3");
GitSCMSource source = new GitSCMSource(sampleRepo.toString());
source.setTraits(new ArrayList<SCMSourceTrait>());
TaskListener listener = StreamTaskListener.fromStderr();
// SCMHeadObserver.Collector.result is a TreeMap so order is predictable:
assertEquals("[]", source.fetch(listener).toString());
source.setTraits(Collections.<SCMSourceTrait>singletonList(new TagDiscoveryTrait()));
assertEquals("[SCMHead{'annotated'}, SCMHead{'lightweight'}]", source.fetch(listener).toString());
// And reuse cache:
assertEquals("[SCMHead{'annotated'}, SCMHead{'lightweight'}]", source.fetch(listener).toString());
}
@Issue("JENKINS-45953")
@Test
public void retrieveRevisions() throws Exception {
sampleRepo.init();
sampleRepo.git("checkout", "-b", "dev");
sampleRepo.write("file", "modified");
sampleRepo.git("commit", "--all", "--message=dev");
sampleRepo.git("tag", "lightweight");
sampleRepo.write("file", "modified2");
sampleRepo.git("commit", "--all", "--message=dev2");
sampleRepo.git("tag", "-a", "annotated", "-m", "annotated");
sampleRepo.write("file", "modified3");
sampleRepo.git("commit", "--all", "--message=dev3");
GitSCMSource source = new GitSCMSource(sampleRepo.toString());
source.setTraits(new ArrayList<SCMSourceTrait>());
TaskListener listener = StreamTaskListener.fromStderr();
assertThat(source.fetchRevisions(listener), hasSize(0));
source.setTraits(Collections.<SCMSourceTrait>singletonList(new BranchDiscoveryTrait()));
assertThat(source.fetchRevisions(listener), containsInAnyOrder("dev", "master"));
source.setTraits(Collections.<SCMSourceTrait>singletonList(new TagDiscoveryTrait()));
assertThat(source.fetchRevisions(listener), containsInAnyOrder("annotated", "lightweight"));
source.setTraits(Arrays.asList(new BranchDiscoveryTrait(), new TagDiscoveryTrait()));
assertThat(source.fetchRevisions(listener), containsInAnyOrder("dev", "master", "annotated", "lightweight"));
}
@Issue("JENKINS-47824")
@Test
public void retrieveByName() throws Exception {
sampleRepo.init();
String masterHash = sampleRepo.head();
sampleRepo.git("checkout", "-b", "dev");
sampleRepo.write("file", "modified");
sampleRepo.git("commit", "--all", "--message=dev");
sampleRepo.git("tag", "v1");
String v1Hash = sampleRepo.head();
sampleRepo.write("file", "modified2");
sampleRepo.git("commit", "--all", "--message=dev2");
sampleRepo.git("tag", "-a", "v2", "-m", "annotated");
String v2Hash = sampleRepo.head();
sampleRepo.write("file", "modified3");
sampleRepo.git("commit", "--all", "--message=dev3");
String devHash = sampleRepo.head();
GitSCMSource source = new GitSCMSource(sampleRepo.toString());
source.setTraits(new ArrayList<SCMSourceTrait>());
TaskListener listener = StreamTaskListener.fromStderr();
listener.getLogger().println("\n=== fetch('master') ===\n");
SCMRevision rev = source.fetch("master", listener);
assertThat(rev, instanceOf(AbstractGitSCMSource.SCMRevisionImpl.class));
assertThat(((AbstractGitSCMSource.SCMRevisionImpl)rev).getHash(), is(masterHash));
listener.getLogger().println("\n=== fetch('dev') ===\n");
rev = source.fetch("dev", listener);
assertThat(rev, instanceOf(AbstractGitSCMSource.SCMRevisionImpl.class));
assertThat(((AbstractGitSCMSource.SCMRevisionImpl)rev).getHash(), is(devHash));
listener.getLogger().println("\n=== fetch('v1') ===\n");
rev = source.fetch("v1", listener);
assertThat(rev, instanceOf(GitTagSCMRevision.class));
assertThat(((GitTagSCMRevision)rev).getHash(), is(v1Hash));
listener.getLogger().println("\n=== fetch('v2') ===\n");
rev = source.fetch("v2", listener);
assertThat(rev, instanceOf(GitTagSCMRevision.class));
assertThat(((GitTagSCMRevision)rev).getHash(), is(v2Hash));
listener.getLogger().printf("%n=== fetch('%s') ===%n%n", masterHash);
rev = source.fetch(masterHash, listener);
assertThat(rev, instanceOf(AbstractGitSCMSource.SCMRevisionImpl.class));
assertThat(((AbstractGitSCMSource.SCMRevisionImpl) rev).getHash(), is(masterHash));
assertThat(rev.getHead().getName(), is("master"));
listener.getLogger().printf("%n=== fetch('%s') ===%n%n", masterHash.substring(0, 10));
rev = source.fetch(masterHash.substring(0, 10), listener);
assertThat(rev, instanceOf(AbstractGitSCMSource.SCMRevisionImpl.class));
assertThat(((AbstractGitSCMSource.SCMRevisionImpl) rev).getHash(), is(masterHash));
assertThat(rev.getHead().getName(), is("master"));
listener.getLogger().printf("%n=== fetch('%s') ===%n%n", devHash);
rev = source.fetch(devHash, listener);
assertThat(rev, instanceOf(AbstractGitSCMSource.SCMRevisionImpl.class));
assertThat(((AbstractGitSCMSource.SCMRevisionImpl) rev).getHash(), is(devHash));
assertThat(rev.getHead().getName(), is("dev"));
listener.getLogger().printf("%n=== fetch('%s') ===%n%n", devHash.substring(0, 10));
rev = source.fetch(devHash.substring(0, 10), listener);
assertThat(rev, instanceOf(AbstractGitSCMSource.SCMRevisionImpl.class));
assertThat(((AbstractGitSCMSource.SCMRevisionImpl) rev).getHash(), is(devHash));
assertThat(rev.getHead().getName(), is("dev"));
listener.getLogger().printf("%n=== fetch('%s') ===%n%n", v1Hash);
rev = source.fetch(v1Hash, listener);
assertThat(rev, instanceOf(AbstractGitSCMSource.SCMRevisionImpl.class));
assertThat(((AbstractGitSCMSource.SCMRevisionImpl) rev).getHash(), is(v1Hash));
listener.getLogger().printf("%n=== fetch('%s') ===%n%n", v1Hash.substring(0, 10));
rev = source.fetch(v1Hash.substring(0, 10), listener);
assertThat(rev, instanceOf(AbstractGitSCMSource.SCMRevisionImpl.class));
assertThat(((AbstractGitSCMSource.SCMRevisionImpl) rev).getHash(), is(v1Hash));
listener.getLogger().printf("%n=== fetch('%s') ===%n%n", v2Hash);
rev = source.fetch(v2Hash, listener);
assertThat(rev, instanceOf(AbstractGitSCMSource.SCMRevisionImpl.class));
assertThat(((AbstractGitSCMSource.SCMRevisionImpl) rev).getHash(), is(v2Hash));
listener.getLogger().printf("%n=== fetch('%s') ===%n%n", v2Hash.substring(0, 10));
rev = source.fetch(v2Hash.substring(0, 10), listener);
assertThat(rev, instanceOf(AbstractGitSCMSource.SCMRevisionImpl.class));
assertThat(((AbstractGitSCMSource.SCMRevisionImpl) rev).getHash(), is(v2Hash));
String v2Tag = "refs/tags/v2";
listener.getLogger().printf("%n=== fetch('%s') ===%n%n", v2Tag);
rev = source.fetch(v2Tag, listener);
assertThat(rev, instanceOf(AbstractGitSCMSource.SCMRevisionImpl.class));
assertThat(((AbstractGitSCMSource.SCMRevisionImpl) rev).getHash(), is(v2Hash));
}
public static abstract class ActionableSCMSourceOwner extends Actionable implements SCMSourceOwner {
}
@Test
public void retrievePrimaryHead_NotDuplicated() throws Exception {
retrievePrimaryHead(false);
}
@Test
public void retrievePrimaryHead_Duplicated() throws Exception {
retrievePrimaryHead(true);
}
public void retrievePrimaryHead(boolean duplicatePrimary) throws Exception {
sampleRepo.init();
sampleRepo.write("file.txt", "");
sampleRepo.git("add", "file.txt");
sampleRepo.git("commit", "--all", "--message=add-empty-file");
sampleRepo.git("checkout", "-b", "new-primary");
sampleRepo.write("file.txt", "content");
sampleRepo.git("add", "file.txt");
sampleRepo.git("commit", "--all", "--message=add-file");
if (duplicatePrimary) {
// If more than one branch points to same sha1 as new-primary and the
// command line git implementation is older than 2.8.0, then the guesser
// for primary won't be able to choose between the two alternatives.
// The next line illustrates that case with older command line git.
sampleRepo.git("checkout", "-b", "new-primary-duplicate", "new-primary");
}
sampleRepo.git("checkout", "master");
sampleRepo.git("checkout", "-b", "dev");
sampleRepo.git("symbolic-ref", "HEAD", "refs/heads/new-primary");
SCMSource source = new GitSCMSource(null, sampleRepo.toString(), "", "*", "", true);
ActionableSCMSourceOwner owner = Mockito.mock(ActionableSCMSourceOwner.class);
when(owner.getSCMSource(source.getId())).thenReturn(source);
when(owner.getSCMSources()).thenReturn(Collections.singletonList(source));
source.setOwner(owner);
TaskListener listener = StreamTaskListener.fromStderr();
Map<String, SCMHead> headByName = new TreeMap<>();
for (SCMHead h: source.fetch(listener)) {
headByName.put(h.getName(), h);
}
if (duplicatePrimary) {
assertThat(headByName.keySet(), containsInAnyOrder("master", "dev", "new-primary", "new-primary-duplicate"));
} else {
assertThat(headByName.keySet(), containsInAnyOrder("master", "dev", "new-primary"));
}
List<Action> actions = source.fetchActions(null, listener);
GitRemoteHeadRefAction refAction = null;
for (Action a: actions) {
if (a instanceof GitRemoteHeadRefAction) {
refAction = (GitRemoteHeadRefAction) a;
break;
}
}
final boolean CLI_GIT_LESS_THAN_280 = !sampleRepo.gitVersionAtLeast(2, 8);
if (duplicatePrimary && CLI_GIT_LESS_THAN_280) {
assertThat(refAction, is(nullValue()));
} else {
assertThat(refAction, notNullValue());
assertThat(refAction.getName(), is("new-primary"));
when(owner.getAction(GitRemoteHeadRefAction.class)).thenReturn(refAction);
when(owner.getActions(GitRemoteHeadRefAction.class)).thenReturn(Collections.singletonList(refAction));
actions = source.fetchActions(headByName.get("new-primary"), null, listener);
}
PrimaryInstanceMetadataAction primary = null;
for (Action a: actions) {
if (a instanceof PrimaryInstanceMetadataAction) {
primary = (PrimaryInstanceMetadataAction) a;
break;
}
}
if (duplicatePrimary && CLI_GIT_LESS_THAN_280) {
assertThat(primary, is(nullValue()));
} else {
assertThat(primary, notNullValue());
}
}
@Issue("JENKINS-31155")
@Test
public void retrieveRevision() throws Exception {
sampleRepo.init();
sampleRepo.write("file", "v1");
sampleRepo.git("commit", "--all", "--message=v1");
sampleRepo.git("tag", "v1");
String v1 = sampleRepo.head();
sampleRepo.write("file", "v2");
sampleRepo.git("commit", "--all", "--message=v2"); // master
sampleRepo.git("checkout", "-b", "dev");
sampleRepo.write("file", "v3");
sampleRepo.git("commit", "--all", "--message=v3"); // dev
// SCM.checkout does not permit a null build argument, unfortunately.
Run<?,?> run = r.buildAndAssertSuccess(r.createFreeStyleProject());
GitSCMSource source = new GitSCMSource(sampleRepo.toString());
source.setTraits(Arrays.asList(new BranchDiscoveryTrait(), new TagDiscoveryTrait()));
StreamTaskListener listener = StreamTaskListener.fromStderr();
// Test retrieval of branches:
assertEquals("v2", fileAt("master", run, source, listener));
assertEquals("v3", fileAt("dev", run, source, listener));
// Tags:
assertEquals("v1", fileAt("v1", run, source, listener));
// And commit hashes:
assertEquals("v1", fileAt(v1, run, source, listener));
assertEquals("v1", fileAt(v1.substring(0, 7), run, source, listener));
// Nonexistent stuff:
assertNull(fileAt("nonexistent", run, source, listener));
assertNull(fileAt("1234567", run, source, listener));
assertNull(fileAt("", run, source, listener));
assertNull(fileAt("\n", run, source, listener));
assertThat(source.fetchRevisions(listener), hasItems("master", "dev", "v1"));
// we do not care to return commit hashes or other references
}
@Issue("JENKINS-48061")
@Test
public void retrieveRevision_nonHead() throws Exception {
sampleRepo.init();
sampleRepo.write("file", "v1");
sampleRepo.git("commit", "--all", "--message=v1");
sampleRepo.git("tag", "v1");
String v1 = sampleRepo.head();
sampleRepo.write("file", "v2");
sampleRepo.git("commit", "--all", "--message=v2"); // master
sampleRepo.git("checkout", "-b", "dev");
sampleRepo.write("file", "v3");
sampleRepo.git("commit", "--all", "--message=v3"); // dev
String v3 = sampleRepo.head();
sampleRepo.write("file", "v4");
sampleRepo.git("commit", "--all", "--message=v4"); // dev
// SCM.checkout does not permit a null build argument, unfortunately.
Run<?,?> run = r.buildAndAssertSuccess(r.createFreeStyleProject());
GitSCMSource source = new GitSCMSource(sampleRepo.toString());
source.setTraits(Arrays.asList(new BranchDiscoveryTrait(), new TagDiscoveryTrait()));
StreamTaskListener listener = StreamTaskListener.fromStderr();
// Test retrieval of non head revision:
assertEquals("v3", fileAt(v3, run, source, listener));
}
@Issue("JENKINS-48061")
@Test
@Ignore("At least file:// protocol doesn't allow fetching unannounced commits")
public void retrieveRevision_nonAdvertised() throws Exception {
sampleRepo.init();
sampleRepo.write("file", "v1");
sampleRepo.git("commit", "--all", "--message=v1");
sampleRepo.git("tag", "v1");
String v1 = sampleRepo.head();
sampleRepo.write("file", "v2");
sampleRepo.git("commit", "--all", "--message=v2"); // master
sampleRepo.git("checkout", "-b", "dev");
sampleRepo.write("file", "v3");
sampleRepo.git("commit", "--all", "--message=v3"); // dev
String v3 = sampleRepo.head();
sampleRepo.git("reset", "--hard", "HEAD^"); // dev, the v3 ref is eligible for GC but still fetchable
sampleRepo.write("file", "v4");
sampleRepo.git("commit", "--all", "--message=v4"); // dev
// SCM.checkout does not permit a null build argument, unfortunately.
Run<?,?> run = r.buildAndAssertSuccess(r.createFreeStyleProject());
GitSCMSource source = new GitSCMSource(sampleRepo.toString());
source.setTraits(Arrays.asList(new BranchDiscoveryTrait(), new TagDiscoveryTrait()));
StreamTaskListener listener = StreamTaskListener.fromStderr();
// Test retrieval of non head revision:
assertEquals("v3", fileAt(v3, run, source, listener));
}
@Issue("JENKINS-48061")
@Test
public void retrieveRevision_customRef() throws Exception {
sampleRepo.init();
sampleRepo.write("file", "v1");
sampleRepo.git("commit", "--all", "--message=v1");
sampleRepo.git("tag", "v1");
String v1 = sampleRepo.head();
sampleRepo.write("file", "v2");
sampleRepo.git("commit", "--all", "--message=v2"); // master
sampleRepo.git("checkout", "-b", "dev");
sampleRepo.write("file", "v3");
sampleRepo.git("commit", "--all", "--message=v3"); // dev
String v3 = sampleRepo.head();
sampleRepo.git("update-ref", "refs/custom/foo", v3); // now this is an advertised ref so cannot be GC'd
sampleRepo.git("reset", "--hard", "HEAD^"); // dev
sampleRepo.write("file", "v4");
sampleRepo.git("commit", "--all", "--message=v4"); // dev
// SCM.checkout does not permit a null build argument, unfortunately.
Run<?,?> run = r.buildAndAssertSuccess(r.createFreeStyleProject());
GitSCMSource source = new GitSCMSource(sampleRepo.toString());
source.setTraits(Arrays.asList(
new BranchDiscoveryTrait(),
new TagDiscoveryTrait(),
new DiscoverOtherRefsTrait("refs/custom/foo")));
StreamTaskListener listener = StreamTaskListener.fromStderr();
// Test retrieval of non head revision:
assertEquals("v3", fileAt(v3, run, source, listener));
}
@Issue("JENKINS-48061")
@Test
public void retrieveRevision_customRef_descendant() throws Exception {
sampleRepo.init();
sampleRepo.write("file", "v1");
sampleRepo.git("commit", "--all", "--message=v1");
sampleRepo.git("tag", "v1");
sampleRepo.write("file", "v2");
sampleRepo.git("commit", "--all", "--message=v2"); // master
sampleRepo.git("checkout", "-b", "dev");
String v2 = sampleRepo.head();
sampleRepo.write("file", "v3");
sampleRepo.git("commit", "--all", "--message=v3"); // dev
String v3 = sampleRepo.head();
sampleRepo.write("file", "v4");
sampleRepo.git("commit", "--all", "--message=v4"); // dev
sampleRepo.git("update-ref", "refs/custom/foo", v3); // now this is an advertised ref so cannot be GC'd
sampleRepo.git("reset", "--hard", "HEAD~2"); // dev
String dev = sampleRepo.head();
assertNotEquals(dev, v3); //Just verifying the reset nav got correct
assertEquals(dev, v2);
sampleRepo.write("file", "v5");
sampleRepo.git("commit", "--all", "--message=v4"); // dev
// SCM.checkout does not permit a null build argument, unfortunately.
Run<?,?> run = r.buildAndAssertSuccess(r.createFreeStyleProject());
GitSCMSource source = new GitSCMSource(sampleRepo.toString());
source.setTraits(Arrays.asList(
new BranchDiscoveryTrait(),
new TagDiscoveryTrait(),
new DiscoverOtherRefsTrait("refs/custom/*")));
StreamTaskListener listener = StreamTaskListener.fromStderr();
// Test retrieval of non head revision:
assertEquals("v3", fileAt(v3, run, source, listener));
}
@Issue("JENKINS-48061")
@Test
public void retrieveRevision_customRef_abbrev_sha1() throws Exception {
sampleRepo.init();
sampleRepo.write("file", "v1");
sampleRepo.git("commit", "--all", "--message=v1");
sampleRepo.git("tag", "v1");
String v1 = sampleRepo.head();
sampleRepo.write("file", "v2");
sampleRepo.git("commit", "--all", "--message=v2"); // master
sampleRepo.git("checkout", "-b", "dev");
sampleRepo.write("file", "v3");
sampleRepo.git("commit", "--all", "--message=v3"); // dev
String v3 = sampleRepo.head();
sampleRepo.git("update-ref", "refs/custom/foo", v3); // now this is an advertised ref so cannot be GC'd
sampleRepo.git("reset", "--hard", "HEAD^"); // dev
sampleRepo.write("file", "v4");
sampleRepo.git("commit", "--all", "--message=v4"); // dev
// SCM.checkout does not permit a null build argument, unfortunately.
Run<?,?> run = r.buildAndAssertSuccess(r.createFreeStyleProject());
GitSCMSource source = new GitSCMSource(sampleRepo.toString());
source.setTraits(Arrays.asList(
new BranchDiscoveryTrait(),
new TagDiscoveryTrait(),
new DiscoverOtherRefsTrait("refs/custom/foo")));
StreamTaskListener listener = StreamTaskListener.fromStderr();
// Test retrieval of non head revision:
assertEquals("v3", fileAt(v3.substring(0, 7), run, source, listener));
}
@Issue("JENKINS-48061")
@Test
public void retrieveRevision_pr_refspec() throws Exception {
sampleRepo.init();
sampleRepo.write("file", "v1");
sampleRepo.git("commit", "--all", "--message=v1");
sampleRepo.git("tag", "v1");
String v1 = sampleRepo.head();
sampleRepo.write("file", "v2");
sampleRepo.git("commit", "--all", "--message=v2"); // master
sampleRepo.git("checkout", "-b", "dev");
sampleRepo.write("file", "v3");
sampleRepo.git("commit", "--all", "--message=v3"); // dev
String v3 = sampleRepo.head();
sampleRepo.git("update-ref", "refs/pull-requests/1/from", v3); // now this is an advertised ref so cannot be GC'd
sampleRepo.git("reset", "--hard", "HEAD^"); // dev
sampleRepo.write("file", "v4");
sampleRepo.git("commit", "--all", "--message=v4"); // dev
// SCM.checkout does not permit a null build argument, unfortunately.
Run<?,?> run = r.buildAndAssertSuccess(r.createFreeStyleProject());
GitSCMSource source = new GitSCMSource(sampleRepo.toString());
source.setTraits(Arrays.asList(new BranchDiscoveryTrait(), new TagDiscoveryTrait(), new DiscoverOtherRefsTrait("pull-requests/*/from")));
StreamTaskListener listener = StreamTaskListener.fromStderr();
// Test retrieval of non head revision:
assertEquals("v3", fileAt("pull-requests/1/from", run, source, listener));
}
@Issue("JENKINS-48061")
@Test
public void retrieveRevision_pr_local_refspec() throws Exception {
sampleRepo.init();
sampleRepo.write("file", "v1");
sampleRepo.git("commit", "--all", "--message=v1");
sampleRepo.git("tag", "v1");
String v1 = sampleRepo.head();
sampleRepo.write("file", "v2");
sampleRepo.git("commit", "--all", "--message=v2"); // master
sampleRepo.git("checkout", "-b", "dev");
sampleRepo.write("file", "v3");
sampleRepo.git("commit", "--all", "--message=v3"); // dev
String v3 = sampleRepo.head();
sampleRepo.git("update-ref", "refs/pull-requests/1/from", v3); // now this is an advertised ref so cannot be GC'd
sampleRepo.git("reset", "--hard", "HEAD^"); // dev
sampleRepo.write("file", "v4");
sampleRepo.git("commit", "--all", "--message=v4"); // dev
// SCM.checkout does not permit a null build argument, unfortunately.
Run<?,?> run = r.buildAndAssertSuccess(r.createFreeStyleProject());
GitSCMSource source = new GitSCMSource(sampleRepo.toString());
//new RefSpecsSCMSourceTrait("+refs/pull-requests/*/from:refs/remotes/@{remote}/pr/*")
source.setTraits(Arrays.asList(new BranchDiscoveryTrait(), new TagDiscoveryTrait(),
new DiscoverOtherRefsTrait("/pull-requests/*/from", "pr/@{1}")));
StreamTaskListener listener = StreamTaskListener.fromStderr();
// Test retrieval of non head revision:
assertEquals("v3", fileAt("pr/1", run, source, listener));
}
private String fileAt(String revision, Run<?,?> run, SCMSource source, TaskListener listener) throws Exception {
SCMRevision rev = source.fetch(revision, listener);
if (rev == null) {
return null;
} else {
FilePath ws = new FilePath(run.getRootDir()).child("tmp-" + revision);
source.build(rev.getHead(), rev).checkout(run, new Launcher.LocalLauncher(listener), ws, listener, null, SCMRevisionState.NONE);
return ws.child("file").readToString();
}
}
@Issue("JENKINS-48061")
@Test
public void fetchOtherRef() throws Exception {
sampleRepo.init();
sampleRepo.write("file", "v1");
sampleRepo.git("commit", "--all", "--message=v1");
sampleRepo.git("tag", "v1");
String v1 = sampleRepo.head();
sampleRepo.write("file", "v2");
sampleRepo.git("commit", "--all", "--message=v2"); // master
sampleRepo.git("checkout", "-b", "dev");
sampleRepo.write("file", "v3");
sampleRepo.git("commit", "--all", "--message=v3"); // dev
String v3 = sampleRepo.head();
sampleRepo.git("update-ref", "refs/custom/1", v3);
sampleRepo.git("reset", "--hard", "HEAD^"); // dev
sampleRepo.write("file", "v4");
sampleRepo.git("commit", "--all", "--message=v4"); // dev
// SCM.checkout does not permit a null build argument, unfortunately.
Run<?,?> run = r.buildAndAssertSuccess(r.createFreeStyleProject());
GitSCMSource source = new GitSCMSource(sampleRepo.toString());
source.setTraits(Arrays.asList(new BranchDiscoveryTrait(), new TagDiscoveryTrait(), new DiscoverOtherRefsTrait("custom/*")));
StreamTaskListener listener = StreamTaskListener.fromStderr();
final SCMHeadObserver.Collector collector =
source.fetch(new SCMSourceCriteria() {
@Override
public boolean isHead(@NonNull Probe probe, @NonNull TaskListener listener) throws IOException {
return true;
}
}, new SCMHeadObserver.Collector(), listener);
final Map<SCMHead, SCMRevision> result = collector.result();
assertThat(result.entrySet(), hasSize(4));
assertThat(result, hasKey(allOf(
instanceOf(GitRefSCMHead.class),
hasProperty("name", equalTo("custom-1"))
)));
}
@Issue("JENKINS-48061")
@Test
public void fetchOtherRevisions() throws Exception {
sampleRepo.init();
sampleRepo.write("file", "v1");
sampleRepo.git("commit", "--all", "--message=v1");
sampleRepo.git("tag", "v1");
String v1 = sampleRepo.head();
sampleRepo.write("file", "v2");
sampleRepo.git("commit", "--all", "--message=v2"); // master
sampleRepo.git("checkout", "-b", "dev");
sampleRepo.write("file", "v3");
sampleRepo.git("commit", "--all", "--message=v3"); // dev
String v3 = sampleRepo.head();
sampleRepo.git("update-ref", "refs/custom/1", v3);
sampleRepo.git("reset", "--hard", "HEAD^"); // dev
sampleRepo.write("file", "v4");
sampleRepo.git("commit", "--all", "--message=v4"); // dev
// SCM.checkout does not permit a null build argument, unfortunately.
Run<?,?> run = r.buildAndAssertSuccess(r.createFreeStyleProject());
GitSCMSource source = new GitSCMSource(sampleRepo.toString());
source.setTraits(Arrays.asList(new BranchDiscoveryTrait(), new TagDiscoveryTrait(), new DiscoverOtherRefsTrait("custom/*")));
StreamTaskListener listener = StreamTaskListener.fromStderr();
final Set<String> revisions = source.fetchRevisions(listener);
assertThat(revisions, hasSize(4));
assertThat(revisions, containsInAnyOrder(
equalTo("custom-1"),
equalTo("v1"),
equalTo("dev"),
equalTo("master")
));
}
@Issue("JENKINS-37727")
@Test
public void pruneRemovesDeletedBranches() throws Exception {
sampleRepo.init();
/* Write a file to the master branch */
sampleRepo.write("master-file", "master-content-" + UUID.randomUUID().toString());
sampleRepo.git("add", "master-file");
sampleRepo.git("commit", "--message=master-branch-commit-message");
/* Write a file to the dev branch */
sampleRepo.git("checkout", "-b", "dev");
sampleRepo.write("dev-file", "dev-content-" + UUID.randomUUID().toString());
sampleRepo.git("add", "dev-file");
sampleRepo.git("commit", "--message=dev-branch-commit-message");
/* Fetch from sampleRepo */
GitSCMSource source = new GitSCMSource(null, sampleRepo.toString(), "", "*", "", true);
TaskListener listener = StreamTaskListener.fromStderr();
// SCMHeadObserver.Collector.result is a TreeMap so order is predictable:
assertEquals(GitBranchSCMHead_DEV_MASTER, source.fetch(listener).toString());
// And reuse cache:
assertEquals(GitBranchSCMHead_DEV_MASTER, source.fetch(listener).toString());
/* Create dev2 branch and write a file to it */
sampleRepo.git("checkout", "-b", "dev2", "master");
sampleRepo.write("dev2-file", "dev2-content-" + UUID.randomUUID().toString());
sampleRepo.git("add", "dev2-file");
sampleRepo.git("commit", "--message=dev2-branch-commit-message");
// Verify new branch is visible
assertEquals(GitBranchSCMHead_DEV_DEV2_MASTER, source.fetch(listener).toString());
/* Delete the dev branch */
sampleRepo.git("branch", "-D", "dev");
/* Fetch and confirm dev branch was pruned */
assertEquals("[GitBranchSCMHead{name='dev2', ref='refs/heads/dev2'}, GitBranchSCMHead{name='master', ref='refs/heads/master'}]", source.fetch(listener).toString());
}
@Test
public void testSpecificRevisionBuildChooser() throws Exception {
sampleRepo.init();
/* Write a file to the master branch */
sampleRepo.write("master-file", "master-content-" + UUID.randomUUID().toString());
sampleRepo.git("add", "master-file");
sampleRepo.git("commit", "--message=master-branch-commit-message");
/* Fetch from sampleRepo */
GitSCMSource source = new GitSCMSource(sampleRepo.toString());
source.setTraits(Collections.<SCMSourceTrait>singletonList(new IgnoreOnPushNotificationTrait()));
List<GitSCMExtension> extensions = new ArrayList<>();
assertThat(source.getExtensions(), is(empty()));
LocalBranch localBranchExtension = new LocalBranch("**");
extensions.add(localBranchExtension);
source.setExtensions(extensions);
assertThat(source.getExtensions(), contains(
allOf(
instanceOf(LocalBranch.class),
hasProperty("localBranch", is("**")
)
)
));
SCMHead head = new SCMHead("master");
SCMRevision revision = new AbstractGitSCMSource.SCMRevisionImpl(head, "beaded4deed2bed4feed2deaf78933d0f97a5a34");
// because we are ignoring push notifications we also ignore commits
extensions.add(new IgnoreNotifyCommit());
/* Check that BuildChooserSetting not added to extensions by build() */
GitSCM scm = (GitSCM) source.build(head);
assertThat(scm.getExtensions(), containsInAnyOrder(
allOf(
instanceOf(LocalBranch.class),
hasProperty("localBranch", is("**")
)
),
// no BuildChooserSetting
instanceOf(IgnoreNotifyCommit.class),
instanceOf(GitSCMSourceDefaults.class)
));
/* Check that BuildChooserSetting has been added to extensions by build() */
GitSCM scmRevision = (GitSCM) source.build(head, revision);
assertThat(scmRevision.getExtensions(), containsInAnyOrder(
allOf(
instanceOf(LocalBranch.class),
hasProperty("localBranch", is("**")
)
),
instanceOf(BuildChooserSetting.class),
instanceOf(IgnoreNotifyCommit.class),
instanceOf(GitSCMSourceDefaults.class)
));
}
@Test
public void testCustomRemoteName() throws Exception {
sampleRepo.init();
GitSCMSource source = new GitSCMSource(null, sampleRepo.toString(), "", "upstream", null, "*", "", true);
SCMHead head = new SCMHead("master");
GitSCM scm = (GitSCM) source.build(head);
List<UserRemoteConfig> configs = scm.getUserRemoteConfigs();
assertEquals(1, configs.size());
UserRemoteConfig config = configs.get(0);
assertEquals("upstream", config.getName());
assertEquals("+refs/heads/*:refs/remotes/upstream/*", config.getRefspec());
}
@Test
public void testCustomRefSpecs() throws Exception {
sampleRepo.init();
GitSCMSource source = new GitSCMSource(null, sampleRepo.toString(), "", null, "+refs/heads/*:refs/remotes/origin/* +refs/merge-requests/*/head:refs/remotes/origin/merge-requests/*", "*", "", true);
SCMHead head = new SCMHead("master");
GitSCM scm = (GitSCM) source.build(head);
List<UserRemoteConfig> configs = scm.getUserRemoteConfigs();
assertEquals(1, configs.size());
UserRemoteConfig config = configs.get(0);
assertEquals("origin", config.getName());
assertEquals("+refs/heads/*:refs/remotes/origin/* +refs/merge-requests/*/head:refs/remotes/origin/merge-requests/*", config.getRefspec());
}
private boolean isWindows() {
return File.pathSeparatorChar == ';';
}
}
| mit |
wichtounet/thor-os | kernel/include/conc/mutex.hpp | 2148 | //=======================================================================
// Copyright Baptiste Wicht 2013-2018.
// Distributed under the terms of the MIT License.
// (See accompanying file LICENSE or copy at
// http://www.opensource.org/licenses/MIT)
//=======================================================================
#ifndef MUTEX_H
#define MUTEX_H
#include <types.hpp>
#include <lock_guard.hpp>
#include "conc/spinlock.hpp"
#include "conc/wait_list.hpp"
#include "scheduler.hpp"
#include "logging.hpp"
/*!
* \brief A mutex implementation.
*
* Once the lock is acquired, the critical section is only accessible by the
* thread who acquired the mutex.
*/
struct mutex {
/*!
* \brief Initialize the mutex (either to 1 or 0)
* \param v The intial value of the mutex
*/
void init(size_t v = 1) {
if (v > 1) {
value = 1;
} else {
value = v;
}
}
/*!
* \brief Acquire the lock
*/
void lock() {
value_lock.lock();
if (value > 0) {
value = 0;
value_lock.unlock();
} else {
queue.enqueue();
value_lock.unlock();
scheduler::reschedule();
}
}
/*!
* \brief Try to acquire the lock.
*
* This function returns immediately.
*
* \return true if the lock was acquired, false otherwise.
*/
bool try_lock() {
std::lock_guard<spinlock> l(value_lock);
if (value > 0) {
value = 0;
return true;
} else {
return false;
}
}
/*!
* \brief Release the lock
*/
void unlock() {
std::lock_guard<spinlock> l(value_lock);
if (queue.empty()) {
value = 1;
} else {
queue.dequeue();
//No need to increment value, the process won't
//decrement it
}
}
private:
mutable spinlock value_lock; ///< The spin protecting the value
volatile size_t value = 1; ///< The value of the mutex
wait_list queue; ///< The sleep queue
};
#endif
| mit |
edosgn/colossus-sit | src/JHWEB/FinancieroBundle/Tests/Controller/FroCfgTipoRecaudoControllerTest.php | 788 | <?php
namespace JHWEB\FinancieroBundle\Tests\Controller;
use Symfony\Bundle\FrameworkBundle\Test\WebTestCase;
class FroCfgTipoRecaudoControllerTest extends WebTestCase
{
/*
public function testCompleteScenario()
{
// Create a new client to browse the application
$client = static::createClient();
// Go to the list view
$crawler = $client->request('GET', '/frocfgtiporecaudo/');
$this->assertEquals(200, $client->getResponse()->getStatusCode(), "Unexpected HTTP status code for GET /frocfgtiporecaudo/");
// Go to the show view
$crawler = $client->click($crawler->selectLink('show')->link());
$this->assertEquals(200, $client->getResponse()->getStatusCode(), "Unexpected HTTP status code");
}
*/
}
| mit |
hovsepm/azure-libraries-for-net | src/ResourceManagement/TrafficManager/Generated/Models/TrafficFlow.cs | 2956 | // <auto-generated>
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License. See License.txt in the project root for
// license information.
//
// Code generated by Microsoft (R) AutoRest Code Generator.
// </auto-generated>
namespace Microsoft.Azure.Management.TrafficManager.Fluent.Models
{
using Newtonsoft.Json;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
/// <summary>
/// Class representing a Traffic Manager HeatMap traffic flow properties.
/// </summary>
public partial class TrafficFlow
{
/// <summary>
/// Initializes a new instance of the TrafficFlow class.
/// </summary>
public TrafficFlow()
{
CustomInit();
}
/// <summary>
/// Initializes a new instance of the TrafficFlow class.
/// </summary>
/// <param name="sourceIp">The IP address that this query experience
/// originated from.</param>
/// <param name="latitude">The approximate latitude that these queries
/// originated from.</param>
/// <param name="longitude">The approximate longitude that these
/// queries originated from.</param>
/// <param name="queryExperiences">The query experiences produced in
/// this HeatMap calculation.</param>
public TrafficFlow(string sourceIp = default(string), double? latitude = default(double?), double? longitude = default(double?), IList<QueryExperience> queryExperiences = default(IList<QueryExperience>))
{
SourceIp = sourceIp;
Latitude = latitude;
Longitude = longitude;
QueryExperiences = queryExperiences;
CustomInit();
}
/// <summary>
/// An initialization method that performs custom operations like setting defaults
/// </summary>
partial void CustomInit();
/// <summary>
/// Gets or sets the IP address that this query experience originated
/// from.
/// </summary>
[JsonProperty(PropertyName = "sourceIp")]
public string SourceIp { get; set; }
/// <summary>
/// Gets or sets the approximate latitude that these queries originated
/// from.
/// </summary>
[JsonProperty(PropertyName = "latitude")]
public double? Latitude { get; set; }
/// <summary>
/// Gets or sets the approximate longitude that these queries
/// originated from.
/// </summary>
[JsonProperty(PropertyName = "longitude")]
public double? Longitude { get; set; }
/// <summary>
/// Gets or sets the query experiences produced in this HeatMap
/// calculation.
/// </summary>
[JsonProperty(PropertyName = "queryExperiences")]
public IList<QueryExperience> QueryExperiences { get; set; }
}
}
| mit |
sparcs-kaist/araplus | apps/main/urls.py | 799 | """araplus URL Configuration
The `urlpatterns` list routes URLs to views. For more information please see:
https://docs.djangoproject.com/en/1.8/topics/http/urls/
Examples:
Function views
1. Add an import: from my_app import views
2. Add a URL to urlpatterns: url(r'^$', views.home, name='home')
Class-based views
1. Add an import: from other_app.views import Home
2. Add a URL to urlpatterns: url(r'^$', Home.as_view(), name='home')
Including another URLconf
1. Add an import: from blog import urls as blog_urls
2. Add a URL to urlpatterns: url(r'^blog/', include(blog_urls))
"""
from django.conf.urls import include, url
from django.contrib import admin
urlpatterns = [
url(r'^$', 'apps.main.views.home'),
url(r'^credit/', 'apps.main.views.credit'),
]
| mit |
koxder/DemoPlayer | content/scripts/model/presentationlayer/controllers/player/indexController.js | 2266 | angular.module('app').
controller('player_indexController',
['$scope','playerID','$http','$rootScope',
function($scope,playerID,$http,$rootScope){
$scope.id = playerID;
$scope.$parent.homepage = "no-sidebar";
$scope.dash_player_visibility = false;
$scope.native_player_visibility = false;
$scope.language = $rootScope.language;
$scope.$on('changeLanguageEvent', function(event, data){
if ($scope.language != $rootScope.language){
$scope.language = $rootScope.language;
ServiceManager.
VideoService.
GetVideoInfo(
ServiceManager.
VideoService.
CreateServiceParams(
VideosServicePersistenceTechnologies.REST,
$scope,
$http));
}
});
var VideosServicePersistenceTechnologies =
ServiceManager.
VideoService.
GetAvailablePersistenceTechnologies();
ServiceManager.
VideoService.
GetVideoById(
ServiceManager.
VideoService.
CreateServiceParams(
VideosServicePersistenceTechnologies.LocalStorage,
$scope,
$http));
ServiceManager.
VideoService.
GetVideoInfo(
ServiceManager.
VideoService.
CreateServiceParams(
VideosServicePersistenceTechnologies.REST,
$scope,
$http));
// This part should be in a player service, and add player dinamically
if (UtilitiesManager.GetBrowser()=='safari' ){
$scope.native_player_visibility = true;
$scope.dash_player_visibility = false;
}else{
$scope.dash_player_visibility = true;
(function(){
var url = $scope.video.url;
console.log(url);
var player = dashjs.MediaPlayer().create();
player.initialize(document.querySelector("#videoPlayer"), url, true);
})();
};
}]);
| mit |
sstephenson/hector | lib/hector/logging.rb | 256 | module Hector
class NullLogger
def level=(l) end
def debug(*) end
def info(*) end
def warn(*) end
def error(*) end
def fatal(*) end
end
class << self
attr_accessor :logger
end
self.logger = NullLogger.new
end
| mit |
flyinghail/Hail-Framework | src/Jose/Exception/JWTException.php | 67 | <?php
namespace Hail\Jose\Exception;
interface JWTException
{
} | mit |
WaterlooSchedulingAssistant/wsa | db.js | 35094 | module.exports = {
apiKey: '<user api key>',
// All sizes are equal and persisted
// There are five columns with adjustable widths
// and the leftmost time column which has a fixed width
// The column size is calculated using the viewport width
// subtracted by the hour column width (a fixed value)
// If all columns do not fit, the table can be scrolled
// This % does not need to be 100% when multiplied by five
columnSize: 20, // %
// The hour height is set in pixels since there is no logical
// relative size to use
hourSize: 80, // px
// The selected term defaults to the next term
selected_term: 1171,
terms: [
{
id: 1151,
name: 'Winter 2015',
},
{
id: 1155,
name: 'Spring 2015',
},
{
id: 1159,
name: 'Fall 2015',
},
{
id: 1161,
name: 'Winter 2016',
},
{
id: 1165,
name: 'Spring 2016',
},
{
id: 1169,
name: 'Fall 2016',
},
{
id: 1171,
name: 'Winter 2017',
courses: [
{
subject: 'MATH',
catalog_number: '138',
units: 0.5,
title: 'Calculus 2 For Honours Mathematics',
note: null,
// We fetch all the sections of every course the user selects from a term
sections: [
{
// Used to select sections, note that this property will be automatically
// set to true for related components as well
selected: false,
// Provided by API
class_number: 5500,
section: 'LEC 001',
campus: 'UW U',
associated_class: 1,
related_component_1: null,
related_component_2: '201',
enrollment_capacity: 191,
enrollment_total: 191,
waiting_capacity: 0,
waiting_total: 0,
topic: null,
reserves: [],
classes: [
{
date: {
start_time: '14:30',
end_time: '15:20',
weekdays: 'MWF',
start_date: null,
end_date: null,
is_tba: false,
is_cancelled: false,
is_closed: false,
},
location: {
building: 'DC',
room: '1351',
},
instructors: [
'Hamilton,Jordan',
],
},
],
held_with: [],
term: 1171,
academic_level: 'undergraduate',
last_updated: '2016-12-14T10:09:36-05:00',
},
{
class_number: 5501,
section: 'LEC 002',
campus: 'UW U',
associated_class: 2,
related_component_1: null,
related_component_2: '201',
enrollment_capacity: 191,
enrollment_total: 191,
waiting_capacity: 0,
waiting_total: 0,
topic: null,
reserves: [],
classes: [
{
date: {
start_time: '09:30',
end_time: '10:20',
weekdays: 'MWF',
start_date: null,
end_date: null,
is_tba: false,
is_cancelled: false,
is_closed: false,
},
location: {
building: 'MC',
room: '2065',
},
instructors: [
'Hamilton,Jordan',
],
},
],
held_with: [],
term: 1171,
academic_level: 'undergraduate',
last_updated: '2016-12-14T10:09:36-05:00',
},
{
class_number: 5503,
section: 'LEC 004',
campus: 'UW U',
associated_class: 4,
related_component_1: null,
related_component_2: '201',
enrollment_capacity: 191,
enrollment_total: 181,
waiting_capacity: 0,
waiting_total: 0,
topic: null,
reserves: [
{
reserve_group: 'MATH ELAS students ',
enrollment_capacity: 10,
},
],
classes: [
{
date: {
start_time: '08:30',
end_time: '09:20',
weekdays: 'MWF',
start_date: null,
end_date: null,
is_tba: false,
is_cancelled: false,
is_closed: false,
},
location: {
building: 'MC',
room: '2065',
},
instructors: [
'Horvath,Tamas',
],
},
],
held_with: [],
term: 1171,
academic_level: 'undergraduate',
last_updated: '2016-12-14T10:09:36-05:00',
},
{
class_number: 5504,
section: 'LEC 005',
campus: 'UW U',
associated_class: 5,
related_component_1: '101',
related_component_2: '202',
enrollment_capacity: 140,
enrollment_total: 111,
waiting_capacity: 0,
waiting_total: 0,
topic: null,
reserves: [
{
reserve_group: 'MATHPHYS and PHYS students ',
enrollment_capacity: 140,
enrollment_total: 38,
},
],
classes: [
{
date: {
start_time: '13:30',
end_time: '14:20',
weekdays: 'MWF',
start_date: null,
end_date: null,
is_tba: false,
is_cancelled: false,
is_closed: false,
},
location: {
building: 'MC',
room: '2066',
},
instructors: [
'Vrscay,Edward R',
],
},
],
held_with: [],
term: 1171,
academic_level: 'undergraduate',
last_updated: '2016-12-14T10:09:36-05:00',
},
{
class_number: 5647,
section: 'TUT 101',
campus: 'UW U',
associated_class: 5,
related_component_1: null,
related_component_2: null,
enrollment_capacity: 140,
enrollment_total: 111,
waiting_capacity: 0,
waiting_total: 0,
topic: null,
reserves: [],
classes: [
{
date: {
start_time: '15:30',
end_time: '16:20',
weekdays: 'M',
start_date: null,
end_date: null,
is_tba: false,
is_cancelled: false,
is_closed: false,
},
location: {
building: 'STC',
room: '0020',
},
instructors: [],
},
],
held_with: [],
term: 1171,
academic_level: 'undergraduate',
last_updated: '2016-12-14T10:09:36-05:00',
},
{
class_number: 5716,
section: 'TST 201',
campus: 'UW U',
associated_class: 99,
related_component_1: '99',
related_component_2: null,
enrollment_capacity: 1717,
enrollment_total: 1352,
waiting_capacity: 0,
waiting_total: 0,
topic: null,
reserves: [],
classes: [
{
date: {
start_time: '19:00',
end_time: '20:50',
weekdays: 'M',
start_date: '02/13',
end_date: '02/13',
is_tba: false,
is_cancelled: false,
is_closed: false,
},
location: {
building: null,
room: null,
},
instructors: [],
},
],
held_with: [],
term: 1171,
academic_level: 'undergraduate',
last_updated: '2016-12-14T10:09:36-05:00',
},
],
},
{
subject: 'STAT',
catalog_number: '230',
units: 0.5,
title: 'Probability',
note: 'For LEC 002 and LEC 003 choose TUT section for Related 1.',
sections: [
{
class_number: 5421,
section: 'LEC 001',
campus: 'UW U',
associated_class: 1,
related_component_1: '101',
related_component_2: '201',
enrollment_capacity: 100,
enrollment_total: 79,
waiting_capacity: 0,
waiting_total: 0,
topic: null,
reserves: [
{
reserve_group: 'CS Majors (incl CFM and SE) ',
enrollment_capacity: 100,
enrollment_total: 78,
},
],
classes: [
{
date: {
start_time: '09:30',
end_time: '10:20',
weekdays: 'MWF',
start_date: null,
end_date: null,
is_tba: false,
is_cancelled: false,
is_closed: false,
},
location: {
building: 'RCH',
room: '211',
},
instructors: [
'Rice,Gregory',
],
},
],
held_with: [],
term: 1171,
academic_level: 'undergraduate',
last_updated: '2016-12-14T11:11:58-05:00',
},
{
class_number: 5846,
section: 'LEC 002',
campus: 'UW U',
associated_class: 2,
related_component_1: null,
related_component_2: '201',
enrollment_capacity: 170,
enrollment_total: 89,
waiting_capacity: 0,
waiting_total: 0,
topic: null,
reserves: [
{
reserve_group: 'Not open to CS Majors ',
enrollment_capacity: 170,
enrollment_total: 88,
},
],
classes: [
{
date: {
start_time: '11:30',
end_time: '12:20',
weekdays: 'MWF',
start_date: null,
end_date: null,
is_tba: false,
is_cancelled: false,
is_closed: false,
},
location: {
building: 'DC',
room: '1350',
},
instructors: [
'Skrzydlo,Diana Katherine',
],
},
],
held_with: [
'STAT 220',
],
term: 1171,
academic_level: 'undergraduate',
last_updated: '2016-12-14T11:11:58-05:00',
},
{
class_number: 9525,
section: 'LEC 003',
campus: 'UW U',
associated_class: 3,
related_component_1: null,
related_component_2: '201',
enrollment_capacity: 200,
enrollment_total: 148,
waiting_capacity: 0,
waiting_total: 0,
topic: null,
reserves: [
{
reserve_group: 'Not open to CS Majors ',
enrollment_capacity: 200,
enrollment_total: 148,
},
],
classes: [
{
date: {
start_time: '13:30',
end_time: '14:20',
weekdays: 'MWF',
start_date: null,
end_date: null,
is_tba: false,
is_cancelled: false,
is_closed: false,
},
location: {
building: 'DC',
room: '1351',
},
instructors: [
'Skrzydlo,Diana Katherine',
],
},
],
held_with: [],
term: 1171,
academic_level: 'undergraduate',
last_updated: '2016-12-14T11:11:58-05:00',
},
{
class_number: 5422,
section: 'TUT 101',
campus: 'UW U',
associated_class: 1,
related_component_1: null,
related_component_2: null,
enrollment_capacity: 100,
enrollment_total: 79,
waiting_capacity: 0,
waiting_total: 0,
topic: null,
reserves: [],
classes: [
{
date: {
start_time: '14:30',
end_time: '15:20',
weekdays: 'F',
start_date: null,
end_date: null,
is_tba: false,
is_cancelled: false,
is_closed: false,
},
location: {
building: 'AL',
room: '113',
},
instructors: [
'Rice,Gregory',
],
},
],
held_with: [],
term: 1171,
academic_level: 'undergraduate',
last_updated: '2016-12-14T11:11:58-05:00',
},
{
class_number: 6040,
section: 'TUT 102',
campus: 'UW U',
associated_class: 99,
related_component_1: '99',
related_component_2: null,
enrollment_capacity: 170,
enrollment_total: 135,
waiting_capacity: 0,
waiting_total: 0,
topic: null,
reserves: [],
classes: [
{
date: {
start_time: '15:30',
end_time: '16:20',
weekdays: 'F',
start_date: null,
end_date: null,
is_tba: false,
is_cancelled: false,
is_closed: false,
},
location: {
building: 'AL',
room: '113',
},
instructors: [
'Skrzydlo,Diana Katherine',
],
},
],
held_with: [],
term: 1171,
academic_level: 'undergraduate',
last_updated: '2016-12-14T11:11:58-05:00',
},
{
class_number: 9526,
section: 'TUT 103',
campus: 'UW U',
associated_class: 99,
related_component_1: '99',
related_component_2: null,
enrollment_capacity: 200,
enrollment_total: 102,
waiting_capacity: 0,
waiting_total: 0,
topic: null,
reserves: [],
classes: [
{
date: {
start_time: '10:30',
end_time: '11:20',
weekdays: 'Th',
start_date: null,
end_date: null,
is_tba: false,
is_cancelled: false,
is_closed: false,
},
location: {
building: 'AL',
room: '113',
},
instructors: [
'Skrzydlo,Diana Katherine',
],
},
],
held_with: [],
term: 1171,
academic_level: 'undergraduate',
last_updated: '2016-12-14T11:11:58-05:00',
},
{
class_number: 5709,
section: 'TST 201',
campus: 'UW U',
associated_class: 99,
related_component_1: '99',
related_component_2: null,
enrollment_capacity: 470,
enrollment_total: 316,
waiting_capacity: 0,
waiting_total: 0,
topic: null,
reserves: [],
classes: [
{
date: {
start_time: '16:30',
end_time: '18:20',
weekdays: 'Th',
start_date: '02/02',
end_date: '02/02',
is_tba: false,
is_cancelled: false,
is_closed: false,
},
location: {
building: null,
room: null,
},
instructors: [
'Skrzydlo,Diana Katherine',
],
},
{
date: {
start_time: '16:30',
end_time: '18:20',
weekdays: 'Th',
start_date: '03/09',
end_date: '03/09',
is_tba: false,
is_cancelled: false,
is_closed: false,
},
location: {
building: null,
room: null,
},
instructors: [
'Rice,Gregory',
'Skrzydlo,Diana Katherine',
],
},
],
held_with: [
'STAT 220',
],
term: 1171,
academic_level: 'undergraduate',
last_updated: '2016-12-14T11:11:58-05:00',
},
{
class_number: 7126,
section: 'LEC 081',
campus: 'ONLN ONLINE',
associated_class: 81,
related_component_1: null,
related_component_2: null,
enrollment_capacity: 70,
enrollment_total: 55,
waiting_capacity: 0,
waiting_total: 0,
topic: null,
reserves: [],
classes: [
{
date: {
start_time: null,
end_time: null,
weekdays: null,
start_date: null,
end_date: null,
is_tba: true,
is_cancelled: false,
is_closed: false,
},
location: {
building: null,
room: null,
},
instructors: [
'McLeish,Donald L',
],
},
],
held_with: [],
term: 1171,
academic_level: 'undergraduate',
last_updated: '2016-12-14T11:11:58-05:00',
},
],
},
{
subject: 'MATH',
catalog_number: '136',
units: 0.5,
title: 'Linear Algebra 1 for Honours Mathematics',
note: null,
sections: [
{
class_number: 5492,
section: 'LEC 001',
campus: 'UW U',
associated_class: 1,
related_component_1: null,
related_component_2: '201',
enrollment_capacity: 191,
enrollment_total: 191,
waiting_capacity: 0,
waiting_total: 0,
topic: null,
reserves: [],
classes: [
{
date: {
start_time: '09:30',
end_time: '10:20',
weekdays: 'MWF',
start_date: null,
end_date: null,
is_tba: false,
is_cancelled: false,
is_closed: false,
},
location: {
building: 'B1',
room: '271',
},
instructors: [
'Wolczuk,Dan Sean Terry',
],
},
],
held_with: [],
term: 1171,
academic_level: 'undergraduate',
last_updated: '2016-12-14T11:09:50-05:00',
},
{
class_number: 5493,
section: 'LEC 002',
campus: 'UW U',
associated_class: 2,
related_component_1: null,
related_component_2: '201',
enrollment_capacity: 191,
enrollment_total: 191,
waiting_capacity: 0,
waiting_total: 0,
topic: null,
reserves: [],
classes: [
{
date: {
start_time: '10:30',
end_time: '11:20',
weekdays: 'MWF',
start_date: null,
end_date: null,
is_tba: false,
is_cancelled: false,
is_closed: false,
},
location: {
building: 'MC',
room: '2066',
},
instructors: [
'Akash,Mukto',
],
},
],
held_with: [],
term: 1171,
academic_level: 'undergraduate',
last_updated: '2016-12-14T11:09:50-05:00',
},
{
class_number: 5494,
section: 'LEC 003',
campus: 'UW U',
associated_class: 3,
related_component_1: null,
related_component_2: '201',
enrollment_capacity: 191,
enrollment_total: 190,
waiting_capacity: 0,
waiting_total: 0,
topic: null,
reserves: [],
classes: [
{
date: {
start_time: '09:30',
end_time: '10:20',
weekdays: 'MWF',
start_date: null,
end_date: null,
is_tba: false,
is_cancelled: false,
is_closed: false,
},
location: {
building: 'MC',
room: '2066',
},
instructors: [
'Akash,Mukto',
],
},
],
held_with: [],
term: 1171,
academic_level: 'undergraduate',
last_updated: '2016-12-14T11:09:50-05:00',
},
{
class_number: 5495,
section: 'LEC 004',
campus: 'UW U',
associated_class: 4,
related_component_1: null,
related_component_2: '201',
enrollment_capacity: 191,
enrollment_total: 157,
waiting_capacity: 0,
waiting_total: 0,
topic: null,
reserves: [],
classes: [
{
date: {
start_time: '11:30',
end_time: '12:20',
weekdays: 'MWF',
start_date: null,
end_date: null,
is_tba: false,
is_cancelled: false,
is_closed: false,
},
location: {
building: 'AL',
room: '113',
},
instructors: [
'Andre,Robert',
],
},
],
held_with: [],
term: 1171,
academic_level: 'undergraduate',
last_updated: '2016-12-14T11:09:50-05:00',
},
{
class_number: 5496,
section: 'LEC 005',
campus: 'UW U',
associated_class: 5,
related_component_1: null,
related_component_2: '201',
enrollment_capacity: 191,
enrollment_total: 134,
waiting_capacity: 0,
waiting_total: 0,
topic: null,
reserves: [],
classes: [
{
date: {
start_time: '08:30',
end_time: '09:20',
weekdays: 'MWF',
start_date: null,
end_date: null,
is_tba: false,
is_cancelled: false,
is_closed: false,
},
location: {
building: 'MC',
room: '2066',
},
instructors: [
'Andre,Robert',
],
},
],
held_with: [],
term: 1171,
academic_level: 'undergraduate',
last_updated: '2016-12-14T11:09:50-05:00',
},
{
class_number: 5497,
section: 'LEC 006',
campus: 'UW U',
associated_class: 6,
related_component_1: null,
related_component_2: '201',
enrollment_capacity: 191,
enrollment_total: 128,
waiting_capacity: 0,
waiting_total: 0,
topic: null,
reserves: [],
classes: [
{
date: {
start_time: '12:30',
end_time: '13:20',
weekdays: 'MWF',
start_date: null,
end_date: null,
is_tba: false,
is_cancelled: false,
is_closed: false,
},
location: {
building: 'PHY',
room: '145',
},
instructors: [
'Gianniotis,Panagiotis',
],
},
],
held_with: [],
term: 1171,
academic_level: 'undergraduate',
last_updated: '2016-12-14T11:09:50-05:00',
},
{
class_number: 5644,
section: 'LEC 007',
campus: 'UW J',
associated_class: 7,
related_component_1: null,
related_component_2: '201',
enrollment_capacity: 60,
enrollment_total: 60,
waiting_capacity: 0,
waiting_total: 0,
topic: null,
reserves: [],
classes: [
{
date: {
start_time: '08:30',
end_time: '09:20',
weekdays: 'MWF',
start_date: null,
end_date: null,
is_tba: false,
is_cancelled: false,
is_closed: false,
},
location: {
building: 'SJ1',
room: '3014',
},
instructors: [
'Trelford,Ryan',
],
},
],
held_with: [],
term: 1171,
academic_level: 'undergraduate',
last_updated: '2016-12-14T11:09:50-05:00',
},
{
class_number: 5806,
section: 'LEC 008',
campus: 'UW U',
associated_class: 8,
related_component_1: null,
related_component_2: '201',
enrollment_capacity: 191,
enrollment_total: 76,
waiting_capacity: 0,
waiting_total: 0,
topic: null,
reserves: [],
classes: [
{
date: {
start_time: '12:30',
end_time: '13:20',
weekdays: 'MWF',
start_date: null,
end_date: null,
is_tba: false,
is_cancelled: false,
is_closed: false,
},
location: {
building: 'B1',
room: '271',
},
instructors: [
'Roh,Patrick Young',
],
},
],
held_with: [],
term: 1171,
academic_level: 'undergraduate',
last_updated: '2016-12-14T11:09:50-05:00',
},
{
class_number: 7828,
section: 'LEC 009',
campus: 'UW U',
associated_class: 9,
related_component_1: null,
related_component_2: '201',
enrollment_capacity: 191,
enrollment_total: 191,
waiting_capacity: 0,
waiting_total: 0,
topic: null,
reserves: [],
classes: [
{
date: {
start_time: '11:30',
end_time: '12:20',
weekdays: 'MWF',
start_date: null,
end_date: null,
is_tba: false,
is_cancelled: false,
is_closed: false,
},
location: {
building: 'MC',
room: '2065',
},
instructors: [
'Park,Doug',
],
},
],
held_with: [],
term: 1171,
academic_level: 'undergraduate',
last_updated: '2016-12-14T11:09:50-05:00',
},
{
class_number: 5715,
section: 'TST 201',
campus: 'UW U',
associated_class: 99,
related_component_1: '99',
related_component_2: null,
enrollment_capacity: 1588,
enrollment_total: 1318,
waiting_capacity: 0,
waiting_total: 0,
topic: null,
reserves: [],
classes: [
{
date: {
start_time: '19:00',
end_time: '20:50',
weekdays: 'M',
start_date: '02/06',
end_date: '02/06',
is_tba: false,
is_cancelled: false,
is_closed: false,
},
location: {
building: null,
room: null,
},
instructors: [],
},
],
held_with: [],
term: 1171,
academic_level: 'undergraduate',
last_updated: '2016-12-14T11:09:50-05:00',
},
{
class_number: 7113,
section: 'LEC 081',
campus: 'ONLN ONLINE',
associated_class: 81,
related_component_1: null,
related_component_2: null,
enrollment_capacity: 80,
enrollment_total: 22,
waiting_capacity: 0,
waiting_total: 0,
topic: null,
reserves: [
{
reserve_group: 'No first year CFM students ',
enrollment_capacity: 80,
enrollment_total: 22,
},
],
classes: [
{
date: {
start_time: null,
end_time: null,
weekdays: null,
start_date: null,
end_date: null,
is_tba: true,
is_cancelled: false,
is_closed: false,
},
location: {
building: null,
room: null,
},
instructors: [
'Vicente Colmenares,Alejandra',
],
},
],
held_with: [],
term: 1171,
academic_level: 'undergraduate',
last_updated: '2016-12-14T11:09:50-05:00',
},
],
},
],
},
{
id: 1175,
name: 'Spring 2017',
},
{
id: 1179,
name: 'Fall 2017',
},
],
};
| mit |
adaltas/node-nikita | packages/docker/lib/rmi.js | 1828 | // Generated by CoffeeScript 2.6.1
// # `nikita.docker.rmi`
// Remove images. All container using image should be stopped to delete it unless
// force options is set.
// ## Output
// * `err`
// Error object if any.
// * `status`
// True if image was removed.
// ## Schema definitions
var definitions, handler;
definitions = {
config: {
type: 'object',
properties: {
'cwd': {
type: 'string',
description: `Change the build working directory.`
},
'docker': {
$ref: 'module://@nikitajs/docker/lib/tools/execute#/definitions/docker'
},
'image': {
type: 'string',
description: `Name of the Docker image present in the registry.`
},
'no_prune': {
type: 'boolean',
description: `Do not delete untagged parents.`
},
'tag': {
type: 'string',
description: `Tag of the Docker image, default to latest.`
}
},
required: ['image']
}
};
// ## Handler
handler = async function({config}) {
await this.docker.tools.execute({
command: ['images', `| grep '${config.image} '`, config.tag != null ? `| grep ' ${config.tag} '` : void 0].join(' '),
code_skipped: [1]
});
return (await this.docker.tools.execute({
$if: function({parent}) {
return parent.parent.tools.status(-1);
},
command: [
'rmi',
['force',
'no_prune'].filter(function(opt) {
return config[opt] != null;
}).map(function(opt) {
return ` --${opt.replace('_',
'-')}`;
}),
` ${config.image}`,
config.tag != null ? `:${config.tag}` : void 0
].join('')
}));
};
// ## Exports
module.exports = {
handler: handler,
metadata: {
argument_to_config: 'image',
global: 'docker',
definitions: definitions
}
};
| mit |
Vincent0209/simple-rtmp-server | trunk/src/protocol/srs_protocol_io.hpp | 5519 | /*
The MIT License (MIT)
Copyright (c) 2013-2015 SRS(simple-rtmp-server)
Permission is hereby granted, free of charge, to any person obtaining a copy of
this software and associated documentation files (the "Software"), to deal in
the Software without restriction, including without limitation the rights to
use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
the Software, and to permit persons to whom the Software is furnished to do so,
subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
#ifndef SRS_PROTOCOL_IO_HPP
#define SRS_PROTOCOL_IO_HPP
/*
#include <srs_protocol_io.hpp>
*/
#include <srs_core.hpp>
// for srs-librtmp, @see https://github.com/simple-rtmp-server/srs/issues/213
#ifndef _WIN32
#include <sys/uio.h>
#endif
/**
* the system io reader/writer architecture:
+---------------+ +--------------------+ +---------------+
| IBufferReader | | IStatistic | | IBufferWriter |
+---------------+ +--------------------+ +---------------+
| + read() | | + get_recv_bytes() | | + write() |
+------+--------+ | + get_recv_bytes() | | + writev() |
/ \ +---+--------------+-+ +-------+-------+
| / \ / \ / \
| | | |
+------+------------------+-+ +-----+----------------+--+
| IProtocolReader | | IProtocolWriter |
+---------------------------+ +-------------------------+
| + readfully() | | + set_send_timeout() |
| + set_recv_timeout() | +-------+-----------------+
+------------+--------------+ / \
/ \ |
| |
+--+-----------------------------+-+
| IProtocolReaderWriter |
+----------------------------------+
| + is_never_timeout() |
+----------------------------------+
*/
/**
* the reader for the buffer to read from whatever channel.
*/
class ISrsBufferReader
{
public:
ISrsBufferReader();
virtual ~ISrsBufferReader();
// for protocol/amf0/msg-codec
public:
virtual int read(void* buf, size_t size, ssize_t* nread) = 0;
};
/**
* the writer for the buffer to write to whatever channel.
*/
class ISrsBufferWriter
{
public:
ISrsBufferWriter();
virtual ~ISrsBufferWriter();
// for protocol
public:
/**
* write bytes over writer.
* @nwrite the actual written bytes. NULL to ignore.
*/
virtual int write(void* buf, size_t size, ssize_t* nwrite) = 0;
/**
* write iov over writer.
* @nwrite the actual written bytes. NULL to ignore.
*/
virtual int writev(const iovec *iov, int iov_size, ssize_t* nwrite) = 0;
};
/**
* get the statistic of channel.
*/
class ISrsProtocolStatistic
{
public:
ISrsProtocolStatistic();
virtual ~ISrsProtocolStatistic();
// for protocol
public:
/**
* get the total recv bytes over underlay fd.
*/
virtual int64_t get_recv_bytes() = 0;
/**
* get the total send bytes over underlay fd.
*/
virtual int64_t get_send_bytes() = 0;
};
/**
* the reader for the protocol to read from whatever channel.
*/
class ISrsProtocolReader : public virtual ISrsBufferReader, public virtual ISrsProtocolStatistic
{
public:
ISrsProtocolReader();
virtual ~ISrsProtocolReader();
// for protocol
public:
/**
* set the recv timeout in us, recv will error when timeout.
* @remark, if not set, use ST_UTIME_NO_TIMEOUT, never timeout.
*/
virtual void set_recv_timeout(int64_t timeout_us) = 0;
/**
* get the recv timeout in us.
*/
virtual int64_t get_recv_timeout() = 0;
// for handshake.
public:
/**
* read specified size bytes of data
* @param nread, the actually read size, NULL to ignore.
*/
virtual int read_fully(void* buf, size_t size, ssize_t* nread) = 0;
};
/**
* the writer for the protocol to write to whatever channel.
*/
class ISrsProtocolWriter : public virtual ISrsBufferWriter, public virtual ISrsProtocolStatistic
{
public:
ISrsProtocolWriter();
virtual ~ISrsProtocolWriter();
// for protocol
public:
/**
* set the send timeout in us, send will error when timeout.
* @remark, if not set, use ST_UTIME_NO_TIMEOUT, never timeout.
*/
virtual void set_send_timeout(int64_t timeout_us) = 0;
/**
* get the send timeout in us.
*/
virtual int64_t get_send_timeout() = 0;
};
/**
* the reader and writer.
*/
class ISrsProtocolReaderWriter : public virtual ISrsProtocolReader, public virtual ISrsProtocolWriter
{
public:
ISrsProtocolReaderWriter();
virtual ~ISrsProtocolReaderWriter();
// for protocol
public:
/**
* whether the specified timeout_us is never timeout.
*/
virtual bool is_never_timeout(int64_t timeout_us) = 0;
};
#endif
| mit |
lgollut/material-ui | docs/src/pages/components/steppers/HorizontalLinearStepper.tsx | 4312 | import React from 'react';
import { makeStyles, Theme, createStyles } from '@material-ui/core/styles';
import Stepper from '@material-ui/core/Stepper';
import Step from '@material-ui/core/Step';
import StepLabel from '@material-ui/core/StepLabel';
import Button from '@material-ui/core/Button';
import Typography from '@material-ui/core/Typography';
const useStyles = makeStyles((theme: Theme) =>
createStyles({
root: {
width: '100%',
},
button: {
marginRight: theme.spacing(1),
},
instructions: {
marginTop: theme.spacing(1),
marginBottom: theme.spacing(1),
},
}),
);
function getSteps() {
return ['Select campaign settings', 'Create an ad group', 'Create an ad'];
}
function getStepContent(step: number) {
switch (step) {
case 0:
return 'Select campaign settings...';
case 1:
return 'What is an ad group anyways?';
case 2:
return 'This is the bit I really care about!';
default:
return 'Unknown step';
}
}
export default function HorizontalLinearStepper() {
const classes = useStyles();
const [activeStep, setActiveStep] = React.useState(0);
const [skipped, setSkipped] = React.useState(new Set<number>());
const steps = getSteps();
const isStepOptional = (step: number) => {
return step === 1;
};
const isStepSkipped = (step: number) => {
return skipped.has(step);
};
const handleNext = () => {
let newSkipped = skipped;
if (isStepSkipped(activeStep)) {
newSkipped = new Set(newSkipped.values());
newSkipped.delete(activeStep);
}
setActiveStep((prevActiveStep) => prevActiveStep + 1);
setSkipped(newSkipped);
};
const handleBack = () => {
setActiveStep((prevActiveStep) => prevActiveStep - 1);
};
const handleSkip = () => {
if (!isStepOptional(activeStep)) {
// You probably want to guard against something like this,
// it should never occur unless someone's actively trying to break something.
throw new Error("You can't skip a step that isn't optional.");
}
setActiveStep((prevActiveStep) => prevActiveStep + 1);
setSkipped((prevSkipped) => {
const newSkipped = new Set(prevSkipped.values());
newSkipped.add(activeStep);
return newSkipped;
});
};
const handleReset = () => {
setActiveStep(0);
};
return (
<div className={classes.root}>
<Stepper activeStep={activeStep}>
{steps.map((label, index) => {
const stepProps: { completed?: boolean } = {};
const labelProps: { optional?: React.ReactNode } = {};
if (isStepOptional(index)) {
labelProps.optional = <Typography variant="caption">Optional</Typography>;
}
if (isStepSkipped(index)) {
stepProps.completed = false;
}
return (
<Step key={label} {...stepProps}>
<StepLabel {...labelProps}>{label}</StepLabel>
</Step>
);
})}
</Stepper>
<div>
{activeStep === steps.length ? (
<div>
<Typography className={classes.instructions}>
All steps completed - you're finished
</Typography>
<Button onClick={handleReset} className={classes.button}>
Reset
</Button>
</div>
) : (
<div>
<Typography className={classes.instructions}>{getStepContent(activeStep)}</Typography>
<div>
<Button disabled={activeStep === 0} onClick={handleBack} className={classes.button}>
Back
</Button>
{isStepOptional(activeStep) && (
<Button
variant="contained"
color="primary"
onClick={handleSkip}
className={classes.button}
>
Skip
</Button>
)}
<Button
variant="contained"
color="primary"
onClick={handleNext}
className={classes.button}
>
{activeStep === steps.length - 1 ? 'Finish' : 'Next'}
</Button>
</div>
</div>
)}
</div>
</div>
);
}
| mit |
mjelks/webvideo | rating.php | 362 | <?php
require_once 'src/VideoLibrary.php';
$library = new VideoLibrary();
$library->updateRating($_REQUEST['movie'], $_REQUEST['rating']);
?>
<div class="alert alert-dismissable alert-success">
<button type="button" class="close" data-dismiss="alert">ร</button>
<strong>We have updated the rating to : </strong> <?php print $_REQUEST['rating']; ?>.
</div> | mit |
QuinntyneBrown/azure-search-getting-started | src/Chloe/wwwroot/video/video.component.ts | 478 | import { CanActivate, ChangeDetectionStrategy, Component } from "../core";
import { VideoActionCreator } from "./video.actions";
@Component({
template: require("./video.component.html"),
styles: require("./video.component.css"),
selector: "video",
viewProviders: ["videoActionCreator"],
inputs:["video"],
changeDetection: ChangeDetectionStrategy.OnPush
})
export class VideoComponent {
constructor(private videoActionCreator: VideoActionCreator) { }
}
| mit |
SomMeri/simplesamples | src/main/java/meristuff/blog/simplesamples/utils/PubliclyCloneable.java | 138 | package meristuff.blog.simplesamples.utils;
public interface PubliclyCloneable extends Cloneable {
public PubliclyCloneable clone();
}
| mit |
git-pull-request/php-git | Tests/GitCommand/ConfigTraitTest.php | 1939 | <?php
/*
* This file is part of git-pull-request/git.
*
* (c) Julien Dufresne <https://github.com/git-pull-request/git>
*
* For the full copyright and license information, please view
* the LICENSE file that was distributed with this source code.
*/
declare(strict_types=1);
namespace GitPullRequest\Git\Tests\GitCommand;
use GitPullRequest\Git\GitCommand\ConfigTrait;
use PHPUnit_Framework_TestCase;
use Symfony\Component\Process\Process;
/**
* Test of the trait ConfigTrait.
*/
final class ConfigTraitTest extends PHPUnit_Framework_TestCase
{
use GitTestTrait;
/** @var ConfigTrait */
private $object;
protected function setUp()
{
$this->object = $this->getObjectForTrait(ConfigTrait::class);
$this->prepareWorkingDirectory();
}
protected function tearDown()
{
$this->cleanWorkingDirectory();
}
public function testSetUserEmail()
{
$name = 'github@dfrsn.me';
static::assertTrue($this->object->setUserEmail($name));
$output = explode(PHP_EOL, (new Process('git config --list'))->mustRun()->getOutput());
$found = false;
foreach ($output as $line) {
$line = trim($line);
if ($line === 'user.email='.$name) {
$found = true;
break;
}
}
static::assertTrue($found, 'user.email should be set');
}
public function testSetUserName()
{
$name = 'Julien Dufresne';
static::assertTrue($this->object->setUserName($name));
$output = explode(PHP_EOL, (new Process('git config --list'))->mustRun()->getOutput());
$found = false;
foreach ($output as $line) {
$line = trim($line);
if ($line === 'user.name='.$name) {
$found = true;
break;
}
}
static::assertTrue($found, 'user.name should be set');
}
}
| mit |
tbruyelle/buildnumber-maven-plugin | src/main/java/org/codehaus/mojo/build/HgChangeSetMojo.java | 5295 | package org.codehaus.mojo.build;
/*
* Copyright 2001-2005 The Apache Software Foundation.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import java.io.File;
import org.apache.maven.plugin.AbstractMojo;
import org.apache.maven.plugin.MojoExecutionException;
import org.apache.maven.project.MavenProject;
import org.apache.maven.scm.ScmException;
import org.apache.maven.scm.ScmFileStatus;
import org.apache.maven.scm.ScmResult;
import org.apache.maven.scm.log.ScmLogDispatcher;
import org.apache.maven.scm.log.ScmLogger;
import org.apache.maven.scm.provider.hg.HgUtils;
import org.apache.maven.scm.provider.hg.command.HgConsumer;
import org.codehaus.plexus.util.StringUtils;
/**
* Goal which sets project properties for changeSet and changeSetDate from the
* current Mercurial repository.
*
* @author Tomas Pollak
* @goal hgchangeset
* @requiresProject
* @since 1.0-beta-4
*/
public class HgChangeSetMojo
extends AbstractMojo
{
private ScmLogDispatcher logger = new ScmLogDispatcher();
/**
* The maven project.
*
* @parameter expression="${project}"
* @readonly
*/
private MavenProject project;
/**
* Local directory to be used to issue SCM actions
*
* @parameter expression="${maven.changeSet.scmDirectory}" default-value="${basedir}
* @since 1.0
*/
private File scmDirectory;
private void checkResult( ScmResult result )
throws MojoExecutionException
{
if ( !result.isSuccess() )
{
getLog().debug( "Provider message:" );
getLog().debug( result.getProviderMessage() == null ? "" : result.getProviderMessage() );
getLog().debug( "Command output:" );
getLog().debug( result.getCommandOutput() == null ? "" : result.getCommandOutput() );
throw new MojoExecutionException( "Command failed."
+ StringUtils.defaultString( result.getProviderMessage() ) );
}
}
public void execute()
throws MojoExecutionException
{
try
{
String previousChangeSet = getChangeSetProperty();
String previousChangeSetDate = getChangeSetDateProperty();
if ( previousChangeSet == null || previousChangeSetDate == null )
{
String changeSet = getChangeSet();
String changeSetDate = getChangeSetDate();
getLog().info( "Setting Mercurial Changeset: " + changeSet );
getLog().info( "Setting Mercurial Changeset Date: " + changeSetDate );
setChangeSetProperty( changeSet );
setChangeSetDateProperty( changeSetDate );
}
}
catch ( ScmException e )
{
throw new MojoExecutionException( "SCM Exception", e );
}
}
protected String getChangeSet()
throws ScmException, MojoExecutionException
{
HgOutputConsumer consumer = new HgOutputConsumer( logger );
ScmResult result = HgUtils.execute( consumer, logger, scmDirectory, new String[] { "id", "-i" } );
checkResult( result );
return consumer.getOutput();
}
protected String getChangeSetDate()
throws ScmException, MojoExecutionException
{
HgOutputConsumer consumer = new HgOutputConsumer( logger );
ScmResult result =
HgUtils.execute( consumer, logger, scmDirectory, new String[] { "log", "-r", ".",
"--template", "\"{date|isodate}\"" } );
checkResult( result );
return consumer.getOutput();
}
protected String getChangeSetDateProperty()
{
return getProperty( "changeSetDate" );
}
protected String getChangeSetProperty()
{
return getProperty( "changeSet" );
}
protected String getProperty( String property )
{
return project.getProperties().getProperty( property );
}
private void setChangeSetDateProperty( String changeSetDate )
{
setProperty( "changeSetDate", changeSetDate );
}
private void setChangeSetProperty( String changeSet )
{
setProperty( "changeSet", changeSet );
}
private void setProperty( String property, String value )
{
if ( value != null )
{
project.getProperties().put( property, value );
}
}
private static class HgOutputConsumer
extends HgConsumer
{
private String output;
private HgOutputConsumer( ScmLogger logger )
{
super( logger );
}
public void doConsume( ScmFileStatus status, String line )
{
output = line;
}
private String getOutput()
{
return output;
}
}
}
| mit |
Opiumtm/Imageboard10 | Imageboard10/CodeTemplates/Esent/Model/EsentSetIndexRangeGrbit.cs | 151 | ๏ปฟnamespace CodeTemplates.Esent.Model
{
public enum EsentSetIndexRangeGrbit
{
Inclusive = 0x0001,
UpperLimit = 0x0002,
}
} | mit |
shaiun/devopsbuddy | src/test/java/com/devopsbuddy/DevopsbuddyApplicationTests.java | 972 | package com.devopsbuddy;
import com.devopsbuddy.backend.service.I18NService;
import org.junit.Assert;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.context.web.WebAppConfiguration;
import org.springframework.boot.test.SpringApplicationConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
@RunWith(SpringJUnit4ClassRunner.class)
@SpringApplicationConfiguration(classes = DevopsbuddyApplication.class)
@WebAppConfiguration
public class DevopsbuddyApplicationTests {
@Autowired
private I18NService i18NService;
@Test
public void testMessageByLocaleService() throws Exception {
String expectedResult = "Bootstrap starter template";
String messageId = "index.main.callout";
String actual = i18NService.getMessage(messageId);
Assert.assertEquals("The actual and expected Strings don't match", expectedResult, actual);
}
} | mit |
camspiers/Bayes | scripts/lib/d3.v2.js | 234916 | //Copyright (c) 2012, Michael Bostock
//All rights reserved.
//
//Redistribution and use in source and binary forms, with or without
//modification, are permitted provided that the following conditions are met:
//
//* Redistributions of source code must retain the above copyright notice, this
// list of conditions and the following disclaimer.
//
//* Redistributions in binary form must reproduce the above copyright notice,
// this list of conditions and the following disclaimer in the documentation
// and/or other materials provided with the distribution.
//
//* The name Michael Bostock may not be used to endorse or promote products
// derived from this software without specific prior written permission.
//
//THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
//AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
//IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
//DISCLAIMED. IN NO EVENT SHALL MICHAEL BOSTOCK BE LIABLE FOR ANY DIRECT,
//INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
//BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
//DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
//OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
//NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE,
//EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
(function() {
if (!Date.now) Date.now = function() {
return +(new Date);
};
try {
document.createElement("div").style.setProperty("opacity", 0, "");
} catch (error) {
var d3_style_prototype = CSSStyleDeclaration.prototype, d3_style_setProperty = d3_style_prototype.setProperty;
d3_style_prototype.setProperty = function(name, value, priority) {
d3_style_setProperty.call(this, name, value + "", priority);
};
}
d3 = {
version: "2.9.7"
};
function d3_class(ctor, properties) {
try {
for (var key in properties) {
Object.defineProperty(ctor.prototype, key, {
value: properties[key],
enumerable: false
});
}
} catch (e) {
ctor.prototype = properties;
}
}
var d3_array = d3_arraySlice;
function d3_arrayCopy(pseudoarray) {
var i = -1, n = pseudoarray.length, array = [];
while (++i < n) array.push(pseudoarray[i]);
return array;
}
function d3_arraySlice(pseudoarray) {
return Array.prototype.slice.call(pseudoarray);
}
try {
d3_array(document.documentElement.childNodes)[0].nodeType;
} catch (e) {
d3_array = d3_arrayCopy;
}
var d3_arraySubclass = [].__proto__ ? function(array, prototype) {
array.__proto__ = prototype;
} : function(array, prototype) {
for (var property in prototype) array[property] = prototype[property];
};
d3.map = function(object) {
var map = new d3_Map;
for (var key in object) map.set(key, object[key]);
return map;
};
function d3_Map() {}
d3_class(d3_Map, {
has: function(key) {
return d3_map_prefix + key in this;
},
get: function(key) {
return this[d3_map_prefix + key];
},
set: function(key, value) {
return this[d3_map_prefix + key] = value;
},
remove: function(key) {
key = d3_map_prefix + key;
return key in this && delete this[key];
},
keys: function() {
var keys = [];
this.forEach(function(key) {
keys.push(key);
});
return keys;
},
values: function() {
var values = [];
this.forEach(function(key, value) {
values.push(value);
});
return values;
},
entries: function() {
var entries = [];
this.forEach(function(key, value) {
entries.push({
key: key,
value: value
});
});
return entries;
},
forEach: function(f) {
for (var key in this) {
if (key.charCodeAt(0) === d3_map_prefixCode) {
f.call(this, key.substring(1), this[key]);
}
}
}
});
var d3_map_prefix = "\0", d3_map_prefixCode = d3_map_prefix.charCodeAt(0);
function d3_identity(d) {
return d;
}
function d3_this() {
return this;
}
function d3_true() {
return true;
}
function d3_functor(v) {
return typeof v === "function" ? v : function() {
return v;
};
}
d3.functor = d3_functor;
d3.rebind = function(target, source) {
var i = 1, n = arguments.length, method;
while (++i < n) target[method = arguments[i]] = d3_rebind(target, source, source[method]);
return target;
};
function d3_rebind(target, source, method) {
return function() {
var value = method.apply(source, arguments);
return arguments.length ? target : value;
};
}
d3.ascending = function(a, b) {
return a < b ? -1 : a > b ? 1 : a >= b ? 0 : NaN;
};
d3.descending = function(a, b) {
return b < a ? -1 : b > a ? 1 : b >= a ? 0 : NaN;
};
d3.mean = function(array, f) {
var n = array.length, a, m = 0, i = -1, j = 0;
if (arguments.length === 1) {
while (++i < n) if (d3_number(a = array[i])) m += (a - m) / ++j;
} else {
while (++i < n) if (d3_number(a = f.call(array, array[i], i))) m += (a - m) / ++j;
}
return j ? m : undefined;
};
d3.median = function(array, f) {
if (arguments.length > 1) array = array.map(f);
array = array.filter(d3_number);
return array.length ? d3.quantile(array.sort(d3.ascending), .5) : undefined;
};
d3.min = function(array, f) {
var i = -1, n = array.length, a, b;
if (arguments.length === 1) {
while (++i < n && ((a = array[i]) == null || a != a)) a = undefined;
while (++i < n) if ((b = array[i]) != null && a > b) a = b;
} else {
while (++i < n && ((a = f.call(array, array[i], i)) == null || a != a)) a = undefined;
while (++i < n) if ((b = f.call(array, array[i], i)) != null && a > b) a = b;
}
return a;
};
d3.max = function(array, f) {
var i = -1, n = array.length, a, b;
if (arguments.length === 1) {
while (++i < n && ((a = array[i]) == null || a != a)) a = undefined;
while (++i < n) if ((b = array[i]) != null && b > a) a = b;
} else {
while (++i < n && ((a = f.call(array, array[i], i)) == null || a != a)) a = undefined;
while (++i < n) if ((b = f.call(array, array[i], i)) != null && b > a) a = b;
}
return a;
};
d3.extent = function(array, f) {
var i = -1, n = array.length, a, b, c;
if (arguments.length === 1) {
while (++i < n && ((a = c = array[i]) == null || a != a)) a = c = undefined;
while (++i < n) if ((b = array[i]) != null) {
if (a > b) a = b;
if (c < b) c = b;
}
} else {
while (++i < n && ((a = c = f.call(array, array[i], i)) == null || a != a)) a = undefined;
while (++i < n) if ((b = f.call(array, array[i], i)) != null) {
if (a > b) a = b;
if (c < b) c = b;
}
}
return [ a, c ];
};
d3.random = {
normal: function(mean, deviation) {
if (arguments.length < 2) deviation = 1;
if (arguments.length < 1) mean = 0;
return function() {
var x, y, r;
do {
x = Math.random() * 2 - 1;
y = Math.random() * 2 - 1;
r = x * x + y * y;
} while (!r || r > 1);
return mean + deviation * x * Math.sqrt(-2 * Math.log(r) / r);
};
}
};
function d3_number(x) {
return x != null && !isNaN(x);
}
d3.sum = function(array, f) {
var s = 0, n = array.length, a, i = -1;
if (arguments.length === 1) {
while (++i < n) if (!isNaN(a = +array[i])) s += a;
} else {
while (++i < n) if (!isNaN(a = +f.call(array, array[i], i))) s += a;
}
return s;
};
d3.quantile = function(values, p) {
var H = (values.length - 1) * p + 1, h = Math.floor(H), v = values[h - 1], e = H - h;
return e ? v + e * (values[h] - v) : v;
};
d3.transpose = function(matrix) {
return d3.zip.apply(d3, matrix);
};
d3.zip = function() {
if (!(n = arguments.length)) return [];
for (var i = -1, m = d3.min(arguments, d3_zipLength), zips = new Array(m); ++i < m; ) {
for (var j = -1, n, zip = zips[i] = new Array(n); ++j < n; ) {
zip[j] = arguments[j][i];
}
}
return zips;
};
function d3_zipLength(d) {
return d.length;
}
d3.bisector = function(f) {
return {
left: function(a, x, lo, hi) {
if (arguments.length < 3) lo = 0;
if (arguments.length < 4) hi = a.length;
while (lo < hi) {
var mid = lo + hi >>> 1;
if (f.call(a, a[mid], mid) < x) lo = mid + 1; else hi = mid;
}
return lo;
},
right: function(a, x, lo, hi) {
if (arguments.length < 3) lo = 0;
if (arguments.length < 4) hi = a.length;
while (lo < hi) {
var mid = lo + hi >>> 1;
if (x < f.call(a, a[mid], mid)) hi = mid; else lo = mid + 1;
}
return lo;
}
};
};
var d3_bisector = d3.bisector(function(d) {
return d;
});
d3.bisectLeft = d3_bisector.left;
d3.bisect = d3.bisectRight = d3_bisector.right;
d3.first = function(array, f) {
var i = 0, n = array.length, a = array[0], b;
if (arguments.length === 1) f = d3.ascending;
while (++i < n) {
if (f.call(array, a, b = array[i]) > 0) {
a = b;
}
}
return a;
};
d3.last = function(array, f) {
var i = 0, n = array.length, a = array[0], b;
if (arguments.length === 1) f = d3.ascending;
while (++i < n) {
if (f.call(array, a, b = array[i]) <= 0) {
a = b;
}
}
return a;
};
d3.nest = function() {
var nest = {}, keys = [], sortKeys = [], sortValues, rollup;
function map(array, depth) {
if (depth >= keys.length) return rollup ? rollup.call(nest, array) : sortValues ? array.sort(sortValues) : array;
var i = -1, n = array.length, key = keys[depth++], keyValue, object, valuesByKey = new d3_Map, values, o = {};
while (++i < n) {
if (values = valuesByKey.get(keyValue = key(object = array[i]))) {
values.push(object);
} else {
valuesByKey.set(keyValue, [ object ]);
}
}
valuesByKey.forEach(function(keyValue) {
o[keyValue] = map(valuesByKey.get(keyValue), depth);
});
return o;
}
function entries(map, depth) {
if (depth >= keys.length) return map;
var a = [], sortKey = sortKeys[depth++], key;
for (key in map) {
a.push({
key: key,
values: entries(map[key], depth)
});
}
if (sortKey) a.sort(function(a, b) {
return sortKey(a.key, b.key);
});
return a;
}
nest.map = function(array) {
return map(array, 0);
};
nest.entries = function(array) {
return entries(map(array, 0), 0);
};
nest.key = function(d) {
keys.push(d);
return nest;
};
nest.sortKeys = function(order) {
sortKeys[keys.length - 1] = order;
return nest;
};
nest.sortValues = function(order) {
sortValues = order;
return nest;
};
nest.rollup = function(f) {
rollup = f;
return nest;
};
return nest;
};
d3.keys = function(map) {
var keys = [];
for (var key in map) keys.push(key);
return keys;
};
d3.values = function(map) {
var values = [];
for (var key in map) values.push(map[key]);
return values;
};
d3.entries = function(map) {
var entries = [];
for (var key in map) entries.push({
key: key,
value: map[key]
});
return entries;
};
d3.permute = function(array, indexes) {
var permutes = [], i = -1, n = indexes.length;
while (++i < n) permutes[i] = array[indexes[i]];
return permutes;
};
d3.merge = function(arrays) {
return Array.prototype.concat.apply([], arrays);
};
d3.split = function(array, f) {
var arrays = [], values = [], value, i = -1, n = array.length;
if (arguments.length < 2) f = d3_splitter;
while (++i < n) {
if (f.call(values, value = array[i], i)) {
values = [];
} else {
if (!values.length) arrays.push(values);
values.push(value);
}
}
return arrays;
};
function d3_splitter(d) {
return d == null;
}
function d3_collapse(s) {
return s.replace(/^\s+|\s+$/g, "").replace(/\s+/g, " ");
}
d3.range = function(start, stop, step) {
if (arguments.length < 3) {
step = 1;
if (arguments.length < 2) {
stop = start;
start = 0;
}
}
if ((stop - start) / step === Infinity) throw new Error("infinite range");
var range = [], k = d3_range_integerScale(Math.abs(step)), i = -1, j;
start *= k, stop *= k, step *= k;
if (step < 0) while ((j = start + step * ++i) > stop) range.push(j / k); else while ((j = start + step * ++i) < stop) range.push(j / k);
return range;
};
function d3_range_integerScale(x) {
var k = 1;
while (x * k % 1) k *= 10;
return k;
}
d3.requote = function(s) {
return s.replace(d3_requote_re, "\\$&");
};
var d3_requote_re = /[\\\^\$\*\+\?\|\[\]\(\)\.\{\}]/g;
d3.round = function(x, n) {
return n ? Math.round(x * (n = Math.pow(10, n))) / n : Math.round(x);
};
d3.xhr = function(url, mime, callback) {
var req = new XMLHttpRequest;
if (arguments.length < 3) callback = mime, mime = null; else if (mime && req.overrideMimeType) req.overrideMimeType(mime);
req.open("GET", url, true);
if (mime) req.setRequestHeader("Accept", mime);
req.onreadystatechange = function() {
if (req.readyState === 4) {
var s = req.status;
callback(!s && req.response || s >= 200 && s < 300 || s === 304 ? req : null);
}
};
req.send(null);
};
d3.text = function(url, mime, callback) {
function ready(req) {
callback(req && req.responseText);
}
if (arguments.length < 3) {
callback = mime;
mime = null;
}
d3.xhr(url, mime, ready);
};
d3.json = function(url, callback) {
d3.text(url, "application/json", function(text) {
callback(text ? JSON.parse(text) : null);
});
};
d3.html = function(url, callback) {
d3.text(url, "text/html", function(text) {
if (text != null) {
var range = document.createRange();
range.selectNode(document.body);
text = range.createContextualFragment(text);
}
callback(text);
});
};
d3.xml = function(url, mime, callback) {
function ready(req) {
callback(req && req.responseXML);
}
if (arguments.length < 3) {
callback = mime;
mime = null;
}
d3.xhr(url, mime, ready);
};
var d3_nsPrefix = {
svg: "http://www.w3.org/2000/svg",
xhtml: "http://www.w3.org/1999/xhtml",
xlink: "http://www.w3.org/1999/xlink",
xml: "http://www.w3.org/XML/1998/namespace",
xmlns: "http://www.w3.org/2000/xmlns/"
};
d3.ns = {
prefix: d3_nsPrefix,
qualify: function(name) {
var i = name.indexOf(":"), prefix = name;
if (i >= 0) {
prefix = name.substring(0, i);
name = name.substring(i + 1);
}
return d3_nsPrefix.hasOwnProperty(prefix) ? {
space: d3_nsPrefix[prefix],
local: name
} : name;
}
};
d3.dispatch = function() {
var dispatch = new d3_dispatch, i = -1, n = arguments.length;
while (++i < n) dispatch[arguments[i]] = d3_dispatch_event(dispatch);
return dispatch;
};
function d3_dispatch() {}
d3_dispatch.prototype.on = function(type, listener) {
var i = type.indexOf("."), name = "";
if (i > 0) {
name = type.substring(i + 1);
type = type.substring(0, i);
}
return arguments.length < 2 ? this[type].on(name) : this[type].on(name, listener);
};
function d3_dispatch_event(dispatch) {
var listeners = [], listenerByName = new d3_Map;
function event() {
var z = listeners, i = -1, n = z.length, l;
while (++i < n) if (l = z[i].on) l.apply(this, arguments);
return dispatch;
}
event.on = function(name, listener) {
var l = listenerByName.get(name), i;
if (arguments.length < 2) return l && l.on;
if (l) {
l.on = null;
listeners = listeners.slice(0, i = listeners.indexOf(l)).concat(listeners.slice(i + 1));
listenerByName.remove(name);
}
if (listener) listeners.push(listenerByName.set(name, {
on: listener
}));
return dispatch;
};
return event;
}
d3.format = function(specifier) {
var match = d3_format_re.exec(specifier), fill = match[1] || " ", sign = match[3] || "", zfill = match[5], width = +match[6], comma = match[7], precision = match[8], type = match[9], scale = 1, suffix = "", integer = false;
if (precision) precision = +precision.substring(1);
if (zfill) {
fill = "0";
if (comma) width -= Math.floor((width - 1) / 4);
}
switch (type) {
case "n":
comma = true;
type = "g";
break;
case "%":
scale = 100;
suffix = "%";
type = "f";
break;
case "p":
scale = 100;
suffix = "%";
type = "r";
break;
case "d":
integer = true;
precision = 0;
break;
case "s":
scale = -1;
type = "r";
break;
}
if (type == "r" && !precision) type = "g";
type = d3_format_types.get(type) || d3_format_typeDefault;
return function(value) {
if (integer && value % 1) return "";
var negative = value < 0 && (value = -value) ? "โ" : sign;
if (scale < 0) {
var prefix = d3.formatPrefix(value, precision);
value = prefix.scale(value);
suffix = prefix.symbol;
} else {
value *= scale;
}
value = type(value, precision);
if (zfill) {
var length = value.length + negative.length;
if (length < width) value = (new Array(width - length + 1)).join(fill) + value;
if (comma) value = d3_format_group(value);
value = negative + value;
} else {
if (comma) value = d3_format_group(value);
value = negative + value;
var length = value.length;
if (length < width) value = (new Array(width - length + 1)).join(fill) + value;
}
return value + suffix;
};
};
var d3_format_re = /(?:([^{])?([<>=^]))?([+\- ])?(#)?(0)?([0-9]+)?(,)?(\.[0-9]+)?([a-zA-Z%])?/;
var d3_format_types = d3.map({
g: function(x, p) {
return x.toPrecision(p);
},
e: function(x, p) {
return x.toExponential(p);
},
f: function(x, p) {
return x.toFixed(p);
},
r: function(x, p) {
return d3.round(x, p = d3_format_precision(x, p)).toFixed(Math.max(0, Math.min(20, p)));
}
});
function d3_format_precision(x, p) {
return p - (x ? 1 + Math.floor(Math.log(x + Math.pow(10, 1 + Math.floor(Math.log(x) / Math.LN10) - p)) / Math.LN10) : 1);
}
function d3_format_typeDefault(x) {
return x + "";
}
function d3_format_group(value) {
var i = value.lastIndexOf("."), f = i >= 0 ? value.substring(i) : (i = value.length, ""), t = [];
while (i > 0) t.push(value.substring(i -= 3, i + 3));
return t.reverse().join(",") + f;
}
var d3_formatPrefixes = [ "y", "z", "a", "f", "p", "n", "ฮผ", "m", "", "k", "M", "G", "T", "P", "E", "Z", "Y" ].map(d3_formatPrefix);
d3.formatPrefix = function(value, precision) {
var i = 0;
if (value) {
if (value < 0) value *= -1;
if (precision) value = d3.round(value, d3_format_precision(value, precision));
i = 1 + Math.floor(1e-12 + Math.log(value) / Math.LN10);
i = Math.max(-24, Math.min(24, Math.floor((i <= 0 ? i + 1 : i - 1) / 3) * 3));
}
return d3_formatPrefixes[8 + i / 3];
};
function d3_formatPrefix(d, i) {
var k = Math.pow(10, Math.abs(8 - i) * 3);
return {
scale: i > 8 ? function(d) {
return d / k;
} : function(d) {
return d * k;
},
symbol: d
};
}
var d3_ease_quad = d3_ease_poly(2), d3_ease_cubic = d3_ease_poly(3), d3_ease_default = function() {
return d3_ease_identity;
};
var d3_ease = d3.map({
linear: d3_ease_default,
poly: d3_ease_poly,
quad: function() {
return d3_ease_quad;
},
cubic: function() {
return d3_ease_cubic;
},
sin: function() {
return d3_ease_sin;
},
exp: function() {
return d3_ease_exp;
},
circle: function() {
return d3_ease_circle;
},
elastic: d3_ease_elastic,
back: d3_ease_back,
bounce: function() {
return d3_ease_bounce;
}
});
var d3_ease_mode = d3.map({
"in": d3_ease_identity,
out: d3_ease_reverse,
"in-out": d3_ease_reflect,
"out-in": function(f) {
return d3_ease_reflect(d3_ease_reverse(f));
}
});
d3.ease = function(name) {
var i = name.indexOf("-"), t = i >= 0 ? name.substring(0, i) : name, m = i >= 0 ? name.substring(i + 1) : "in";
t = d3_ease.get(t) || d3_ease_default;
m = d3_ease_mode.get(m) || d3_ease_identity;
return d3_ease_clamp(m(t.apply(null, Array.prototype.slice.call(arguments, 1))));
};
function d3_ease_clamp(f) {
return function(t) {
return t <= 0 ? 0 : t >= 1 ? 1 : f(t);
};
}
function d3_ease_reverse(f) {
return function(t) {
return 1 - f(1 - t);
};
}
function d3_ease_reflect(f) {
return function(t) {
return .5 * (t < .5 ? f(2 * t) : 2 - f(2 - 2 * t));
};
}
function d3_ease_identity(t) {
return t;
}
function d3_ease_poly(e) {
return function(t) {
return Math.pow(t, e);
};
}
function d3_ease_sin(t) {
return 1 - Math.cos(t * Math.PI / 2);
}
function d3_ease_exp(t) {
return Math.pow(2, 10 * (t - 1));
}
function d3_ease_circle(t) {
return 1 - Math.sqrt(1 - t * t);
}
function d3_ease_elastic(a, p) {
var s;
if (arguments.length < 2) p = .45;
if (arguments.length < 1) {
a = 1;
s = p / 4;
} else s = p / (2 * Math.PI) * Math.asin(1 / a);
return function(t) {
return 1 + a * Math.pow(2, 10 * -t) * Math.sin((t - s) * 2 * Math.PI / p);
};
}
function d3_ease_back(s) {
if (!s) s = 1.70158;
return function(t) {
return t * t * ((s + 1) * t - s);
};
}
function d3_ease_bounce(t) {
return t < 1 / 2.75 ? 7.5625 * t * t : t < 2 / 2.75 ? 7.5625 * (t -= 1.5 / 2.75) * t + .75 : t < 2.5 / 2.75 ? 7.5625 * (t -= 2.25 / 2.75) * t + .9375 : 7.5625 * (t -= 2.625 / 2.75) * t + .984375;
}
d3.event = null;
function d3_eventCancel() {
d3.event.stopPropagation();
d3.event.preventDefault();
}
function d3_eventSource() {
var e = d3.event, s;
while (s = e.sourceEvent) e = s;
return e;
}
function d3_eventDispatch(target) {
var dispatch = new d3_dispatch, i = 0, n = arguments.length;
while (++i < n) dispatch[arguments[i]] = d3_dispatch_event(dispatch);
dispatch.of = function(thiz, argumentz) {
return function(e1) {
try {
var e0 = e1.sourceEvent = d3.event;
e1.target = target;
d3.event = e1;
dispatch[e1.type].apply(thiz, argumentz);
} finally {
d3.event = e0;
}
};
};
return dispatch;
}
d3.transform = function(string) {
var g = document.createElementNS(d3.ns.prefix.svg, "g");
return (d3.transform = function(string) {
g.setAttribute("transform", string);
var t = g.transform.baseVal.consolidate();
return new d3_transform(t ? t.matrix : d3_transformIdentity);
})(string);
};
function d3_transform(m) {
var r0 = [ m.a, m.b ], r1 = [ m.c, m.d ], kx = d3_transformNormalize(r0), kz = d3_transformDot(r0, r1), ky = d3_transformNormalize(d3_transformCombine(r1, r0, -kz)) || 0;
if (r0[0] * r1[1] < r1[0] * r0[1]) {
r0[0] *= -1;
r0[1] *= -1;
kx *= -1;
kz *= -1;
}
this.rotate = (kx ? Math.atan2(r0[1], r0[0]) : Math.atan2(-r1[0], r1[1])) * d3_transformDegrees;
this.translate = [ m.e, m.f ];
this.scale = [ kx, ky ];
this.skew = ky ? Math.atan2(kz, ky) * d3_transformDegrees : 0;
}
d3_transform.prototype.toString = function() {
return "translate(" + this.translate + ")rotate(" + this.rotate + ")skewX(" + this.skew + ")scale(" + this.scale + ")";
};
function d3_transformDot(a, b) {
return a[0] * b[0] + a[1] * b[1];
}
function d3_transformNormalize(a) {
var k = Math.sqrt(d3_transformDot(a, a));
if (k) {
a[0] /= k;
a[1] /= k;
}
return k;
}
function d3_transformCombine(a, b, k) {
a[0] += k * b[0];
a[1] += k * b[1];
return a;
}
var d3_transformDegrees = 180 / Math.PI, d3_transformIdentity = {
a: 1,
b: 0,
c: 0,
d: 1,
e: 0,
f: 0
};
d3.interpolate = function(a, b) {
var i = d3.interpolators.length, f;
while (--i >= 0 && !(f = d3.interpolators[i](a, b))) ;
return f;
};
d3.interpolateNumber = function(a, b) {
b -= a;
return function(t) {
return a + b * t;
};
};
d3.interpolateRound = function(a, b) {
b -= a;
return function(t) {
return Math.round(a + b * t);
};
};
d3.interpolateString = function(a, b) {
var m, i, j, s0 = 0, s1 = 0, s = [], q = [], n, o;
d3_interpolate_number.lastIndex = 0;
for (i = 0; m = d3_interpolate_number.exec(b); ++i) {
if (m.index) s.push(b.substring(s0, s1 = m.index));
q.push({
i: s.length,
x: m[0]
});
s.push(null);
s0 = d3_interpolate_number.lastIndex;
}
if (s0 < b.length) s.push(b.substring(s0));
for (i = 0, n = q.length; (m = d3_interpolate_number.exec(a)) && i < n; ++i) {
o = q[i];
if (o.x == m[0]) {
if (o.i) {
if (s[o.i + 1] == null) {
s[o.i - 1] += o.x;
s.splice(o.i, 1);
for (j = i + 1; j < n; ++j) q[j].i--;
} else {
s[o.i - 1] += o.x + s[o.i + 1];
s.splice(o.i, 2);
for (j = i + 1; j < n; ++j) q[j].i -= 2;
}
} else {
if (s[o.i + 1] == null) {
s[o.i] = o.x;
} else {
s[o.i] = o.x + s[o.i + 1];
s.splice(o.i + 1, 1);
for (j = i + 1; j < n; ++j) q[j].i--;
}
}
q.splice(i, 1);
n--;
i--;
} else {
o.x = d3.interpolateNumber(parseFloat(m[0]), parseFloat(o.x));
}
}
while (i < n) {
o = q.pop();
if (s[o.i + 1] == null) {
s[o.i] = o.x;
} else {
s[o.i] = o.x + s[o.i + 1];
s.splice(o.i + 1, 1);
}
n--;
}
if (s.length === 1) {
return s[0] == null ? q[0].x : function() {
return b;
};
}
return function(t) {
for (i = 0; i < n; ++i) s[(o = q[i]).i] = o.x(t);
return s.join("");
};
};
d3.interpolateTransform = function(a, b) {
if (n = d3_interpolateTransformSimilar(a, b)) return n;
var s = [], q = [], n, A = d3.transform(a), B = d3.transform(b), ta = A.translate, tb = B.translate, ra = A.rotate, rb = B.rotate, wa = A.skew, wb = B.skew, ka = A.scale, kb = B.scale;
if (ta[0] != tb[0] || ta[1] != tb[1]) {
s.push("translate(", null, ",", null, ")");
q.push({
i: 1,
x: d3.interpolateNumber(ta[0], tb[0])
}, {
i: 3,
x: d3.interpolateNumber(ta[1], tb[1])
});
} else if (tb[0] || tb[1]) {
s.push("translate(" + tb + ")");
} else {
s.push("");
}
if (ra != rb) {
if (ra - rb > 180) rb += 360; else if (rb - ra > 180) ra += 360;
q.push({
i: s.push(s.pop() + "rotate(", null, ")") - 2,
x: d3.interpolateNumber(ra, rb)
});
} else if (rb) {
s.push(s.pop() + "rotate(" + rb + ")");
}
if (wa != wb) {
q.push({
i: s.push(s.pop() + "skewX(", null, ")") - 2,
x: d3.interpolateNumber(wa, wb)
});
} else if (wb) {
s.push(s.pop() + "skewX(" + wb + ")");
}
if (ka[0] != kb[0] || ka[1] != kb[1]) {
n = s.push(s.pop() + "scale(", null, ",", null, ")");
q.push({
i: n - 4,
x: d3.interpolateNumber(ka[0], kb[0])
}, {
i: n - 2,
x: d3.interpolateNumber(ka[1], kb[1])
});
} else if (kb[0] != 1 || kb[1] != 1) {
s.push(s.pop() + "scale(" + kb + ")");
}
n = q.length;
return function(t) {
var i = -1, o;
while (++i < n) s[(o = q[i]).i] = o.x(t);
return s.join("");
};
};
var d3_interpolateTransformTypes = [ "", "", "translate", "scale", "rotate", "skewX", "skewY" ];
var d3_interpolateTransformSimilar = function(a, b) {
var ga = document.createElementNS(d3.ns.prefix.svg, "g"), gb = document.createElementNS(d3.ns.prefix.svg, "g");
return (d3_interpolateTransformSimilar = function(a, b) {
ga.setAttribute("transform", a);
gb.setAttribute("transform", b);
a = ga.transform.baseVal;
b = gb.transform.baseVal;
var sa = [], sb = [], i = -1, n = a.numberOfItems, m = b.numberOfItems, ta, tb, type;
if (m !== n) {
if (!m) b = d3_interpolateTransformIdentity(a); else if (!n) a = d3_interpolateTransformIdentity(b), n = m; else return;
} else if (!m) return;
while (++i < n) {
ta = a.getItem(i);
tb = b.getItem(i);
type = ta.type;
if (type !== tb.type || !type) return;
switch (type) {
case 1:
{
sa.push(new d3_transform(ta.matrix));
sb.push(new d3_transform(tb.matrix));
continue;
}
case 2:
{
ra = ta.matrix.e + "," + ta.matrix.f;
rb = tb.matrix.e + "," + tb.matrix.f;
break;
}
case 3:
{
ra = ta.matrix.a + "," + ta.matrix.d;
rb = tb.matrix.a + "," + tb.matrix.d;
break;
}
default:
{
ra = ta.angle;
rb = tb.angle;
}
}
sa.push(type = d3_interpolateTransformTypes[type], "(", ra, ")");
sb.push(type, "(", rb, ")");
}
return d3.interpolateString(sa.join(""), sb.join(""));
})(a, b);
};
function d3_interpolateTransformIdentity(a) {
return {
getItem: function(i) {
return {
type: a.getItem(i).type,
angle: 0,
matrix: d3_transformIdentity
};
}
};
}
d3.interpolateRgb = function(a, b) {
a = d3.rgb(a);
b = d3.rgb(b);
var ar = a.r, ag = a.g, ab = a.b, br = b.r - ar, bg = b.g - ag, bb = b.b - ab;
return function(t) {
return "#" + d3_rgb_hex(Math.round(ar + br * t)) + d3_rgb_hex(Math.round(ag + bg * t)) + d3_rgb_hex(Math.round(ab + bb * t));
};
};
d3.interpolateHsl = function(a, b) {
a = d3.hsl(a);
b = d3.hsl(b);
var h0 = a.h, s0 = a.s, l0 = a.l, h1 = b.h - h0, s1 = b.s - s0, l1 = b.l - l0;
if (h1 > 180) h1 -= 360; else if (h1 < -180) h1 += 360;
return function(t) {
return d3_hsl_rgb(h0 + h1 * t, s0 + s1 * t, l0 + l1 * t).toString();
};
};
d3.interpolateArray = function(a, b) {
var x = [], c = [], na = a.length, nb = b.length, n0 = Math.min(a.length, b.length), i;
for (i = 0; i < n0; ++i) x.push(d3.interpolate(a[i], b[i]));
for (; i < na; ++i) c[i] = a[i];
for (; i < nb; ++i) c[i] = b[i];
return function(t) {
for (i = 0; i < n0; ++i) c[i] = x[i](t);
return c;
};
};
d3.interpolateObject = function(a, b) {
var i = {}, c = {}, k;
for (k in a) {
if (k in b) {
i[k] = d3_interpolateByName(k)(a[k], b[k]);
} else {
c[k] = a[k];
}
}
for (k in b) {
if (!(k in a)) {
c[k] = b[k];
}
}
return function(t) {
for (k in i) c[k] = i[k](t);
return c;
};
};
var d3_interpolate_number = /[-+]?(?:\d+\.?\d*|\.?\d+)(?:[eE][-+]?\d+)?/g;
function d3_interpolateByName(n) {
return n == "transform" ? d3.interpolateTransform : d3.interpolate;
}
d3.interpolators = [ d3.interpolateObject, function(a, b) {
return b instanceof Array && d3.interpolateArray(a, b);
}, function(a, b) {
return (typeof a === "string" || typeof b === "string") && d3.interpolateString(a + "", b + "");
}, function(a, b) {
return (typeof b === "string" ? d3_rgb_names.has(b) || /^(#|rgb\(|hsl\()/.test(b) : b instanceof d3_Rgb || b instanceof d3_Hsl) && d3.interpolateRgb(a, b);
}, function(a, b) {
return !isNaN(a = +a) && !isNaN(b = +b) && d3.interpolateNumber(a, b);
} ];
function d3_uninterpolateNumber(a, b) {
b = b - (a = +a) ? 1 / (b - a) : 0;
return function(x) {
return (x - a) * b;
};
}
function d3_uninterpolateClamp(a, b) {
b = b - (a = +a) ? 1 / (b - a) : 0;
return function(x) {
return Math.max(0, Math.min(1, (x - a) * b));
};
}
d3.rgb = function(r, g, b) {
return arguments.length === 1 ? r instanceof d3_Rgb ? d3_rgb(r.r, r.g, r.b) : d3_rgb_parse("" + r, d3_rgb, d3_hsl_rgb) : d3_rgb(~~r, ~~g, ~~b);
};
function d3_rgb(r, g, b) {
return new d3_Rgb(r, g, b);
}
function d3_Rgb(r, g, b) {
this.r = r;
this.g = g;
this.b = b;
}
d3_Rgb.prototype.brighter = function(k) {
k = Math.pow(.7, arguments.length ? k : 1);
var r = this.r, g = this.g, b = this.b, i = 30;
if (!r && !g && !b) return d3_rgb(i, i, i);
if (r && r < i) r = i;
if (g && g < i) g = i;
if (b && b < i) b = i;
return d3_rgb(Math.min(255, Math.floor(r / k)), Math.min(255, Math.floor(g / k)), Math.min(255, Math.floor(b / k)));
};
d3_Rgb.prototype.darker = function(k) {
k = Math.pow(.7, arguments.length ? k : 1);
return d3_rgb(Math.floor(k * this.r), Math.floor(k * this.g), Math.floor(k * this.b));
};
d3_Rgb.prototype.hsl = function() {
return d3_rgb_hsl(this.r, this.g, this.b);
};
d3_Rgb.prototype.toString = function() {
return "#" + d3_rgb_hex(this.r) + d3_rgb_hex(this.g) + d3_rgb_hex(this.b);
};
function d3_rgb_hex(v) {
return v < 16 ? "0" + Math.max(0, v).toString(16) : Math.min(255, v).toString(16);
}
function d3_rgb_parse(format, rgb, hsl) {
var r = 0, g = 0, b = 0, m1, m2, name;
m1 = /([a-z]+)\((.*)\)/i.exec(format);
if (m1) {
m2 = m1[2].split(",");
switch (m1[1]) {
case "hsl":
{
return hsl(parseFloat(m2[0]), parseFloat(m2[1]) / 100, parseFloat(m2[2]) / 100);
}
case "rgb":
{
return rgb(d3_rgb_parseNumber(m2[0]), d3_rgb_parseNumber(m2[1]), d3_rgb_parseNumber(m2[2]));
}
}
}
if (name = d3_rgb_names.get(format)) return rgb(name.r, name.g, name.b);
if (format != null && format.charAt(0) === "#") {
if (format.length === 4) {
r = format.charAt(1);
r += r;
g = format.charAt(2);
g += g;
b = format.charAt(3);
b += b;
} else if (format.length === 7) {
r = format.substring(1, 3);
g = format.substring(3, 5);
b = format.substring(5, 7);
}
r = parseInt(r, 16);
g = parseInt(g, 16);
b = parseInt(b, 16);
}
return rgb(r, g, b);
}
function d3_rgb_hsl(r, g, b) {
var min = Math.min(r /= 255, g /= 255, b /= 255), max = Math.max(r, g, b), d = max - min, h, s, l = (max + min) / 2;
if (d) {
s = l < .5 ? d / (max + min) : d / (2 - max - min);
if (r == max) h = (g - b) / d + (g < b ? 6 : 0); else if (g == max) h = (b - r) / d + 2; else h = (r - g) / d + 4;
h *= 60;
} else {
s = h = 0;
}
return d3_hsl(h, s, l);
}
function d3_rgb_parseNumber(c) {
var f = parseFloat(c);
return c.charAt(c.length - 1) === "%" ? Math.round(f * 2.55) : f;
}
var d3_rgb_names = d3.map({
aliceblue: "#f0f8ff",
antiquewhite: "#faebd7",
aqua: "#00ffff",
aquamarine: "#7fffd4",
azure: "#f0ffff",
beige: "#f5f5dc",
bisque: "#ffe4c4",
black: "#000000",
blanchedalmond: "#ffebcd",
blue: "#0000ff",
blueviolet: "#8a2be2",
brown: "#a52a2a",
burlywood: "#deb887",
cadetblue: "#5f9ea0",
chartreuse: "#7fff00",
chocolate: "#d2691e",
coral: "#ff7f50",
cornflowerblue: "#6495ed",
cornsilk: "#fff8dc",
crimson: "#dc143c",
cyan: "#00ffff",
darkblue: "#00008b",
darkcyan: "#008b8b",
darkgoldenrod: "#b8860b",
darkgray: "#a9a9a9",
darkgreen: "#006400",
darkgrey: "#a9a9a9",
darkkhaki: "#bdb76b",
darkmagenta: "#8b008b",
darkolivegreen: "#556b2f",
darkorange: "#ff8c00",
darkorchid: "#9932cc",
darkred: "#8b0000",
darksalmon: "#e9967a",
darkseagreen: "#8fbc8f",
darkslateblue: "#483d8b",
darkslategray: "#2f4f4f",
darkslategrey: "#2f4f4f",
darkturquoise: "#00ced1",
darkviolet: "#9400d3",
deeppink: "#ff1493",
deepskyblue: "#00bfff",
dimgray: "#696969",
dimgrey: "#696969",
dodgerblue: "#1e90ff",
firebrick: "#b22222",
floralwhite: "#fffaf0",
forestgreen: "#228b22",
fuchsia: "#ff00ff",
gainsboro: "#dcdcdc",
ghostwhite: "#f8f8ff",
gold: "#ffd700",
goldenrod: "#daa520",
gray: "#808080",
green: "#008000",
greenyellow: "#adff2f",
grey: "#808080",
honeydew: "#f0fff0",
hotpink: "#ff69b4",
indianred: "#cd5c5c",
indigo: "#4b0082",
ivory: "#fffff0",
khaki: "#f0e68c",
lavender: "#e6e6fa",
lavenderblush: "#fff0f5",
lawngreen: "#7cfc00",
lemonchiffon: "#fffacd",
lightblue: "#add8e6",
lightcoral: "#f08080",
lightcyan: "#e0ffff",
lightgoldenrodyellow: "#fafad2",
lightgray: "#d3d3d3",
lightgreen: "#90ee90",
lightgrey: "#d3d3d3",
lightpink: "#ffb6c1",
lightsalmon: "#ffa07a",
lightseagreen: "#20b2aa",
lightskyblue: "#87cefa",
lightslategray: "#778899",
lightslategrey: "#778899",
lightsteelblue: "#b0c4de",
lightyellow: "#ffffe0",
lime: "#00ff00",
limegreen: "#32cd32",
linen: "#faf0e6",
magenta: "#ff00ff",
maroon: "#800000",
mediumaquamarine: "#66cdaa",
mediumblue: "#0000cd",
mediumorchid: "#ba55d3",
mediumpurple: "#9370db",
mediumseagreen: "#3cb371",
mediumslateblue: "#7b68ee",
mediumspringgreen: "#00fa9a",
mediumturquoise: "#48d1cc",
mediumvioletred: "#c71585",
midnightblue: "#191970",
mintcream: "#f5fffa",
mistyrose: "#ffe4e1",
moccasin: "#ffe4b5",
navajowhite: "#ffdead",
navy: "#000080",
oldlace: "#fdf5e6",
olive: "#808000",
olivedrab: "#6b8e23",
orange: "#ffa500",
orangered: "#ff4500",
orchid: "#da70d6",
palegoldenrod: "#eee8aa",
palegreen: "#98fb98",
paleturquoise: "#afeeee",
palevioletred: "#db7093",
papayawhip: "#ffefd5",
peachpuff: "#ffdab9",
peru: "#cd853f",
pink: "#ffc0cb",
plum: "#dda0dd",
powderblue: "#b0e0e6",
purple: "#800080",
red: "#ff0000",
rosybrown: "#bc8f8f",
royalblue: "#4169e1",
saddlebrown: "#8b4513",
salmon: "#fa8072",
sandybrown: "#f4a460",
seagreen: "#2e8b57",
seashell: "#fff5ee",
sienna: "#a0522d",
silver: "#c0c0c0",
skyblue: "#87ceeb",
slateblue: "#6a5acd",
slategray: "#708090",
slategrey: "#708090",
snow: "#fffafa",
springgreen: "#00ff7f",
steelblue: "#4682b4",
tan: "#d2b48c",
teal: "#008080",
thistle: "#d8bfd8",
tomato: "#ff6347",
turquoise: "#40e0d0",
violet: "#ee82ee",
wheat: "#f5deb3",
white: "#ffffff",
whitesmoke: "#f5f5f5",
yellow: "#ffff00",
yellowgreen: "#9acd32"
});
d3_rgb_names.forEach(function(key, value) {
d3_rgb_names.set(key, d3_rgb_parse(value, d3_rgb, d3_hsl_rgb));
});
d3.hsl = function(h, s, l) {
return arguments.length === 1 ? h instanceof d3_Hsl ? d3_hsl(h.h, h.s, h.l) : d3_rgb_parse("" + h, d3_rgb_hsl, d3_hsl) : d3_hsl(+h, +s, +l);
};
function d3_hsl(h, s, l) {
return new d3_Hsl(h, s, l);
}
function d3_Hsl(h, s, l) {
this.h = h;
this.s = s;
this.l = l;
}
d3_Hsl.prototype.brighter = function(k) {
k = Math.pow(.7, arguments.length ? k : 1);
return d3_hsl(this.h, this.s, this.l / k);
};
d3_Hsl.prototype.darker = function(k) {
k = Math.pow(.7, arguments.length ? k : 1);
return d3_hsl(this.h, this.s, k * this.l);
};
d3_Hsl.prototype.rgb = function() {
return d3_hsl_rgb(this.h, this.s, this.l);
};
d3_Hsl.prototype.toString = function() {
return this.rgb().toString();
};
function d3_hsl_rgb(h, s, l) {
var m1, m2;
h = h % 360;
if (h < 0) h += 360;
s = s < 0 ? 0 : s > 1 ? 1 : s;
l = l < 0 ? 0 : l > 1 ? 1 : l;
m2 = l <= .5 ? l * (1 + s) : l + s - l * s;
m1 = 2 * l - m2;
function v(h) {
if (h > 360) h -= 360; else if (h < 0) h += 360;
if (h < 60) return m1 + (m2 - m1) * h / 60;
if (h < 180) return m2;
if (h < 240) return m1 + (m2 - m1) * (240 - h) / 60;
return m1;
}
function vv(h) {
return Math.round(v(h) * 255);
}
return d3_rgb(vv(h + 120), vv(h), vv(h - 120));
}
function d3_selection(groups) {
d3_arraySubclass(groups, d3_selectionPrototype);
return groups;
}
var d3_select = function(s, n) {
return n.querySelector(s);
}, d3_selectAll = function(s, n) {
return n.querySelectorAll(s);
}, d3_selectRoot = document.documentElement, d3_selectMatcher = d3_selectRoot.matchesSelector || d3_selectRoot.webkitMatchesSelector || d3_selectRoot.mozMatchesSelector || d3_selectRoot.msMatchesSelector || d3_selectRoot.oMatchesSelector, d3_selectMatches = function(n, s) {
return d3_selectMatcher.call(n, s);
};
if (typeof Sizzle === "function") {
d3_select = function(s, n) {
return Sizzle(s, n)[0] || null;
};
d3_selectAll = function(s, n) {
return Sizzle.uniqueSort(Sizzle(s, n));
};
d3_selectMatches = Sizzle.matchesSelector;
}
var d3_selectionPrototype = [];
d3.selection = function() {
return d3_selectionRoot;
};
d3.selection.prototype = d3_selectionPrototype;
d3_selectionPrototype.select = function(selector) {
var subgroups = [], subgroup, subnode, group, node;
if (typeof selector !== "function") selector = d3_selection_selector(selector);
for (var j = -1, m = this.length; ++j < m; ) {
subgroups.push(subgroup = []);
subgroup.parentNode = (group = this[j]).parentNode;
for (var i = -1, n = group.length; ++i < n; ) {
if (node = group[i]) {
subgroup.push(subnode = selector.call(node, node.__data__, i));
if (subnode && "__data__" in node) subnode.__data__ = node.__data__;
} else {
subgroup.push(null);
}
}
}
return d3_selection(subgroups);
};
function d3_selection_selector(selector) {
return function() {
return d3_select(selector, this);
};
}
d3_selectionPrototype.selectAll = function(selector) {
var subgroups = [], subgroup, node;
if (typeof selector !== "function") selector = d3_selection_selectorAll(selector);
for (var j = -1, m = this.length; ++j < m; ) {
for (var group = this[j], i = -1, n = group.length; ++i < n; ) {
if (node = group[i]) {
subgroups.push(subgroup = d3_array(selector.call(node, node.__data__, i)));
subgroup.parentNode = node;
}
}
}
return d3_selection(subgroups);
};
function d3_selection_selectorAll(selector) {
return function() {
return d3_selectAll(selector, this);
};
}
d3_selectionPrototype.attr = function(name, value) {
name = d3.ns.qualify(name);
if (arguments.length < 2) {
var node = this.node();
return name.local ? node.getAttributeNS(name.space, name.local) : node.getAttribute(name);
}
function attrNull() {
this.removeAttribute(name);
}
function attrNullNS() {
this.removeAttributeNS(name.space, name.local);
}
function attrConstant() {
this.setAttribute(name, value);
}
function attrConstantNS() {
this.setAttributeNS(name.space, name.local, value);
}
function attrFunction() {
var x = value.apply(this, arguments);
if (x == null) this.removeAttribute(name); else this.setAttribute(name, x);
}
function attrFunctionNS() {
var x = value.apply(this, arguments);
if (x == null) this.removeAttributeNS(name.space, name.local); else this.setAttributeNS(name.space, name.local, x);
}
return this.each(value == null ? name.local ? attrNullNS : attrNull : typeof value === "function" ? name.local ? attrFunctionNS : attrFunction : name.local ? attrConstantNS : attrConstant);
};
d3_selectionPrototype.classed = function(name, value) {
var names = d3_collapse(name).split(" "), n = names.length, i = -1;
if (arguments.length > 1) {
while (++i < n) d3_selection_classed.call(this, names[i], value);
return this;
} else {
while (++i < n) if (!d3_selection_classed.call(this, names[i])) return false;
return true;
}
};
function d3_selection_classed(name, value) {
var re = new RegExp("(^|\\s+)" + d3.requote(name) + "(\\s+|$)", "g");
if (arguments.length < 2) {
var node = this.node();
if (c = node.classList) return c.contains(name);
var c = node.className;
re.lastIndex = 0;
return re.test(c.baseVal != null ? c.baseVal : c);
}
function classedAdd() {
if (c = this.classList) return c.add(name);
var c = this.className, cb = c.baseVal != null, cv = cb ? c.baseVal : c;
re.lastIndex = 0;
if (!re.test(cv)) {
cv = d3_collapse(cv + " " + name);
if (cb) c.baseVal = cv; else this.className = cv;
}
}
function classedRemove() {
if (c = this.classList) return c.remove(name);
var c = this.className, cb = c.baseVal != null, cv = cb ? c.baseVal : c;
if (cv) {
cv = d3_collapse(cv.replace(re, " "));
if (cb) c.baseVal = cv; else this.className = cv;
}
}
function classedFunction() {
(value.apply(this, arguments) ? classedAdd : classedRemove).call(this);
}
return this.each(typeof value === "function" ? classedFunction : value ? classedAdd : classedRemove);
}
d3_selectionPrototype.style = function(name, value, priority) {
if (arguments.length < 3) priority = "";
if (arguments.length < 2) return window.getComputedStyle(this.node(), null).getPropertyValue(name);
function styleNull() {
this.style.removeProperty(name);
}
function styleConstant() {
this.style.setProperty(name, value, priority);
}
function styleFunction() {
var x = value.apply(this, arguments);
if (x == null) this.style.removeProperty(name); else this.style.setProperty(name, x, priority);
}
return this.each(value == null ? styleNull : typeof value === "function" ? styleFunction : styleConstant);
};
d3_selectionPrototype.property = function(name, value) {
if (arguments.length < 2) return this.node()[name];
function propertyNull() {
delete this[name];
}
function propertyConstant() {
this[name] = value;
}
function propertyFunction() {
var x = value.apply(this, arguments);
if (x == null) delete this[name]; else this[name] = x;
}
return this.each(value == null ? propertyNull : typeof value === "function" ? propertyFunction : propertyConstant);
};
d3_selectionPrototype.text = function(value) {
return arguments.length < 1 ? this.node().textContent : this.each(typeof value === "function" ? function() {
var v = value.apply(this, arguments);
this.textContent = v == null ? "" : v;
} : value == null ? function() {
this.textContent = "";
} : function() {
this.textContent = value;
});
};
d3_selectionPrototype.html = function(value) {
return arguments.length < 1 ? this.node().innerHTML : this.each(typeof value === "function" ? function() {
var v = value.apply(this, arguments);
this.innerHTML = v == null ? "" : v;
} : value == null ? function() {
this.innerHTML = "";
} : function() {
this.innerHTML = value;
});
};
d3_selectionPrototype.append = function(name) {
name = d3.ns.qualify(name);
function append() {
return this.appendChild(document.createElementNS(this.namespaceURI, name));
}
function appendNS() {
return this.appendChild(document.createElementNS(name.space, name.local));
}
return this.select(name.local ? appendNS : append);
};
d3_selectionPrototype.insert = function(name, before) {
name = d3.ns.qualify(name);
function insert() {
return this.insertBefore(document.createElementNS(this.namespaceURI, name), d3_select(before, this));
}
function insertNS() {
return this.insertBefore(document.createElementNS(name.space, name.local), d3_select(before, this));
}
return this.select(name.local ? insertNS : insert);
};
d3_selectionPrototype.remove = function() {
return this.each(function() {
var parent = this.parentNode;
if (parent) parent.removeChild(this);
});
};
d3_selectionPrototype.data = function(value, key) {
var i = -1, n = this.length, group, node;
if (!arguments.length) {
value = new Array(n = (group = this[0]).length);
while (++i < n) {
if (node = group[i]) {
value[i] = node.__data__;
}
}
return value;
}
function bind(group, groupData) {
var i, n = group.length, m = groupData.length, n0 = Math.min(n, m), n1 = Math.max(n, m), updateNodes = [], enterNodes = [], exitNodes = [], node, nodeData;
if (key) {
var nodeByKeyValue = new d3_Map, keyValues = [], keyValue, j = groupData.length;
for (i = -1; ++i < n; ) {
keyValue = key.call(node = group[i], node.__data__, i);
if (nodeByKeyValue.has(keyValue)) {
exitNodes[j++] = node;
} else {
nodeByKeyValue.set(keyValue, node);
}
keyValues.push(keyValue);
}
for (i = -1; ++i < m; ) {
keyValue = key.call(groupData, nodeData = groupData[i], i);
if (nodeByKeyValue.has(keyValue)) {
updateNodes[i] = node = nodeByKeyValue.get(keyValue);
node.__data__ = nodeData;
enterNodes[i] = exitNodes[i] = null;
} else {
enterNodes[i] = d3_selection_dataNode(nodeData);
updateNodes[i] = exitNodes[i] = null;
}
nodeByKeyValue.remove(keyValue);
}
for (i = -1; ++i < n; ) {
if (nodeByKeyValue.has(keyValues[i])) {
exitNodes[i] = group[i];
}
}
} else {
for (i = -1; ++i < n0; ) {
node = group[i];
nodeData = groupData[i];
if (node) {
node.__data__ = nodeData;
updateNodes[i] = node;
enterNodes[i] = exitNodes[i] = null;
} else {
enterNodes[i] = d3_selection_dataNode(nodeData);
updateNodes[i] = exitNodes[i] = null;
}
}
for (; i < m; ++i) {
enterNodes[i] = d3_selection_dataNode(groupData[i]);
updateNodes[i] = exitNodes[i] = null;
}
for (; i < n1; ++i) {
exitNodes[i] = group[i];
enterNodes[i] = updateNodes[i] = null;
}
}
enterNodes.update = updateNodes;
enterNodes.parentNode = updateNodes.parentNode = exitNodes.parentNode = group.parentNode;
enter.push(enterNodes);
update.push(updateNodes);
exit.push(exitNodes);
}
var enter = d3_selection_enter([]), update = d3_selection([]), exit = d3_selection([]);
if (typeof value === "function") {
while (++i < n) {
bind(group = this[i], value.call(group, group.parentNode.__data__, i));
}
} else {
while (++i < n) {
bind(group = this[i], value);
}
}
update.enter = function() {
return enter;
};
update.exit = function() {
return exit;
};
return update;
};
function d3_selection_dataNode(data) {
return {
__data__: data
};
}
d3_selectionPrototype.datum = d3_selectionPrototype.map = function(value) {
return arguments.length < 1 ? this.property("__data__") : this.property("__data__", value);
};
d3_selectionPrototype.filter = function(filter) {
var subgroups = [], subgroup, group, node;
if (typeof filter !== "function") filter = d3_selection_filter(filter);
for (var j = 0, m = this.length; j < m; j++) {
subgroups.push(subgroup = []);
subgroup.parentNode = (group = this[j]).parentNode;
for (var i = 0, n = group.length; i < n; i++) {
if ((node = group[i]) && filter.call(node, node.__data__, i)) {
subgroup.push(node);
}
}
}
return d3_selection(subgroups);
};
function d3_selection_filter(selector) {
return function() {
return d3_selectMatches(this, selector);
};
}
d3_selectionPrototype.order = function() {
for (var j = -1, m = this.length; ++j < m; ) {
for (var group = this[j], i = group.length - 1, next = group[i], node; --i >= 0; ) {
if (node = group[i]) {
if (next && next !== node.nextSibling) next.parentNode.insertBefore(node, next);
next = node;
}
}
}
return this;
};
d3_selectionPrototype.sort = function(comparator) {
comparator = d3_selection_sortComparator.apply(this, arguments);
for (var j = -1, m = this.length; ++j < m; ) this[j].sort(comparator);
return this.order();
};
function d3_selection_sortComparator(comparator) {
if (!arguments.length) comparator = d3.ascending;
return function(a, b) {
return comparator(a && a.__data__, b && b.__data__);
};
}
d3_selectionPrototype.on = function(type, listener, capture) {
if (arguments.length < 3) capture = false;
var name = "__on" + type, i = type.indexOf(".");
if (i > 0) type = type.substring(0, i);
if (arguments.length < 2) return (i = this.node()[name]) && i._;
return this.each(function() {
var node = this, args = arguments, o = node[name];
if (o) {
node.removeEventListener(type, o, o.$);
delete node[name];
}
if (listener) {
node.addEventListener(type, node[name] = l, l.$ = capture);
l._ = listener;
}
function l(e) {
var o = d3.event;
d3.event = e;
args[0] = node.__data__;
try {
listener.apply(node, args);
} finally {
d3.event = o;
}
}
});
};
d3_selectionPrototype.each = function(callback) {
return d3_selection_each(this, function(node, i, j) {
callback.call(node, node.__data__, i, j);
});
};
function d3_selection_each(groups, callback) {
for (var j = 0, m = groups.length; j < m; j++) {
for (var group = groups[j], i = 0, n = group.length, node; i < n; i++) {
if (node = group[i]) callback(node, i, j);
}
}
return groups;
}
d3_selectionPrototype.call = function(callback) {
callback.apply(this, (arguments[0] = this, arguments));
return this;
};
d3_selectionPrototype.empty = function() {
return !this.node();
};
d3_selectionPrototype.node = function(callback) {
for (var j = 0, m = this.length; j < m; j++) {
for (var group = this[j], i = 0, n = group.length; i < n; i++) {
var node = group[i];
if (node) return node;
}
}
return null;
};
d3_selectionPrototype.transition = function() {
var subgroups = [], subgroup, node;
for (var j = -1, m = this.length; ++j < m; ) {
subgroups.push(subgroup = []);
for (var group = this[j], i = -1, n = group.length; ++i < n; ) {
subgroup.push((node = group[i]) ? {
node: node,
delay: d3_transitionDelay,
duration: d3_transitionDuration
} : null);
}
}
return d3_transition(subgroups, d3_transitionId || ++d3_transitionNextId, Date.now());
};
var d3_selectionRoot = d3_selection([ [ document ] ]);
d3_selectionRoot[0].parentNode = d3_selectRoot;
d3.select = function(selector) {
return typeof selector === "string" ? d3_selectionRoot.select(selector) : d3_selection([ [ selector ] ]);
};
d3.selectAll = function(selector) {
return typeof selector === "string" ? d3_selectionRoot.selectAll(selector) : d3_selection([ d3_array(selector) ]);
};
function d3_selection_enter(selection) {
d3_arraySubclass(selection, d3_selection_enterPrototype);
return selection;
}
var d3_selection_enterPrototype = [];
d3.selection.enter = d3_selection_enter;
d3.selection.enter.prototype = d3_selection_enterPrototype;
d3_selection_enterPrototype.append = d3_selectionPrototype.append;
d3_selection_enterPrototype.insert = d3_selectionPrototype.insert;
d3_selection_enterPrototype.empty = d3_selectionPrototype.empty;
d3_selection_enterPrototype.node = d3_selectionPrototype.node;
d3_selection_enterPrototype.select = function(selector) {
var subgroups = [], subgroup, subnode, upgroup, group, node;
for (var j = -1, m = this.length; ++j < m; ) {
upgroup = (group = this[j]).update;
subgroups.push(subgroup = []);
subgroup.parentNode = group.parentNode;
for (var i = -1, n = group.length; ++i < n; ) {
if (node = group[i]) {
subgroup.push(upgroup[i] = subnode = selector.call(group.parentNode, node.__data__, i));
subnode.__data__ = node.__data__;
} else {
subgroup.push(null);
}
}
}
return d3_selection(subgroups);
};
function d3_transition(groups, id, time) {
d3_arraySubclass(groups, d3_transitionPrototype);
var tweens = new d3_Map, event = d3.dispatch("start", "end"), ease = d3_transitionEase;
groups.id = id;
groups.time = time;
groups.tween = function(name, tween) {
if (arguments.length < 2) return tweens.get(name);
if (tween == null) tweens.remove(name); else tweens.set(name, tween);
return groups;
};
groups.ease = function(value) {
if (!arguments.length) return ease;
ease = typeof value === "function" ? value : d3.ease.apply(d3, arguments);
return groups;
};
groups.each = function(type, listener) {
if (arguments.length < 2) return d3_transition_each.call(groups, type);
event.on(type, listener);
return groups;
};
d3.timer(function(elapsed) {
return d3_selection_each(groups, function(node, i, j) {
var tweened = [], delay = node.delay, duration = node.duration, lock = (node = node.node).__transition__ || (node.__transition__ = {
active: 0,
count: 0
}), d = node.__data__;
++lock.count;
delay <= elapsed ? start(elapsed) : d3.timer(start, delay, time);
function start(elapsed) {
if (lock.active > id) return stop();
lock.active = id;
tweens.forEach(function(key, value) {
if (value = value.call(node, d, i)) {
tweened.push(value);
}
});
event.start.call(node, d, i);
if (!tick(elapsed)) d3.timer(tick, 0, time);
return 1;
}
function tick(elapsed) {
if (lock.active !== id) return stop();
var t = (elapsed - delay) / duration, e = ease(t), n = tweened.length;
while (n > 0) {
tweened[--n].call(node, e);
}
if (t >= 1) {
stop();
d3_transitionId = id;
event.end.call(node, d, i);
d3_transitionId = 0;
return 1;
}
}
function stop() {
if (!--lock.count) delete node.__transition__;
return 1;
}
});
}, 0, time);
return groups;
}
var d3_transitionRemove = {};
function d3_transitionNull(d, i, a) {
return a != "" && d3_transitionRemove;
}
function d3_transitionTween(name, b) {
var interpolate = d3_interpolateByName(name);
function transitionFunction(d, i, a) {
var v = b.call(this, d, i);
return v == null ? a != "" && d3_transitionRemove : a != v && interpolate(a, v);
}
function transitionString(d, i, a) {
return a != b && interpolate(a, b);
}
return typeof b === "function" ? transitionFunction : b == null ? d3_transitionNull : (b += "", transitionString);
}
var d3_transitionPrototype = [], d3_transitionNextId = 0, d3_transitionId = 0, d3_transitionDefaultDelay = 0, d3_transitionDefaultDuration = 250, d3_transitionDefaultEase = d3.ease("cubic-in-out"), d3_transitionDelay = d3_transitionDefaultDelay, d3_transitionDuration = d3_transitionDefaultDuration, d3_transitionEase = d3_transitionDefaultEase;
d3_transitionPrototype.call = d3_selectionPrototype.call;
d3.transition = function(selection) {
return arguments.length ? d3_transitionId ? selection.transition() : selection : d3_selectionRoot.transition();
};
d3.transition.prototype = d3_transitionPrototype;
d3_transitionPrototype.select = function(selector) {
var subgroups = [], subgroup, subnode, node;
if (typeof selector !== "function") selector = d3_selection_selector(selector);
for (var j = -1, m = this.length; ++j < m; ) {
subgroups.push(subgroup = []);
for (var group = this[j], i = -1, n = group.length; ++i < n; ) {
if ((node = group[i]) && (subnode = selector.call(node.node, node.node.__data__, i))) {
if ("__data__" in node.node) subnode.__data__ = node.node.__data__;
subgroup.push({
node: subnode,
delay: node.delay,
duration: node.duration
});
} else {
subgroup.push(null);
}
}
}
return d3_transition(subgroups, this.id, this.time).ease(this.ease());
};
d3_transitionPrototype.selectAll = function(selector) {
var subgroups = [], subgroup, subnodes, node;
if (typeof selector !== "function") selector = d3_selection_selectorAll(selector);
for (var j = -1, m = this.length; ++j < m; ) {
for (var group = this[j], i = -1, n = group.length; ++i < n; ) {
if (node = group[i]) {
subnodes = selector.call(node.node, node.node.__data__, i);
subgroups.push(subgroup = []);
for (var k = -1, o = subnodes.length; ++k < o; ) {
subgroup.push({
node: subnodes[k],
delay: node.delay,
duration: node.duration
});
}
}
}
}
return d3_transition(subgroups, this.id, this.time).ease(this.ease());
};
d3_transitionPrototype.filter = function(filter) {
var subgroups = [], subgroup, group, node;
if (typeof filter !== "function") filter = d3_selection_filter(filter);
for (var j = 0, m = this.length; j < m; j++) {
subgroups.push(subgroup = []);
for (var group = this[j], i = 0, n = group.length; i < n; i++) {
if ((node = group[i]) && filter.call(node.node, node.node.__data__, i)) {
subgroup.push(node);
}
}
}
return d3_transition(subgroups, this.id, this.time).ease(this.ease());
};
d3_transitionPrototype.attr = function(name, value) {
return this.attrTween(name, d3_transitionTween(name, value));
};
d3_transitionPrototype.attrTween = function(nameNS, tween) {
var name = d3.ns.qualify(nameNS);
function attrTween(d, i) {
var f = tween.call(this, d, i, this.getAttribute(name));
return f === d3_transitionRemove ? (this.removeAttribute(name), null) : f && function(t) {
this.setAttribute(name, f(t));
};
}
function attrTweenNS(d, i) {
var f = tween.call(this, d, i, this.getAttributeNS(name.space, name.local));
return f === d3_transitionRemove ? (this.removeAttributeNS(name.space, name.local), null) : f && function(t) {
this.setAttributeNS(name.space, name.local, f(t));
};
}
return this.tween("attr." + nameNS, name.local ? attrTweenNS : attrTween);
};
d3_transitionPrototype.style = function(name, value, priority) {
if (arguments.length < 3) priority = "";
return this.styleTween(name, d3_transitionTween(name, value), priority);
};
d3_transitionPrototype.styleTween = function(name, tween, priority) {
if (arguments.length < 3) priority = "";
return this.tween("style." + name, function(d, i) {
var f = tween.call(this, d, i, window.getComputedStyle(this, null).getPropertyValue(name));
return f === d3_transitionRemove ? (this.style.removeProperty(name), null) : f && function(t) {
this.style.setProperty(name, f(t), priority);
};
});
};
d3_transitionPrototype.text = function(value) {
return this.tween("text", function(d, i) {
this.textContent = typeof value === "function" ? value.call(this, d, i) : value;
});
};
d3_transitionPrototype.remove = function() {
return this.each("end.transition", function() {
var p;
if (!this.__transition__ && (p = this.parentNode)) p.removeChild(this);
});
};
d3_transitionPrototype.delay = function(value) {
return d3_selection_each(this, typeof value === "function" ? function(node, i, j) {
node.delay = value.call(node = node.node, node.__data__, i, j) | 0;
} : (value = value | 0, function(node) {
node.delay = value;
}));
};
d3_transitionPrototype.duration = function(value) {
return d3_selection_each(this, typeof value === "function" ? function(node, i, j) {
node.duration = Math.max(1, value.call(node = node.node, node.__data__, i, j) | 0);
} : (value = Math.max(1, value | 0), function(node) {
node.duration = value;
}));
};
function d3_transition_each(callback) {
var id = d3_transitionId, ease = d3_transitionEase, delay = d3_transitionDelay, duration = d3_transitionDuration;
d3_transitionId = this.id;
d3_transitionEase = this.ease();
d3_selection_each(this, function(node, i, j) {
d3_transitionDelay = node.delay;
d3_transitionDuration = node.duration;
callback.call(node = node.node, node.__data__, i, j);
});
d3_transitionId = id;
d3_transitionEase = ease;
d3_transitionDelay = delay;
d3_transitionDuration = duration;
return this;
}
d3_transitionPrototype.transition = function() {
return this.select(d3_this);
};
var d3_timer_queue = null, d3_timer_interval, d3_timer_timeout;
d3.timer = function(callback, delay, then) {
var found = false, t0, t1 = d3_timer_queue;
if (arguments.length < 3) {
if (arguments.length < 2) delay = 0; else if (!isFinite(delay)) return;
then = Date.now();
}
while (t1) {
if (t1.callback === callback) {
t1.then = then;
t1.delay = delay;
found = true;
break;
}
t0 = t1;
t1 = t1.next;
}
if (!found) d3_timer_queue = {
callback: callback,
then: then,
delay: delay,
next: d3_timer_queue
};
if (!d3_timer_interval) {
d3_timer_timeout = clearTimeout(d3_timer_timeout);
d3_timer_interval = 1;
d3_timer_frame(d3_timer_step);
}
};
function d3_timer_step() {
var elapsed, now = Date.now(), t1 = d3_timer_queue;
while (t1) {
elapsed = now - t1.then;
if (elapsed >= t1.delay) t1.flush = t1.callback(elapsed);
t1 = t1.next;
}
var delay = d3_timer_flush() - now;
if (delay > 24) {
if (isFinite(delay)) {
clearTimeout(d3_timer_timeout);
d3_timer_timeout = setTimeout(d3_timer_step, delay);
}
d3_timer_interval = 0;
} else {
d3_timer_interval = 1;
d3_timer_frame(d3_timer_step);
}
}
d3.timer.flush = function() {
var elapsed, now = Date.now(), t1 = d3_timer_queue;
while (t1) {
elapsed = now - t1.then;
if (!t1.delay) t1.flush = t1.callback(elapsed);
t1 = t1.next;
}
d3_timer_flush();
};
function d3_timer_flush() {
var t0 = null, t1 = d3_timer_queue, then = Infinity;
while (t1) {
if (t1.flush) {
t1 = t0 ? t0.next = t1.next : d3_timer_queue = t1.next;
} else {
then = Math.min(then, t1.then + t1.delay);
t1 = (t0 = t1).next;
}
}
return then;
}
var d3_timer_frame = window.requestAnimationFrame || window.webkitRequestAnimationFrame || window.mozRequestAnimationFrame || window.oRequestAnimationFrame || window.msRequestAnimationFrame || function(callback) {
setTimeout(callback, 17);
};
d3.mouse = function(container) {
return d3_mousePoint(container, d3_eventSource());
};
var d3_mouse_bug44083 = /WebKit/.test(navigator.userAgent) ? -1 : 0;
function d3_mousePoint(container, e) {
var svg = container.ownerSVGElement || container;
if (svg.createSVGPoint) {
var point = svg.createSVGPoint();
if (d3_mouse_bug44083 < 0 && (window.scrollX || window.scrollY)) {
svg = d3.select(document.body).append("svg").style("position", "absolute").style("top", 0).style("left", 0);
var ctm = svg[0][0].getScreenCTM();
d3_mouse_bug44083 = !(ctm.f || ctm.e);
svg.remove();
}
if (d3_mouse_bug44083) {
point.x = e.pageX;
point.y = e.pageY;
} else {
point.x = e.clientX;
point.y = e.clientY;
}
point = point.matrixTransform(container.getScreenCTM().inverse());
return [ point.x, point.y ];
}
var rect = container.getBoundingClientRect();
return [ e.clientX - rect.left - container.clientLeft, e.clientY - rect.top - container.clientTop ];
}
d3.touches = function(container, touches) {
if (arguments.length < 2) touches = d3_eventSource().touches;
return touches ? d3_array(touches).map(function(touch) {
var point = d3_mousePoint(container, touch);
point.identifier = touch.identifier;
return point;
}) : [];
};
function d3_noop() {}
d3.scale = {};
function d3_scaleExtent(domain) {
var start = domain[0], stop = domain[domain.length - 1];
return start < stop ? [ start, stop ] : [ stop, start ];
}
function d3_scaleRange(scale) {
return scale.rangeExtent ? scale.rangeExtent() : d3_scaleExtent(scale.range());
}
function d3_scale_nice(domain, nice) {
var i0 = 0, i1 = domain.length - 1, x0 = domain[i0], x1 = domain[i1], dx;
if (x1 < x0) {
dx = i0;
i0 = i1;
i1 = dx;
dx = x0;
x0 = x1;
x1 = dx;
}
if (dx = x1 - x0) {
nice = nice(dx);
domain[i0] = nice.floor(x0);
domain[i1] = nice.ceil(x1);
}
return domain;
}
function d3_scale_niceDefault() {
return Math;
}
d3.scale.linear = function() {
return d3_scale_linear([ 0, 1 ], [ 0, 1 ], d3.interpolate, false);
};
function d3_scale_linear(domain, range, interpolate, clamp) {
var output, input;
function rescale() {
var linear = Math.min(domain.length, range.length) > 2 ? d3_scale_polylinear : d3_scale_bilinear, uninterpolate = clamp ? d3_uninterpolateClamp : d3_uninterpolateNumber;
output = linear(domain, range, uninterpolate, interpolate);
input = linear(range, domain, uninterpolate, d3.interpolate);
return scale;
}
function scale(x) {
return output(x);
}
scale.invert = function(y) {
return input(y);
};
scale.domain = function(x) {
if (!arguments.length) return domain;
domain = x.map(Number);
return rescale();
};
scale.range = function(x) {
if (!arguments.length) return range;
range = x;
return rescale();
};
scale.rangeRound = function(x) {
return scale.range(x).interpolate(d3.interpolateRound);
};
scale.clamp = function(x) {
if (!arguments.length) return clamp;
clamp = x;
return rescale();
};
scale.interpolate = function(x) {
if (!arguments.length) return interpolate;
interpolate = x;
return rescale();
};
scale.ticks = function(m) {
return d3_scale_linearTicks(domain, m);
};
scale.tickFormat = function(m) {
return d3_scale_linearTickFormat(domain, m);
};
scale.nice = function() {
d3_scale_nice(domain, d3_scale_linearNice);
return rescale();
};
scale.copy = function() {
return d3_scale_linear(domain, range, interpolate, clamp);
};
return rescale();
}
function d3_scale_linearRebind(scale, linear) {
return d3.rebind(scale, linear, "range", "rangeRound", "interpolate", "clamp");
}
function d3_scale_linearNice(dx) {
dx = Math.pow(10, Math.round(Math.log(dx) / Math.LN10) - 1);
return {
floor: function(x) {
return Math.floor(x / dx) * dx;
},
ceil: function(x) {
return Math.ceil(x / dx) * dx;
}
};
}
function d3_scale_linearTickRange(domain, m) {
var extent = d3_scaleExtent(domain), span = extent[1] - extent[0], step = Math.pow(10, Math.floor(Math.log(span / m) / Math.LN10)), err = m / span * step;
if (err <= .15) step *= 10; else if (err <= .35) step *= 5; else if (err <= .75) step *= 2;
extent[0] = Math.ceil(extent[0] / step) * step;
extent[1] = Math.floor(extent[1] / step) * step + step * .5;
extent[2] = step;
return extent;
}
function d3_scale_linearTicks(domain, m) {
return d3.range.apply(d3, d3_scale_linearTickRange(domain, m));
}
function d3_scale_linearTickFormat(domain, m) {
return d3.format(",." + Math.max(0, -Math.floor(Math.log(d3_scale_linearTickRange(domain, m)[2]) / Math.LN10 + .01)) + "f");
}
function d3_scale_bilinear(domain, range, uninterpolate, interpolate) {
var u = uninterpolate(domain[0], domain[1]), i = interpolate(range[0], range[1]);
return function(x) {
return i(u(x));
};
}
function d3_scale_polylinear(domain, range, uninterpolate, interpolate) {
var u = [], i = [], j = 0, k = Math.min(domain.length, range.length) - 1;
if (domain[k] < domain[0]) {
domain = domain.slice().reverse();
range = range.slice().reverse();
}
while (++j <= k) {
u.push(uninterpolate(domain[j - 1], domain[j]));
i.push(interpolate(range[j - 1], range[j]));
}
return function(x) {
var j = d3.bisect(domain, x, 1, k) - 1;
return i[j](u[j](x));
};
}
d3.scale.log = function() {
return d3_scale_log(d3.scale.linear(), d3_scale_logp);
};
function d3_scale_log(linear, log) {
var pow = log.pow;
function scale(x) {
return linear(log(x));
}
scale.invert = function(x) {
return pow(linear.invert(x));
};
scale.domain = function(x) {
if (!arguments.length) return linear.domain().map(pow);
log = x[0] < 0 ? d3_scale_logn : d3_scale_logp;
pow = log.pow;
linear.domain(x.map(log));
return scale;
};
scale.nice = function() {
linear.domain(d3_scale_nice(linear.domain(), d3_scale_niceDefault));
return scale;
};
scale.ticks = function() {
var extent = d3_scaleExtent(linear.domain()), ticks = [];
if (extent.every(isFinite)) {
var i = Math.floor(extent[0]), j = Math.ceil(extent[1]), u = pow(extent[0]), v = pow(extent[1]);
if (log === d3_scale_logn) {
ticks.push(pow(i));
for (; i++ < j; ) for (var k = 9; k > 0; k--) ticks.push(pow(i) * k);
} else {
for (; i < j; i++) for (var k = 1; k < 10; k++) ticks.push(pow(i) * k);
ticks.push(pow(i));
}
for (i = 0; ticks[i] < u; i++) {}
for (j = ticks.length; ticks[j - 1] > v; j--) {}
ticks = ticks.slice(i, j);
}
return ticks;
};
scale.tickFormat = function(n, format) {
if (arguments.length < 2) format = d3_scale_logFormat;
if (arguments.length < 1) return format;
var k = Math.max(.1, n / scale.ticks().length), f = log === d3_scale_logn ? (e = -1e-12, Math.floor) : (e = 1e-12, Math.ceil), e;
return function(d) {
return d / pow(f(log(d) + e)) <= k ? format(d) : "";
};
};
scale.copy = function() {
return d3_scale_log(linear.copy(), log);
};
return d3_scale_linearRebind(scale, linear);
}
var d3_scale_logFormat = d3.format(".0e");
function d3_scale_logp(x) {
return Math.log(x < 0 ? 0 : x) / Math.LN10;
}
function d3_scale_logn(x) {
return -Math.log(x > 0 ? 0 : -x) / Math.LN10;
}
d3_scale_logp.pow = function(x) {
return Math.pow(10, x);
};
d3_scale_logn.pow = function(x) {
return -Math.pow(10, -x);
};
d3.scale.pow = function() {
return d3_scale_pow(d3.scale.linear(), 1);
};
function d3_scale_pow(linear, exponent) {
var powp = d3_scale_powPow(exponent), powb = d3_scale_powPow(1 / exponent);
function scale(x) {
return linear(powp(x));
}
scale.invert = function(x) {
return powb(linear.invert(x));
};
scale.domain = function(x) {
if (!arguments.length) return linear.domain().map(powb);
linear.domain(x.map(powp));
return scale;
};
scale.ticks = function(m) {
return d3_scale_linearTicks(scale.domain(), m);
};
scale.tickFormat = function(m) {
return d3_scale_linearTickFormat(scale.domain(), m);
};
scale.nice = function() {
return scale.domain(d3_scale_nice(scale.domain(), d3_scale_linearNice));
};
scale.exponent = function(x) {
if (!arguments.length) return exponent;
var domain = scale.domain();
powp = d3_scale_powPow(exponent = x);
powb = d3_scale_powPow(1 / exponent);
return scale.domain(domain);
};
scale.copy = function() {
return d3_scale_pow(linear.copy(), exponent);
};
return d3_scale_linearRebind(scale, linear);
}
function d3_scale_powPow(e) {
return function(x) {
return x < 0 ? -Math.pow(-x, e) : Math.pow(x, e);
};
}
d3.scale.sqrt = function() {
return d3.scale.pow().exponent(.5);
};
d3.scale.ordinal = function() {
return d3_scale_ordinal([], {
t: "range",
x: []
});
};
function d3_scale_ordinal(domain, ranger) {
var index, range, rangeBand;
function scale(x) {
return range[((index.get(x) || index.set(x, domain.push(x))) - 1) % range.length];
}
function steps(start, step) {
return d3.range(domain.length).map(function(i) {
return start + step * i;
});
}
scale.domain = function(x) {
if (!arguments.length) return domain;
domain = [];
index = new d3_Map;
var i = -1, n = x.length, xi;
while (++i < n) if (!index.has(xi = x[i])) index.set(xi, domain.push(xi));
return scale[ranger.t](ranger.x, ranger.p);
};
scale.range = function(x) {
if (!arguments.length) return range;
range = x;
rangeBand = 0;
ranger = {
t: "range",
x: x
};
return scale;
};
scale.rangePoints = function(x, padding) {
if (arguments.length < 2) padding = 0;
var start = x[0], stop = x[1], step = (stop - start) / (domain.length - 1 + padding);
range = steps(domain.length < 2 ? (start + stop) / 2 : start + step * padding / 2, step);
rangeBand = 0;
ranger = {
t: "rangePoints",
x: x,
p: padding
};
return scale;
};
scale.rangeBands = function(x, padding) {
if (arguments.length < 2) padding = 0;
var reverse = x[1] < x[0], start = x[reverse - 0], stop = x[1 - reverse], step = (stop - start) / (domain.length + padding);
range = steps(start + step * padding, step);
if (reverse) range.reverse();
rangeBand = step * (1 - padding);
ranger = {
t: "rangeBands",
x: x,
p: padding
};
return scale;
};
scale.rangeRoundBands = function(x, padding) {
if (arguments.length < 2) padding = 0;
var reverse = x[1] < x[0], start = x[reverse - 0], stop = x[1 - reverse], step = Math.floor((stop - start) / (domain.length + padding)), error = stop - start - (domain.length - padding) * step;
range = steps(start + Math.round(error / 2), step);
if (reverse) range.reverse();
rangeBand = Math.round(step * (1 - padding));
ranger = {
t: "rangeRoundBands",
x: x,
p: padding
};
return scale;
};
scale.rangeBand = function() {
return rangeBand;
};
scale.rangeExtent = function() {
return d3_scaleExtent(ranger.x);
};
scale.copy = function() {
return d3_scale_ordinal(domain, ranger);
};
return scale.domain(domain);
}
d3.scale.category10 = function() {
return d3.scale.ordinal().range(d3_category10);
};
d3.scale.category20 = function() {
return d3.scale.ordinal().range(d3_category20);
};
d3.scale.category20b = function() {
return d3.scale.ordinal().range(d3_category20b);
};
d3.scale.category20c = function() {
return d3.scale.ordinal().range(d3_category20c);
};
var d3_category10 = [ "#1f77b4", "#ff7f0e", "#2ca02c", "#d62728", "#9467bd", "#8c564b", "#e377c2", "#7f7f7f", "#bcbd22", "#17becf" ];
var d3_category20 = [ "#1f77b4", "#aec7e8", "#ff7f0e", "#ffbb78", "#2ca02c", "#98df8a", "#d62728", "#ff9896", "#9467bd", "#c5b0d5", "#8c564b", "#c49c94", "#e377c2", "#f7b6d2", "#7f7f7f", "#c7c7c7", "#bcbd22", "#dbdb8d", "#17becf", "#9edae5" ];
var d3_category20b = [ "#393b79", "#5254a3", "#6b6ecf", "#9c9ede", "#637939", "#8ca252", "#b5cf6b", "#cedb9c", "#8c6d31", "#bd9e39", "#e7ba52", "#e7cb94", "#843c39", "#ad494a", "#d6616b", "#e7969c", "#7b4173", "#a55194", "#ce6dbd", "#de9ed6" ];
var d3_category20c = [ "#3182bd", "#6baed6", "#9ecae1", "#c6dbef", "#e6550d", "#fd8d3c", "#fdae6b", "#fdd0a2", "#31a354", "#74c476", "#a1d99b", "#c7e9c0", "#756bb1", "#9e9ac8", "#bcbddc", "#dadaeb", "#636363", "#969696", "#bdbdbd", "#d9d9d9" ];
d3.scale.quantile = function() {
return d3_scale_quantile([], []);
};
function d3_scale_quantile(domain, range) {
var thresholds;
function rescale() {
var k = 0, n = domain.length, q = range.length;
thresholds = [];
while (++k < q) thresholds[k - 1] = d3.quantile(domain, k / q);
return scale;
}
function scale(x) {
if (isNaN(x = +x)) return NaN;
return range[d3.bisect(thresholds, x)];
}
scale.domain = function(x) {
if (!arguments.length) return domain;
domain = x.filter(function(d) {
return !isNaN(d);
}).sort(d3.ascending);
return rescale();
};
scale.range = function(x) {
if (!arguments.length) return range;
range = x;
return rescale();
};
scale.quantiles = function() {
return thresholds;
};
scale.copy = function() {
return d3_scale_quantile(domain, range);
};
return rescale();
}
d3.scale.quantize = function() {
return d3_scale_quantize(0, 1, [ 0, 1 ]);
};
function d3_scale_quantize(x0, x1, range) {
var kx, i;
function scale(x) {
return range[Math.max(0, Math.min(i, Math.floor(kx * (x - x0))))];
}
function rescale() {
kx = range.length / (x1 - x0);
i = range.length - 1;
return scale;
}
scale.domain = function(x) {
if (!arguments.length) return [ x0, x1 ];
x0 = +x[0];
x1 = +x[x.length - 1];
return rescale();
};
scale.range = function(x) {
if (!arguments.length) return range;
range = x;
return rescale();
};
scale.copy = function() {
return d3_scale_quantize(x0, x1, range);
};
return rescale();
}
d3.scale.identity = function() {
return d3_scale_identity([ 0, 1 ]);
};
function d3_scale_identity(domain) {
function identity(x) {
return +x;
}
identity.invert = identity;
identity.domain = identity.range = function(x) {
if (!arguments.length) return domain;
domain = x.map(identity);
return identity;
};
identity.ticks = function(m) {
return d3_scale_linearTicks(domain, m);
};
identity.tickFormat = function(m) {
return d3_scale_linearTickFormat(domain, m);
};
identity.copy = function() {
return d3_scale_identity(domain);
};
return identity;
}
d3.svg = {};
d3.svg.arc = function() {
var innerRadius = d3_svg_arcInnerRadius, outerRadius = d3_svg_arcOuterRadius, startAngle = d3_svg_arcStartAngle, endAngle = d3_svg_arcEndAngle;
function arc() {
var r0 = innerRadius.apply(this, arguments), r1 = outerRadius.apply(this, arguments), a0 = startAngle.apply(this, arguments) + d3_svg_arcOffset, a1 = endAngle.apply(this, arguments) + d3_svg_arcOffset, da = (a1 < a0 && (da = a0, a0 = a1, a1 = da), a1 - a0), df = da < Math.PI ? "0" : "1", c0 = Math.cos(a0), s0 = Math.sin(a0), c1 = Math.cos(a1), s1 = Math.sin(a1);
return da >= d3_svg_arcMax ? r0 ? "M0," + r1 + "A" + r1 + "," + r1 + " 0 1,1 0," + -r1 + "A" + r1 + "," + r1 + " 0 1,1 0," + r1 + "M0," + r0 + "A" + r0 + "," + r0 + " 0 1,0 0," + -r0 + "A" + r0 + "," + r0 + " 0 1,0 0," + r0 + "Z" : "M0," + r1 + "A" + r1 + "," + r1 + " 0 1,1 0," + -r1 + "A" + r1 + "," + r1 + " 0 1,1 0," + r1 + "Z" : r0 ? "M" + r1 * c0 + "," + r1 * s0 + "A" + r1 + "," + r1 + " 0 " + df + ",1 " + r1 * c1 + "," + r1 * s1 + "L" + r0 * c1 + "," + r0 * s1 + "A" + r0 + "," + r0 + " 0 " + df + ",0 " + r0 * c0 + "," + r0 * s0 + "Z" : "M" + r1 * c0 + "," + r1 * s0 + "A" + r1 + "," + r1 + " 0 " + df + ",1 " + r1 * c1 + "," + r1 * s1 + "L0,0" + "Z";
}
arc.innerRadius = function(v) {
if (!arguments.length) return innerRadius;
innerRadius = d3_functor(v);
return arc;
};
arc.outerRadius = function(v) {
if (!arguments.length) return outerRadius;
outerRadius = d3_functor(v);
return arc;
};
arc.startAngle = function(v) {
if (!arguments.length) return startAngle;
startAngle = d3_functor(v);
return arc;
};
arc.endAngle = function(v) {
if (!arguments.length) return endAngle;
endAngle = d3_functor(v);
return arc;
};
arc.centroid = function() {
var r = (innerRadius.apply(this, arguments) + outerRadius.apply(this, arguments)) / 2, a = (startAngle.apply(this, arguments) + endAngle.apply(this, arguments)) / 2 + d3_svg_arcOffset;
return [ Math.cos(a) * r, Math.sin(a) * r ];
};
return arc;
};
var d3_svg_arcOffset = -Math.PI / 2, d3_svg_arcMax = 2 * Math.PI - 1e-6;
function d3_svg_arcInnerRadius(d) {
return d.innerRadius;
}
function d3_svg_arcOuterRadius(d) {
return d.outerRadius;
}
function d3_svg_arcStartAngle(d) {
return d.startAngle;
}
function d3_svg_arcEndAngle(d) {
return d.endAngle;
}
function d3_svg_line(projection) {
var x = d3_svg_lineX, y = d3_svg_lineY, defined = d3_true, interpolate = d3_svg_lineInterpolatorDefault, interpolator = d3_svg_lineLinear, tension = .7;
function line(data) {
var segments = [], points = [], i = -1, n = data.length, d, fx = d3_functor(x), fy = d3_functor(y);
function segment() {
segments.push("M", interpolator(projection(points), tension));
}
while (++i < n) {
if (defined.call(this, d = data[i], i)) {
points.push([ +fx.call(this, d, i), +fy.call(this, d, i) ]);
} else if (points.length) {
segment();
points = [];
}
}
if (points.length) segment();
return segments.length ? segments.join("") : null;
}
line.x = function(_) {
if (!arguments.length) return x;
x = _;
return line;
};
line.y = function(_) {
if (!arguments.length) return y;
y = _;
return line;
};
line.defined = function(_) {
if (!arguments.length) return defined;
defined = _;
return line;
};
line.interpolate = function(_) {
if (!arguments.length) return interpolate;
if (!d3_svg_lineInterpolators.has(_ += "")) _ = d3_svg_lineInterpolatorDefault;
interpolator = d3_svg_lineInterpolators.get(interpolate = _);
return line;
};
line.tension = function(_) {
if (!arguments.length) return tension;
tension = _;
return line;
};
return line;
}
d3.svg.line = function() {
return d3_svg_line(d3_identity);
};
function d3_svg_lineX(d) {
return d[0];
}
function d3_svg_lineY(d) {
return d[1];
}
var d3_svg_lineInterpolatorDefault = "linear";
var d3_svg_lineInterpolators = d3.map({
linear: d3_svg_lineLinear,
"linear-closed": d3_svg_lineLinearClosed,
"step-before": d3_svg_lineStepBefore,
"step-after": d3_svg_lineStepAfter,
basis: d3_svg_lineBasis,
"basis-open": d3_svg_lineBasisOpen,
"basis-closed": d3_svg_lineBasisClosed,
bundle: d3_svg_lineBundle,
cardinal: d3_svg_lineCardinal,
"cardinal-open": d3_svg_lineCardinalOpen,
"cardinal-closed": d3_svg_lineCardinalClosed,
monotone: d3_svg_lineMonotone
});
function d3_svg_lineLinear(points) {
return points.join("L");
}
function d3_svg_lineLinearClosed(points) {
return d3_svg_lineLinear(points) + "Z";
}
function d3_svg_lineStepBefore(points) {
var i = 0, n = points.length, p = points[0], path = [ p[0], ",", p[1] ];
while (++i < n) path.push("V", (p = points[i])[1], "H", p[0]);
return path.join("");
}
function d3_svg_lineStepAfter(points) {
var i = 0, n = points.length, p = points[0], path = [ p[0], ",", p[1] ];
while (++i < n) path.push("H", (p = points[i])[0], "V", p[1]);
return path.join("");
}
function d3_svg_lineCardinalOpen(points, tension) {
return points.length < 4 ? d3_svg_lineLinear(points) : points[1] + d3_svg_lineHermite(points.slice(1, points.length - 1), d3_svg_lineCardinalTangents(points, tension));
}
function d3_svg_lineCardinalClosed(points, tension) {
return points.length < 3 ? d3_svg_lineLinear(points) : points[0] + d3_svg_lineHermite((points.push(points[0]), points), d3_svg_lineCardinalTangents([ points[points.length - 2] ].concat(points, [ points[1] ]), tension));
}
function d3_svg_lineCardinal(points, tension, closed) {
return points.length < 3 ? d3_svg_lineLinear(points) : points[0] + d3_svg_lineHermite(points, d3_svg_lineCardinalTangents(points, tension));
}
function d3_svg_lineHermite(points, tangents) {
if (tangents.length < 1 || points.length != tangents.length && points.length != tangents.length + 2) {
return d3_svg_lineLinear(points);
}
var quad = points.length != tangents.length, path = "", p0 = points[0], p = points[1], t0 = tangents[0], t = t0, pi = 1;
if (quad) {
path += "Q" + (p[0] - t0[0] * 2 / 3) + "," + (p[1] - t0[1] * 2 / 3) + "," + p[0] + "," + p[1];
p0 = points[1];
pi = 2;
}
if (tangents.length > 1) {
t = tangents[1];
p = points[pi];
pi++;
path += "C" + (p0[0] + t0[0]) + "," + (p0[1] + t0[1]) + "," + (p[0] - t[0]) + "," + (p[1] - t[1]) + "," + p[0] + "," + p[1];
for (var i = 2; i < tangents.length; i++, pi++) {
p = points[pi];
t = tangents[i];
path += "S" + (p[0] - t[0]) + "," + (p[1] - t[1]) + "," + p[0] + "," + p[1];
}
}
if (quad) {
var lp = points[pi];
path += "Q" + (p[0] + t[0] * 2 / 3) + "," + (p[1] + t[1] * 2 / 3) + "," + lp[0] + "," + lp[1];
}
return path;
}
function d3_svg_lineCardinalTangents(points, tension) {
var tangents = [], a = (1 - tension) / 2, p0, p1 = points[0], p2 = points[1], i = 1, n = points.length;
while (++i < n) {
p0 = p1;
p1 = p2;
p2 = points[i];
tangents.push([ a * (p2[0] - p0[0]), a * (p2[1] - p0[1]) ]);
}
return tangents;
}
function d3_svg_lineBasis(points) {
if (points.length < 3) return d3_svg_lineLinear(points);
var i = 1, n = points.length, pi = points[0], x0 = pi[0], y0 = pi[1], px = [ x0, x0, x0, (pi = points[1])[0] ], py = [ y0, y0, y0, pi[1] ], path = [ x0, ",", y0 ];
d3_svg_lineBasisBezier(path, px, py);
while (++i < n) {
pi = points[i];
px.shift();
px.push(pi[0]);
py.shift();
py.push(pi[1]);
d3_svg_lineBasisBezier(path, px, py);
}
i = -1;
while (++i < 2) {
px.shift();
px.push(pi[0]);
py.shift();
py.push(pi[1]);
d3_svg_lineBasisBezier(path, px, py);
}
return path.join("");
}
function d3_svg_lineBasisOpen(points) {
if (points.length < 4) return d3_svg_lineLinear(points);
var path = [], i = -1, n = points.length, pi, px = [ 0 ], py = [ 0 ];
while (++i < 3) {
pi = points[i];
px.push(pi[0]);
py.push(pi[1]);
}
path.push(d3_svg_lineDot4(d3_svg_lineBasisBezier3, px) + "," + d3_svg_lineDot4(d3_svg_lineBasisBezier3, py));
--i;
while (++i < n) {
pi = points[i];
px.shift();
px.push(pi[0]);
py.shift();
py.push(pi[1]);
d3_svg_lineBasisBezier(path, px, py);
}
return path.join("");
}
function d3_svg_lineBasisClosed(points) {
var path, i = -1, n = points.length, m = n + 4, pi, px = [], py = [];
while (++i < 4) {
pi = points[i % n];
px.push(pi[0]);
py.push(pi[1]);
}
path = [ d3_svg_lineDot4(d3_svg_lineBasisBezier3, px), ",", d3_svg_lineDot4(d3_svg_lineBasisBezier3, py) ];
--i;
while (++i < m) {
pi = points[i % n];
px.shift();
px.push(pi[0]);
py.shift();
py.push(pi[1]);
d3_svg_lineBasisBezier(path, px, py);
}
return path.join("");
}
function d3_svg_lineBundle(points, tension) {
var n = points.length - 1;
if (n) {
var x0 = points[0][0], y0 = points[0][1], dx = points[n][0] - x0, dy = points[n][1] - y0, i = -1, p, t;
while (++i <= n) {
p = points[i];
t = i / n;
p[0] = tension * p[0] + (1 - tension) * (x0 + t * dx);
p[1] = tension * p[1] + (1 - tension) * (y0 + t * dy);
}
}
return d3_svg_lineBasis(points);
}
function d3_svg_lineDot4(a, b) {
return a[0] * b[0] + a[1] * b[1] + a[2] * b[2] + a[3] * b[3];
}
var d3_svg_lineBasisBezier1 = [ 0, 2 / 3, 1 / 3, 0 ], d3_svg_lineBasisBezier2 = [ 0, 1 / 3, 2 / 3, 0 ], d3_svg_lineBasisBezier3 = [ 0, 1 / 6, 2 / 3, 1 / 6 ];
function d3_svg_lineBasisBezier(path, x, y) {
path.push("C", d3_svg_lineDot4(d3_svg_lineBasisBezier1, x), ",", d3_svg_lineDot4(d3_svg_lineBasisBezier1, y), ",", d3_svg_lineDot4(d3_svg_lineBasisBezier2, x), ",", d3_svg_lineDot4(d3_svg_lineBasisBezier2, y), ",", d3_svg_lineDot4(d3_svg_lineBasisBezier3, x), ",", d3_svg_lineDot4(d3_svg_lineBasisBezier3, y));
}
function d3_svg_lineSlope(p0, p1) {
return (p1[1] - p0[1]) / (p1[0] - p0[0]);
}
function d3_svg_lineFiniteDifferences(points) {
var i = 0, j = points.length - 1, m = [], p0 = points[0], p1 = points[1], d = m[0] = d3_svg_lineSlope(p0, p1);
while (++i < j) {
m[i] = d + (d = d3_svg_lineSlope(p0 = p1, p1 = points[i + 1]));
}
m[i] = d;
return m;
}
function d3_svg_lineMonotoneTangents(points) {
var tangents = [], d, a, b, s, m = d3_svg_lineFiniteDifferences(points), i = -1, j = points.length - 1;
while (++i < j) {
d = d3_svg_lineSlope(points[i], points[i + 1]);
if (Math.abs(d) < 1e-6) {
m[i] = m[i + 1] = 0;
} else {
a = m[i] / d;
b = m[i + 1] / d;
s = a * a + b * b;
if (s > 9) {
s = d * 3 / Math.sqrt(s);
m[i] = s * a;
m[i + 1] = s * b;
}
}
}
i = -1;
while (++i <= j) {
s = (points[Math.min(j, i + 1)][0] - points[Math.max(0, i - 1)][0]) / (6 * (1 + m[i] * m[i]));
tangents.push([ s || 0, m[i] * s || 0 ]);
}
return tangents;
}
function d3_svg_lineMonotone(points) {
return points.length < 3 ? d3_svg_lineLinear(points) : points[0] + d3_svg_lineHermite(points, d3_svg_lineMonotoneTangents(points));
}
d3.svg.line.radial = function() {
var line = d3_svg_line(d3_svg_lineRadial);
line.radius = line.x, delete line.x;
line.angle = line.y, delete line.y;
return line;
};
function d3_svg_lineRadial(points) {
var point, i = -1, n = points.length, r, a;
while (++i < n) {
point = points[i];
r = point[0];
a = point[1] + d3_svg_arcOffset;
point[0] = r * Math.cos(a);
point[1] = r * Math.sin(a);
}
return points;
}
function d3_svg_area(projection) {
var x0 = d3_svg_lineX, x1 = d3_svg_lineX, y0 = 0, y1 = d3_svg_lineY, defined = d3_true, interpolate = d3_svg_lineInterpolatorDefault, i0 = d3_svg_lineLinear, i1 = d3_svg_lineLinear, L = "L", tension = .7;
function area(data) {
var segments = [], points0 = [], points1 = [], i = -1, n = data.length, d, fx0 = d3_functor(x0), fy0 = d3_functor(y0), fx1 = x0 === x1 ? function() {
return x;
} : d3_functor(x1), fy1 = y0 === y1 ? function() {
return y;
} : d3_functor(y1), x, y;
function segment() {
segments.push("M", i0(projection(points1), tension), L, i1(projection(points0.reverse()), tension), "Z");
}
while (++i < n) {
if (defined.call(this, d = data[i], i)) {
points0.push([ x = +fx0.call(this, d, i), y = +fy0.call(this, d, i) ]);
points1.push([ +fx1.call(this, d, i), +fy1.call(this, d, i) ]);
} else if (points0.length) {
segment();
points0 = [];
points1 = [];
}
}
if (points0.length) segment();
return segments.length ? segments.join("") : null;
}
area.x = function(_) {
if (!arguments.length) return x1;
x0 = x1 = _;
return area;
};
area.x0 = function(_) {
if (!arguments.length) return x0;
x0 = _;
return area;
};
area.x1 = function(_) {
if (!arguments.length) return x1;
x1 = _;
return area;
};
area.y = function(_) {
if (!arguments.length) return y1;
y0 = y1 = _;
return area;
};
area.y0 = function(_) {
if (!arguments.length) return y0;
y0 = _;
return area;
};
area.y1 = function(_) {
if (!arguments.length) return y1;
y1 = _;
return area;
};
area.defined = function(_) {
if (!arguments.length) return defined;
defined = _;
return area;
};
area.interpolate = function(_) {
if (!arguments.length) return interpolate;
if (!d3_svg_lineInterpolators.has(_ += "")) _ = d3_svg_lineInterpolatorDefault;
i0 = d3_svg_lineInterpolators.get(interpolate = _);
i1 = i0.reverse || i0;
L = /-closed$/.test(_) ? "M" : "L";
return area;
};
area.tension = function(_) {
if (!arguments.length) return tension;
tension = _;
return area;
};
return area;
}
d3_svg_lineStepBefore.reverse = d3_svg_lineStepAfter;
d3_svg_lineStepAfter.reverse = d3_svg_lineStepBefore;
d3.svg.area = function() {
return d3_svg_area(Object);
};
d3.svg.area.radial = function() {
var area = d3_svg_area(d3_svg_lineRadial);
area.radius = area.x, delete area.x;
area.innerRadius = area.x0, delete area.x0;
area.outerRadius = area.x1, delete area.x1;
area.angle = area.y, delete area.y;
area.startAngle = area.y0, delete area.y0;
area.endAngle = area.y1, delete area.y1;
return area;
};
d3.svg.chord = function() {
var source = d3_svg_chordSource, target = d3_svg_chordTarget, radius = d3_svg_chordRadius, startAngle = d3_svg_arcStartAngle, endAngle = d3_svg_arcEndAngle;
function chord(d, i) {
var s = subgroup(this, source, d, i), t = subgroup(this, target, d, i);
return "M" + s.p0 + arc(s.r, s.p1, s.a1 - s.a0) + (equals(s, t) ? curve(s.r, s.p1, s.r, s.p0) : curve(s.r, s.p1, t.r, t.p0) + arc(t.r, t.p1, t.a1 - t.a0) + curve(t.r, t.p1, s.r, s.p0)) + "Z";
}
function subgroup(self, f, d, i) {
var subgroup = f.call(self, d, i), r = radius.call(self, subgroup, i), a0 = startAngle.call(self, subgroup, i) + d3_svg_arcOffset, a1 = endAngle.call(self, subgroup, i) + d3_svg_arcOffset;
return {
r: r,
a0: a0,
a1: a1,
p0: [ r * Math.cos(a0), r * Math.sin(a0) ],
p1: [ r * Math.cos(a1), r * Math.sin(a1) ]
};
}
function equals(a, b) {
return a.a0 == b.a0 && a.a1 == b.a1;
}
function arc(r, p, a) {
return "A" + r + "," + r + " 0 " + +(a > Math.PI) + ",1 " + p;
}
function curve(r0, p0, r1, p1) {
return "Q 0,0 " + p1;
}
chord.radius = function(v) {
if (!arguments.length) return radius;
radius = d3_functor(v);
return chord;
};
chord.source = function(v) {
if (!arguments.length) return source;
source = d3_functor(v);
return chord;
};
chord.target = function(v) {
if (!arguments.length) return target;
target = d3_functor(v);
return chord;
};
chord.startAngle = function(v) {
if (!arguments.length) return startAngle;
startAngle = d3_functor(v);
return chord;
};
chord.endAngle = function(v) {
if (!arguments.length) return endAngle;
endAngle = d3_functor(v);
return chord;
};
return chord;
};
function d3_svg_chordSource(d) {
return d.source;
}
function d3_svg_chordTarget(d) {
return d.target;
}
function d3_svg_chordRadius(d) {
return d.radius;
}
function d3_svg_chordStartAngle(d) {
return d.startAngle;
}
function d3_svg_chordEndAngle(d) {
return d.endAngle;
}
d3.svg.diagonal = function() {
var source = d3_svg_chordSource, target = d3_svg_chordTarget, projection = d3_svg_diagonalProjection;
function diagonal(d, i) {
var p0 = source.call(this, d, i), p3 = target.call(this, d, i), m = (p0.y + p3.y) / 2, p = [ p0, {
x: p0.x,
y: m
}, {
x: p3.x,
y: m
}, p3 ];
p = p.map(projection);
return "M" + p[0] + "C" + p[1] + " " + p[2] + " " + p[3];
}
diagonal.source = function(x) {
if (!arguments.length) return source;
source = d3_functor(x);
return diagonal;
};
diagonal.target = function(x) {
if (!arguments.length) return target;
target = d3_functor(x);
return diagonal;
};
diagonal.projection = function(x) {
if (!arguments.length) return projection;
projection = x;
return diagonal;
};
return diagonal;
};
function d3_svg_diagonalProjection(d) {
return [ d.x, d.y ];
}
d3.svg.diagonal.radial = function() {
var diagonal = d3.svg.diagonal(), projection = d3_svg_diagonalProjection, projection_ = diagonal.projection;
diagonal.projection = function(x) {
return arguments.length ? projection_(d3_svg_diagonalRadialProjection(projection = x)) : projection;
};
return diagonal;
};
function d3_svg_diagonalRadialProjection(projection) {
return function() {
var d = projection.apply(this, arguments), r = d[0], a = d[1] + d3_svg_arcOffset;
return [ r * Math.cos(a), r * Math.sin(a) ];
};
}
d3.svg.mouse = d3.mouse;
d3.svg.touches = d3.touches;
d3.svg.symbol = function() {
var type = d3_svg_symbolType, size = d3_svg_symbolSize;
function symbol(d, i) {
return (d3_svg_symbols.get(type.call(this, d, i)) || d3_svg_symbolCircle)(size.call(this, d, i));
}
symbol.type = function(x) {
if (!arguments.length) return type;
type = d3_functor(x);
return symbol;
};
symbol.size = function(x) {
if (!arguments.length) return size;
size = d3_functor(x);
return symbol;
};
return symbol;
};
function d3_svg_symbolSize() {
return 64;
}
function d3_svg_symbolType() {
return "circle";
}
function d3_svg_symbolCircle(size) {
var r = Math.sqrt(size / Math.PI);
return "M0," + r + "A" + r + "," + r + " 0 1,1 0," + -r + "A" + r + "," + r + " 0 1,1 0," + r + "Z";
}
var d3_svg_symbols = d3.map({
circle: d3_svg_symbolCircle,
cross: function(size) {
var r = Math.sqrt(size / 5) / 2;
return "M" + -3 * r + "," + -r + "H" + -r + "V" + -3 * r + "H" + r + "V" + -r + "H" + 3 * r + "V" + r + "H" + r + "V" + 3 * r + "H" + -r + "V" + r + "H" + -3 * r + "Z";
},
diamond: function(size) {
var ry = Math.sqrt(size / (2 * d3_svg_symbolTan30)), rx = ry * d3_svg_symbolTan30;
return "M0," + -ry + "L" + rx + ",0" + " 0," + ry + " " + -rx + ",0" + "Z";
},
square: function(size) {
var r = Math.sqrt(size) / 2;
return "M" + -r + "," + -r + "L" + r + "," + -r + " " + r + "," + r + " " + -r + "," + r + "Z";
},
"triangle-down": function(size) {
var rx = Math.sqrt(size / d3_svg_symbolSqrt3), ry = rx * d3_svg_symbolSqrt3 / 2;
return "M0," + ry + "L" + rx + "," + -ry + " " + -rx + "," + -ry + "Z";
},
"triangle-up": function(size) {
var rx = Math.sqrt(size / d3_svg_symbolSqrt3), ry = rx * d3_svg_symbolSqrt3 / 2;
return "M0," + -ry + "L" + rx + "," + ry + " " + -rx + "," + ry + "Z";
}
});
d3.svg.symbolTypes = d3_svg_symbols.keys();
var d3_svg_symbolSqrt3 = Math.sqrt(3), d3_svg_symbolTan30 = Math.tan(30 * Math.PI / 180);
d3.svg.axis = function() {
var scale = d3.scale.linear(), orient = "bottom", tickMajorSize = 6, tickMinorSize = 6, tickEndSize = 6, tickPadding = 3, tickArguments_ = [ 10 ], tickValues = null, tickFormat_, tickSubdivide = 0;
function axis(g) {
g.each(function() {
var g = d3.select(this);
var ticks = tickValues == null ? scale.ticks ? scale.ticks.apply(scale, tickArguments_) : scale.domain() : tickValues, tickFormat = tickFormat_ == null ? scale.tickFormat ? scale.tickFormat.apply(scale, tickArguments_) : String : tickFormat_;
var subticks = d3_svg_axisSubdivide(scale, ticks, tickSubdivide), subtick = g.selectAll(".minor").data(subticks, String), subtickEnter = subtick.enter().insert("line", "g").attr("class", "tick minor").style("opacity", 1e-6), subtickExit = d3.transition(subtick.exit()).style("opacity", 1e-6).remove(), subtickUpdate = d3.transition(subtick).style("opacity", 1);
var tick = g.selectAll("g").data(ticks, String), tickEnter = tick.enter().insert("g", "path").style("opacity", 1e-6), tickExit = d3.transition(tick.exit()).style("opacity", 1e-6).remove(), tickUpdate = d3.transition(tick).style("opacity", 1), tickTransform;
var range = d3_scaleRange(scale), path = g.selectAll(".domain").data([ 0 ]), pathEnter = path.enter().append("path").attr("class", "domain"), pathUpdate = d3.transition(path);
var scale1 = scale.copy(), scale0 = this.__chart__ || scale1;
this.__chart__ = scale1;
tickEnter.append("line").attr("class", "tick");
tickEnter.append("text");
var lineEnter = tickEnter.select("line"), lineUpdate = tickUpdate.select("line"), text = tick.select("text").text(tickFormat), textEnter = tickEnter.select("text"), textUpdate = tickUpdate.select("text");
switch (orient) {
case "bottom":
{
tickTransform = d3_svg_axisX;
subtickEnter.attr("y2", tickMinorSize);
subtickUpdate.attr("x2", 0).attr("y2", tickMinorSize);
lineEnter.attr("y2", tickMajorSize);
textEnter.attr("y", Math.max(tickMajorSize, 0) + tickPadding);
lineUpdate.attr("x2", 0).attr("y2", tickMajorSize);
textUpdate.attr("x", 0).attr("y", Math.max(tickMajorSize, 0) + tickPadding);
text.attr("dy", ".71em").attr("text-anchor", "middle");
pathUpdate.attr("d", "M" + range[0] + "," + tickEndSize + "V0H" + range[1] + "V" + tickEndSize);
break;
}
case "top":
{
tickTransform = d3_svg_axisX;
subtickEnter.attr("y2", -tickMinorSize);
subtickUpdate.attr("x2", 0).attr("y2", -tickMinorSize);
lineEnter.attr("y2", -tickMajorSize);
textEnter.attr("y", -(Math.max(tickMajorSize, 0) + tickPadding));
lineUpdate.attr("x2", 0).attr("y2", -tickMajorSize);
textUpdate.attr("x", 0).attr("y", -(Math.max(tickMajorSize, 0) + tickPadding));
text.attr("dy", "0em").attr("text-anchor", "middle");
pathUpdate.attr("d", "M" + range[0] + "," + -tickEndSize + "V0H" + range[1] + "V" + -tickEndSize);
break;
}
case "left":
{
tickTransform = d3_svg_axisY;
subtickEnter.attr("x2", -tickMinorSize);
subtickUpdate.attr("x2", -tickMinorSize).attr("y2", 0);
lineEnter.attr("x2", -tickMajorSize);
textEnter.attr("x", -(Math.max(tickMajorSize, 0) + tickPadding));
lineUpdate.attr("x2", -tickMajorSize).attr("y2", 0);
textUpdate.attr("x", -(Math.max(tickMajorSize, 0) + tickPadding)).attr("y", 0);
text.attr("dy", ".32em").attr("text-anchor", "end");
pathUpdate.attr("d", "M" + -tickEndSize + "," + range[0] + "H0V" + range[1] + "H" + -tickEndSize);
break;
}
case "right":
{
tickTransform = d3_svg_axisY;
subtickEnter.attr("x2", tickMinorSize);
subtickUpdate.attr("x2", tickMinorSize).attr("y2", 0);
lineEnter.attr("x2", tickMajorSize);
textEnter.attr("x", Math.max(tickMajorSize, 0) + tickPadding);
lineUpdate.attr("x2", tickMajorSize).attr("y2", 0);
textUpdate.attr("x", Math.max(tickMajorSize, 0) + tickPadding).attr("y", 0);
text.attr("dy", ".32em").attr("text-anchor", "start");
pathUpdate.attr("d", "M" + tickEndSize + "," + range[0] + "H0V" + range[1] + "H" + tickEndSize);
break;
}
}
if (scale.ticks) {
tickEnter.call(tickTransform, scale0);
tickUpdate.call(tickTransform, scale1);
tickExit.call(tickTransform, scale1);
subtickEnter.call(tickTransform, scale0);
subtickUpdate.call(tickTransform, scale1);
subtickExit.call(tickTransform, scale1);
} else {
var dx = scale1.rangeBand() / 2, x = function(d) {
return scale1(d) + dx;
};
tickEnter.call(tickTransform, x);
tickUpdate.call(tickTransform, x);
}
});
}
axis.scale = function(x) {
if (!arguments.length) return scale;
scale = x;
return axis;
};
axis.orient = function(x) {
if (!arguments.length) return orient;
orient = x;
return axis;
};
axis.ticks = function() {
if (!arguments.length) return tickArguments_;
tickArguments_ = arguments;
return axis;
};
axis.tickValues = function(x) {
if (!arguments.length) return tickValues;
tickValues = x;
return axis;
};
axis.tickFormat = function(x) {
if (!arguments.length) return tickFormat_;
tickFormat_ = x;
return axis;
};
axis.tickSize = function(x, y, z) {
if (!arguments.length) return tickMajorSize;
var n = arguments.length - 1;
tickMajorSize = +x;
tickMinorSize = n > 1 ? +y : tickMajorSize;
tickEndSize = n > 0 ? +arguments[n] : tickMajorSize;
return axis;
};
axis.tickPadding = function(x) {
if (!arguments.length) return tickPadding;
tickPadding = +x;
return axis;
};
axis.tickSubdivide = function(x) {
if (!arguments.length) return tickSubdivide;
tickSubdivide = +x;
return axis;
};
return axis;
};
function d3_svg_axisX(selection, x) {
selection.attr("transform", function(d) {
return "translate(" + x(d) + ",0)";
});
}
function d3_svg_axisY(selection, y) {
selection.attr("transform", function(d) {
return "translate(0," + y(d) + ")";
});
}
function d3_svg_axisSubdivide(scale, ticks, m) {
subticks = [];
if (m && ticks.length > 1) {
var extent = d3_scaleExtent(scale.domain()), subticks, i = -1, n = ticks.length, d = (ticks[1] - ticks[0]) / ++m, j, v;
while (++i < n) {
for (j = m; --j > 0; ) {
if ((v = +ticks[i] - j * d) >= extent[0]) {
subticks.push(v);
}
}
}
for (--i, j = 0; ++j < m && (v = +ticks[i] + j * d) < extent[1]; ) {
subticks.push(v);
}
}
return subticks;
}
d3.svg.brush = function() {
var event = d3_eventDispatch(brush, "brushstart", "brush", "brushend"), x = null, y = null, resizes = d3_svg_brushResizes[0], extent = [ [ 0, 0 ], [ 0, 0 ] ], extentDomain;
function brush(g) {
g.each(function() {
var g = d3.select(this), bg = g.selectAll(".background").data([ 0 ]), fg = g.selectAll(".extent").data([ 0 ]), tz = g.selectAll(".resize").data(resizes, String), e;
g.style("pointer-events", "all").on("mousedown.brush", brushstart).on("touchstart.brush", brushstart);
bg.enter().append("rect").attr("class", "background").style("visibility", "hidden").style("cursor", "crosshair");
fg.enter().append("rect").attr("class", "extent").style("cursor", "move");
tz.enter().append("g").attr("class", function(d) {
return "resize " + d;
}).style("cursor", function(d) {
return d3_svg_brushCursor[d];
}).append("rect").attr("x", function(d) {
return /[ew]$/.test(d) ? -3 : null;
}).attr("y", function(d) {
return /^[ns]/.test(d) ? -3 : null;
}).attr("width", 6).attr("height", 6).style("visibility", "hidden");
tz.style("display", brush.empty() ? "none" : null);
tz.exit().remove();
if (x) {
e = d3_scaleRange(x);
bg.attr("x", e[0]).attr("width", e[1] - e[0]);
redrawX(g);
}
if (y) {
e = d3_scaleRange(y);
bg.attr("y", e[0]).attr("height", e[1] - e[0]);
redrawY(g);
}
redraw(g);
});
}
function redraw(g) {
g.selectAll(".resize").attr("transform", function(d) {
return "translate(" + extent[+/e$/.test(d)][0] + "," + extent[+/^s/.test(d)][1] + ")";
});
}
function redrawX(g) {
g.select(".extent").attr("x", extent[0][0]);
g.selectAll(".extent,.n>rect,.s>rect").attr("width", extent[1][0] - extent[0][0]);
}
function redrawY(g) {
g.select(".extent").attr("y", extent[0][1]);
g.selectAll(".extent,.e>rect,.w>rect").attr("height", extent[1][1] - extent[0][1]);
}
function brushstart() {
var target = this, eventTarget = d3.select(d3.event.target), event_ = event.of(target, arguments), g = d3.select(target), resizing = eventTarget.datum(), resizingX = !/^(n|s)$/.test(resizing) && x, resizingY = !/^(e|w)$/.test(resizing) && y, dragging = eventTarget.classed("extent"), center, origin = mouse(), offset;
var w = d3.select(window).on("mousemove.brush", brushmove).on("mouseup.brush", brushend).on("touchmove.brush", brushmove).on("touchend.brush", brushend).on("keydown.brush", keydown).on("keyup.brush", keyup);
if (dragging) {
origin[0] = extent[0][0] - origin[0];
origin[1] = extent[0][1] - origin[1];
} else if (resizing) {
var ex = +/w$/.test(resizing), ey = +/^n/.test(resizing);
offset = [ extent[1 - ex][0] - origin[0], extent[1 - ey][1] - origin[1] ];
origin[0] = extent[ex][0];
origin[1] = extent[ey][1];
} else if (d3.event.altKey) center = origin.slice();
g.style("pointer-events", "none").selectAll(".resize").style("display", null);
d3.select("body").style("cursor", eventTarget.style("cursor"));
event_({
type: "brushstart"
});
brushmove();
d3_eventCancel();
function mouse() {
var touches = d3.event.changedTouches;
return touches ? d3.touches(target, touches)[0] : d3.mouse(target);
}
function keydown() {
if (d3.event.keyCode == 32) {
if (!dragging) {
center = null;
origin[0] -= extent[1][0];
origin[1] -= extent[1][1];
dragging = 2;
}
d3_eventCancel();
}
}
function keyup() {
if (d3.event.keyCode == 32 && dragging == 2) {
origin[0] += extent[1][0];
origin[1] += extent[1][1];
dragging = 0;
d3_eventCancel();
}
}
function brushmove() {
var point = mouse(), moved = false;
if (offset) {
point[0] += offset[0];
point[1] += offset[1];
}
if (!dragging) {
if (d3.event.altKey) {
if (!center) center = [ (extent[0][0] + extent[1][0]) / 2, (extent[0][1] + extent[1][1]) / 2 ];
origin[0] = extent[+(point[0] < center[0])][0];
origin[1] = extent[+(point[1] < center[1])][1];
} else center = null;
}
if (resizingX && move1(point, x, 0)) {
redrawX(g);
moved = true;
}
if (resizingY && move1(point, y, 1)) {
redrawY(g);
moved = true;
}
if (moved) {
redraw(g);
event_({
type: "brush",
mode: dragging ? "move" : "resize"
});
}
}
function move1(point, scale, i) {
var range = d3_scaleRange(scale), r0 = range[0], r1 = range[1], position = origin[i], size = extent[1][i] - extent[0][i], min, max;
if (dragging) {
r0 -= position;
r1 -= size + position;
}
min = Math.max(r0, Math.min(r1, point[i]));
if (dragging) {
max = (min += position) + size;
} else {
if (center) position = Math.max(r0, Math.min(r1, 2 * center[i] - min));
if (position < min) {
max = min;
min = position;
} else {
max = position;
}
}
if (extent[0][i] !== min || extent[1][i] !== max) {
extentDomain = null;
extent[0][i] = min;
extent[1][i] = max;
return true;
}
}
function brushend() {
brushmove();
g.style("pointer-events", "all").selectAll(".resize").style("display", brush.empty() ? "none" : null);
d3.select("body").style("cursor", null);
w.on("mousemove.brush", null).on("mouseup.brush", null).on("touchmove.brush", null).on("touchend.brush", null).on("keydown.brush", null).on("keyup.brush", null);
event_({
type: "brushend"
});
d3_eventCancel();
}
}
brush.x = function(z) {
if (!arguments.length) return x;
x = z;
resizes = d3_svg_brushResizes[!x << 1 | !y];
return brush;
};
brush.y = function(z) {
if (!arguments.length) return y;
y = z;
resizes = d3_svg_brushResizes[!x << 1 | !y];
return brush;
};
brush.extent = function(z) {
var x0, x1, y0, y1, t;
if (!arguments.length) {
z = extentDomain || extent;
if (x) {
x0 = z[0][0], x1 = z[1][0];
if (!extentDomain) {
x0 = extent[0][0], x1 = extent[1][0];
if (x.invert) x0 = x.invert(x0), x1 = x.invert(x1);
if (x1 < x0) t = x0, x0 = x1, x1 = t;
}
}
if (y) {
y0 = z[0][1], y1 = z[1][1];
if (!extentDomain) {
y0 = extent[0][1], y1 = extent[1][1];
if (y.invert) y0 = y.invert(y0), y1 = y.invert(y1);
if (y1 < y0) t = y0, y0 = y1, y1 = t;
}
}
return x && y ? [ [ x0, y0 ], [ x1, y1 ] ] : x ? [ x0, x1 ] : y && [ y0, y1 ];
}
extentDomain = [ [ 0, 0 ], [ 0, 0 ] ];
if (x) {
x0 = z[0], x1 = z[1];
if (y) x0 = x0[0], x1 = x1[0];
extentDomain[0][0] = x0, extentDomain[1][0] = x1;
if (x.invert) x0 = x(x0), x1 = x(x1);
if (x1 < x0) t = x0, x0 = x1, x1 = t;
extent[0][0] = x0 | 0, extent[1][0] = x1 | 0;
}
if (y) {
y0 = z[0], y1 = z[1];
if (x) y0 = y0[1], y1 = y1[1];
extentDomain[0][1] = y0, extentDomain[1][1] = y1;
if (y.invert) y0 = y(y0), y1 = y(y1);
if (y1 < y0) t = y0, y0 = y1, y1 = t;
extent[0][1] = y0 | 0, extent[1][1] = y1 | 0;
}
return brush;
};
brush.clear = function() {
extentDomain = null;
extent[0][0] = extent[0][1] = extent[1][0] = extent[1][1] = 0;
return brush;
};
brush.empty = function() {
return x && extent[0][0] === extent[1][0] || y && extent[0][1] === extent[1][1];
};
return d3.rebind(brush, event, "on");
};
var d3_svg_brushCursor = {
n: "ns-resize",
e: "ew-resize",
s: "ns-resize",
w: "ew-resize",
nw: "nwse-resize",
ne: "nesw-resize",
se: "nwse-resize",
sw: "nesw-resize"
};
var d3_svg_brushResizes = [ [ "n", "e", "s", "w", "nw", "ne", "se", "sw" ], [ "e", "w" ], [ "n", "s" ], [] ];
d3.behavior = {};
d3.behavior.drag = function() {
var event = d3_eventDispatch(drag, "drag", "dragstart", "dragend"), origin = null;
function drag() {
this.on("mousedown.drag", mousedown).on("touchstart.drag", mousedown);
}
function mousedown() {
var target = this, event_ = event.of(target, arguments), eventTarget = d3.event.target, offset, origin_ = point(), moved = 0;
var w = d3.select(window).on("mousemove.drag", dragmove).on("touchmove.drag", dragmove).on("mouseup.drag", dragend, true).on("touchend.drag", dragend, true);
if (origin) {
offset = origin.apply(target, arguments);
offset = [ offset.x - origin_[0], offset.y - origin_[1] ];
} else {
offset = [ 0, 0 ];
}
d3_eventCancel();
event_({
type: "dragstart"
});
function point() {
var p = target.parentNode, t = d3.event.changedTouches;
return t ? d3.touches(p, t)[0] : d3.mouse(p);
}
function dragmove() {
if (!target.parentNode) return dragend();
var p = point(), dx = p[0] - origin_[0], dy = p[1] - origin_[1];
moved |= dx | dy;
origin_ = p;
d3_eventCancel();
event_({
type: "drag",
x: p[0] + offset[0],
y: p[1] + offset[1],
dx: dx,
dy: dy
});
}
function dragend() {
event_({
type: "dragend"
});
if (moved) {
d3_eventCancel();
if (d3.event.target === eventTarget) w.on("click.drag", click, true);
}
w.on("mousemove.drag", null).on("touchmove.drag", null).on("mouseup.drag", null).on("touchend.drag", null);
}
function click() {
d3_eventCancel();
w.on("click.drag", null);
}
}
drag.origin = function(x) {
if (!arguments.length) return origin;
origin = x;
return drag;
};
return d3.rebind(drag, event, "on");
};
d3.behavior.zoom = function() {
var translate = [ 0, 0 ], translate0, scale = 1, scale0, scaleExtent = d3_behavior_zoomInfinity, event = d3_eventDispatch(zoom, "zoom"), x0, x1, y0, y1, touchtime;
function zoom() {
this.on("mousedown.zoom", mousedown).on("mousewheel.zoom", mousewheel).on("mousemove.zoom", mousemove).on("DOMMouseScroll.zoom", mousewheel).on("dblclick.zoom", dblclick).on("touchstart.zoom", touchstart).on("touchmove.zoom", touchmove).on("touchend.zoom", touchstart);
}
zoom.translate = function(x) {
if (!arguments.length) return translate;
translate = x.map(Number);
return zoom;
};
zoom.scale = function(x) {
if (!arguments.length) return scale;
scale = +x;
return zoom;
};
zoom.scaleExtent = function(x) {
if (!arguments.length) return scaleExtent;
scaleExtent = x == null ? d3_behavior_zoomInfinity : x.map(Number);
return zoom;
};
zoom.x = function(z) {
if (!arguments.length) return x1;
x1 = z;
x0 = z.copy();
return zoom;
};
zoom.y = function(z) {
if (!arguments.length) return y1;
y1 = z;
y0 = z.copy();
return zoom;
};
function location(p) {
return [ (p[0] - translate[0]) / scale, (p[1] - translate[1]) / scale ];
}
function point(l) {
return [ l[0] * scale + translate[0], l[1] * scale + translate[1] ];
}
function scaleTo(s) {
scale = Math.max(scaleExtent[0], Math.min(scaleExtent[1], s));
}
function translateTo(p, l) {
l = point(l);
translate[0] += p[0] - l[0];
translate[1] += p[1] - l[1];
}
function dispatch(event) {
if (x1) x1.domain(x0.range().map(function(x) {
return (x - translate[0]) / scale;
}).map(x0.invert));
if (y1) y1.domain(y0.range().map(function(y) {
return (y - translate[1]) / scale;
}).map(y0.invert));
d3.event.preventDefault();
event({
type: "zoom",
scale: scale,
translate: translate
});
}
function mousedown() {
var target = this, event_ = event.of(target, arguments), eventTarget = d3.event.target, moved = 0, w = d3.select(window).on("mousemove.zoom", mousemove).on("mouseup.zoom", mouseup), l = location(d3.mouse(target));
window.focus();
d3_eventCancel();
function mousemove() {
moved = 1;
translateTo(d3.mouse(target), l);
dispatch(event_);
}
function mouseup() {
if (moved) d3_eventCancel();
w.on("mousemove.zoom", null).on("mouseup.zoom", null);
if (moved && d3.event.target === eventTarget) w.on("click.zoom", click, true);
}
function click() {
d3_eventCancel();
w.on("click.zoom", null);
}
}
function mousewheel() {
if (!translate0) translate0 = location(d3.mouse(this));
scaleTo(Math.pow(2, d3_behavior_zoomDelta() * .002) * scale);
translateTo(d3.mouse(this), translate0);
dispatch(event.of(this, arguments));
}
function mousemove() {
translate0 = null;
}
function dblclick() {
var p = d3.mouse(this), l = location(p);
scaleTo(d3.event.shiftKey ? scale / 2 : scale * 2);
translateTo(p, l);
dispatch(event.of(this, arguments));
}
function touchstart() {
var touches = d3.touches(this), now = Date.now();
scale0 = scale;
translate0 = {};
touches.forEach(function(t) {
translate0[t.identifier] = location(t);
});
d3_eventCancel();
if (touches.length === 1) {
if (now - touchtime < 500) {
var p = touches[0], l = location(touches[0]);
scaleTo(scale * 2);
translateTo(p, l);
dispatch(event.of(this, arguments));
}
touchtime = now;
}
}
function touchmove() {
var touches = d3.touches(this), p0 = touches[0], l0 = translate0[p0.identifier];
if (p1 = touches[1]) {
var p1, l1 = translate0[p1.identifier];
p0 = [ (p0[0] + p1[0]) / 2, (p0[1] + p1[1]) / 2 ];
l0 = [ (l0[0] + l1[0]) / 2, (l0[1] + l1[1]) / 2 ];
scaleTo(d3.event.scale * scale0);
}
translateTo(p0, l0);
touchtime = null;
dispatch(event.of(this, arguments));
}
return d3.rebind(zoom, event, "on");
};
var d3_behavior_zoomDiv, d3_behavior_zoomInfinity = [ 0, Infinity ];
function d3_behavior_zoomDelta() {
if (!d3_behavior_zoomDiv) {
d3_behavior_zoomDiv = d3.select("body").append("div").style("visibility", "hidden").style("top", 0).style("height", 0).style("width", 0).style("overflow-y", "scroll").append("div").style("height", "2000px").node().parentNode;
}
var e = d3.event, delta;
try {
d3_behavior_zoomDiv.scrollTop = 1e3;
d3_behavior_zoomDiv.dispatchEvent(e);
delta = 1e3 - d3_behavior_zoomDiv.scrollTop;
} catch (error) {
delta = e.wheelDelta || -e.detail * 5;
}
return delta;
}
d3.layout = {};
d3.layout.bundle = function() {
return function(links) {
var paths = [], i = -1, n = links.length;
while (++i < n) paths.push(d3_layout_bundlePath(links[i]));
return paths;
};
};
function d3_layout_bundlePath(link) {
var start = link.source, end = link.target, lca = d3_layout_bundleLeastCommonAncestor(start, end), points = [ start ];
while (start !== lca) {
start = start.parent;
points.push(start);
}
var k = points.length;
while (end !== lca) {
points.splice(k, 0, end);
end = end.parent;
}
return points;
}
function d3_layout_bundleAncestors(node) {
var ancestors = [], parent = node.parent;
while (parent != null) {
ancestors.push(node);
node = parent;
parent = parent.parent;
}
ancestors.push(node);
return ancestors;
}
function d3_layout_bundleLeastCommonAncestor(a, b) {
if (a === b) return a;
var aNodes = d3_layout_bundleAncestors(a), bNodes = d3_layout_bundleAncestors(b), aNode = aNodes.pop(), bNode = bNodes.pop(), sharedNode = null;
while (aNode === bNode) {
sharedNode = aNode;
aNode = aNodes.pop();
bNode = bNodes.pop();
}
return sharedNode;
}
d3.layout.chord = function() {
var chord = {}, chords, groups, matrix, n, padding = 0, sortGroups, sortSubgroups, sortChords;
function relayout() {
var subgroups = {}, groupSums = [], groupIndex = d3.range(n), subgroupIndex = [], k, x, x0, i, j;
chords = [];
groups = [];
k = 0, i = -1;
while (++i < n) {
x = 0, j = -1;
while (++j < n) {
x += matrix[i][j];
}
groupSums.push(x);
subgroupIndex.push(d3.range(n));
k += x;
}
if (sortGroups) {
groupIndex.sort(function(a, b) {
return sortGroups(groupSums[a], groupSums[b]);
});
}
if (sortSubgroups) {
subgroupIndex.forEach(function(d, i) {
d.sort(function(a, b) {
return sortSubgroups(matrix[i][a], matrix[i][b]);
});
});
}
k = (2 * Math.PI - padding * n) / k;
x = 0, i = -1;
while (++i < n) {
x0 = x, j = -1;
while (++j < n) {
var di = groupIndex[i], dj = subgroupIndex[di][j], v = matrix[di][dj], a0 = x, a1 = x += v * k;
subgroups[di + "-" + dj] = {
index: di,
subindex: dj,
startAngle: a0,
endAngle: a1,
value: v
};
}
groups[di] = {
index: di,
startAngle: x0,
endAngle: x,
value: (x - x0) / k
};
x += padding;
}
i = -1;
while (++i < n) {
j = i - 1;
while (++j < n) {
var source = subgroups[i + "-" + j], target = subgroups[j + "-" + i];
if (source.value || target.value) {
chords.push(source.value < target.value ? {
source: target,
target: source
} : {
source: source,
target: target
});
}
}
}
if (sortChords) resort();
}
function resort() {
chords.sort(function(a, b) {
return sortChords((a.source.value + a.target.value) / 2, (b.source.value + b.target.value) / 2);
});
}
chord.matrix = function(x) {
if (!arguments.length) return matrix;
n = (matrix = x) && matrix.length;
chords = groups = null;
return chord;
};
chord.padding = function(x) {
if (!arguments.length) return padding;
padding = x;
chords = groups = null;
return chord;
};
chord.sortGroups = function(x) {
if (!arguments.length) return sortGroups;
sortGroups = x;
chords = groups = null;
return chord;
};
chord.sortSubgroups = function(x) {
if (!arguments.length) return sortSubgroups;
sortSubgroups = x;
chords = null;
return chord;
};
chord.sortChords = function(x) {
if (!arguments.length) return sortChords;
sortChords = x;
if (chords) resort();
return chord;
};
chord.chords = function() {
if (!chords) relayout();
return chords;
};
chord.groups = function() {
if (!groups) relayout();
return groups;
};
return chord;
};
d3.layout.force = function() {
var force = {}, event = d3.dispatch("start", "tick", "end"), size = [ 1, 1 ], drag, alpha, friction = .9, linkDistance = d3_layout_forceLinkDistance, linkStrength = d3_layout_forceLinkStrength, charge = -30, gravity = .1, theta = .8, interval, nodes = [], links = [], distances, strengths, charges;
function repulse(node) {
return function(quad, x1, y1, x2, y2) {
if (quad.point !== node) {
var dx = quad.cx - node.x, dy = quad.cy - node.y, dn = 1 / Math.sqrt(dx * dx + dy * dy);
if ((x2 - x1) * dn < theta) {
var k = quad.charge * dn * dn;
node.px -= dx * k;
node.py -= dy * k;
return true;
}
if (quad.point && isFinite(dn)) {
var k = quad.pointCharge * dn * dn;
node.px -= dx * k;
node.py -= dy * k;
}
}
return !quad.charge;
};
}
force.tick = function() {
if ((alpha *= .99) < .005) {
event.end({
type: "end",
alpha: alpha = 0
});
return true;
}
var n = nodes.length, m = links.length, q, i, o, s, t, l, k, x, y;
for (i = 0; i < m; ++i) {
o = links[i];
s = o.source;
t = o.target;
x = t.x - s.x;
y = t.y - s.y;
if (l = x * x + y * y) {
l = alpha * strengths[i] * ((l = Math.sqrt(l)) - distances[i]) / l;
x *= l;
y *= l;
t.x -= x * (k = s.weight / (t.weight + s.weight));
t.y -= y * k;
s.x += x * (k = 1 - k);
s.y += y * k;
}
}
if (k = alpha * gravity) {
x = size[0] / 2;
y = size[1] / 2;
i = -1;
if (k) while (++i < n) {
o = nodes[i];
o.x += (x - o.x) * k;
o.y += (y - o.y) * k;
}
}
if (charge) {
d3_layout_forceAccumulate(q = d3.geom.quadtree(nodes), alpha, charges);
i = -1;
while (++i < n) {
if (!(o = nodes[i]).fixed) {
q.visit(repulse(o));
}
}
}
i = -1;
while (++i < n) {
o = nodes[i];
if (o.fixed) {
o.x = o.px;
o.y = o.py;
} else {
o.x -= (o.px - (o.px = o.x)) * friction;
o.y -= (o.py - (o.py = o.y)) * friction;
}
}
event.tick({
type: "tick",
alpha: alpha
});
};
force.nodes = function(x) {
if (!arguments.length) return nodes;
nodes = x;
return force;
};
force.links = function(x) {
if (!arguments.length) return links;
links = x;
return force;
};
force.size = function(x) {
if (!arguments.length) return size;
size = x;
return force;
};
force.linkDistance = function(x) {
if (!arguments.length) return linkDistance;
linkDistance = d3_functor(x);
return force;
};
force.distance = force.linkDistance;
force.linkStrength = function(x) {
if (!arguments.length) return linkStrength;
linkStrength = d3_functor(x);
return force;
};
force.friction = function(x) {
if (!arguments.length) return friction;
friction = x;
return force;
};
force.charge = function(x) {
if (!arguments.length) return charge;
charge = typeof x === "function" ? x : +x;
return force;
};
force.gravity = function(x) {
if (!arguments.length) return gravity;
gravity = x;
return force;
};
force.theta = function(x) {
if (!arguments.length) return theta;
theta = x;
return force;
};
force.alpha = function(x) {
if (!arguments.length) return alpha;
if (alpha) {
if (x > 0) alpha = x; else alpha = 0;
} else if (x > 0) {
event.start({
type: "start",
alpha: alpha = x
});
d3.timer(force.tick);
}
return force;
};
force.start = function() {
var i, j, n = nodes.length, m = links.length, w = size[0], h = size[1], neighbors, o;
for (i = 0; i < n; ++i) {
(o = nodes[i]).index = i;
o.weight = 0;
}
distances = [];
strengths = [];
for (i = 0; i < m; ++i) {
o = links[i];
if (typeof o.source == "number") o.source = nodes[o.source];
if (typeof o.target == "number") o.target = nodes[o.target];
distances[i] = linkDistance.call(this, o, i);
strengths[i] = linkStrength.call(this, o, i);
++o.source.weight;
++o.target.weight;
}
for (i = 0; i < n; ++i) {
o = nodes[i];
if (isNaN(o.x)) o.x = position("x", w);
if (isNaN(o.y)) o.y = position("y", h);
if (isNaN(o.px)) o.px = o.x;
if (isNaN(o.py)) o.py = o.y;
}
charges = [];
if (typeof charge === "function") {
for (i = 0; i < n; ++i) {
charges[i] = +charge.call(this, nodes[i], i);
}
} else {
for (i = 0; i < n; ++i) {
charges[i] = charge;
}
}
function position(dimension, size) {
var neighbors = neighbor(i), j = -1, m = neighbors.length, x;
while (++j < m) if (!isNaN(x = neighbors[j][dimension])) return x;
return Math.random() * size;
}
function neighbor() {
if (!neighbors) {
neighbors = [];
for (j = 0; j < n; ++j) {
neighbors[j] = [];
}
for (j = 0; j < m; ++j) {
var o = links[j];
neighbors[o.source.index].push(o.target);
neighbors[o.target.index].push(o.source);
}
}
return neighbors[i];
}
return force.resume();
};
force.resume = function() {
return force.alpha(.1);
};
force.stop = function() {
return force.alpha(0);
};
force.drag = function() {
if (!drag) drag = d3.behavior.drag().origin(d3_identity).on("dragstart", dragstart).on("drag", d3_layout_forceDrag).on("dragend", d3_layout_forceDragEnd);
this.on("mouseover.force", d3_layout_forceDragOver).on("mouseout.force", d3_layout_forceDragOut).call(drag);
};
function dragstart(d) {
d3_layout_forceDragOver(d3_layout_forceDragNode = d);
d3_layout_forceDragForce = force;
}
return d3.rebind(force, event, "on");
};
var d3_layout_forceDragForce, d3_layout_forceDragNode;
function d3_layout_forceDragOver(d) {
d.fixed |= 2;
}
function d3_layout_forceDragOut(d) {
if (d !== d3_layout_forceDragNode) d.fixed &= 1;
}
function d3_layout_forceDragEnd() {
d3_layout_forceDragNode.fixed &= 1;
d3_layout_forceDragForce = d3_layout_forceDragNode = null;
}
function d3_layout_forceDrag() {
d3_layout_forceDragNode.px = d3.event.x;
d3_layout_forceDragNode.py = d3.event.y;
d3_layout_forceDragForce.resume();
}
function d3_layout_forceAccumulate(quad, alpha, charges) {
var cx = 0, cy = 0;
quad.charge = 0;
if (!quad.leaf) {
var nodes = quad.nodes, n = nodes.length, i = -1, c;
while (++i < n) {
c = nodes[i];
if (c == null) continue;
d3_layout_forceAccumulate(c, alpha, charges);
quad.charge += c.charge;
cx += c.charge * c.cx;
cy += c.charge * c.cy;
}
}
if (quad.point) {
if (!quad.leaf) {
quad.point.x += Math.random() - .5;
quad.point.y += Math.random() - .5;
}
var k = alpha * charges[quad.point.index];
quad.charge += quad.pointCharge = k;
cx += k * quad.point.x;
cy += k * quad.point.y;
}
quad.cx = cx / quad.charge;
quad.cy = cy / quad.charge;
}
function d3_layout_forceLinkDistance(link) {
return 20;
}
function d3_layout_forceLinkStrength(link) {
return 1;
}
d3.layout.partition = function() {
var hierarchy = d3.layout.hierarchy(), size = [ 1, 1 ];
function position(node, x, dx, dy) {
var children = node.children;
node.x = x;
node.y = node.depth * dy;
node.dx = dx;
node.dy = dy;
if (children && (n = children.length)) {
var i = -1, n, c, d;
dx = node.value ? dx / node.value : 0;
while (++i < n) {
position(c = children[i], x, d = c.value * dx, dy);
x += d;
}
}
}
function depth(node) {
var children = node.children, d = 0;
if (children && (n = children.length)) {
var i = -1, n;
while (++i < n) d = Math.max(d, depth(children[i]));
}
return 1 + d;
}
function partition(d, i) {
var nodes = hierarchy.call(this, d, i);
position(nodes[0], 0, size[0], size[1] / depth(nodes[0]));
return nodes;
}
partition.size = function(x) {
if (!arguments.length) return size;
size = x;
return partition;
};
return d3_layout_hierarchyRebind(partition, hierarchy);
};
d3.layout.pie = function() {
var value = Number, sort = d3_layout_pieSortByValue, startAngle = 0, endAngle = 2 * Math.PI;
function pie(data, i) {
var values = data.map(function(d, i) {
return +value.call(pie, d, i);
});
var a = +(typeof startAngle === "function" ? startAngle.apply(this, arguments) : startAngle);
var k = ((typeof endAngle === "function" ? endAngle.apply(this, arguments) : endAngle) - startAngle) / d3.sum(values);
var index = d3.range(data.length);
if (sort != null) index.sort(sort === d3_layout_pieSortByValue ? function(i, j) {
return values[j] - values[i];
} : function(i, j) {
return sort(data[i], data[j]);
});
var arcs = [];
index.forEach(function(i) {
var d;
arcs[i] = {
data: data[i],
value: d = values[i],
startAngle: a,
endAngle: a += d * k
};
});
return arcs;
}
pie.value = function(x) {
if (!arguments.length) return value;
value = x;
return pie;
};
pie.sort = function(x) {
if (!arguments.length) return sort;
sort = x;
return pie;
};
pie.startAngle = function(x) {
if (!arguments.length) return startAngle;
startAngle = x;
return pie;
};
pie.endAngle = function(x) {
if (!arguments.length) return endAngle;
endAngle = x;
return pie;
};
return pie;
};
var d3_layout_pieSortByValue = {};
d3.layout.stack = function() {
var values = d3_identity, order = d3_layout_stackOrderDefault, offset = d3_layout_stackOffsetZero, out = d3_layout_stackOut, x = d3_layout_stackX, y = d3_layout_stackY;
function stack(data, index) {
var series = data.map(function(d, i) {
return values.call(stack, d, i);
});
var points = series.map(function(d, i) {
return d.map(function(v, i) {
return [ x.call(stack, v, i), y.call(stack, v, i) ];
});
});
var orders = order.call(stack, points, index);
series = d3.permute(series, orders);
points = d3.permute(points, orders);
var offsets = offset.call(stack, points, index);
var n = series.length, m = series[0].length, i, j, o;
for (j = 0; j < m; ++j) {
out.call(stack, series[0][j], o = offsets[j], points[0][j][1]);
for (i = 1; i < n; ++i) {
out.call(stack, series[i][j], o += points[i - 1][j][1], points[i][j][1]);
}
}
return data;
}
stack.values = function(x) {
if (!arguments.length) return values;
values = x;
return stack;
};
stack.order = function(x) {
if (!arguments.length) return order;
order = typeof x === "function" ? x : d3_layout_stackOrders.get(x) || d3_layout_stackOrderDefault;
return stack;
};
stack.offset = function(x) {
if (!arguments.length) return offset;
offset = typeof x === "function" ? x : d3_layout_stackOffsets.get(x) || d3_layout_stackOffsetZero;
return stack;
};
stack.x = function(z) {
if (!arguments.length) return x;
x = z;
return stack;
};
stack.y = function(z) {
if (!arguments.length) return y;
y = z;
return stack;
};
stack.out = function(z) {
if (!arguments.length) return out;
out = z;
return stack;
};
return stack;
};
function d3_layout_stackX(d) {
return d.x;
}
function d3_layout_stackY(d) {
return d.y;
}
function d3_layout_stackOut(d, y0, y) {
d.y0 = y0;
d.y = y;
}
var d3_layout_stackOrders = d3.map({
"inside-out": function(data) {
var n = data.length, i, j, max = data.map(d3_layout_stackMaxIndex), sums = data.map(d3_layout_stackReduceSum), index = d3.range(n).sort(function(a, b) {
return max[a] - max[b];
}), top = 0, bottom = 0, tops = [], bottoms = [];
for (i = 0; i < n; ++i) {
j = index[i];
if (top < bottom) {
top += sums[j];
tops.push(j);
} else {
bottom += sums[j];
bottoms.push(j);
}
}
return bottoms.reverse().concat(tops);
},
reverse: function(data) {
return d3.range(data.length).reverse();
},
"default": d3_layout_stackOrderDefault
});
var d3_layout_stackOffsets = d3.map({
silhouette: function(data) {
var n = data.length, m = data[0].length, sums = [], max = 0, i, j, o, y0 = [];
for (j = 0; j < m; ++j) {
for (i = 0, o = 0; i < n; i++) o += data[i][j][1];
if (o > max) max = o;
sums.push(o);
}
for (j = 0; j < m; ++j) {
y0[j] = (max - sums[j]) / 2;
}
return y0;
},
wiggle: function(data) {
var n = data.length, x = data[0], m = x.length, max = 0, i, j, k, s1, s2, s3, dx, o, o0, y0 = [];
y0[0] = o = o0 = 0;
for (j = 1; j < m; ++j) {
for (i = 0, s1 = 0; i < n; ++i) s1 += data[i][j][1];
for (i = 0, s2 = 0, dx = x[j][0] - x[j - 1][0]; i < n; ++i) {
for (k = 0, s3 = (data[i][j][1] - data[i][j - 1][1]) / (2 * dx); k < i; ++k) {
s3 += (data[k][j][1] - data[k][j - 1][1]) / dx;
}
s2 += s3 * data[i][j][1];
}
y0[j] = o -= s1 ? s2 / s1 * dx : 0;
if (o < o0) o0 = o;
}
for (j = 0; j < m; ++j) y0[j] -= o0;
return y0;
},
expand: function(data) {
var n = data.length, m = data[0].length, k = 1 / n, i, j, o, y0 = [];
for (j = 0; j < m; ++j) {
for (i = 0, o = 0; i < n; i++) o += data[i][j][1];
if (o) for (i = 0; i < n; i++) data[i][j][1] /= o; else for (i = 0; i < n; i++) data[i][j][1] = k;
}
for (j = 0; j < m; ++j) y0[j] = 0;
return y0;
},
zero: d3_layout_stackOffsetZero
});
function d3_layout_stackOrderDefault(data) {
return d3.range(data.length);
}
function d3_layout_stackOffsetZero(data) {
var j = -1, m = data[0].length, y0 = [];
while (++j < m) y0[j] = 0;
return y0;
}
function d3_layout_stackMaxIndex(array) {
var i = 1, j = 0, v = array[0][1], k, n = array.length;
for (; i < n; ++i) {
if ((k = array[i][1]) > v) {
j = i;
v = k;
}
}
return j;
}
function d3_layout_stackReduceSum(d) {
return d.reduce(d3_layout_stackSum, 0);
}
function d3_layout_stackSum(p, d) {
return p + d[1];
}
d3.layout.histogram = function() {
var frequency = true, valuer = Number, ranger = d3_layout_histogramRange, binner = d3_layout_histogramBinSturges;
function histogram(data, i) {
var bins = [], values = data.map(valuer, this), range = ranger.call(this, values, i), thresholds = binner.call(this, range, values, i), bin, i = -1, n = values.length, m = thresholds.length - 1, k = frequency ? 1 : 1 / n, x;
while (++i < m) {
bin = bins[i] = [];
bin.dx = thresholds[i + 1] - (bin.x = thresholds[i]);
bin.y = 0;
}
if (m > 0) {
i = -1;
while (++i < n) {
x = values[i];
if (x >= range[0] && x <= range[1]) {
bin = bins[d3.bisect(thresholds, x, 1, m) - 1];
bin.y += k;
bin.push(data[i]);
}
}
}
return bins;
}
histogram.value = function(x) {
if (!arguments.length) return valuer;
valuer = x;
return histogram;
};
histogram.range = function(x) {
if (!arguments.length) return ranger;
ranger = d3_functor(x);
return histogram;
};
histogram.bins = function(x) {
if (!arguments.length) return binner;
binner = typeof x === "number" ? function(range) {
return d3_layout_histogramBinFixed(range, x);
} : d3_functor(x);
return histogram;
};
histogram.frequency = function(x) {
if (!arguments.length) return frequency;
frequency = !!x;
return histogram;
};
return histogram;
};
function d3_layout_histogramBinSturges(range, values) {
return d3_layout_histogramBinFixed(range, Math.ceil(Math.log(values.length) / Math.LN2 + 1));
}
function d3_layout_histogramBinFixed(range, n) {
var x = -1, b = +range[0], m = (range[1] - b) / n, f = [];
while (++x <= n) f[x] = m * x + b;
return f;
}
function d3_layout_histogramRange(values) {
return [ d3.min(values), d3.max(values) ];
}
d3.layout.hierarchy = function() {
var sort = d3_layout_hierarchySort, children = d3_layout_hierarchyChildren, value = d3_layout_hierarchyValue;
function recurse(data, depth, nodes) {
var childs = children.call(hierarchy, data, depth), node = d3_layout_hierarchyInline ? data : {
data: data
};
node.depth = depth;
nodes.push(node);
if (childs && (n = childs.length)) {
var i = -1, n, c = node.children = [], v = 0, j = depth + 1, d;
while (++i < n) {
d = recurse(childs[i], j, nodes);
d.parent = node;
c.push(d);
v += d.value;
}
if (sort) c.sort(sort);
if (value) node.value = v;
} else if (value) {
node.value = +value.call(hierarchy, data, depth) || 0;
}
return node;
}
function revalue(node, depth) {
var children = node.children, v = 0;
if (children && (n = children.length)) {
var i = -1, n, j = depth + 1;
while (++i < n) v += revalue(children[i], j);
} else if (value) {
v = +value.call(hierarchy, d3_layout_hierarchyInline ? node : node.data, depth) || 0;
}
if (value) node.value = v;
return v;
}
function hierarchy(d) {
var nodes = [];
recurse(d, 0, nodes);
return nodes;
}
hierarchy.sort = function(x) {
if (!arguments.length) return sort;
sort = x;
return hierarchy;
};
hierarchy.children = function(x) {
if (!arguments.length) return children;
children = x;
return hierarchy;
};
hierarchy.value = function(x) {
if (!arguments.length) return value;
value = x;
return hierarchy;
};
hierarchy.revalue = function(root) {
revalue(root, 0);
return root;
};
return hierarchy;
};
function d3_layout_hierarchyRebind(object, hierarchy) {
d3.rebind(object, hierarchy, "sort", "children", "value");
object.links = d3_layout_hierarchyLinks;
object.nodes = function(d) {
d3_layout_hierarchyInline = true;
return (object.nodes = object)(d);
};
return object;
}
function d3_layout_hierarchyChildren(d) {
return d.children;
}
function d3_layout_hierarchyValue(d) {
return d.value;
}
function d3_layout_hierarchySort(a, b) {
return b.value - a.value;
}
function d3_layout_hierarchyLinks(nodes) {
return d3.merge(nodes.map(function(parent) {
return (parent.children || []).map(function(child) {
return {
source: parent,
target: child
};
});
}));
}
var d3_layout_hierarchyInline = false;
d3.layout.pack = function() {
var hierarchy = d3.layout.hierarchy().sort(d3_layout_packSort), size = [ 1, 1 ];
function pack(d, i) {
var nodes = hierarchy.call(this, d, i), root = nodes[0];
root.x = 0;
root.y = 0;
d3_layout_packTree(root);
var w = size[0], h = size[1], k = 1 / Math.max(2 * root.r / w, 2 * root.r / h);
d3_layout_packTransform(root, w / 2, h / 2, k);
return nodes;
}
pack.size = function(x) {
if (!arguments.length) return size;
size = x;
return pack;
};
return d3_layout_hierarchyRebind(pack, hierarchy);
};
function d3_layout_packSort(a, b) {
return a.value - b.value;
}
function d3_layout_packInsert(a, b) {
var c = a._pack_next;
a._pack_next = b;
b._pack_prev = a;
b._pack_next = c;
c._pack_prev = b;
}
function d3_layout_packSplice(a, b) {
a._pack_next = b;
b._pack_prev = a;
}
function d3_layout_packIntersects(a, b) {
var dx = b.x - a.x, dy = b.y - a.y, dr = a.r + b.r;
return dr * dr - dx * dx - dy * dy > .001;
}
function d3_layout_packCircle(nodes) {
var xMin = Infinity, xMax = -Infinity, yMin = Infinity, yMax = -Infinity, n = nodes.length, a, b, c, j, k;
function bound(node) {
xMin = Math.min(node.x - node.r, xMin);
xMax = Math.max(node.x + node.r, xMax);
yMin = Math.min(node.y - node.r, yMin);
yMax = Math.max(node.y + node.r, yMax);
}
nodes.forEach(d3_layout_packLink);
a = nodes[0];
a.x = -a.r;
a.y = 0;
bound(a);
if (n > 1) {
b = nodes[1];
b.x = b.r;
b.y = 0;
bound(b);
if (n > 2) {
c = nodes[2];
d3_layout_packPlace(a, b, c);
bound(c);
d3_layout_packInsert(a, c);
a._pack_prev = c;
d3_layout_packInsert(c, b);
b = a._pack_next;
for (var i = 3; i < n; i++) {
d3_layout_packPlace(a, b, c = nodes[i]);
var isect = 0, s1 = 1, s2 = 1;
for (j = b._pack_next; j !== b; j = j._pack_next, s1++) {
if (d3_layout_packIntersects(j, c)) {
isect = 1;
break;
}
}
if (isect == 1) {
for (k = a._pack_prev; k !== j._pack_prev; k = k._pack_prev, s2++) {
if (d3_layout_packIntersects(k, c)) {
break;
}
}
}
if (isect) {
if (s1 < s2 || s1 == s2 && b.r < a.r) d3_layout_packSplice(a, b = j); else d3_layout_packSplice(a = k, b);
i--;
} else {
d3_layout_packInsert(a, c);
b = c;
bound(c);
}
}
}
}
var cx = (xMin + xMax) / 2, cy = (yMin + yMax) / 2, cr = 0;
for (var i = 0; i < n; i++) {
var node = nodes[i];
node.x -= cx;
node.y -= cy;
cr = Math.max(cr, node.r + Math.sqrt(node.x * node.x + node.y * node.y));
}
nodes.forEach(d3_layout_packUnlink);
return cr;
}
function d3_layout_packLink(node) {
node._pack_next = node._pack_prev = node;
}
function d3_layout_packUnlink(node) {
delete node._pack_next;
delete node._pack_prev;
}
function d3_layout_packTree(node) {
var children = node.children;
if (children && children.length) {
children.forEach(d3_layout_packTree);
node.r = d3_layout_packCircle(children);
} else {
node.r = Math.sqrt(node.value);
}
}
function d3_layout_packTransform(node, x, y, k) {
var children = node.children;
node.x = x += k * node.x;
node.y = y += k * node.y;
node.r *= k;
if (children) {
var i = -1, n = children.length;
while (++i < n) d3_layout_packTransform(children[i], x, y, k);
}
}
function d3_layout_packPlace(a, b, c) {
var db = a.r + c.r, dx = b.x - a.x, dy = b.y - a.y;
if (db && (dx || dy)) {
var da = b.r + c.r, dc = dx * dx + dy * dy;
da *= da;
db *= db;
var x = .5 + (db - da) / (2 * dc), y = Math.sqrt(Math.max(0, 2 * da * (db + dc) - (db -= dc) * db - da * da)) / (2 * dc);
c.x = a.x + x * dx + y * dy;
c.y = a.y + x * dy - y * dx;
} else {
c.x = a.x + db;
c.y = a.y;
}
}
d3.layout.cluster = function() {
var hierarchy = d3.layout.hierarchy().sort(null).value(null), separation = d3_layout_treeSeparation, size = [ 1, 1 ];
function cluster(d, i) {
var nodes = hierarchy.call(this, d, i), root = nodes[0], previousNode, x = 0, kx, ky;
d3_layout_treeVisitAfter(root, function(node) {
var children = node.children;
if (children && children.length) {
node.x = d3_layout_clusterX(children);
node.y = d3_layout_clusterY(children);
} else {
node.x = previousNode ? x += separation(node, previousNode) : 0;
node.y = 0;
previousNode = node;
}
});
var left = d3_layout_clusterLeft(root), right = d3_layout_clusterRight(root), x0 = left.x - separation(left, right) / 2, x1 = right.x + separation(right, left) / 2;
d3_layout_treeVisitAfter(root, function(node) {
node.x = (node.x - x0) / (x1 - x0) * size[0];
node.y = (1 - (root.y ? node.y / root.y : 1)) * size[1];
});
return nodes;
}
cluster.separation = function(x) {
if (!arguments.length) return separation;
separation = x;
return cluster;
};
cluster.size = function(x) {
if (!arguments.length) return size;
size = x;
return cluster;
};
return d3_layout_hierarchyRebind(cluster, hierarchy);
};
function d3_layout_clusterY(children) {
return 1 + d3.max(children, function(child) {
return child.y;
});
}
function d3_layout_clusterX(children) {
return children.reduce(function(x, child) {
return x + child.x;
}, 0) / children.length;
}
function d3_layout_clusterLeft(node) {
var children = node.children;
return children && children.length ? d3_layout_clusterLeft(children[0]) : node;
}
function d3_layout_clusterRight(node) {
var children = node.children, n;
return children && (n = children.length) ? d3_layout_clusterRight(children[n - 1]) : node;
}
d3.layout.tree = function() {
var hierarchy = d3.layout.hierarchy().sort(null).value(null), separation = d3_layout_treeSeparation, size = [ 1, 1 ];
function tree(d, i) {
var nodes = hierarchy.call(this, d, i), root = nodes[0];
function firstWalk(node, previousSibling) {
var children = node.children, layout = node._tree;
if (children && (n = children.length)) {
var n, firstChild = children[0], previousChild, ancestor = firstChild, child, i = -1;
while (++i < n) {
child = children[i];
firstWalk(child, previousChild);
ancestor = apportion(child, previousChild, ancestor);
previousChild = child;
}
d3_layout_treeShift(node);
var midpoint = .5 * (firstChild._tree.prelim + child._tree.prelim);
if (previousSibling) {
layout.prelim = previousSibling._tree.prelim + separation(node, previousSibling);
layout.mod = layout.prelim - midpoint;
} else {
layout.prelim = midpoint;
}
} else {
if (previousSibling) {
layout.prelim = previousSibling._tree.prelim + separation(node, previousSibling);
}
}
}
function secondWalk(node, x) {
node.x = node._tree.prelim + x;
var children = node.children;
if (children && (n = children.length)) {
var i = -1, n;
x += node._tree.mod;
while (++i < n) {
secondWalk(children[i], x);
}
}
}
function apportion(node, previousSibling, ancestor) {
if (previousSibling) {
var vip = node, vop = node, vim = previousSibling, vom = node.parent.children[0], sip = vip._tree.mod, sop = vop._tree.mod, sim = vim._tree.mod, som = vom._tree.mod, shift;
while (vim = d3_layout_treeRight(vim), vip = d3_layout_treeLeft(vip), vim && vip) {
vom = d3_layout_treeLeft(vom);
vop = d3_layout_treeRight(vop);
vop._tree.ancestor = node;
shift = vim._tree.prelim + sim - vip._tree.prelim - sip + separation(vim, vip);
if (shift > 0) {
d3_layout_treeMove(d3_layout_treeAncestor(vim, node, ancestor), node, shift);
sip += shift;
sop += shift;
}
sim += vim._tree.mod;
sip += vip._tree.mod;
som += vom._tree.mod;
sop += vop._tree.mod;
}
if (vim && !d3_layout_treeRight(vop)) {
vop._tree.thread = vim;
vop._tree.mod += sim - sop;
}
if (vip && !d3_layout_treeLeft(vom)) {
vom._tree.thread = vip;
vom._tree.mod += sip - som;
ancestor = node;
}
}
return ancestor;
}
d3_layout_treeVisitAfter(root, function(node, previousSibling) {
node._tree = {
ancestor: node,
prelim: 0,
mod: 0,
change: 0,
shift: 0,
number: previousSibling ? previousSibling._tree.number + 1 : 0
};
});
firstWalk(root);
secondWalk(root, -root._tree.prelim);
var left = d3_layout_treeSearch(root, d3_layout_treeLeftmost), right = d3_layout_treeSearch(root, d3_layout_treeRightmost), deep = d3_layout_treeSearch(root, d3_layout_treeDeepest), x0 = left.x - separation(left, right) / 2, x1 = right.x + separation(right, left) / 2, y1 = deep.depth || 1;
d3_layout_treeVisitAfter(root, function(node) {
node.x = (node.x - x0) / (x1 - x0) * size[0];
node.y = node.depth / y1 * size[1];
delete node._tree;
});
return nodes;
}
tree.separation = function(x) {
if (!arguments.length) return separation;
separation = x;
return tree;
};
tree.size = function(x) {
if (!arguments.length) return size;
size = x;
return tree;
};
return d3_layout_hierarchyRebind(tree, hierarchy);
};
function d3_layout_treeSeparation(a, b) {
return a.parent == b.parent ? 1 : 2;
}
function d3_layout_treeLeft(node) {
var children = node.children;
return children && children.length ? children[0] : node._tree.thread;
}
function d3_layout_treeRight(node) {
var children = node.children, n;
return children && (n = children.length) ? children[n - 1] : node._tree.thread;
}
function d3_layout_treeSearch(node, compare) {
var children = node.children;
if (children && (n = children.length)) {
var child, n, i = -1;
while (++i < n) {
if (compare(child = d3_layout_treeSearch(children[i], compare), node) > 0) {
node = child;
}
}
}
return node;
}
function d3_layout_treeRightmost(a, b) {
return a.x - b.x;
}
function d3_layout_treeLeftmost(a, b) {
return b.x - a.x;
}
function d3_layout_treeDeepest(a, b) {
return a.depth - b.depth;
}
function d3_layout_treeVisitAfter(node, callback) {
function visit(node, previousSibling) {
var children = node.children;
if (children && (n = children.length)) {
var child, previousChild = null, i = -1, n;
while (++i < n) {
child = children[i];
visit(child, previousChild);
previousChild = child;
}
}
callback(node, previousSibling);
}
visit(node, null);
}
function d3_layout_treeShift(node) {
var shift = 0, change = 0, children = node.children, i = children.length, child;
while (--i >= 0) {
child = children[i]._tree;
child.prelim += shift;
child.mod += shift;
shift += child.shift + (change += child.change);
}
}
function d3_layout_treeMove(ancestor, node, shift) {
ancestor = ancestor._tree;
node = node._tree;
var change = shift / (node.number - ancestor.number);
ancestor.change += change;
node.change -= change;
node.shift += shift;
node.prelim += shift;
node.mod += shift;
}
function d3_layout_treeAncestor(vim, node, ancestor) {
return vim._tree.ancestor.parent == node.parent ? vim._tree.ancestor : ancestor;
}
d3.layout.treemap = function() {
var hierarchy = d3.layout.hierarchy(), round = Math.round, size = [ 1, 1 ], padding = null, pad = d3_layout_treemapPadNull, sticky = false, stickies, ratio = .5 * (1 + Math.sqrt(5));
function scale(children, k) {
var i = -1, n = children.length, child, area;
while (++i < n) {
area = (child = children[i]).value * (k < 0 ? 0 : k);
child.area = isNaN(area) || area <= 0 ? 0 : area;
}
}
function squarify(node) {
var children = node.children;
if (children && children.length) {
var rect = pad(node), row = [], remaining = children.slice(), child, best = Infinity, score, u = Math.min(rect.dx, rect.dy), n;
scale(remaining, rect.dx * rect.dy / node.value);
row.area = 0;
while ((n = remaining.length) > 0) {
row.push(child = remaining[n - 1]);
row.area += child.area;
if ((score = worst(row, u)) <= best) {
remaining.pop();
best = score;
} else {
row.area -= row.pop().area;
position(row, u, rect, false);
u = Math.min(rect.dx, rect.dy);
row.length = row.area = 0;
best = Infinity;
}
}
if (row.length) {
position(row, u, rect, true);
row.length = row.area = 0;
}
children.forEach(squarify);
}
}
function stickify(node) {
var children = node.children;
if (children && children.length) {
var rect = pad(node), remaining = children.slice(), child, row = [];
scale(remaining, rect.dx * rect.dy / node.value);
row.area = 0;
while (child = remaining.pop()) {
row.push(child);
row.area += child.area;
if (child.z != null) {
position(row, child.z ? rect.dx : rect.dy, rect, !remaining.length);
row.length = row.area = 0;
}
}
children.forEach(stickify);
}
}
function worst(row, u) {
var s = row.area, r, rmax = 0, rmin = Infinity, i = -1, n = row.length;
while (++i < n) {
if (!(r = row[i].area)) continue;
if (r < rmin) rmin = r;
if (r > rmax) rmax = r;
}
s *= s;
u *= u;
return s ? Math.max(u * rmax * ratio / s, s / (u * rmin * ratio)) : Infinity;
}
function position(row, u, rect, flush) {
var i = -1, n = row.length, x = rect.x, y = rect.y, v = u ? round(row.area / u) : 0, o;
if (u == rect.dx) {
if (flush || v > rect.dy) v = rect.dy;
while (++i < n) {
o = row[i];
o.x = x;
o.y = y;
o.dy = v;
x += o.dx = Math.min(rect.x + rect.dx - x, v ? round(o.area / v) : 0);
}
o.z = true;
o.dx += rect.x + rect.dx - x;
rect.y += v;
rect.dy -= v;
} else {
if (flush || v > rect.dx) v = rect.dx;
while (++i < n) {
o = row[i];
o.x = x;
o.y = y;
o.dx = v;
y += o.dy = Math.min(rect.y + rect.dy - y, v ? round(o.area / v) : 0);
}
o.z = false;
o.dy += rect.y + rect.dy - y;
rect.x += v;
rect.dx -= v;
}
}
function treemap(d) {
var nodes = stickies || hierarchy(d), root = nodes[0];
root.x = 0;
root.y = 0;
root.dx = size[0];
root.dy = size[1];
if (stickies) hierarchy.revalue(root);
scale([ root ], root.dx * root.dy / root.value);
(stickies ? stickify : squarify)(root);
if (sticky) stickies = nodes;
return nodes;
}
treemap.size = function(x) {
if (!arguments.length) return size;
size = x;
return treemap;
};
treemap.padding = function(x) {
if (!arguments.length) return padding;
function padFunction(node) {
var p = x.call(treemap, node, node.depth);
return p == null ? d3_layout_treemapPadNull(node) : d3_layout_treemapPad(node, typeof p === "number" ? [ p, p, p, p ] : p);
}
function padConstant(node) {
return d3_layout_treemapPad(node, x);
}
var type;
pad = (padding = x) == null ? d3_layout_treemapPadNull : (type = typeof x) === "function" ? padFunction : type === "number" ? (x = [ x, x, x, x ], padConstant) : padConstant;
return treemap;
};
treemap.round = function(x) {
if (!arguments.length) return round != Number;
round = x ? Math.round : Number;
return treemap;
};
treemap.sticky = function(x) {
if (!arguments.length) return sticky;
sticky = x;
stickies = null;
return treemap;
};
treemap.ratio = function(x) {
if (!arguments.length) return ratio;
ratio = x;
return treemap;
};
return d3_layout_hierarchyRebind(treemap, hierarchy);
};
function d3_layout_treemapPadNull(node) {
return {
x: node.x,
y: node.y,
dx: node.dx,
dy: node.dy
};
}
function d3_layout_treemapPad(node, padding) {
var x = node.x + padding[3], y = node.y + padding[0], dx = node.dx - padding[1] - padding[3], dy = node.dy - padding[0] - padding[2];
if (dx < 0) {
x += dx / 2;
dx = 0;
}
if (dy < 0) {
y += dy / 2;
dy = 0;
}
return {
x: x,
y: y,
dx: dx,
dy: dy
};
}
d3.csv = function(url, callback) {
d3.text(url, "text/csv", function(text) {
callback(text && d3.csv.parse(text));
});
};
d3.csv.parse = function(text) {
var header;
return d3.csv.parseRows(text, function(row, i) {
if (i) {
var o = {}, j = -1, m = header.length;
while (++j < m) o[header[j]] = row[j];
return o;
} else {
header = row;
return null;
}
});
};
d3.csv.parseRows = function(text, f) {
var EOL = {}, EOF = {}, rows = [], re = /\r\n|[,\r\n]/g, n = 0, t, eol;
re.lastIndex = 0;
function token() {
if (re.lastIndex >= text.length) return EOF;
if (eol) {
eol = false;
return EOL;
}
var j = re.lastIndex;
if (text.charCodeAt(j) === 34) {
var i = j;
while (i++ < text.length) {
if (text.charCodeAt(i) === 34) {
if (text.charCodeAt(i + 1) !== 34) break;
i++;
}
}
re.lastIndex = i + 2;
var c = text.charCodeAt(i + 1);
if (c === 13) {
eol = true;
if (text.charCodeAt(i + 2) === 10) re.lastIndex++;
} else if (c === 10) {
eol = true;
}
return text.substring(j + 1, i).replace(/""/g, '"');
}
var m = re.exec(text);
if (m) {
eol = m[0].charCodeAt(0) !== 44;
return text.substring(j, m.index);
}
re.lastIndex = text.length;
return text.substring(j);
}
while ((t = token()) !== EOF) {
var a = [];
while (t !== EOL && t !== EOF) {
a.push(t);
t = token();
}
if (f && !(a = f(a, n++))) continue;
rows.push(a);
}
return rows;
};
d3.csv.format = function(rows) {
return rows.map(d3_csv_formatRow).join("\n");
};
function d3_csv_formatRow(row) {
return row.map(d3_csv_formatValue).join(",");
}
function d3_csv_formatValue(text) {
return /[",\n]/.test(text) ? '"' + text.replace(/\"/g, '""') + '"' : text;
}
d3.geo = {};
var d3_geo_radians = Math.PI / 180;
d3.geo.azimuthal = function() {
var mode = "orthographic", origin, scale = 200, translate = [ 480, 250 ], x0, y0, cy0, sy0;
function azimuthal(coordinates) {
var x1 = coordinates[0] * d3_geo_radians - x0, y1 = coordinates[1] * d3_geo_radians, cx1 = Math.cos(x1), sx1 = Math.sin(x1), cy1 = Math.cos(y1), sy1 = Math.sin(y1), cc = mode !== "orthographic" ? sy0 * sy1 + cy0 * cy1 * cx1 : null, c, k = mode === "stereographic" ? 1 / (1 + cc) : mode === "gnomonic" ? 1 / cc : mode === "equidistant" ? (c = Math.acos(cc), c ? c / Math.sin(c) : 0) : mode === "equalarea" ? Math.sqrt(2 / (1 + cc)) : 1, x = k * cy1 * sx1, y = k * (sy0 * cy1 * cx1 - cy0 * sy1);
return [ scale * x + translate[0], scale * y + translate[1] ];
}
azimuthal.invert = function(coordinates) {
var x = (coordinates[0] - translate[0]) / scale, y = (coordinates[1] - translate[1]) / scale, p = Math.sqrt(x * x + y * y), c = mode === "stereographic" ? 2 * Math.atan(p) : mode === "gnomonic" ? Math.atan(p) : mode === "equidistant" ? p : mode === "equalarea" ? 2 * Math.asin(.5 * p) : Math.asin(p), sc = Math.sin(c), cc = Math.cos(c);
return [ (x0 + Math.atan2(x * sc, p * cy0 * cc + y * sy0 * sc)) / d3_geo_radians, Math.asin(cc * sy0 - (p ? y * sc * cy0 / p : 0)) / d3_geo_radians ];
};
azimuthal.mode = function(x) {
if (!arguments.length) return mode;
mode = x + "";
return azimuthal;
};
azimuthal.origin = function(x) {
if (!arguments.length) return origin;
origin = x;
x0 = origin[0] * d3_geo_radians;
y0 = origin[1] * d3_geo_radians;
cy0 = Math.cos(y0);
sy0 = Math.sin(y0);
return azimuthal;
};
azimuthal.scale = function(x) {
if (!arguments.length) return scale;
scale = +x;
return azimuthal;
};
azimuthal.translate = function(x) {
if (!arguments.length) return translate;
translate = [ +x[0], +x[1] ];
return azimuthal;
};
return azimuthal.origin([ 0, 0 ]);
};
d3.geo.albers = function() {
var origin = [ -98, 38 ], parallels = [ 29.5, 45.5 ], scale = 1e3, translate = [ 480, 250 ], lng0, n, C, p0;
function albers(coordinates) {
var t = n * (d3_geo_radians * coordinates[0] - lng0), p = Math.sqrt(C - 2 * n * Math.sin(d3_geo_radians * coordinates[1])) / n;
return [ scale * p * Math.sin(t) + translate[0], scale * (p * Math.cos(t) - p0) + translate[1] ];
}
albers.invert = function(coordinates) {
var x = (coordinates[0] - translate[0]) / scale, y = (coordinates[1] - translate[1]) / scale, p0y = p0 + y, t = Math.atan2(x, p0y), p = Math.sqrt(x * x + p0y * p0y);
return [ (lng0 + t / n) / d3_geo_radians, Math.asin((C - p * p * n * n) / (2 * n)) / d3_geo_radians ];
};
function reload() {
var phi1 = d3_geo_radians * parallels[0], phi2 = d3_geo_radians * parallels[1], lat0 = d3_geo_radians * origin[1], s = Math.sin(phi1), c = Math.cos(phi1);
lng0 = d3_geo_radians * origin[0];
n = .5 * (s + Math.sin(phi2));
C = c * c + 2 * n * s;
p0 = Math.sqrt(C - 2 * n * Math.sin(lat0)) / n;
return albers;
}
albers.origin = function(x) {
if (!arguments.length) return origin;
origin = [ +x[0], +x[1] ];
return reload();
};
albers.parallels = function(x) {
if (!arguments.length) return parallels;
parallels = [ +x[0], +x[1] ];
return reload();
};
albers.scale = function(x) {
if (!arguments.length) return scale;
scale = +x;
return albers;
};
albers.translate = function(x) {
if (!arguments.length) return translate;
translate = [ +x[0], +x[1] ];
return albers;
};
return reload();
};
d3.geo.albersUsa = function() {
var lower48 = d3.geo.albers();
var alaska = d3.geo.albers().origin([ -160, 60 ]).parallels([ 55, 65 ]);
var hawaii = d3.geo.albers().origin([ -160, 20 ]).parallels([ 8, 18 ]);
var puertoRico = d3.geo.albers().origin([ -60, 10 ]).parallels([ 8, 18 ]);
function albersUsa(coordinates) {
var lon = coordinates[0], lat = coordinates[1];
return (lat > 50 ? alaska : lon < -140 ? hawaii : lat < 21 ? puertoRico : lower48)(coordinates);
}
albersUsa.scale = function(x) {
if (!arguments.length) return lower48.scale();
lower48.scale(x);
alaska.scale(x * .6);
hawaii.scale(x);
puertoRico.scale(x * 1.5);
return albersUsa.translate(lower48.translate());
};
albersUsa.translate = function(x) {
if (!arguments.length) return lower48.translate();
var dz = lower48.scale() / 1e3, dx = x[0], dy = x[1];
lower48.translate(x);
alaska.translate([ dx - 400 * dz, dy + 170 * dz ]);
hawaii.translate([ dx - 190 * dz, dy + 200 * dz ]);
puertoRico.translate([ dx + 580 * dz, dy + 430 * dz ]);
return albersUsa;
};
return albersUsa.scale(lower48.scale());
};
d3.geo.bonne = function() {
var scale = 200, translate = [ 480, 250 ], x0, y0, y1, c1;
function bonne(coordinates) {
var x = coordinates[0] * d3_geo_radians - x0, y = coordinates[1] * d3_geo_radians - y0;
if (y1) {
var p = c1 + y1 - y, E = x * Math.cos(y) / p;
x = p * Math.sin(E);
y = p * Math.cos(E) - c1;
} else {
x *= Math.cos(y);
y *= -1;
}
return [ scale * x + translate[0], scale * y + translate[1] ];
}
bonne.invert = function(coordinates) {
var x = (coordinates[0] - translate[0]) / scale, y = (coordinates[1] - translate[1]) / scale;
if (y1) {
var c = c1 + y, p = Math.sqrt(x * x + c * c);
y = c1 + y1 - p;
x = x0 + p * Math.atan2(x, c) / Math.cos(y);
} else {
y *= -1;
x /= Math.cos(y);
}
return [ x / d3_geo_radians, y / d3_geo_radians ];
};
bonne.parallel = function(x) {
if (!arguments.length) return y1 / d3_geo_radians;
c1 = 1 / Math.tan(y1 = x * d3_geo_radians);
return bonne;
};
bonne.origin = function(x) {
if (!arguments.length) return [ x0 / d3_geo_radians, y0 / d3_geo_radians ];
x0 = x[0] * d3_geo_radians;
y0 = x[1] * d3_geo_radians;
return bonne;
};
bonne.scale = function(x) {
if (!arguments.length) return scale;
scale = +x;
return bonne;
};
bonne.translate = function(x) {
if (!arguments.length) return translate;
translate = [ +x[0], +x[1] ];
return bonne;
};
return bonne.origin([ 0, 0 ]).parallel(45);
};
d3.geo.equirectangular = function() {
var scale = 500, translate = [ 480, 250 ];
function equirectangular(coordinates) {
var x = coordinates[0] / 360, y = -coordinates[1] / 360;
return [ scale * x + translate[0], scale * y + translate[1] ];
}
equirectangular.invert = function(coordinates) {
var x = (coordinates[0] - translate[0]) / scale, y = (coordinates[1] - translate[1]) / scale;
return [ 360 * x, -360 * y ];
};
equirectangular.scale = function(x) {
if (!arguments.length) return scale;
scale = +x;
return equirectangular;
};
equirectangular.translate = function(x) {
if (!arguments.length) return translate;
translate = [ +x[0], +x[1] ];
return equirectangular;
};
return equirectangular;
};
d3.geo.mercator = function() {
var scale = 500, translate = [ 480, 250 ];
function mercator(coordinates) {
var x = coordinates[0] / 360, y = -(Math.log(Math.tan(Math.PI / 4 + coordinates[1] * d3_geo_radians / 2)) / d3_geo_radians) / 360;
return [ scale * x + translate[0], scale * Math.max(-.5, Math.min(.5, y)) + translate[1] ];
}
mercator.invert = function(coordinates) {
var x = (coordinates[0] - translate[0]) / scale, y = (coordinates[1] - translate[1]) / scale;
return [ 360 * x, 2 * Math.atan(Math.exp(-360 * y * d3_geo_radians)) / d3_geo_radians - 90 ];
};
mercator.scale = function(x) {
if (!arguments.length) return scale;
scale = +x;
return mercator;
};
mercator.translate = function(x) {
if (!arguments.length) return translate;
translate = [ +x[0], +x[1] ];
return mercator;
};
return mercator;
};
function d3_geo_type(types, defaultValue) {
return function(object) {
return object && types.hasOwnProperty(object.type) ? types[object.type](object) : defaultValue;
};
}
d3.geo.path = function() {
var pointRadius = 4.5, pointCircle = d3_path_circle(pointRadius), projection = d3.geo.albersUsa(), buffer = [];
function path(d, i) {
if (typeof pointRadius === "function") pointCircle = d3_path_circle(pointRadius.apply(this, arguments));
pathType(d);
var result = buffer.length ? buffer.join("") : null;
buffer = [];
return result;
}
function project(coordinates) {
return projection(coordinates).join(",");
}
var pathType = d3_geo_type({
FeatureCollection: function(o) {
var features = o.features, i = -1, n = features.length;
while (++i < n) buffer.push(pathType(features[i].geometry));
},
Feature: function(o) {
pathType(o.geometry);
},
Point: function(o) {
buffer.push("M", project(o.coordinates), pointCircle);
},
MultiPoint: function(o) {
var coordinates = o.coordinates, i = -1, n = coordinates.length;
while (++i < n) buffer.push("M", project(coordinates[i]), pointCircle);
},
LineString: function(o) {
var coordinates = o.coordinates, i = -1, n = coordinates.length;
buffer.push("M");
while (++i < n) buffer.push(project(coordinates[i]), "L");
buffer.pop();
},
MultiLineString: function(o) {
var coordinates = o.coordinates, i = -1, n = coordinates.length, subcoordinates, j, m;
while (++i < n) {
subcoordinates = coordinates[i];
j = -1;
m = subcoordinates.length;
buffer.push("M");
while (++j < m) buffer.push(project(subcoordinates[j]), "L");
buffer.pop();
}
},
Polygon: function(o) {
var coordinates = o.coordinates, i = -1, n = coordinates.length, subcoordinates, j, m;
while (++i < n) {
subcoordinates = coordinates[i];
j = -1;
if ((m = subcoordinates.length - 1) > 0) {
buffer.push("M");
while (++j < m) buffer.push(project(subcoordinates[j]), "L");
buffer[buffer.length - 1] = "Z";
}
}
},
MultiPolygon: function(o) {
var coordinates = o.coordinates, i = -1, n = coordinates.length, subcoordinates, j, m, subsubcoordinates, k, p;
while (++i < n) {
subcoordinates = coordinates[i];
j = -1;
m = subcoordinates.length;
while (++j < m) {
subsubcoordinates = subcoordinates[j];
k = -1;
if ((p = subsubcoordinates.length - 1) > 0) {
buffer.push("M");
while (++k < p) buffer.push(project(subsubcoordinates[k]), "L");
buffer[buffer.length - 1] = "Z";
}
}
}
},
GeometryCollection: function(o) {
var geometries = o.geometries, i = -1, n = geometries.length;
while (++i < n) buffer.push(pathType(geometries[i]));
}
});
var areaType = path.area = d3_geo_type({
FeatureCollection: function(o) {
var area = 0, features = o.features, i = -1, n = features.length;
while (++i < n) area += areaType(features[i]);
return area;
},
Feature: function(o) {
return areaType(o.geometry);
},
Polygon: function(o) {
return polygonArea(o.coordinates);
},
MultiPolygon: function(o) {
var sum = 0, coordinates = o.coordinates, i = -1, n = coordinates.length;
while (++i < n) sum += polygonArea(coordinates[i]);
return sum;
},
GeometryCollection: function(o) {
var sum = 0, geometries = o.geometries, i = -1, n = geometries.length;
while (++i < n) sum += areaType(geometries[i]);
return sum;
}
}, 0);
function polygonArea(coordinates) {
var sum = area(coordinates[0]), i = 0, n = coordinates.length;
while (++i < n) sum -= area(coordinates[i]);
return sum;
}
function polygonCentroid(coordinates) {
var polygon = d3.geom.polygon(coordinates[0].map(projection)), area = polygon.area(), centroid = polygon.centroid(area < 0 ? (area *= -1, 1) : -1), x = centroid[0], y = centroid[1], z = area, i = 0, n = coordinates.length;
while (++i < n) {
polygon = d3.geom.polygon(coordinates[i].map(projection));
area = polygon.area();
centroid = polygon.centroid(area < 0 ? (area *= -1, 1) : -1);
x -= centroid[0];
y -= centroid[1];
z -= area;
}
return [ x, y, 6 * z ];
}
var centroidType = path.centroid = d3_geo_type({
Feature: function(o) {
return centroidType(o.geometry);
},
Polygon: function(o) {
var centroid = polygonCentroid(o.coordinates);
return [ centroid[0] / centroid[2], centroid[1] / centroid[2] ];
},
MultiPolygon: function(o) {
var area = 0, coordinates = o.coordinates, centroid, x = 0, y = 0, z = 0, i = -1, n = coordinates.length;
while (++i < n) {
centroid = polygonCentroid(coordinates[i]);
x += centroid[0];
y += centroid[1];
z += centroid[2];
}
return [ x / z, y / z ];
}
});
function area(coordinates) {
return Math.abs(d3.geom.polygon(coordinates.map(projection)).area());
}
path.projection = function(x) {
projection = x;
return path;
};
path.pointRadius = function(x) {
if (typeof x === "function") pointRadius = x; else {
pointRadius = +x;
pointCircle = d3_path_circle(pointRadius);
}
return path;
};
return path;
};
function d3_path_circle(radius) {
return "m0," + radius + "a" + radius + "," + radius + " 0 1,1 0," + -2 * radius + "a" + radius + "," + radius + " 0 1,1 0," + +2 * radius + "z";
}
d3.geo.bounds = function(feature) {
var left = Infinity, bottom = Infinity, right = -Infinity, top = -Infinity;
d3_geo_bounds(feature, function(x, y) {
if (x < left) left = x;
if (x > right) right = x;
if (y < bottom) bottom = y;
if (y > top) top = y;
});
return [ [ left, bottom ], [ right, top ] ];
};
function d3_geo_bounds(o, f) {
if (d3_geo_boundsTypes.hasOwnProperty(o.type)) d3_geo_boundsTypes[o.type](o, f);
}
var d3_geo_boundsTypes = {
Feature: d3_geo_boundsFeature,
FeatureCollection: d3_geo_boundsFeatureCollection,
GeometryCollection: d3_geo_boundsGeometryCollection,
LineString: d3_geo_boundsLineString,
MultiLineString: d3_geo_boundsMultiLineString,
MultiPoint: d3_geo_boundsLineString,
MultiPolygon: d3_geo_boundsMultiPolygon,
Point: d3_geo_boundsPoint,
Polygon: d3_geo_boundsPolygon
};
function d3_geo_boundsFeature(o, f) {
d3_geo_bounds(o.geometry, f);
}
function d3_geo_boundsFeatureCollection(o, f) {
for (var a = o.features, i = 0, n = a.length; i < n; i++) {
d3_geo_bounds(a[i].geometry, f);
}
}
function d3_geo_boundsGeometryCollection(o, f) {
for (var a = o.geometries, i = 0, n = a.length; i < n; i++) {
d3_geo_bounds(a[i], f);
}
}
function d3_geo_boundsLineString(o, f) {
for (var a = o.coordinates, i = 0, n = a.length; i < n; i++) {
f.apply(null, a[i]);
}
}
function d3_geo_boundsMultiLineString(o, f) {
for (var a = o.coordinates, i = 0, n = a.length; i < n; i++) {
for (var b = a[i], j = 0, m = b.length; j < m; j++) {
f.apply(null, b[j]);
}
}
}
function d3_geo_boundsMultiPolygon(o, f) {
for (var a = o.coordinates, i = 0, n = a.length; i < n; i++) {
for (var b = a[i][0], j = 0, m = b.length; j < m; j++) {
f.apply(null, b[j]);
}
}
}
function d3_geo_boundsPoint(o, f) {
f.apply(null, o.coordinates);
}
function d3_geo_boundsPolygon(o, f) {
for (var a = o.coordinates[0], i = 0, n = a.length; i < n; i++) {
f.apply(null, a[i]);
}
}
d3.geo.circle = function() {
var origin = [ 0, 0 ], degrees = 90 - .01, radians = degrees * d3_geo_radians, arc = d3.geo.greatArc().source(origin).target(d3_identity);
function circle() {}
function visible(point) {
return arc.distance(point) < radians;
}
circle.clip = function(d) {
if (typeof origin === "function") arc.source(origin.apply(this, arguments));
return clipType(d) || null;
};
var clipType = d3_geo_type({
FeatureCollection: function(o) {
var features = o.features.map(clipType).filter(d3_identity);
return features && (o = Object.create(o), o.features = features, o);
},
Feature: function(o) {
var geometry = clipType(o.geometry);
return geometry && (o = Object.create(o), o.geometry = geometry, o);
},
Point: function(o) {
return visible(o.coordinates) && o;
},
MultiPoint: function(o) {
var coordinates = o.coordinates.filter(visible);
return coordinates.length && {
type: o.type,
coordinates: coordinates
};
},
LineString: function(o) {
var coordinates = clip(o.coordinates);
return coordinates.length && (o = Object.create(o), o.coordinates = coordinates, o);
},
MultiLineString: function(o) {
var coordinates = o.coordinates.map(clip).filter(function(d) {
return d.length;
});
return coordinates.length && (o = Object.create(o), o.coordinates = coordinates, o);
},
Polygon: function(o) {
var coordinates = o.coordinates.map(clip);
return coordinates[0].length && (o = Object.create(o), o.coordinates = coordinates, o);
},
MultiPolygon: function(o) {
var coordinates = o.coordinates.map(function(d) {
return d.map(clip);
}).filter(function(d) {
return d[0].length;
});
return coordinates.length && (o = Object.create(o), o.coordinates = coordinates, o);
},
GeometryCollection: function(o) {
var geometries = o.geometries.map(clipType).filter(d3_identity);
return geometries.length && (o = Object.create(o), o.geometries = geometries, o);
}
});
function clip(coordinates) {
var i = -1, n = coordinates.length, clipped = [], p0, p1, p2, d0, d1;
while (++i < n) {
d1 = arc.distance(p2 = coordinates[i]);
if (d1 < radians) {
if (p1) clipped.push(d3_geo_greatArcInterpolate(p1, p2)((d0 - radians) / (d0 - d1)));
clipped.push(p2);
p0 = p1 = null;
} else {
p1 = p2;
if (!p0 && clipped.length) {
clipped.push(d3_geo_greatArcInterpolate(clipped[clipped.length - 1], p1)((radians - d0) / (d1 - d0)));
p0 = p1;
}
}
d0 = d1;
}
p0 = coordinates[0];
p1 = clipped[0];
if (p1 && p2[0] === p0[0] && p2[1] === p0[1] && !(p2[0] === p1[0] && p2[1] === p1[1])) {
clipped.push(p1);
}
return resample(clipped);
}
function resample(coordinates) {
var i = 0, n = coordinates.length, j, m, resampled = n ? [ coordinates[0] ] : coordinates, resamples, origin = arc.source();
while (++i < n) {
resamples = arc.source(coordinates[i - 1])(coordinates[i]).coordinates;
for (j = 0, m = resamples.length; ++j < m; ) resampled.push(resamples[j]);
}
arc.source(origin);
return resampled;
}
circle.origin = function(x) {
if (!arguments.length) return origin;
origin = x;
if (typeof origin !== "function") arc.source(origin);
return circle;
};
circle.angle = function(x) {
if (!arguments.length) return degrees;
radians = (degrees = +x) * d3_geo_radians;
return circle;
};
return d3.rebind(circle, arc, "precision");
};
d3.geo.greatArc = function() {
var source = d3_geo_greatArcSource, p0, target = d3_geo_greatArcTarget, p1, precision = 6 * d3_geo_radians, interpolate = d3_geo_greatArcInterpolator();
function greatArc() {
var d = greatArc.distance.apply(this, arguments), t = 0, dt = precision / d, coordinates = [ p0 ];
while ((t += dt) < 1) coordinates.push(interpolate(t));
coordinates.push(p1);
return {
type: "LineString",
coordinates: coordinates
};
}
greatArc.distance = function() {
if (typeof source === "function") interpolate.source(p0 = source.apply(this, arguments));
if (typeof target === "function") interpolate.target(p1 = target.apply(this, arguments));
return interpolate.distance();
};
greatArc.source = function(_) {
if (!arguments.length) return source;
source = _;
if (typeof source !== "function") interpolate.source(p0 = source);
return greatArc;
};
greatArc.target = function(_) {
if (!arguments.length) return target;
target = _;
if (typeof target !== "function") interpolate.target(p1 = target);
return greatArc;
};
greatArc.precision = function(_) {
if (!arguments.length) return precision / d3_geo_radians;
precision = _ * d3_geo_radians;
return greatArc;
};
return greatArc;
};
function d3_geo_greatArcSource(d) {
return d.source;
}
function d3_geo_greatArcTarget(d) {
return d.target;
}
function d3_geo_greatArcInterpolator() {
var x0, y0, cy0, sy0, kx0, ky0, x1, y1, cy1, sy1, kx1, ky1, d, k;
function interpolate(t) {
var B = Math.sin(t *= d) * k, A = Math.sin(d - t) * k, x = A * kx0 + B * kx1, y = A * ky0 + B * ky1, z = A * sy0 + B * sy1;
return [ Math.atan2(y, x) / d3_geo_radians, Math.atan2(z, Math.sqrt(x * x + y * y)) / d3_geo_radians ];
}
interpolate.distance = function() {
if (d == null) k = 1 / Math.sin(d = Math.acos(Math.max(-1, Math.min(1, sy0 * sy1 + cy0 * cy1 * Math.cos(x1 - x0)))));
return d;
};
interpolate.source = function(_) {
var cx0 = Math.cos(x0 = _[0] * d3_geo_radians), sx0 = Math.sin(x0);
cy0 = Math.cos(y0 = _[1] * d3_geo_radians);
sy0 = Math.sin(y0);
kx0 = cy0 * cx0;
ky0 = cy0 * sx0;
d = null;
return interpolate;
};
interpolate.target = function(_) {
var cx1 = Math.cos(x1 = _[0] * d3_geo_radians), sx1 = Math.sin(x1);
cy1 = Math.cos(y1 = _[1] * d3_geo_radians);
sy1 = Math.sin(y1);
kx1 = cy1 * cx1;
ky1 = cy1 * sx1;
d = null;
return interpolate;
};
return interpolate;
}
function d3_geo_greatArcInterpolate(a, b) {
var i = d3_geo_greatArcInterpolator().source(a).target(b);
i.distance();
return i;
}
d3.geo.greatCircle = d3.geo.circle;
d3.geom = {};
d3.geom.contour = function(grid, start) {
var s = start || d3_geom_contourStart(grid), c = [], x = s[0], y = s[1], dx = 0, dy = 0, pdx = NaN, pdy = NaN, i = 0;
do {
i = 0;
if (grid(x - 1, y - 1)) i += 1;
if (grid(x, y - 1)) i += 2;
if (grid(x - 1, y)) i += 4;
if (grid(x, y)) i += 8;
if (i === 6) {
dx = pdy === -1 ? -1 : 1;
dy = 0;
} else if (i === 9) {
dx = 0;
dy = pdx === 1 ? -1 : 1;
} else {
dx = d3_geom_contourDx[i];
dy = d3_geom_contourDy[i];
}
if (dx != pdx && dy != pdy) {
c.push([ x, y ]);
pdx = dx;
pdy = dy;
}
x += dx;
y += dy;
} while (s[0] != x || s[1] != y);
return c;
};
var d3_geom_contourDx = [ 1, 0, 1, 1, -1, 0, -1, 1, 0, 0, 0, 0, -1, 0, -1, NaN ], d3_geom_contourDy = [ 0, -1, 0, 0, 0, -1, 0, 0, 1, -1, 1, 1, 0, -1, 0, NaN ];
function d3_geom_contourStart(grid) {
var x = 0, y = 0;
while (true) {
if (grid(x, y)) {
return [ x, y ];
}
if (x === 0) {
x = y + 1;
y = 0;
} else {
x = x - 1;
y = y + 1;
}
}
}
d3.geom.hull = function(vertices) {
if (vertices.length < 3) return [];
var len = vertices.length, plen = len - 1, points = [], stack = [], i, j, h = 0, x1, y1, x2, y2, u, v, a, sp;
for (i = 1; i < len; ++i) {
if (vertices[i][1] < vertices[h][1]) {
h = i;
} else if (vertices[i][1] == vertices[h][1]) {
h = vertices[i][0] < vertices[h][0] ? i : h;
}
}
for (i = 0; i < len; ++i) {
if (i === h) continue;
y1 = vertices[i][1] - vertices[h][1];
x1 = vertices[i][0] - vertices[h][0];
points.push({
angle: Math.atan2(y1, x1),
index: i
});
}
points.sort(function(a, b) {
return a.angle - b.angle;
});
a = points[0].angle;
v = points[0].index;
u = 0;
for (i = 1; i < plen; ++i) {
j = points[i].index;
if (a == points[i].angle) {
x1 = vertices[v][0] - vertices[h][0];
y1 = vertices[v][1] - vertices[h][1];
x2 = vertices[j][0] - vertices[h][0];
y2 = vertices[j][1] - vertices[h][1];
if (x1 * x1 + y1 * y1 >= x2 * x2 + y2 * y2) {
points[i].index = -1;
} else {
points[u].index = -1;
a = points[i].angle;
u = i;
v = j;
}
} else {
a = points[i].angle;
u = i;
v = j;
}
}
stack.push(h);
for (i = 0, j = 0; i < 2; ++j) {
if (points[j].index !== -1) {
stack.push(points[j].index);
i++;
}
}
sp = stack.length;
for (; j < plen; ++j) {
if (points[j].index === -1) continue;
while (!d3_geom_hullCCW(stack[sp - 2], stack[sp - 1], points[j].index, vertices)) {
--sp;
}
stack[sp++] = points[j].index;
}
var poly = [];
for (i = 0; i < sp; ++i) {
poly.push(vertices[stack[i]]);
}
return poly;
};
function d3_geom_hullCCW(i1, i2, i3, v) {
var t, a, b, c, d, e, f;
t = v[i1];
a = t[0];
b = t[1];
t = v[i2];
c = t[0];
d = t[1];
t = v[i3];
e = t[0];
f = t[1];
return (f - b) * (c - a) - (d - b) * (e - a) > 0;
}
d3.geom.polygon = function(coordinates) {
coordinates.area = function() {
var i = 0, n = coordinates.length, a = coordinates[n - 1][0] * coordinates[0][1], b = coordinates[n - 1][1] * coordinates[0][0];
while (++i < n) {
a += coordinates[i - 1][0] * coordinates[i][1];
b += coordinates[i - 1][1] * coordinates[i][0];
}
return (b - a) * .5;
};
coordinates.centroid = function(k) {
var i = -1, n = coordinates.length, x = 0, y = 0, a, b = coordinates[n - 1], c;
if (!arguments.length) k = -1 / (6 * coordinates.area());
while (++i < n) {
a = b;
b = coordinates[i];
c = a[0] * b[1] - b[0] * a[1];
x += (a[0] + b[0]) * c;
y += (a[1] + b[1]) * c;
}
return [ x * k, y * k ];
};
coordinates.clip = function(subject) {
var input, i = -1, n = coordinates.length, j, m, a = coordinates[n - 1], b, c, d;
while (++i < n) {
input = subject.slice();
subject.length = 0;
b = coordinates[i];
c = input[(m = input.length) - 1];
j = -1;
while (++j < m) {
d = input[j];
if (d3_geom_polygonInside(d, a, b)) {
if (!d3_geom_polygonInside(c, a, b)) {
subject.push(d3_geom_polygonIntersect(c, d, a, b));
}
subject.push(d);
} else if (d3_geom_polygonInside(c, a, b)) {
subject.push(d3_geom_polygonIntersect(c, d, a, b));
}
c = d;
}
a = b;
}
return subject;
};
return coordinates;
};
function d3_geom_polygonInside(p, a, b) {
return (b[0] - a[0]) * (p[1] - a[1]) < (b[1] - a[1]) * (p[0] - a[0]);
}
function d3_geom_polygonIntersect(c, d, a, b) {
var x1 = c[0], x2 = d[0], x3 = a[0], x4 = b[0], y1 = c[1], y2 = d[1], y3 = a[1], y4 = b[1], x13 = x1 - x3, x21 = x2 - x1, x43 = x4 - x3, y13 = y1 - y3, y21 = y2 - y1, y43 = y4 - y3, ua = (x43 * y13 - y43 * x13) / (y43 * x21 - x43 * y21);
return [ x1 + ua * x21, y1 + ua * y21 ];
}
d3.geom.voronoi = function(vertices) {
var polygons = vertices.map(function() {
return [];
});
d3_voronoi_tessellate(vertices, function(e) {
var s1, s2, x1, x2, y1, y2;
if (e.a === 1 && e.b >= 0) {
s1 = e.ep.r;
s2 = e.ep.l;
} else {
s1 = e.ep.l;
s2 = e.ep.r;
}
if (e.a === 1) {
y1 = s1 ? s1.y : -1e6;
x1 = e.c - e.b * y1;
y2 = s2 ? s2.y : 1e6;
x2 = e.c - e.b * y2;
} else {
x1 = s1 ? s1.x : -1e6;
y1 = e.c - e.a * x1;
x2 = s2 ? s2.x : 1e6;
y2 = e.c - e.a * x2;
}
var v1 = [ x1, y1 ], v2 = [ x2, y2 ];
polygons[e.region.l.index].push(v1, v2);
polygons[e.region.r.index].push(v1, v2);
});
return polygons.map(function(polygon, i) {
var cx = vertices[i][0], cy = vertices[i][1];
polygon.forEach(function(v) {
v.angle = Math.atan2(v[0] - cx, v[1] - cy);
});
return polygon.sort(function(a, b) {
return a.angle - b.angle;
}).filter(function(d, i) {
return !i || d.angle - polygon[i - 1].angle > 1e-10;
});
});
};
var d3_voronoi_opposite = {
l: "r",
r: "l"
};
function d3_voronoi_tessellate(vertices, callback) {
var Sites = {
list: vertices.map(function(v, i) {
return {
index: i,
x: v[0],
y: v[1]
};
}).sort(function(a, b) {
return a.y < b.y ? -1 : a.y > b.y ? 1 : a.x < b.x ? -1 : a.x > b.x ? 1 : 0;
}),
bottomSite: null
};
var EdgeList = {
list: [],
leftEnd: null,
rightEnd: null,
init: function() {
EdgeList.leftEnd = EdgeList.createHalfEdge(null, "l");
EdgeList.rightEnd = EdgeList.createHalfEdge(null, "l");
EdgeList.leftEnd.r = EdgeList.rightEnd;
EdgeList.rightEnd.l = EdgeList.leftEnd;
EdgeList.list.unshift(EdgeList.leftEnd, EdgeList.rightEnd);
},
createHalfEdge: function(edge, side) {
return {
edge: edge,
side: side,
vertex: null,
l: null,
r: null
};
},
insert: function(lb, he) {
he.l = lb;
he.r = lb.r;
lb.r.l = he;
lb.r = he;
},
leftBound: function(p) {
var he = EdgeList.leftEnd;
do {
he = he.r;
} while (he != EdgeList.rightEnd && Geom.rightOf(he, p));
he = he.l;
return he;
},
del: function(he) {
he.l.r = he.r;
he.r.l = he.l;
he.edge = null;
},
right: function(he) {
return he.r;
},
left: function(he) {
return he.l;
},
leftRegion: function(he) {
return he.edge == null ? Sites.bottomSite : he.edge.region[he.side];
},
rightRegion: function(he) {
return he.edge == null ? Sites.bottomSite : he.edge.region[d3_voronoi_opposite[he.side]];
}
};
var Geom = {
bisect: function(s1, s2) {
var newEdge = {
region: {
l: s1,
r: s2
},
ep: {
l: null,
r: null
}
};
var dx = s2.x - s1.x, dy = s2.y - s1.y, adx = dx > 0 ? dx : -dx, ady = dy > 0 ? dy : -dy;
newEdge.c = s1.x * dx + s1.y * dy + (dx * dx + dy * dy) * .5;
if (adx > ady) {
newEdge.a = 1;
newEdge.b = dy / dx;
newEdge.c /= dx;
} else {
newEdge.b = 1;
newEdge.a = dx / dy;
newEdge.c /= dy;
}
return newEdge;
},
intersect: function(el1, el2) {
var e1 = el1.edge, e2 = el2.edge;
if (!e1 || !e2 || e1.region.r == e2.region.r) {
return null;
}
var d = e1.a * e2.b - e1.b * e2.a;
if (Math.abs(d) < 1e-10) {
return null;
}
var xint = (e1.c * e2.b - e2.c * e1.b) / d, yint = (e2.c * e1.a - e1.c * e2.a) / d, e1r = e1.region.r, e2r = e2.region.r, el, e;
if (e1r.y < e2r.y || e1r.y == e2r.y && e1r.x < e2r.x) {
el = el1;
e = e1;
} else {
el = el2;
e = e2;
}
var rightOfSite = xint >= e.region.r.x;
if (rightOfSite && el.side === "l" || !rightOfSite && el.side === "r") {
return null;
}
return {
x: xint,
y: yint
};
},
rightOf: function(he, p) {
var e = he.edge, topsite = e.region.r, rightOfSite = p.x > topsite.x;
if (rightOfSite && he.side === "l") {
return 1;
}
if (!rightOfSite && he.side === "r") {
return 0;
}
if (e.a === 1) {
var dyp = p.y - topsite.y, dxp = p.x - topsite.x, fast = 0, above = 0;
if (!rightOfSite && e.b < 0 || rightOfSite && e.b >= 0) {
above = fast = dyp >= e.b * dxp;
} else {
above = p.x + p.y * e.b > e.c;
if (e.b < 0) {
above = !above;
}
if (!above) {
fast = 1;
}
}
if (!fast) {
var dxs = topsite.x - e.region.l.x;
above = e.b * (dxp * dxp - dyp * dyp) < dxs * dyp * (1 + 2 * dxp / dxs + e.b * e.b);
if (e.b < 0) {
above = !above;
}
}
} else {
var yl = e.c - e.a * p.x, t1 = p.y - yl, t2 = p.x - topsite.x, t3 = yl - topsite.y;
above = t1 * t1 > t2 * t2 + t3 * t3;
}
return he.side === "l" ? above : !above;
},
endPoint: function(edge, side, site) {
edge.ep[side] = site;
if (!edge.ep[d3_voronoi_opposite[side]]) return;
callback(edge);
},
distance: function(s, t) {
var dx = s.x - t.x, dy = s.y - t.y;
return Math.sqrt(dx * dx + dy * dy);
}
};
var EventQueue = {
list: [],
insert: function(he, site, offset) {
he.vertex = site;
he.ystar = site.y + offset;
for (var i = 0, list = EventQueue.list, l = list.length; i < l; i++) {
var next = list[i];
if (he.ystar > next.ystar || he.ystar == next.ystar && site.x > next.vertex.x) {
continue;
} else {
break;
}
}
list.splice(i, 0, he);
},
del: function(he) {
for (var i = 0, ls = EventQueue.list, l = ls.length; i < l && ls[i] != he; ++i) {}
ls.splice(i, 1);
},
empty: function() {
return EventQueue.list.length === 0;
},
nextEvent: function(he) {
for (var i = 0, ls = EventQueue.list, l = ls.length; i < l; ++i) {
if (ls[i] == he) return ls[i + 1];
}
return null;
},
min: function() {
var elem = EventQueue.list[0];
return {
x: elem.vertex.x,
y: elem.ystar
};
},
extractMin: function() {
return EventQueue.list.shift();
}
};
EdgeList.init();
Sites.bottomSite = Sites.list.shift();
var newSite = Sites.list.shift(), newIntStar;
var lbnd, rbnd, llbnd, rrbnd, bisector;
var bot, top, temp, p, v;
var e, pm;
while (true) {
if (!EventQueue.empty()) {
newIntStar = EventQueue.min();
}
if (newSite && (EventQueue.empty() || newSite.y < newIntStar.y || newSite.y == newIntStar.y && newSite.x < newIntStar.x)) {
lbnd = EdgeList.leftBound(newSite);
rbnd = EdgeList.right(lbnd);
bot = EdgeList.rightRegion(lbnd);
e = Geom.bisect(bot, newSite);
bisector = EdgeList.createHalfEdge(e, "l");
EdgeList.insert(lbnd, bisector);
p = Geom.intersect(lbnd, bisector);
if (p) {
EventQueue.del(lbnd);
EventQueue.insert(lbnd, p, Geom.distance(p, newSite));
}
lbnd = bisector;
bisector = EdgeList.createHalfEdge(e, "r");
EdgeList.insert(lbnd, bisector);
p = Geom.intersect(bisector, rbnd);
if (p) {
EventQueue.insert(bisector, p, Geom.distance(p, newSite));
}
newSite = Sites.list.shift();
} else if (!EventQueue.empty()) {
lbnd = EventQueue.extractMin();
llbnd = EdgeList.left(lbnd);
rbnd = EdgeList.right(lbnd);
rrbnd = EdgeList.right(rbnd);
bot = EdgeList.leftRegion(lbnd);
top = EdgeList.rightRegion(rbnd);
v = lbnd.vertex;
Geom.endPoint(lbnd.edge, lbnd.side, v);
Geom.endPoint(rbnd.edge, rbnd.side, v);
EdgeList.del(lbnd);
EventQueue.del(rbnd);
EdgeList.del(rbnd);
pm = "l";
if (bot.y > top.y) {
temp = bot;
bot = top;
top = temp;
pm = "r";
}
e = Geom.bisect(bot, top);
bisector = EdgeList.createHalfEdge(e, pm);
EdgeList.insert(llbnd, bisector);
Geom.endPoint(e, d3_voronoi_opposite[pm], v);
p = Geom.intersect(llbnd, bisector);
if (p) {
EventQueue.del(llbnd);
EventQueue.insert(llbnd, p, Geom.distance(p, bot));
}
p = Geom.intersect(bisector, rrbnd);
if (p) {
EventQueue.insert(bisector, p, Geom.distance(p, bot));
}
} else {
break;
}
}
for (lbnd = EdgeList.right(EdgeList.leftEnd); lbnd != EdgeList.rightEnd; lbnd = EdgeList.right(lbnd)) {
callback(lbnd.edge);
}
}
d3.geom.delaunay = function(vertices) {
var edges = vertices.map(function() {
return [];
}), triangles = [];
d3_voronoi_tessellate(vertices, function(e) {
edges[e.region.l.index].push(vertices[e.region.r.index]);
});
edges.forEach(function(edge, i) {
var v = vertices[i], cx = v[0], cy = v[1];
edge.forEach(function(v) {
v.angle = Math.atan2(v[0] - cx, v[1] - cy);
});
edge.sort(function(a, b) {
return a.angle - b.angle;
});
for (var j = 0, m = edge.length - 1; j < m; j++) {
triangles.push([ v, edge[j], edge[j + 1] ]);
}
});
return triangles;
};
d3.geom.quadtree = function(points, x1, y1, x2, y2) {
var p, i = -1, n = points.length;
if (n && isNaN(points[0].x)) points = points.map(d3_geom_quadtreePoint);
if (arguments.length < 5) {
if (arguments.length === 3) {
y2 = x2 = y1;
y1 = x1;
} else {
x1 = y1 = Infinity;
x2 = y2 = -Infinity;
while (++i < n) {
p = points[i];
if (p.x < x1) x1 = p.x;
if (p.y < y1) y1 = p.y;
if (p.x > x2) x2 = p.x;
if (p.y > y2) y2 = p.y;
}
var dx = x2 - x1, dy = y2 - y1;
if (dx > dy) y2 = y1 + dx; else x2 = x1 + dy;
}
}
function insert(n, p, x1, y1, x2, y2) {
if (isNaN(p.x) || isNaN(p.y)) return;
if (n.leaf) {
var v = n.point;
if (v) {
if (Math.abs(v.x - p.x) + Math.abs(v.y - p.y) < .01) {
insertChild(n, p, x1, y1, x2, y2);
} else {
n.point = null;
insertChild(n, v, x1, y1, x2, y2);
insertChild(n, p, x1, y1, x2, y2);
}
} else {
n.point = p;
}
} else {
insertChild(n, p, x1, y1, x2, y2);
}
}
function insertChild(n, p, x1, y1, x2, y2) {
var sx = (x1 + x2) * .5, sy = (y1 + y2) * .5, right = p.x >= sx, bottom = p.y >= sy, i = (bottom << 1) + right;
n.leaf = false;
n = n.nodes[i] || (n.nodes[i] = d3_geom_quadtreeNode());
if (right) x1 = sx; else x2 = sx;
if (bottom) y1 = sy; else y2 = sy;
insert(n, p, x1, y1, x2, y2);
}
var root = d3_geom_quadtreeNode();
root.add = function(p) {
insert(root, p, x1, y1, x2, y2);
};
root.visit = function(f) {
d3_geom_quadtreeVisit(f, root, x1, y1, x2, y2);
};
points.forEach(root.add);
return root;
};
function d3_geom_quadtreeNode() {
return {
leaf: true,
nodes: [],
point: null
};
}
function d3_geom_quadtreeVisit(f, node, x1, y1, x2, y2) {
if (!f(node, x1, y1, x2, y2)) {
var sx = (x1 + x2) * .5, sy = (y1 + y2) * .5, children = node.nodes;
if (children[0]) d3_geom_quadtreeVisit(f, children[0], x1, y1, sx, sy);
if (children[1]) d3_geom_quadtreeVisit(f, children[1], sx, y1, x2, sy);
if (children[2]) d3_geom_quadtreeVisit(f, children[2], x1, sy, sx, y2);
if (children[3]) d3_geom_quadtreeVisit(f, children[3], sx, sy, x2, y2);
}
}
function d3_geom_quadtreePoint(p) {
return {
x: p[0],
y: p[1]
};
}
d3.time = {};
var d3_time = Date;
function d3_time_utc() {
this._ = new Date(arguments.length > 1 ? Date.UTC.apply(this, arguments) : arguments[0]);
}
d3_time_utc.prototype = {
getDate: function() {
return this._.getUTCDate();
},
getDay: function() {
return this._.getUTCDay();
},
getFullYear: function() {
return this._.getUTCFullYear();
},
getHours: function() {
return this._.getUTCHours();
},
getMilliseconds: function() {
return this._.getUTCMilliseconds();
},
getMinutes: function() {
return this._.getUTCMinutes();
},
getMonth: function() {
return this._.getUTCMonth();
},
getSeconds: function() {
return this._.getUTCSeconds();
},
getTime: function() {
return this._.getTime();
},
getTimezoneOffset: function() {
return 0;
},
valueOf: function() {
return this._.valueOf();
},
setDate: function() {
d3_time_prototype.setUTCDate.apply(this._, arguments);
},
setDay: function() {
d3_time_prototype.setUTCDay.apply(this._, arguments);
},
setFullYear: function() {
d3_time_prototype.setUTCFullYear.apply(this._, arguments);
},
setHours: function() {
d3_time_prototype.setUTCHours.apply(this._, arguments);
},
setMilliseconds: function() {
d3_time_prototype.setUTCMilliseconds.apply(this._, arguments);
},
setMinutes: function() {
d3_time_prototype.setUTCMinutes.apply(this._, arguments);
},
setMonth: function() {
d3_time_prototype.setUTCMonth.apply(this._, arguments);
},
setSeconds: function() {
d3_time_prototype.setUTCSeconds.apply(this._, arguments);
},
setTime: function() {
d3_time_prototype.setTime.apply(this._, arguments);
}
};
var d3_time_prototype = Date.prototype;
d3.time.format = function(template) {
var n = template.length;
function format(date) {
var string = [], i = -1, j = 0, c, f;
while (++i < n) {
if (template.charCodeAt(i) == 37) {
string.push(template.substring(j, i), (f = d3_time_formats[c = template.charAt(++i)]) ? f(date) : c);
j = i + 1;
}
}
string.push(template.substring(j, i));
return string.join("");
}
format.parse = function(string) {
var d = {
y: 1900,
m: 0,
d: 1,
H: 0,
M: 0,
S: 0,
L: 0
}, i = d3_time_parse(d, template, string, 0);
if (i != string.length) return null;
if ("p" in d) d.H = d.H % 12 + d.p * 12;
var date = new d3_time;
date.setFullYear(d.y, d.m, d.d);
date.setHours(d.H, d.M, d.S, d.L);
return date;
};
format.toString = function() {
return template;
};
return format;
};
function d3_time_parse(date, template, string, j) {
var c, p, i = 0, n = template.length, m = string.length;
while (i < n) {
if (j >= m) return -1;
c = template.charCodeAt(i++);
if (c == 37) {
p = d3_time_parsers[template.charAt(i++)];
if (!p || (j = p(date, string, j)) < 0) return -1;
} else if (c != string.charCodeAt(j++)) {
return -1;
}
}
return j;
}
var d3_time_zfill2 = d3.format("02d"), d3_time_zfill3 = d3.format("03d"), d3_time_zfill4 = d3.format("04d"), d3_time_sfill2 = d3.format("2d");
var d3_time_formats = {
a: function(d) {
return d3_time_weekdays[d.getDay()].substring(0, 3);
},
A: function(d) {
return d3_time_weekdays[d.getDay()];
},
b: function(d) {
return d3_time_months[d.getMonth()].substring(0, 3);
},
B: function(d) {
return d3_time_months[d.getMonth()];
},
c: d3.time.format("%a %b %e %H:%M:%S %Y"),
d: function(d) {
return d3_time_zfill2(d.getDate());
},
e: function(d) {
return d3_time_sfill2(d.getDate());
},
H: function(d) {
return d3_time_zfill2(d.getHours());
},
I: function(d) {
return d3_time_zfill2(d.getHours() % 12 || 12);
},
j: function(d) {
return d3_time_zfill3(1 + d3.time.dayOfYear(d));
},
L: function(d) {
return d3_time_zfill3(d.getMilliseconds());
},
m: function(d) {
return d3_time_zfill2(d.getMonth() + 1);
},
M: function(d) {
return d3_time_zfill2(d.getMinutes());
},
p: function(d) {
return d.getHours() >= 12 ? "PM" : "AM";
},
S: function(d) {
return d3_time_zfill2(d.getSeconds());
},
U: function(d) {
return d3_time_zfill2(d3.time.sundayOfYear(d));
},
w: function(d) {
return d.getDay();
},
W: function(d) {
return d3_time_zfill2(d3.time.mondayOfYear(d));
},
x: d3.time.format("%m/%d/%y"),
X: d3.time.format("%H:%M:%S"),
y: function(d) {
return d3_time_zfill2(d.getFullYear() % 100);
},
Y: function(d) {
return d3_time_zfill4(d.getFullYear() % 1e4);
},
Z: d3_time_zone,
"%": function(d) {
return "%";
}
};
var d3_time_parsers = {
a: d3_time_parseWeekdayAbbrev,
A: d3_time_parseWeekday,
b: d3_time_parseMonthAbbrev,
B: d3_time_parseMonth,
c: d3_time_parseLocaleFull,
d: d3_time_parseDay,
e: d3_time_parseDay,
H: d3_time_parseHour24,
I: d3_time_parseHour24,
L: d3_time_parseMilliseconds,
m: d3_time_parseMonthNumber,
M: d3_time_parseMinutes,
p: d3_time_parseAmPm,
S: d3_time_parseSeconds,
x: d3_time_parseLocaleDate,
X: d3_time_parseLocaleTime,
y: d3_time_parseYear,
Y: d3_time_parseFullYear
};
function d3_time_parseWeekdayAbbrev(date, string, i) {
return d3_time_weekdayAbbrevRe.test(string.substring(i, i += 3)) ? i : -1;
}
function d3_time_parseWeekday(date, string, i) {
d3_time_weekdayRe.lastIndex = 0;
var n = d3_time_weekdayRe.exec(string.substring(i, i + 10));
return n ? i += n[0].length : -1;
}
var d3_time_weekdayAbbrevRe = /^(?:sun|mon|tue|wed|thu|fri|sat)/i, d3_time_weekdayRe = /^(?:Sunday|Monday|Tuesday|Wednesday|Thursday|Friday|Saturday)/i, d3_time_weekdays = [ "Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday" ];
function d3_time_parseMonthAbbrev(date, string, i) {
var n = d3_time_monthAbbrevLookup.get(string.substring(i, i += 3).toLowerCase());
return n == null ? -1 : (date.m = n, i);
}
var d3_time_monthAbbrevLookup = d3.map({
jan: 0,
feb: 1,
mar: 2,
apr: 3,
may: 4,
jun: 5,
jul: 6,
aug: 7,
sep: 8,
oct: 9,
nov: 10,
dec: 11
});
function d3_time_parseMonth(date, string, i) {
d3_time_monthRe.lastIndex = 0;
var n = d3_time_monthRe.exec(string.substring(i, i + 12));
return n ? (date.m = d3_time_monthLookup.get(n[0].toLowerCase()), i += n[0].length) : -1;
}
var d3_time_monthRe = /^(?:January|February|March|April|May|June|July|August|September|October|November|December)/ig;
var d3_time_monthLookup = d3.map({
january: 0,
february: 1,
march: 2,
april: 3,
may: 4,
june: 5,
july: 6,
august: 7,
september: 8,
october: 9,
november: 10,
december: 11
});
var d3_time_months = [ "January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December" ];
function d3_time_parseLocaleFull(date, string, i) {
return d3_time_parse(date, d3_time_formats.c.toString(), string, i);
}
function d3_time_parseLocaleDate(date, string, i) {
return d3_time_parse(date, d3_time_formats.x.toString(), string, i);
}
function d3_time_parseLocaleTime(date, string, i) {
return d3_time_parse(date, d3_time_formats.X.toString(), string, i);
}
function d3_time_parseFullYear(date, string, i) {
d3_time_numberRe.lastIndex = 0;
var n = d3_time_numberRe.exec(string.substring(i, i + 4));
return n ? (date.y = +n[0], i += n[0].length) : -1;
}
function d3_time_parseYear(date, string, i) {
d3_time_numberRe.lastIndex = 0;
var n = d3_time_numberRe.exec(string.substring(i, i + 2));
return n ? (date.y = d3_time_expandYear(+n[0]), i += n[0].length) : -1;
}
function d3_time_expandYear(d) {
return d + (d > 68 ? 1900 : 2e3);
}
function d3_time_parseMonthNumber(date, string, i) {
d3_time_numberRe.lastIndex = 0;
var n = d3_time_numberRe.exec(string.substring(i, i + 2));
return n ? (date.m = n[0] - 1, i += n[0].length) : -1;
}
function d3_time_parseDay(date, string, i) {
d3_time_numberRe.lastIndex = 0;
var n = d3_time_numberRe.exec(string.substring(i, i + 2));
return n ? (date.d = +n[0], i += n[0].length) : -1;
}
function d3_time_parseHour24(date, string, i) {
d3_time_numberRe.lastIndex = 0;
var n = d3_time_numberRe.exec(string.substring(i, i + 2));
return n ? (date.H = +n[0], i += n[0].length) : -1;
}
function d3_time_parseMinutes(date, string, i) {
d3_time_numberRe.lastIndex = 0;
var n = d3_time_numberRe.exec(string.substring(i, i + 2));
return n ? (date.M = +n[0], i += n[0].length) : -1;
}
function d3_time_parseSeconds(date, string, i) {
d3_time_numberRe.lastIndex = 0;
var n = d3_time_numberRe.exec(string.substring(i, i + 2));
return n ? (date.S = +n[0], i += n[0].length) : -1;
}
function d3_time_parseMilliseconds(date, string, i) {
d3_time_numberRe.lastIndex = 0;
var n = d3_time_numberRe.exec(string.substring(i, i + 3));
return n ? (date.L = +n[0], i += n[0].length) : -1;
}
var d3_time_numberRe = /\s*\d+/;
function d3_time_parseAmPm(date, string, i) {
var n = d3_time_amPmLookup.get(string.substring(i, i += 2).toLowerCase());
return n == null ? -1 : (date.p = n, i);
}
var d3_time_amPmLookup = d3.map({
am: 0,
pm: 1
});
function d3_time_zone(d) {
var z = d.getTimezoneOffset(), zs = z > 0 ? "-" : "+", zh = ~~(Math.abs(z) / 60), zm = Math.abs(z) % 60;
return zs + d3_time_zfill2(zh) + d3_time_zfill2(zm);
}
d3.time.format.utc = function(template) {
var local = d3.time.format(template);
function format(date) {
try {
d3_time = d3_time_utc;
var utc = new d3_time;
utc._ = date;
return local(utc);
} finally {
d3_time = Date;
}
}
format.parse = function(string) {
try {
d3_time = d3_time_utc;
var date = local.parse(string);
return date && date._;
} finally {
d3_time = Date;
}
};
format.toString = local.toString;
return format;
};
var d3_time_formatIso = d3.time.format.utc("%Y-%m-%dT%H:%M:%S.%LZ");
d3.time.format.iso = Date.prototype.toISOString ? d3_time_formatIsoNative : d3_time_formatIso;
function d3_time_formatIsoNative(date) {
return date.toISOString();
}
d3_time_formatIsoNative.parse = function(string) {
var date = new Date(string);
return isNaN(date) ? null : date;
};
d3_time_formatIsoNative.toString = d3_time_formatIso.toString;
function d3_time_interval(local, step, number) {
function round(date) {
var d0 = local(date), d1 = offset(d0, 1);
return date - d0 < d1 - date ? d0 : d1;
}
function ceil(date) {
step(date = local(new d3_time(date - 1)), 1);
return date;
}
function offset(date, k) {
step(date = new d3_time(+date), k);
return date;
}
function range(t0, t1, dt) {
var time = ceil(t0), times = [];
if (dt > 1) {
while (time < t1) {
if (!(number(time) % dt)) times.push(new Date(+time));
step(time, 1);
}
} else {
while (time < t1) times.push(new Date(+time)), step(time, 1);
}
return times;
}
function range_utc(t0, t1, dt) {
try {
d3_time = d3_time_utc;
var utc = new d3_time_utc;
utc._ = t0;
return range(utc, t1, dt);
} finally {
d3_time = Date;
}
}
local.floor = local;
local.round = round;
local.ceil = ceil;
local.offset = offset;
local.range = range;
var utc = local.utc = d3_time_interval_utc(local);
utc.floor = utc;
utc.round = d3_time_interval_utc(round);
utc.ceil = d3_time_interval_utc(ceil);
utc.offset = d3_time_interval_utc(offset);
utc.range = range_utc;
return local;
}
function d3_time_interval_utc(method) {
return function(date, k) {
try {
d3_time = d3_time_utc;
var utc = new d3_time_utc;
utc._ = date;
return method(utc, k)._;
} finally {
d3_time = Date;
}
};
}
d3.time.second = d3_time_interval(function(date) {
return new d3_time(Math.floor(date / 1e3) * 1e3);
}, function(date, offset) {
date.setTime(date.getTime() + Math.floor(offset) * 1e3);
}, function(date) {
return date.getSeconds();
});
d3.time.seconds = d3.time.second.range;
d3.time.seconds.utc = d3.time.second.utc.range;
d3.time.minute = d3_time_interval(function(date) {
return new d3_time(Math.floor(date / 6e4) * 6e4);
}, function(date, offset) {
date.setTime(date.getTime() + Math.floor(offset) * 6e4);
}, function(date) {
return date.getMinutes();
});
d3.time.minutes = d3.time.minute.range;
d3.time.minutes.utc = d3.time.minute.utc.range;
d3.time.hour = d3_time_interval(function(date) {
var timezone = date.getTimezoneOffset() / 60;
return new d3_time((Math.floor(date / 36e5 - timezone) + timezone) * 36e5);
}, function(date, offset) {
date.setTime(date.getTime() + Math.floor(offset) * 36e5);
}, function(date) {
return date.getHours();
});
d3.time.hours = d3.time.hour.range;
d3.time.hours.utc = d3.time.hour.utc.range;
d3.time.day = d3_time_interval(function(date) {
var day = new d3_time(0, date.getMonth(), date.getDate());
day.setFullYear(date.getFullYear());
return day;
}, function(date, offset) {
date.setDate(date.getDate() + offset);
}, function(date) {
return date.getDate() - 1;
});
d3.time.days = d3.time.day.range;
d3.time.days.utc = d3.time.day.utc.range;
d3.time.dayOfYear = function(date) {
var year = d3.time.year(date);
return Math.floor((date - year - (date.getTimezoneOffset() - year.getTimezoneOffset()) * 6e4) / 864e5);
};
d3_time_weekdays.forEach(function(day, i) {
day = day.toLowerCase();
i = 7 - i;
var interval = d3.time[day] = d3_time_interval(function(date) {
(date = d3.time.day(date)).setDate(date.getDate() - (date.getDay() + i) % 7);
return date;
}, function(date, offset) {
date.setDate(date.getDate() + Math.floor(offset) * 7);
}, function(date) {
var day = d3.time.year(date).getDay();
return Math.floor((d3.time.dayOfYear(date) + (day + i) % 7) / 7) - (day !== i);
});
d3.time[day + "s"] = interval.range;
d3.time[day + "s"].utc = interval.utc.range;
d3.time[day + "OfYear"] = function(date) {
var day = d3.time.year(date).getDay();
return Math.floor((d3.time.dayOfYear(date) + (day + i) % 7) / 7);
};
});
d3.time.week = d3.time.sunday;
d3.time.weeks = d3.time.sunday.range;
d3.time.weeks.utc = d3.time.sunday.utc.range;
d3.time.weekOfYear = d3.time.sundayOfYear;
d3.time.month = d3_time_interval(function(date) {
date = d3.time.day(date);
date.setDate(1);
return date;
}, function(date, offset) {
date.setMonth(date.getMonth() + offset);
}, function(date) {
return date.getMonth();
});
d3.time.months = d3.time.month.range;
d3.time.months.utc = d3.time.month.utc.range;
d3.time.year = d3_time_interval(function(date) {
date = d3.time.day(date);
date.setMonth(0, 1);
return date;
}, function(date, offset) {
date.setFullYear(date.getFullYear() + offset);
}, function(date) {
return date.getFullYear();
});
d3.time.years = d3.time.year.range;
d3.time.years.utc = d3.time.year.utc.range;
function d3_time_scale(linear, methods, format) {
function scale(x) {
return linear(x);
}
scale.invert = function(x) {
return d3_time_scaleDate(linear.invert(x));
};
scale.domain = function(x) {
if (!arguments.length) return linear.domain().map(d3_time_scaleDate);
linear.domain(x);
return scale;
};
scale.nice = function(m) {
var extent = d3_time_scaleExtent(scale.domain());
return scale.domain([ m.floor(extent[0]), m.ceil(extent[1]) ]);
};
scale.ticks = function(m, k) {
var extent = d3_time_scaleExtent(scale.domain());
if (typeof m !== "function") {
var span = extent[1] - extent[0], target = span / m, i = d3.bisect(d3_time_scaleSteps, target);
if (i == d3_time_scaleSteps.length) return methods.year(extent, m);
if (!i) return linear.ticks(m).map(d3_time_scaleDate);
if (Math.log(target / d3_time_scaleSteps[i - 1]) < Math.log(d3_time_scaleSteps[i] / target)) --i;
m = methods[i];
k = m[1];
m = m[0].range;
}
return m(extent[0], new Date(+extent[1] + 1), k);
};
scale.tickFormat = function() {
return format;
};
scale.copy = function() {
return d3_time_scale(linear.copy(), methods, format);
};
return d3.rebind(scale, linear, "range", "rangeRound", "interpolate", "clamp");
}
function d3_time_scaleExtent(domain) {
var start = domain[0], stop = domain[domain.length - 1];
return start < stop ? [ start, stop ] : [ stop, start ];
}
function d3_time_scaleDate(t) {
return new Date(t);
}
function d3_time_scaleFormat(formats) {
return function(date) {
var i = formats.length - 1, f = formats[i];
while (!f[1](date)) f = formats[--i];
return f[0](date);
};
}
function d3_time_scaleSetYear(y) {
var d = new Date(y, 0, 1);
d.setFullYear(y);
return d;
}
function d3_time_scaleGetYear(d) {
var y = d.getFullYear(), d0 = d3_time_scaleSetYear(y), d1 = d3_time_scaleSetYear(y + 1);
return y + (d - d0) / (d1 - d0);
}
var d3_time_scaleSteps = [ 1e3, 5e3, 15e3, 3e4, 6e4, 3e5, 9e5, 18e5, 36e5, 108e5, 216e5, 432e5, 864e5, 1728e5, 6048e5, 2592e6, 7776e6, 31536e6 ];
var d3_time_scaleLocalMethods = [ [ d3.time.second, 1 ], [ d3.time.second, 5 ], [ d3.time.second, 15 ], [ d3.time.second, 30 ], [ d3.time.minute, 1 ], [ d3.time.minute, 5 ], [ d3.time.minute, 15 ], [ d3.time.minute, 30 ], [ d3.time.hour, 1 ], [ d3.time.hour, 3 ], [ d3.time.hour, 6 ], [ d3.time.hour, 12 ], [ d3.time.day, 1 ], [ d3.time.day, 2 ], [ d3.time.week, 1 ], [ d3.time.month, 1 ], [ d3.time.month, 3 ], [ d3.time.year, 1 ] ];
var d3_time_scaleLocalFormats = [ [ d3.time.format("%Y"), function(d) {
return true;
} ], [ d3.time.format("%B"), function(d) {
return d.getMonth();
} ], [ d3.time.format("%b %d"), function(d) {
return d.getDate() != 1;
} ], [ d3.time.format("%a %d"), function(d) {
return d.getDay() && d.getDate() != 1;
} ], [ d3.time.format("%I %p"), function(d) {
return d.getHours();
} ], [ d3.time.format("%I:%M"), function(d) {
return d.getMinutes();
} ], [ d3.time.format(":%S"), function(d) {
return d.getSeconds();
} ], [ d3.time.format(".%L"), function(d) {
return d.getMilliseconds();
} ] ];
var d3_time_scaleLinear = d3.scale.linear(), d3_time_scaleLocalFormat = d3_time_scaleFormat(d3_time_scaleLocalFormats);
d3_time_scaleLocalMethods.year = function(extent, m) {
return d3_time_scaleLinear.domain(extent.map(d3_time_scaleGetYear)).ticks(m).map(d3_time_scaleSetYear);
};
d3.time.scale = function() {
return d3_time_scale(d3.scale.linear(), d3_time_scaleLocalMethods, d3_time_scaleLocalFormat);
};
var d3_time_scaleUTCMethods = d3_time_scaleLocalMethods.map(function(m) {
return [ m[0].utc, m[1] ];
});
var d3_time_scaleUTCFormats = [ [ d3.time.format.utc("%Y"), function(d) {
return true;
} ], [ d3.time.format.utc("%B"), function(d) {
return d.getUTCMonth();
} ], [ d3.time.format.utc("%b %d"), function(d) {
return d.getUTCDate() != 1;
} ], [ d3.time.format.utc("%a %d"), function(d) {
return d.getUTCDay() && d.getUTCDate() != 1;
} ], [ d3.time.format.utc("%I %p"), function(d) {
return d.getUTCHours();
} ], [ d3.time.format.utc("%I:%M"), function(d) {
return d.getUTCMinutes();
} ], [ d3.time.format.utc(":%S"), function(d) {
return d.getUTCSeconds();
} ], [ d3.time.format.utc(".%L"), function(d) {
return d.getUTCMilliseconds();
} ] ];
var d3_time_scaleUTCFormat = d3_time_scaleFormat(d3_time_scaleUTCFormats);
function d3_time_scaleUTCSetYear(y) {
var d = new Date(Date.UTC(y, 0, 1));
d.setUTCFullYear(y);
return d;
}
function d3_time_scaleUTCGetYear(d) {
var y = d.getUTCFullYear(), d0 = d3_time_scaleUTCSetYear(y), d1 = d3_time_scaleUTCSetYear(y + 1);
return y + (d - d0) / (d1 - d0);
}
d3_time_scaleUTCMethods.year = function(extent, m) {
return d3_time_scaleLinear.domain(extent.map(d3_time_scaleUTCGetYear)).ticks(m).map(d3_time_scaleUTCSetYear);
};
d3.time.scale.utc = function() {
return d3_time_scale(d3.scale.linear(), d3_time_scaleUTCMethods, d3_time_scaleUTCFormat);
};
})(); | mit |
daveWid/Owl | classes/Owl/Asset/JavaScript.php | 564 | <?php
namespace Owl\Asset;
/**
* A JavaScript asset for an owl view.
*
* @package Owl
* @author Dave Widmer <dwidmer@bgsu.edu>
*/
class JavaScript
{
/**
* @var string The src for the script tag
*/
public $src;
/**
* Creates a new JS view asset.
*
* @param string $src The script source
*/
public function __construct($src)
{
$this->src = $src;
}
/**
* Renders the asset to html
*
* @return string The html for the <script>
*/
public function __toString()
{
return '<script src="'.$this->src.'"></script>';
}
}
| mit |
kaoscript/kaoscript | test/fixtures/compile/function/function.named.throws.supertype.js | 405 | var Type = require("@kaoscript/runtime").Type;
module.exports = function() {
function foo(bar) {
if(arguments.length < 1) {
throw new SyntaxError("Wrong number of arguments (" + arguments.length + " for 1)");
}
if(bar === void 0 || bar === null) {
throw new TypeError("'bar' is not nullable");
}
}
try {
foo(42);
}
catch(__ks_0) {
if(Type.isClassInstance(__ks_0, Error)) {
}
}
}; | mit |
blebougge/Catel | src/Catel.Core/Catel.Core.Shared/ComponentModel/EventArgs/DataErrorsChangedEventArgs.cs | 1259 | ๏ปฟ// --------------------------------------------------------------------------------------------------------------------
// <copyright file="DataErrorsChangedEventArgs.cs" company="Catel development team">
// Copyright (c) 2008 - 2015 Catel development team. All rights reserved.
// </copyright>
// --------------------------------------------------------------------------------------------------------------------
#if NET40
namespace System.ComponentModel
{
/// <summary>
/// EventArgs for the <see cref="INotifyDataErrorInfo.ErrorsChanged"/> and <see cref="INotifyDataWarningInfo.WarningsChanged"/> events.
/// </summary>
public class DataErrorsChangedEventArgs : EventArgs
{
/// <summary>
/// Initializes a new instance of the <see cref="DataErrorsChangedEventArgs"/> class.
/// </summary>
/// <param name="propertyName">Name of the property.</param>
public DataErrorsChangedEventArgs(string propertyName)
{
PropertyName = propertyName;
}
/// <summary>
/// Gets or sets the name of the property.
/// </summary>
/// <value>The name of the property.</value>
public string PropertyName { get; private set; }
}
}
#endif | mit |
segafan/wme1_jankavan_tlc_edition-repo | src/Integrator/Integrator/Properties/Settings.Designer.cs | 1091 | ๏ปฟ//------------------------------------------------------------------------------
// <auto-generated>
// This code was generated by a tool.
// Runtime Version:2.0.50727.5456
//
// Changes to this file may cause incorrect behavior and will be lost if
// the code is regenerated.
// </auto-generated>
//------------------------------------------------------------------------------
namespace Integrator.Properties {
[global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()]
[global::System.CodeDom.Compiler.GeneratedCodeAttribute("Microsoft.VisualStudio.Editors.SettingsDesigner.SettingsSingleFileGenerator", "9.0.0.0")]
internal sealed partial class Settings : global::System.Configuration.ApplicationSettingsBase {
private static Settings defaultInstance = ((Settings)(global::System.Configuration.ApplicationSettingsBase.Synchronized(new Settings())));
public static Settings Default {
get {
return defaultInstance;
}
}
}
}
| mit |
nook-ru/admin_helper_lib | lib/Widget/HelperWidget.php | 41766 | <?php
namespace DigitalWand\AdminHelper\Widget;
use Bitrix\Main\Localization\Loc;
use DigitalWand\AdminHelper\Helper\AdminBaseHelper;
use DigitalWand\AdminHelper\Helper\AdminEditHelper;
use DigitalWand\AdminHelper\Helper\AdminListHelper;
use Bitrix\Main\Entity\DataManager;
/**
* ะะธะดะถะตั - ะบะปะฐัั, ะพัะฒะตัะฐััะธะน ะทะฐ ะฒะฝะตัะฝะธะน ะฒะธะด ะพัะดะตะปัะฝะพ ะฒะทััะพะณะพ ะฟะพะปั ัััะฝะพััะธ. ะะดะธะฝ ะฒะธะดะถะตั ะพัะฒะตัะฐะตั ะทะฐ:
* <ul>
* <li>ะัะพะฑัะฐะถะตะฝะธะต ะฟะพะปั ะฝะฐ ัััะฐะฝะธัะต ัะตะดะฐะบัะธัะพะฒะฐะฝะธั</li>
* <li>ะัะพะฑัะฐะถะตะฝะธะต ััะตะนะบะธ ะฟะพะปั ะฒ ัะฐะฑะปะธัะต ัะฟะธัะบะฐ - ะฟัะธ ะฟัะพัะผะพััะต ะธ ัะตะดะฐะบัะธัะพะฒะฐะฝะธะธ</li>
* <li>ะัะพะฑัะฐะถะตะฝะธะต ัะธะปัััะฐ ะฟะพ ะดะฐะฝะฝะพะผั ะฟะพะปั</li>
* <li>ะะฐะปะธะดะฐัะธั ะทะฝะฐัะตะฝะธั ะฟะพะปั</li>
* </ul>
*
* ะขะฐะบะถะต ะฒะธะดะถะตัะฐะผะธ ะพัััะตััะฒะปัะตััั ะฟัะตะดะฒะฐัะธัะตะปัะฝะฐั ะพะฑัะฐะฑะพัะบะฐ ะดะฐะฝะฝัั
:
* <ul>
* <li>ะะตัะตะด ัะพั
ัะฐะฝะตะฝะธะตะผ ะทะฝะฐัะตะฝะธั ะฟะพะปั ะฒ ะะ</li>
* <li>ะะพัะปะต ะฟะพะปััะตะฝะธั ะทะฝะฐัะตะฝะธั ะฟะพะปั ะธะท ะะ</li>
* <li>ะะพะดะธัะธะบะฐัะธั ะทะฐะฟัะพัะฐ ะฟะตัะตะด ัะธะปัััะฐัะธะตะน</li>
* <li>ะะพะดะธัะธะบะฐัะธั ะฟัะตะััะต ะฟะตัะตะด ะฒัะฑะพัะบะพะน ะดะฐะฝะฝัั
</li>
* </ul>
*
* ะะปั ะฟะพะปััะตะฝะธั ะผะธะฝะธะผะฐะปัะฝะพะน ััะฝะบัะธะพะฝะฐะปัะฝะพััะธ ะดะพััะฐัะพัะฝะพ ะฟะตัะตะพะฟัะตะดะตะปะธัั ะพัะฝะพะฒะฝัะต ะผะตัะพะดั, ะพัะฒะตัะฐััะธะต ะทะฐ ะพัะพะฑัะฐะถะตะฝะธะต
* ะฒะธะดะถะตัะฐ ะฒ ัะฟะธัะบะต ะธ ะฝะฐ ะดะตัะฐะปัะฝะพะน.
*
* ะะฐะถะดัะน ะฒะธะดะถะตั ะธะผะตะตั ััะด ัะฟะตัะธัะธัะตัะบะธั
ะฝะฐัััะพะตะบ, ะฝะตะบะพัะพััะต ะธะท ะบะพัะพััั
ะพะฑัะทะฐัะตะปัะฝั ะดะปั ะทะฐะฟะพะปะฝะตะฝะธั. ะะพะดัะพะฑะฝัั
* ะดะพะบัะผะตะฝัะฐัะธั ะฟะพ ะฝะฐัััะพะนะบะฐะผ ััะพะธั ะธัะบะฐัั ะฒ ะดะพะบัะผะตะฝัะฐัะธะธ ะบ ะบะพะฝะบัะตัะฝะพะผั ะฒะธะดะถะตัั. ะะฐัััะพะนะบะธ ะผะพะณัั ะฑััั ะฟะตัะตะดะฐะฝั ะฒ
* ะฒะธะดะถะตั ะบะฐะบ ะฟัะธ ะพะฟะธัะฐะฝะธะธ ะฒัะตะณะพ ะธะฝัะตััะตะนัะฐ ะฒ ัะฐะนะปะต Interface.php, ัะฐะบ ะธ ะฝะตะฟะพััะตะดััะฒะตะฝะฝะพ ะฒะพ ะฒัะตะผั ะธัะฟะพะปะฝะตะฝะธั,
* ะฒะฝัััะธ Helper-ะบะปะฐััะพะฒ.
*
* ะัะธ ัะบะฐะทะฐะฝะธะธ ะฝะฐัััะพะตะบ ัะธะฟะฐ "ะดะฐ"/"ะฝะตั", ะฝะตะปัะทั ะธัะฟะพะปัะทะพะฒะฐัั ัััะพะบะพะฒัะต ะพะฑะพะทะฝะฐัะตะฝะธั "Y"/"N":
* ะดะปั ััะพะณะพ ะตััั ะฑัะปะตะฒั true ะธ false.
*
* ะะฐัััะพะนะบะธ ะฑะฐะทะพะฒะพะณะพ ะบะปะฐััะฐ:
* <ul>
* <li><b>HIDE_WHEN_CREATE</b> - ัะบััะฒะฐะตั ะฟะพะปะต ะฒ ัะพัะผะต ัะตะดะฐะบัะธัะพะฒะฐะฝะธั, ะตัะปะธ ัะพะทะดะฐัััั ะฝะพะฒัะน ัะปะตะผะตะฝั, ะฐ ะฝะต ะพัะบััั
* ัััะตััะฒัััะธะน ะฝะฐ ัะตะดะฐะบัะธัะพะฒะฐะฝะธะต.</li>
* <li><b>TITLE</b> - ะฝะฐะทะฒะฐะฝะธะต ะฟะพะปั. ะัะปะธ ะฝะต ะทะฐะดะฐะฝะพ ัะพ ะฒะพะทัะผะตััั ะทะฝะฐัะตะฝะธะต title ะธะท DataManager::getMap()
* ัะตัะตะท getField($code)->getTitle(). ะัะดะตั ะธัะฟะพะปัะทะพะฒะฐะฝะพ ะฒ ัะธะปัััะต, ะทะฐะณะพะปะพะฒะบะต ัะฐะฑะปะธัั ะธ ะฒ ะบะฐัะตััะฒะต ะฟะพะดะฟะธัะธ ะฟะพะปั
* ะฝะฐ
* ัััะฐะฝะธัะต ัะตะดะฐะบัะธัะพะฒะฐะฝะธั.</li>
* <li><b>REQUIRED</b> - ัะฒะปัะตััั ะปะธ ะฟะพะปะต ะพะฑัะทะฐัะตะปัะฝัะผ.</li>
* <li><b>READONLY</b> - ะฟะพะปะต ะฝะตะปัะทั ัะตะดะฐะบัะธัะพะฒะฐัั, ะฟัะตะดะฝะฐะทะฝะฐัะตะฝะพ ัะพะปัะบะพ ะดะปั ััะตะฝะธั</li>
* <li><b>FILTER</b> - ะฟะพะทะฒะพะปัะตั ัะบะฐะทะฐัั ัะฟะพัะพะฑ ัะธะปัััะฐัะธะธ ะฟะพ ะฟะพะปั. ะ ะฑะฐะทะพะฒะพะผ ะบะปะฐััะต ะฒะพะทะผะพะถะตะฝ ัะพะปัะบะพ ะฒะฐัะธะฐะฝั "BETWEEN"
* ะธะปะธ "><". ะ ะฒ ัะพะผ ะธ ะฒ ะดััะณะพะผ ัะปััะฐะต ััะพ ะฑัะดะตั ะพะทะฝะฐัะฐัั ัะธะปัััะฐัะธั ะฟะพ ะดะธะฐะฟะฐะทะพะฝั ะทะฝะฐัะตะฝะธะน. ะะพะปะธัะตััะฒะพ ะฒะพะทะผะพะถะฝัั
* ะฒะฐัะธะฐะฝัะพะฒ ััะพะณะพ ะฟะฐัะฐะผะตััะฐ ะผะพะถะตั ะฑััั ัะฐััะธัะตะฝะพ ะฒ ะฝะฐัะปะตะดัะตะผัั
ะบะปะฐััะฐั
</li>
* <li><b>UNIQUE</b> - ะฟะพะปะต ะดะพะปะถะฝะพ ัะพะดะตัะถะฐัั ัะพะปัะบะพ ัะฝะธะบะฐะปัะฝัะต ะทะฝะฐัะตะฝะธั</li>
* <li><b>VIRTUAL</b> - ะพัะพะฑะฐั ะฝะฐัััะพะนะบะฐ, ะพััะฐะถะฐะตััั ะบะฐะบ ะฝะฐ ะฟะพะฒะตะดะตะฝะธะธ ะฒะธะดะถะตัะฐ, ัะฐะบ ะธ ะฝะฐ ะฟะพะฒะตะดะตะฝะธะธ ั
ัะปะฟะตัะพะฒ. ะะพะปะต,
* ะพะฑััะฒะปะตะฝะฝะพะต ะฒะธัััะฐะปัะฝัะผ, ะพัะพะฑัะฐะถะฐะตััั ะฒ ะณัะฐัะธัะตัะบะพะผ ะธะฝัะตััะตะนัะต, ะพะดะฝะฐะบะพ ะฝะต ััะฐััะฒะพัะตั ะฒ ะทะฐะฟัะพัะฐั
ะบ ะะ. ะะฟัะธั
* ะผะพะถะตั ะฑััั ะฟะพะปะตะทะฝะพะน ะฟัะธ ัะตะฐะปะธะทะฐัะธะธ ะฝะตััะฐะฝะดะฐััะฝะพะน ะปะพะณะธะบะธ, ะบะพะณะดะฐ, ะบ ะฟัะธะผะตัั, ะฟะพะด ะธะผะตะฝะตะผ ะพะดะฝะพะณะพ ะฟะพะปั ะผะพะณัั
* ะฒัะฒะพะดะธัััั ะดะฐะฝะฝัะต ะธะท ะฝะตัะบะพะปัะบะธั
ะฟะพะปะตะน ััะฐะทั. </li>
* <li><b>EDIT_IN_LIST</b> - ะฟะฐัะฐะผะตัั ะฝะต ะพะฑัะฐะฑะฐััะฒะฐะตััั ะฝะตะฟะพััะตะดััะฒะตะฝะฝะพ ะฒะธะดะถะตัะพะผ, ะพะดะฝะฐะบะพ ะธัะฟะพะปัะทัะตััั ั
ัะปะฟะตัะพะผ.
* ะฃะบะฐะทัะฒะฐะตั, ะผะพะถะฝะพ ะปะธ ัะตะดะฐะบัะธัะพะฒะฐัั ะดะฐะฝะฝะพะต ะฟะพะปะต ะฒ ัะฟะธัะบะบะต</li>
* <li><b>MULTIPLE</b> - bool ัะฒะปัะตััั ะปะธ ะฟะพะปะต ะผะฝะพะถะตััะฒะตะฝะฝัะผ</li>
* <li><b>MULTIPLE_FIELDS</b> - array ะฟะพะปั ะธัะฟะพะปัะทัะตะผัะต ะฒ ั
ัะฐะฝะธะปะธัะต ะผะฝะพะถะตััะฒะตะฝะฝัั
ะทะฝะฐัะตะฝะธะน ะธ ะธั
ะฐะปะธะฐัั</li>
* <li><b>LIST</b> - ะพัะพะฑัะฐะถะฐัั ะปะธ ะฟะพะปะต ะฒ ัะฟะธัะบะต ะดะพัััะฟะฝัั
ะฒ ะฝะฐัััะพะนะบะฐั
ััะพะปะฑัะพะฒ ัะฐะฑะปะธัั (ะฟะพ-ัะผะพะปัะฐะฝะธั true)</li>
* <li><b>HEADER</b> - ัะฒะปัะตััั ะปะธ ััะพะปะฑะตั ะพัะพะฑัะฐะถะฐะตะผัะผ ะฟะพ-ัะผะพะปัะฐะฝะธั, ะตัะปะธ ะฒัะฒะพะด ััะพะปะฑัะพะฒ ัะฐะฑะปะธัั ะฝะต ะฝะฐัััะพะตะฝ (ะฟะพ-ัะผะพะปัะฐะฝะธั true)</li>
* </ul>
*
* ะะฐะบ ัะดะตะปะฐัั ะฒะธะดะถะตั ะผะฝะพะถะตััะฒะตะฝะฝัะผ?
* <ul>
* <li>ะ ะตะฐะปะธะทัะนัะต ะผะตัะพะด genMultipleEditHTML(). ะะตัะพะด ะดะพะปะถะตะฝ ะฒัะฒะพะดะธัั ะผะฝะพะถะตััะฒะตะฝะฝัั ัะพัะผั ะฒะฒะพะดะฐ. ะะปั ัะตะฐะปะธะทะฐัะธะธ ัะพัะผั
* ะฒะฒะพะดะฐ ะตััั JS ั
ะตะปะฟะตั HelperWidget::jsHelper()</li>
* <li>ะะฟะธัะธัะต ะฟะพะปั, ะบะพัะพััะต ะฑัะดัั ะฟะตัะตะดะฐะฝั ัะฒัะทะธ ะฒ EntityManager. ะะพะปั ะพะฟะธััะฒะฐัััั ะฒ ะฝะฐัััะพะนะบะต "MULTIPLE_FIELDS"
* ะฒะธะดะถะตัะฐ. ะะพ ัะผะพะปัะฐะฝะธั ะผะฝะพะถะตััะฒะตะฝะฝัะน ะฒะธะดะถะตั ะธัะฟะพะปัะทัะตั ะฟะพะปั ID, ENTITY_ID, VALUE</li>
* <li>ะะพะปััะตะฝะฝัะต ะพั ะฒะธะดะถะตัะฐ ะดะฐะฝะฝัะต ะฑัะดัั ะฟะตัะตะดะฐะฝั ะฒ EntityManager ะธ ัะพั
ัะฐะฝะตะฝั ะบะฐะบ ัะฒัะทะฐะฝะฝัะต ะดะฐะฝะฝัะต</li>
* </ul>
* ะัะธะผะตั ัะตะฐะปะธะทะฐัะธะธ ะผะพะถะฝะพ ัะฒะธะดะตัั ะฒ ะฒะธะดะถะตัะต StringWidget
*
* ะะฐะบ ะธัะฟะพะปัะทะพะฒะฐัั ะผะฝะพะถะตััะฒะตะฝะฝัะน ะฒะธะดะถะตั?
* <ul>
* <li>
* ะกะพะทะดะฐะนัะต ัะฐะฑะปะธัั ะธ ะผะพะดะตะปั, ะบะพัะพัะฐั ะฑัะดะตั ั
ัะฐะฝะธัั ะดะฐะฝะฝัะต ะฟะพะปั
* - ะขะฐะฑะปะธัะฐ ะพะฑัะทะฐัะตะปัะฝะพ ะดะพะปะถะฝะฐ ะธะผะตัั ะฟะพะปั, ะบะพัะพััะต ััะตะฑัะตั ะฒะธะดะถะตั.
* ะะฑัะทะฐัะตะปัะฝัะต ะฟะพะปั ะฒะธะดะถะตัะฐ ะฟะพ ัะผะพะปัะฐะฝะธั ะพะฟะธัะฐะฝั ะฒ: HelperWidget::$settings['MULTIPLE_FIELDS']
* ะัะปะธ ั ะฒะธะดะถะตัะฐ ะฝะตััะฐะฝะดะฐััะฝัะน ะฝะฐะฑะพั ะฟะพะปะตะน, ัะพ ะพะฝะธ ั
ัะฐะฝัััั ะฒ: SomeWidget::$settings['MULTIPLE_FIELDS']
* - ะัะปะธ ะฟะพะปั, ะบะพัะพััะต ััะตะฑัะตั ะฒะธะดะถะตั ะตััั ะฒ ะฒะฐัะตะน ัะฐะฑะปะธัะต, ะฝะพ ะพะฝะธ ะธะผะตัั ะดััะณะธะต ะฝะฐะทะฒะฐะฝะธั,
* ะผะพะถะฝะพ ะฝะฐัััะพะธัั ะฒะธะดะถะตั ะดะปั ัะฐะฑะพัั ั ะฒะฐัะธะผะธ ะฟะพะปัะผะธ.
* ะะปั ััะพะณะพ ะฟะตัะตะพะฟัะตะดะตะปะธัะต ะฝะฐัััะพะนะบั MULTIPLE_FIELDS ะฟัะธ ะพะฑััะฒะปะตะฝะธะธ ะฟะพะปั ะฒ ะธะฝัะตััะตะนัะต ัะปะตะดัััะธะผ ัะฟะพัะพะฑะพะผ:
* ```
* 'RELATED_LINKS' => array(
* 'WIDGET' => new StringWidget(),
* 'TITLE' => 'ะกััะปะบะธ',
* 'MULTIPLE' => true,
* // ะะฑัะฐัะธัะต ะฒะฝะธะผะฐะฝะธะต, ะธะผะตะฝะฝะพ ััั ะฟะตัะตะพะฟัะตะดะตะปััััั ะฟะพะปั ะฒะธะดะถะตัะฐ
* 'MULTIPLE_FIELDS' => array(
* 'ID', // ะะพะปะถะฝั ะฑััั ะฟัะพะฟะธัะฐะฝั ะฒัะต ะฟะพะปั, ะดะฐะถะต ัะต, ะบะพัะพััะต ะฝะต ะฝัะถะฝะพ ะฟะตัะตะพะฟัะตะดะตะปััั
* 'ENTITY_ID' => 'NEWS_ID', // ENTITY_ID - ะฟะพะปะต, ะบะพัะพัะพะต ััะตะฑัะตั ะฒะธะดะถะตั, NEWS_ID - ะฟัะธะผะตั ะฟะพะปั, ะบะพัะพัะพะต
* ะฑัะดะตั ะธัะฟะพะปัะทะพะฒะฐัััั ะฒะผะตััะพ ENTITY_ID
* 'VALUE' => 'LINK', // VALUE - ะฟะพะปะต, ะบะพัะพัะพะต ััะตะฑัะตั ะฒะธะดะถะตั, LINK - ะฟัะธะผะตั ะฟะพะปั, ะบะพัะพัะพะต ะฑัะดะตั
* ะธัะฟะพะปัะทะพะฒะฐัััั ะฒะผะตััะพ VALUE
* )
* ),
* ```
* </li>
*
* <li>
* ะะฐะปะตะต ะฒ ะพัะฝะพะฒะฝะพะน ะผะพะดะตะปะธ (ัะฐ, ะบะพัะพัะฐั ัะบะฐะทะฐะฝะฐ ะฒ AdminBaseHelper::$model) ะฝัะถะฝะพ ะฟัะพะฟะธัะฐัั ัะฒัะทั ั ะผะพะดะตะปัั,
* ะฒ ะบะพัะพัะพะน ะฒั ั
ะพัะธัะต ั
ัะฐะฝะธัั ะดะฐะฝะฝัะต ะฟะพะปั
* ะัะธะผะตั ะพะฑััะฒะปะตะฝะธั ัะฒัะทะธ:
* ```
* new Entity\ReferenceField(
* 'RELATED_LINKS',
* 'namespace\NewsLinksTable',
* array('=this.ID' => 'ref.NEWS_ID'),
* // ะฃัะปะพะฒะธั FIELD ะธ ENTITY ะฝะต ะพะฑัะทะฐัะตะปัะฝั, ะฟะพะดัะพะฑะฝะพััะธ ัะผะพััะธัะต ะฒ ะบะพะผะผะตะฝัะฐัะธัั
ะบ ะบะปะฐััั @see EntityManager
* 'ref.FIELD' => new DB\SqlExpression('?s', 'NEWS_LINKS'),
* 'ref.ENTITY' => new DB\SqlExpression('?s', 'news'),
* ),
* ```
* </li>
*
* <li>
* ะงัะพ ะฑั ะฒะธะดะถะตั ัะฐะฑะพัะฐะป ะฒะพ ะผะฝะพะถะตััะฒะตะฝะฝะพะผ ัะตะถะธะผะต, ะฝัะถะฝะพ ะฟัะธ ะพะฟะธัะฐะฝะธะธ ะธะฝัะตััะตะนัะฐ ะฟะพะปั ัะบะฐะทะฐัั ะฟะฐัะฐะผะตัั MULTIPLE => true
* ```
* 'RELATED_LINKS' => array(
* 'WIDGET' => new StringWidget(),
* 'TITLE' => 'ะกััะปะบะธ',
* // ะะบะปััะฐะตะผ ัะตะถะธะผ ะผะฝะพะถะตััะฒะตะฝะฝะพะณะพ ะฒะฒะพะดะฐ
* 'MULTIPLE' => true,
* )
* ```
* </li>
*
* <li>
* ะะพัะพะฒะพ :)
* </li>
* </ul>
*
* ะ ัะพะผ ะบะฐะบ ัะพั
ัะฐะฝััััั ะดะฐะฝะฝัะต ะผะฝะพะถะตััะฒะตะฝะฝัั
ะฒะธะดะถะตัะพะฒ ะผะพะถะฝะพ ัะทะฝะฐัั ะธะท ะบะพะผะผะตะฝัะฐัะธะตะฒ
* ะบะปะฐััะฐ \DigitalWand\AdminHelper\EntityManager.
*
* @see EntityManager
* @see HelperWidget::getEditHtml()
* @see HelperWidget::generateRow()
* @see showFilterHtml::showFilterHTML()
* @see HelperWidget::setSetting()
*
* @author Nik Samokhvalov <nik@samokhvalov.info>
* @author Dmitriy Baibuhtin <dmitriy.baibuhtin@ya.ru>
*/
abstract class HelperWidget
{
const LIST_HELPER = 1;
const EDIT_HELPER = 2;
/**
* @var string ะะพะด ะฟะพะปั.
*/
protected $code;
/**
* @var array $settings ะะฐัััะพะนะบะธ ะฒะธะดะถะตัะฐ ะดะปั ะดะฐะฝะฝะพะน ะผะพะดะตะปะธ.
*/
protected $settings = array(
// ะะพะปั ะผะฝะพะถะตััะฒะตะฝะฝะพะณะพ ะฒะธะดะถะตัะฐ ะฟะพ ัะผะพะปัะฐะฝะธั (array('ะะ ะะะะะะะฌะะะ ะะะะะะะะ', 'ะะ ะะะะะะะฌะะะ ะะะะะะะะ' => 'ะะะะะก'))
'MULTIPLE_FIELDS' => array('ID', 'VALUE', 'ENTITY_ID')
);
/**
* @var array ะะฐัััะพะนะบะธ "ะฟะพ-ัะผะพะปัะฐะฝะธั" ะดะปั ะผะพะดะตะปะธ.
*/
static protected $defaults;
/**
* @var DataManager ะะฐะทะฒะฐะฝะธะต ะบะปะฐััะฐ ะผะพะดะตะปะธ.
*/
protected $entityName;
/**
* @var array ะะฐะฝะฝัะต ะผะพะดะตะปะธ.
*/
protected $data;
/** @var AdminBaseHelper|AdminListHelper|AdminEditHelper $helper ะญะบะทะตะผะฟะปัั ั
ัะปะฟะตัะฐ, ะฒัะทัะฒะฐััะธะน ะดะฐะฝะฝัะน ะฒะธะดะถะตั.
*/
protected $helper;
/**
* @var bool ะกัะฐััั ะพัะพะฑัะฐะถะตะฝะธั JS ั
ะตะปะฟะตัะฐ. ะัะฟะพะปัะทัะตััั ะดะปั ะธัะบะปััะตะฝะธั ะดัะฑะปะธัะพะฒะฐะฝะธั JS-ะบะพะดะฐ.
*/
protected $jsHelper = false;
/**
* @var array $validationErrors ะัะธะฑะบะธ ะฒะฐะปะธะดะฐัะธะธ ะฟะพะปั.
*/
protected $validationErrors = array();
/**
* @var string ะกััะพะบะฐ, ะดะพะฑะฐะฒะปัะตะผะฐั ะบ ะฟะพะปั name ะฟะพะปะตะน ัะธะปัััะฐ.
*/
protected $filterFieldPrefix = 'find_';
/**
* ะญะบัะตะผะฟะปัั ะฒะธะดะถะตัะฐ ัะพะทะดะฐัััั ะฒัะตะณะพ ะพะดะธะฝ ัะฐะท, ะฟัะธ ะพะฟะธัะฐะฝะธะธ ะฝะฐัััะพะตะบ ะธะฝัะตััะตะนัะฐ. ะัะธ ัะพะทะดะฐะฝะธะธ ะตััั ะฒะพะทะผะพะถะฝะพััั
* ััะฐะทั ัะบะฐะทะฐัั ะดะปั ะฝะตะณะพ ะฝะตะพะฑั
ะพะดะธะผัะต ะฝะฐัััะพะนะบะธ.
*
* @param array $settings
*/
public function __construct(array $settings = array())
{
Loc::loadMessages(__FILE__);
$this->settings = $settings;
}
/**
* ะะตะฝะตัะธััะตั HTML ะดะปั ัะตะดะฐะบัะธัะพะฒะฐะฝะธั ะฟะพะปั.
*
* @return string
*
* @api
*/
abstract protected function getEditHtml();
/**
* ะะตะฝะตัะธััะตั HTML ะดะปั ัะตะดะฐะบัะธัะพะฒะฐะฝะธั ะฟะพะปั ะฒ ะผัะปััะธ-ัะตะถะธะผะต.
*
* @return string
*
* @api
*/
protected function getMultipleEditHtml()
{
return Loc::getMessage('DIGITALWAND_AH_MULTI_NOT_SUPPORT');
}
/**
* ะะฑะพัะฐัะธะฒะฐะตั ะฟะพะปะต ะฒ HTML ะบะพะด, ะบะพัะพััะน ะฒ ะฑะพะปััะธะฝััะฒะต ัะปััะฐะตะฒ ะผะตะฝััั ะฝะต ะฟัะธะดะตััั. ะะฐะปะตะต ะฒัะทัะฒะฐะตััั
* ะบะฐััะพะผะธะทะธััะตะผะฐั ัะฐััั.
*
* @param bool $isPKField ะฏะฒะปัะตััั ะปะธ ะฟะพะปะต ะฟะตัะฒะธัะฝัะผ ะบะปััะพะผ ะผะพะดะตะปะธ.
*
* @see HelperWidget::getEditHtml();
*/
public function showBasicEditField($isPKField)
{
if ($this->getSettings('HIDE_WHEN_CREATE') AND !isset($this->data[$this->helper->pk()])) {
return;
}
// JS ั
ะตะปะฟะตัั
$this->jsHelper();
if ($this->getSettings('USE_BX_API')) {
$this->getEditHtml();
} else {
print '<tr>';
$title = $this->getSettings('TITLE');
if ($this->getSettings('REQUIRED') === true) {
$title = '<b>' . $title . '</b>';
}
print '<td width="40%" style="vertical-align: top;">' . $title . ':</td>';
$field = $this->getValue();
if (is_null($field)) {
$field = '';
}
$readOnly = $this->getSettings('READONLY');
if (!$readOnly AND !$isPKField) {
if ($this->getSettings('MULTIPLE')) {
$field = $this->getMultipleEditHtml();
} else {
$field = $this->getEditHtml();
}
} else {
if ($readOnly) {
if ($this->getSettings('MULTIPLE')) {
$field = $this->getMultipleValueReadonly();
} else {
$field = $this->getValueReadonly();
}
}
}
print '<td width="60%">' . $field . '</td>';
print '</tr>';
}
}
/**
* ะะพะทะฒัะฐัะฐะตั ะทะฝะฐัะตะฝะธะต ะฟะพะปั ะฒ ัะพัะผะต "ัะพะปัะบะพ ะดะปั ััะตะฝะธั" ะดะปั ะฝะต ะผะฝะพะถะตััะฒะตะฝะฝัั
ัะฒะพะนััะฒ.
*
* @return mixed
*/
protected function getValueReadonly()
{
return static::prepareToOutput($this->getValue());
}
/**
* ะะพะทะฒัะฐัะฐะตั ะทะฝะฐัะตะฝะธั ะผะฝะพะถะตััะฒะตะฝะฝะพะณะพ ะฟะพะปั.
*
* @return array
*/
protected function getMultipleValue()
{
$rsEntityData = null;
$values = array();
if (!empty($this->data[$this->helper->pk()])) {
$entityName = $this->entityName;
$rsEntityData = $entityName::getList(array(
'select' => array('REFERENCE_' => $this->getCode() . '.*'),
'filter' => array('=ID' => $this->data[$this->helper->pk()])
));
if ($rsEntityData) {
while ($referenceData = $rsEntityData->fetch()) {
if (empty($referenceData['REFERENCE_' . $this->getMultipleField('ID')])) {
continue;
}
$values[] = $referenceData['REFERENCE_' . $this->getMultipleField('VALUE')];
}
}
} else {
if ($this->data[$this->code]) {
$values = $this->data[$this->code];
}
}
return $values;
}
/**
* ะะพะทะฒัะฐัะฐะตั ะทะฝะฐัะตะฝะธะต ะฟะพะปั ะฒ ัะพัะผะต "ัะพะปัะบะพ ะดะปั ััะตะฝะธั" ะดะปั ะผะฝะพะถะตััะฒะตะฝะฝัั
ัะฒะพะนััะฒ.
*
* @return string
*/
protected function getMultipleValueReadonly()
{
$values = $this->getMultipleValue();
foreach ($values as &$value) {
$value = static::prepareToOutput($value);
}
return join('<br/>', $values);
}
/**
* ะะฑัะฐะฑะพัะบะฐ ัััะพะบะธ ะดะปั ะฑะตะทะพะฟะฐัะฝะพะณะพ ะพัะพะฑัะฐะถะตะฝะธั. ะัะปะธ ะฝัะถะฝะพ ะพัะพะฑัะฐะทะธัั ัะตะบัั ะบะฐะบ ะฐัััะธะฑัั ัะตะณะฐ,
* ะธัะฟะพะปัะทัะนัะต static::prepareToTag().
*
* @param string $string
* @param bool $hideTags ะกะบัััั ัะตะณะธ:
*
* - true - ะฒััะตะทะฐัั ัะตะณะธ ะพััะฐะฒะธะฒ ัะพะดะตัะถะธะผะพะต. ะ ะตะทัะปััะฐั ะพะฑัะฐะฑะพัะบะธ: <b>text</b> = text
*
* - false - ะพัะพะฑัะฐะทะฐะธัั ัะตะณะธ ะฒ ะฒะธะดะต ัะตะบััะฐ. ะ ะตะทัะปััะฐั ะพะฑัะฐะฑะพัะบะธ: <b>text</b> = <b>text</b>
*
* @return string
*/
public static function prepareToOutput($string, $hideTags = true)
{
if ($hideTags) {
return preg_replace('/<.+>/mU', '', $string);
} else {
return htmlspecialchars($string, ENT_QUOTES, SITE_CHARSET);
}
}
/**
* ะะพะดะณะพัะพะฒะบะฐ ัััะพะบะธ ะดะปั ะธัะฟะพะปัะทะพะฒะฐะฝะธั ะฒ ะฐัััะธะฑััะฐั
ัะตะณะพะฒ. ะะฐะฟัะธะผะตั:
* ```
* <input name="test" value="<?= HelperWidget::prepareToTagAttr($value) ?>"/>
* ```
*
* @param string $string
*
* @return string
*/
public static function prepareToTagAttr($string)
{
// ะะต ะธัะฟะพะปัะทัะนัะต addcslashes ะฒ ััะพะผ ะผะตัะพะดะต, ะธะฝะฐัะต ะฒ ัะตะณะฐั
ะฑัะดัั ะดัะฑะปะธ ะพะฑัะฐัะฝัั
ัะปะตัะตะน
return htmlspecialchars($string, ENT_QUOTES, SITE_CHARSET);
}
/**
* ะะพะดะณะพัะพะฒะบะฐ ัััะพะบะธ ะดะปั ะธัะฟะพะปัะทะพะฒะฐะฝะธั ะฒ JS.
*
* @param string $string
*
* @return string
*/
public static function prepareToJs($string)
{
$string = htmlspecialchars($string, ENT_QUOTES, SITE_CHARSET);
$string = addcslashes($string, "\r\n\"\\");
return $string;
}
/**
* ะะตะฝะตัะธััะตั HTML ะดะปั ะฟะพะปั ะฒ ัะฟะธัะบะต.
*
* @param \CAdminListRow $row
* @param array $data ะะฐะฝะฝัะต ัะตะบััะตะน ัััะพะบะธ.
*
* @return void
*
* @see AdminListHelper::addRowCell()
*
* @api
*/
abstract public function generateRow(&$row, $data);
/**
* ะะตะฝะตัะธััะตั HTML ะดะปั ะฟะพะปั ัะธะปัััะฐัะธะธ.
*
* @return void
*
* @see AdminListHelper::createFilterForm()
*
* @api
*/
abstract public function showFilterHtml();
/**
* ะะพะทะฒัะฐัะฐะตั ะผะฐััะธะฒ ะฝะฐัััะพะตะบ ะดะฐะฝะฝะพะณะพ ะฒะธะดะถะตัะฐ, ะปะธะฑะพ ะทะฝะฐัะตะฝะธะต ะพัะดะตะปัะฝะพะณะพ ะฟะฐัะฐะผะตััะฐ, ะตัะปะธ ัะบะฐะทะฐะฝะพ ะตะณะพ ะธะผั.
*
* @param string $name ะะฐะทะฒะฐะฝะธะต ะบะพะฝะบัะตัะฝะพะณะพ ะฟะฐัะฐะผะตััะฐ.
*
* @return array|mixed
*
* @api
*/
public function getSettings($name = '')
{
if (empty($name)) {
return $this->settings;
} else {
if (isset($this->settings[$name])) {
return $this->settings[$name];
} else {
if (isset(static::$defaults[$name])) {
return static::$defaults[$name];
} else {
return false;
}
}
}
}
/**
* ะะตัะตะดะฐัั ะฒ ะฒะธะดะถะตั ัััะปะบั ะฝะฐ ะฒัะทัะฒะฐััะธะน ะตะณะพ ะพะฑัะตะบั.
*
* @param AdminBaseHelper $helper
*/
public function setHelper(&$helper)
{
$this->helper = $helper;
}
/**
* ะะพะทะฒัะฐัะฐะตั ัะตะบัะบัะตะต ะทะฝะฐัะตะฝะธะต ะฟะพะปั ัะธะปัััะฐัะธะธ (ัะฟะตั. ัะธะผะฒะพะปั ัะบัะฐะฝะธัะพะฒะฐะฝั).
*
* @return bool|string
*/
protected function getCurrentFilterValue()
{
if (isset($GLOBALS[$this->filterFieldPrefix . $this->code])) {
return htmlspecialcharsbx($GLOBALS[$this->filterFieldPrefix . $this->code]);
} else {
return false;
}
}
/**
* ะัะพะฒะตััะตั ะบะพััะตะบัะฝะพััั ะฒะฒะตะดะตะฝะฝัั
ะฒ ัะธะปััั ะทะฝะฐัะตะฝะธะน
*
* @param string $operationType ัะธะฟ ะพะฟะตัะฐัะธะธ
* @param mixed $value ะทะฝะฐัะตะฝะธะต ัะธะปัััะฐ
*
* @see AdminListHelper::checkFilter();
* @return bool
*/
public function checkFilter($operationType, $value)
{
return true;
}
/**
* ะะพะทะฒะพะปัะตั ะผะพะดะธัะธัะธัะพะฒะฐัั ะพะฟัะธะธ, ะฟะตัะตะดะฐะฒะฐะตะผัะต ะฒ getList, ะฝะตะฟะพััะตะดััะฒะตะฝะฝะพ ะฟะตัะตะด ะฒัะฑะพัะบะพะน.
* ะัะปะธ ะฒ ะฝะฐัััะพะนะบะฐั
ัะฒะฝะพ ัะบะฐะทะฐะฝ ัะฟะพัะพะฑ ัะธะปัััะฐัะธะธ, ะดะพ ะดะพะฑะฐะฒะปัะตั ัะพะพัะฒะตัััะฒัััะธะน ะฟัะตัะธะบั ะฒ $arFilter.
* ะัะปะธ ัะธะปััั BETWEEN, ัะพ ัะพัะผะธััะตั ัะปะพะถะฝัั ะปะพะณะธะบั ัะธะปัััะฐัะธะธ.
*
* @param array $filter $arFilter ัะตะปะธะบะพะผ
* @param array $select
* @param $sort
* @param array $raw $arSelect, $arFilter, $arSort ะดะพ ะฟัะธะผะตะฝะตะฝะฝัั
ะบ ะฝะธะผ ะฟัะตะพะฑัะฐะทะพะฒะฐะฝะธะน.
*
* @see AdlinListHelper::getData();
*/
public function changeGetListOptions(&$filter, &$select, &$sort, $raw)
{
if ($this->isFilterBetween()) {
$field = $this->getCode();
$from = $to = false;
if (isset($_REQUEST['find_' . $field . '_from'])) {
$from = $_REQUEST['find_' . $field . '_from'];
if (is_a($this, 'DateWidget')) {
$from = date('Y-m-d H:i:s', strtotime($from));
}
}
if (isset($_REQUEST['find_' . $field . '_to'])) {
$to = $_REQUEST['find_' . $field . '_to'];
if (is_a($this, 'DateWidget')) {
$to = date('Y-m-d 23:59:59', strtotime($to));
} else if (
is_a($this, '\DigitalWand\AdminHelper\Widget\DateTimeWidget') &&
!preg_match('/\d{2}:\d{2}:\d{2}/', $to)
) {
$to = date('d.m.Y 23:59:59', strtotime($to));
}
}
if ($from !== false AND $to !== false) {
$filter['><' . $field] = array($from, $to);
} else {
if ($from !== false) {
$filter['>' . $field] = $from;
} else {
if ($to !== false) {
$filter['<' . $field] = $to;
}
}
}
} else {
if ($filterPrefix = $this->getSettings('FILTER') AND $filterPrefix !== true AND isset($filter[$this->getCode()])) {
$filter[$filterPrefix . $this->getCode()] = $filter[$this->getCode()];
unset($filter[$this->getCode()]);
}
}
}
/**
* ะัะพะฒะตััะตั ะพะฟะตัะฐัะพั ัะธะปัััะฐัะธะธ.
*
* @return bool
*/
protected function isFilterBetween()
{
return $this->getSettings('FILTER') === '><' OR $this->getSettings('FILTER') === 'BETWEEN';
}
/**
* ะะตะนััะฒะธั, ะฒัะฟะพะปะฝัะตะผัะต ะฝะฐะด ะฟะพะปะตะผ ะฒ ะฟัะพัะตััะต ัะตะดะฐะบัะธัะพะฒะฐะฝะธั ัะปะตะผะตะฝัะฐ, ะดะพ ะตะณะพ ัะพั
ัะฐะฝะตะฝะธั.
* ะะพ-ัะผะพะปัะฐะฝะธั ะฒัะฟะพะปะฝัะตััั ะฟัะพะฒะตัะบะฐ ะพะฑัะทะฐัะตะปัะฝัั
ะฟะพะปะตะน ะธ ัะฝะธะบะฐะปัะฝะพััะธ.
*
* @see AdminEditHelper::editAction();
* @see AdminListHelper::editAction();
*/
public function processEditAction()
{
if (!$this->checkRequired()) {
$this->addError('DIGITALWAND_AH_REQUIRED_FIELD_ERROR');
}
if ($this->getSettings('UNIQUE') && !$this->isUnique()) {
$this->addError('DIGITALWAND_AH_DUPLICATE_FIELD_ERROR');
}
}
/**
* ะ ัะพะฒัะตะผ ัะบะทะพัะธัะตัะบะธั
ัะปััะฐัั
ะผะพะถะตั ะฟะพััะตะฑะพะฒะฐัััั ะผะพะดะถะธัะธัะธัะพะฒะฐัั ะทะฝะฐัะตะฝะธะต ะฟะพะปั ัะถะต ะฟะพัะปะต ะตะณะพ ัะพั
ัะฐะฝะตะฝะฝะธั ะฒ ะะ -
* ะดะปั ะฟะพัะปะตะดัััะตะน ะพะฑัะฐะฑะพัะบะธ ะบะฐะบะธะผ-ะปะธะฑะพ ะดััะณะธะผ ะบะปะฐััะพะผ.
*/
public function processAfterSaveAction()
{
}
/**
* ะะพะฑะฐะฒะปัะตั ัััะพะบั ะพัะธะฑะบะธ ะฒ ะผะฐััะธะฒ ะพัะธะฑะพะบ.
*
* @param string $messageId ะะพะด ัะพะพะฑัะตะฝะธั ะพะฑ ะพัะธะฑะบะต ะธะท ะปัะฝะณ-ัะฐะนะปะฐ. ะะปะตะนัั
ะพะปะดะตั #FIELD# ะฑัะดะตั ะทะฐะผะตะฝัะฝ ะฝะฐ ะทะฝะฐัะตะฝะธะต
* ะฟะฐัะฐะผะตััะฐ TITLE.
* @param array $replace ะะฐะฝะฝัะต ะดะปั ะทะฐะผะตะฝั.
*
* @see Loc::getMessage()
*/
protected function addError($messageId, $replace = array())
{
$this->validationErrors[$this->getCode()] = Loc::getMessage(
$messageId,
array_merge(array('#FIELD#' => $this->getSettings('TITLE')), $replace)
);
}
/**
* ะัะพะฒะตัะบะฐ ะทะฐะฟะพะปะฝะตะฝะฝะพััะธ ะพะฑัะทะฐัะตะปัะฝัั
ะฟะพะปะตะน.
* ะะต ะดะพะปะถะฝั ะฑััั null ะธะปะธ ัะพะดะตัะถะฐัั ะฟััััั ัััะพะบั.
*
* @return bool
*/
public function checkRequired()
{
if ($this->getSettings('REQUIRED') == true) {
$value = $this->getValue();
return !is_null($value) && !empty($value);
} else {
return true;
}
}
/**
* ะัััะฐะฒะปัะตั ะบะพะด ะดะปั ะดะฐะฝะฝะพะณะพ ะฒะธะดะถะตัะฐ ะฟัะธ ะธะฝะธัะธะฐะปะธะทะฐัะธะธ. ะะตัะตะณััะถะฐะตั ะฝะฐัััะพะนะบะธ.
*
* @param string $code
*/
public function setCode($code)
{
$this->code = $code;
$this->loadSettings();
}
/**
* @return mixed
*/
public function getCode()
{
return $this->code;
}
/**
* ะฃััะฐะฝะฐะฒะปะธะฒะฐะตั ะฝะฐัััะพะนะบะธ ะธะฝัะตััะตะนัะฐ ะดะปั ัะตะบััะตะณะพ ะฟะพะปั.
*
* @param string $code
*
* @return bool
*
* @see AdminBaseHelper::getInterfaceSettings()
* @see AdminBaseHelper::setFields()
*/
public function loadSettings($code = null)
{
$interface = $this->helper->getInterfaceSettings();
$code = is_null($code) ? $this->code : $code;
if (!isset($interface['FIELDS'][$code])) {
return false;
}
unset($interface['FIELDS'][$code]['WIDGET']);
$this->settings = array_merge($this->settings, $interface['FIELDS'][$code]);
$this->setDefaultValue();
return true;
}
/**
* ะะพะทะฒัะฐัะฐะตั ะฝะฐะทะฒะฐะฝะธะต ัััะฝะพััะธ ะดะฐะฝะฝะพะน ะผะพะดะตะปะธ.
*
* @return string|DataManager
*/
public function getEntityName()
{
return $this->entityName;
}
/**
* @param string $entityName
*/
public function setEntityName($entityName)
{
$this->entityName = $entityName;
$this->setDefaultValue();
}
/**
* ะฃััะฐะฝะฐะฒะปะธะฒะฐะตั ะทะฝะฐัะตะฝะธะต ะฟะพ-ัะผะพะปัะฐะฝะธั ะดะปั ะดะฐะฝะฝะพะณะพ ะฟะพะปั
*/
public function setDefaultValue()
{
if (isset($this->settings['DEFAULT']) && is_null($this->getValue())) {
$this->setValue($this->settings['DEFAULT']);
}
}
/**
* ะะตัะตะดะฐะตั ัััะปะบั ะฝะฐ ะดะฐะฝะฝัะต ัััะฝะพััะธ ะฒ ะฒะธะดะถะตั
*
* @param $data
*/
public function setData(&$data)
{
$this->data = &$data;
//FIXME: ะฝะตะปะตะฟัะน ะพะฒะตัั
ัะด ัะฐะดะธ ัะพะณะพ, ััะพะฑั ะผะพะถะฝะพ ะฑัะปะพ ัะตะฝััะฐะปะธะทะพะฒะฐะฝะฝะพ ะฟัะตะพะฑัะฐะทะพะฒัะฒะฐัั ะทะฝะฐัะตะฝะธะต ะฟัะธ ะทะฐะฟะธัะธ
$this->setValue($data[$this->getCode()]);
}
/**
* ะะพะทะฒัะฐัะฐะตั ัะตะบััะตะต ะทะฝะฐัะตะฝะธะต, ั
ัะฐะฝะธะผะพะต ะฒ ะฟะพะปะต ะฒะธะดะถะตัะฐ
* ะัะปะธ ัะฐะบะพะณะพ ะฟะพะปั ะฝะตั, ะฒะพะทะฒัะฐัะฐะตั null
*
* @return mixed|null
*/
public function getValue()
{
$code = $this->getCode();
return isset($this->data[$code]) ? $this->data[$code] : null;
}
/**
* ะฃััะฐะฝะฐะฒะปะธะฒะฐะตั ะทะฝะฐัะตะฝะธะต ะฟะพะปั
*
* @param $value
*
* @return bool
*/
protected function setValue($value)
{
$code = $this->getCode();
$this->data[$code] = $value;
return true;
}
/**
* ะะพะปััะตะฝะธั ะฝะฐะทะฒะฐะฝะธั ะฟะพะปั ัะฐะฑะปะธัั, ะฒ ะบะพัะพัะพะน ั
ัะฐะฝัััั ะผะฝะพะถะตััะฒะตะฝะฝัะต ะดะฐะฝะฝัะต ััะพะณะพ ะฒะธะดะถะตัะฐ
*
* @param string $fieldName ะะฐะทะฒะฐะฝะธะต ะฟะพะปั
*
* @return bool|string
*/
public function getMultipleField($fieldName)
{
$fields = $this->getSettings('MULTIPLE_FIELDS');
if (empty($fields)) {
return $fieldName;
}
// ะะพะธัะบ ะฐะปะธะฐัะฐ ะฝะฐะทะฒะฐะฝะธั ะฟะพะปั
if (isset($fields[$fieldName])) {
return $fields[$fieldName];
}
// ะะพะธัะบ ะพัะธะณะธะฝะฐะปัะฝะพะณะพ ะฝะฐะทะฒะฐะฝะธั ะฟะพะปั
$fieldsFlip = array_flip($fields);
if (isset($fieldsFlip[$fieldName])) {
return $fieldsFlip[$fieldName];
}
return $fieldName;
}
/**
* ะัััะฐะฒะปัะตั ะทะฝะฐัะตะฝะธะต ะพัะดะตะปัะฝะพะน ะฝะฐัััะพะนะบะธ
*
* @param string $name
* @param mixed $value
*/
public function setSetting($name, $value)
{
$this->settings[$name] = $value;
}
/**
* ะะพะทะฒัะฐัะฐะตั ัะพะฑัะฐะฝะฝัะต ะพัะธะฑะบะธ ะฒะฐะปะธะดะฐัะธะธ
* @return array
*/
public function getValidationErrors()
{
return $this->validationErrors;
}
/**
* ะะพะทะฒัะฐัะฐะตั ะธะผะตะฝะฐ ะดะปั ะฐััะธะฑััะฐ name ะฟะพะปะตะน ัะธะปัััะฐ.
* ะัะปะธ ััะพ ัะธะปััั BETWEEN, ัะพ ะฒะตัะฝัั ะผะฐััะธะฒ ั ะฒะฐัะธะฐะฝัะฐะผะธ from ะธ to.
*
* @return array|string
*/
protected function getFilterInputName()
{
if ($this->isFilterBetween()) {
$baseName = $this->filterFieldPrefix . $this->code;;
$inputNameFrom = $baseName . '_from';
$inputNameTo = $baseName . '_to';
return array($inputNameFrom, $inputNameTo);
} else {
return $this->filterFieldPrefix . $this->code;
}
}
/**
* ะะพะทะฒัะฐัะฐะตั ัะตะบัั ะดะปั ะฐััะธะฑััะฐ name ะธะฝะฟััะฐ ัะตะดะฐะบัะธัะพะฒะฐะฝะธั.
*
* @param null $suffix ะพะฟัะธะพะฝะฐะปัะฝะพะต ะดะพะฟะพะปะฝะตะฝะธะต ะบ ะฝะฐะทะฒะฐะฝะธั ะฟะพะปั
*
* @return string
*/
protected function getEditInputName($suffix = null)
{
return 'FIELDS[' . $this->getCode() . $suffix . ']';
}
/**
* ะฃะฝะธะบะฐะปัะฝัะน ID ะดะปั DOM HTML
* @return string
*/
protected function getEditInputHtmlId()
{
$htmlId = end(explode('\\', $this->entityName)) . '-' . $this->getCode();
return strtolower(preg_replace('/[^A-z-]/', '-', $htmlId));
}
/**
* ะะพะทะฒัะฐัะฐะตั ัะตะบัั ะดะปั ะฐััะธะฑััะฐ name ะธะฝะฟััะฐ ัะตะดะฐะบัะธัะพะฒะฐะฝะธั ะฟะพะปั ะฒ ัะฟะธัะบะต
* @return string
*/
protected function getEditableListInputName()
{
$id = $this->data[$this->helper->pk()];
return 'FIELDS[' . $id . '][' . $this->getCode() . ']';
}
/**
* ะะฟัะตะดะตะปัะตั ัะธะฟ ะฒัะทัะฒะฐััะตะณะพ ั
ัะปะฟะตัะฐ, ะพั ัะตะณะพ ะผะพะถะตั ะทะฐะฒะธัะธัั ะฟะพะฒะตะดะตะฝะธะต ะฒะธะดะถะตัะฐ.
*
* @return bool|int
* @see HelperWidget::EDIT_HELPER
* @see HelperWidget::LIST_HELPER
*/
protected function getCurrentViewType()
{
if (is_a($this->helper, 'DigitalWand\AdminHelper\Helper\AdminListHelper')) {
return self::LIST_HELPER;
} else {
if (is_a($this->helper, 'DigitalWand\AdminHelper\Helper\AdminEditHelper')) {
return self::EDIT_HELPER;
}
}
return false;
}
/**
* ะัะพะฒะตััะตั ะทะฝะฐัะตะฝะธะต ะฟะพะปั ะฝะฐ ัะฝะธะบะฐะปัะฝะพััั
* @return bool
*/
private function isUnique()
{
if ($this->getSettings('VIRTUAL')) {
return true;
}
$value = $this->getValue();
if (empty($value)) {
return true;
}
/** @var DataManager $class */
$class = $this->entityName;
$field = $this->getCode();
$idField = 'ID';
$id = $this->data[$idField];
$filter = array(
$field => $value,
);
if (!empty($id)) {
$filter["!=" . $idField] = $id;
}
$count = $class::getCount($filter);
if (!$count) {
return true;
}
return false;
}
/**
* ะัะพะฒะตััะตั, ะฝะต ัะฒะปัะตััั ะปะธ ัะตะบััะธะน ะทะฐะฟัะพั ะฟะพะฟััะบะพะน ะฒัะณััะทะธัั ะดะฐะฝะฝัะต ะฒ Excel
* @return bool
*/
protected function isExcelView()
{
if (isset($_REQUEST['mode']) && $_REQUEST['mode'] == 'excel') {
return true;
}
return false;
}
/**
* @todo ะัะฝะตััะธ ะฒ ัะตัััั (\CJSCore::Init()).
* @todo ะะฟะธัะฐัั.
*/
protected function jsHelper()
{
if ($this->jsHelper == true) {
return true;
}
$this->jsHelper = true;
\CJSCore::Init(array("jquery"));
?>
<script>
/**
* ะะตะฝะตะดะถะตั ะผะฝะพะถะตััะฒะตะฝะฝัั
ะฟะพะปะตะน
* ะะพะทะฒะพะปัะตั ะดะพะฑะฐะฒะปััั ะธ ัะดะฐะปััั ะปัะฑะพะน HTML ะบะพะด ั ะฒะพะทะผะพะถะฝะพััั ะฟะพะดััะฐะฝะพะฒะบะธ ะดะธะฝะฐะผะธัะตัะบะธั
ะดะฐะฝะฝัั
* ะะฝััััะบัะธั:
* - ัะพะทะดะฐะนัะต ะบะพะฝัะตะนะฝะตั, ะณะดะต ะฑัะดัั ั
ัะฐะฝะธััั ะพัะพะฑัะฐะถะฐัััั ะบะพะด
* - ัะพะทะดะฐะนัะต ัะบะทะตะผะฟะปัั MultipleWidgetHelper
* ะะฐะฟัะธะผะตั: var multiple = MultipleWidgetHelper(ัะตะปะตะบัะพั ะบะพะฝัะตะนะฝะตัะฐ, ัะฐะฑะปะพะฝ)
* ัะฐะฑะปะพะฝ - ััะพ HTML ะบะพะด, ะบะพัะพััะน ะผะพะถะฝะพ ะฑัะดะตั ะดะพะฑะฐะฒะปััั ะธ ัะดะฐะปััั ะฒ ะธะฝัะตััะตะนัะต
* ะ ัะฐะฑะปะพะฝ ะผะพะถะฝะพ ะดะพะฑะฐะฒะปััั ะฟะตัะตะผะตะฝะฝัะต, ะธั
ะฝัะถะฝะพ ะพะฑัะฐะผะปััั ัะธะณััะฝัะผะธ ัะบะพะฑะบะฐะผะธ. ะะฐะฟัะธะผะตั {{entity_id}}
* ะัะปะธ ะฒ ัะฐะฑะปะพะฝะต ะฝะตัะบะพะปัะบะพ ะฟะพะปะตะน, ะฟะตัะตะผะตะฝะฝะฐั {{field_id}} ะพะฑัะทะฐัะตะปัะฝะฐ
* ะะฐะฟัะธะผะตั <input type="text" name="image[{{field_id}}][SRC]"><input type="text" name="image[{{field_id}}][DESCRIPTION]">
* ะัะปะธ ะดะพะฑะฐะฒะปัะตะผัะต ะฟะพะปะต ะฝะต ะฝะพะฒะพะต, ัะพ ะพะฑัะทะฐัะตะปัะฝะพ ะฟะตัะตะดะฐะฒะฐะนัะต ะฒ addField ะฟะตัะตะผะตะฝะฝัั field_id ั ID ะทะฐะฟะธัะธ,
* ะดะปั ะฝะพะฒะพัะพะทะดะฐะฝะฝัั
ะฟะพะปะตะน ะฟะตัะตะผะตะฝะฝะฐั ะทะฐะฟะพะปะฝะธััั ะฐะฒัะพะผะฐัะธัะตัะบะธ
*/
function MultipleWidgetHelper(container, fieldTemplate) {
this.$container = $(container);
if (this.$container.size() == 0) {
throw 'ะะปะฐะฒะฝัะน ะบะพะฝัะตะนะฝะตั ะฟะพะปะตะน ะฝะต ะฝะฐะนะดะตะฝ (' + container + ')';
}
if (!fieldTemplate) {
throw 'ะะต ะฟะตัะตะดะฐะฝ ะพะฑัะทะฐัะตะปัะฝัะน ะฟะฐัะฐะผะตัั fieldTemplate';
}
this.fieldTemplate = fieldTemplate;
this._init();
}
MultipleWidgetHelper.prototype = {
/**
* ะัะฝะพะฒะฝะพะน ะบะพะฝัะตะนะฝะตั
*/
$container: null,
/**
* ะะพะฝัะตะนะฝะตั ะฟะพะปะตะน
*/
$fieldsContainer: null,
/**
* ะจะฐะฑะปะพะฝ ะฟะพะปั
*/
fieldTemplate: null,
/**
* ะกัะตััะธะบ ะดะพะฑะฐะฒะปะตะฝะธะน ะฟะพะปะตะน
*/
fieldsCounter: 0,
/**
* ะะพะฑะฐะฒะปะตะฝะธั ะฟะพะปั
* @param data object ะะฐะฝะฝัะต ะดะปั ัะฐะฑะปะพะฝะฐ ะฒ ะฒะธะดะต ะบะปัั: ะทะฝะฐัะตะฝะธะต
*/
addField: function (data) {
// console.log('ะะพะฑะฐะฒะปะตะฝะธะต ะฟะพะปั');
this.addFieldHtml(this.fieldTemplate, data);
},
addFieldHtml: function (fieldTemplate, data) {
this.fieldsCounter++;
this.$fieldsContainer.append(this._generateFieldContent(fieldTemplate, data));
},
/**
* ะฃะดะฐะปะตะฝะธะต ะฟะพะปั
* @param field string|object ะกะตะปะตะบัะพั ะธะปะธ jQuery ะพะฑัะตะบั
*/
deleteField: function (field) {
// console.log('ะฃะดะฐะปะตะฝะธะต ะฟะพะปั');
$(field).remove();
if (this.$fieldsContainer.find('> *').size() == 0) {
this.addField();
}
},
_init: function () {
this.$container.append('<div class="fields-container"></div>');
this.$fieldsContainer = this.$container.find('.fields-container');
this.$container.append(this._getAddButton());
this._trackEvents();
},
/**
* ะะตะฝะตัะฐัะธั ะบะพะฝัะตะฝัะฐ ะบะพะฝัะตะนะฝะตัะฐ ะฟะพะปั
* @param data
* @returns {string}
* @private
*/
_generateFieldContent: function (fieldTemplate, data) {
return '<div class="field-container" style="margin-bottom: 5px;">'
+ this._generateFieldTemplate(fieldTemplate, data) + this._getDeleteButton()
+ '</div>';
},
/**
* ะะตะฝะตัะฐัะธั ัะฐะฑะปะพะฝะฐ ะฟะพะปั
* @param data object ะะฐะฝะฝัะต ะดะปั ะฟะพะดััะฐะฝะพะฒะบะธ
* @returns {null}
* @private
*/
_generateFieldTemplate: function (fieldTemplate, data) {
if (!data) {
data = {};
}
if (typeof data.field_id == 'undefined') {
data.field_id = 'new_' + this.fieldsCounter;
}
$.each(data, function (key, value) {
// ะะพะดััะฐะฒะปะตะฝะธะต ะทะฝะฐัะตะฝะธะน ะฟะตัะตะผะตะฝะฝัั
fieldTemplate = fieldTemplate.replace(new RegExp('\{\{' + key + '\}\}', ['g']), value);
fieldTemplate = fieldTemplate.replace(new RegExp(encodeURIComponent('\{\{' + key + '\}\}'), ['g']), value);
});
// ะฃะดะฐะปะตะฝะธะต ะธะท ัะฐะฑะปะพะฝะฐ ะฝะตะพะฑัะฐะฑะพัะฐะฝะฝัั
ะฟะตัะตะผะตะฝะฝัั
fieldTemplate = fieldTemplate.replace(/\{\{.+?\}\}/g, '');
return fieldTemplate;
},
/**
* ะะฝะพะฟะบะฐ ัะดะฐะปะตะฝะธั
* @returns {string}
* @private
*/
_getDeleteButton: function () {
return '<input type="button" value="-" class="delete-field-button" style="margin-left: 5px;">';
},
/**
* ะะฝะพะฟะบะฐ ะดะพะฑะฐะฒะปะตะฝะธั
* @returns {string}
* @private
*/
_getAddButton: function () {
return '<input type="button" value="<?=Loc::getMessage('DIGITALWAND_AH_MULTI_ADD')?>" class="add-field-button">';
},
/**
* ะััะปะตะถะธะฒะฐะฝะธะต ัะพะฑััะธะน
* @private
*/
_trackEvents: function () {
var context = this;
// ะะพะฑะฐะฒะปะตะฝะธะต ะฟะพะปั
this.$container.find('.add-field-button').on('click', function () {
context.addField();
});
// ะฃะดะฐะปะตะฝะธะต ะฟะพะปั
this.$container.on('click', '.delete-field-button', function () {
context.deleteField($(this).parents('.field-container'));
});
}
};
</script>
<?
}
}
| mit |
gcnew/MP2 | src/re/agiledesign/mp2/internal/expressions/ArgumentAccessExpression.java | 612 | package re.agiledesign.mp2.internal.expressions;
import re.agiledesign.mp2.internal.AssignmentVisitor;
import re.agiledesign.mp2.internal.FunctionScope;
import re.agiledesign.mp2.internal.Scope;
public class ArgumentAccessExpression extends AccessExpression {
private final int mIndex;
public ArgumentAccessExpression(final int aIndex) {
mIndex = aIndex;
}
public void visit(final AssignmentVisitor aVisitor) {
aVisitor.visitArgumentAssignment(mIndex);
}
public Object execute(final Scope aScope) throws Exception {
return ((FunctionScope) aScope).getArgument(mIndex);
}
}
| mit |
stopyoukid/DojoToTypescriptConverter | out/separate/dojox.widget.PortletDialogSettings.d.ts | 232 | /// <reference path="Object.d.ts" />
/// <reference path="dojox.widget.PortletSettings.d.ts" />
module dojox.widget{
export class PortletDialogSettings extends dojox.widget.PortletSettings {
dimensions : any[];
dialog : Object;
}
}
| mit |
frunjik/poly-please | server/cigly/views/page_poly_edit.php | 4982 | <!doctype html>
<html>
<head>
<title>/poly/please/edit/[get_url]</title>
<meta name="viewport" content="width=device-width, minimum-scale=1.0, initial-scale=1.0, user-scalable=yes">
<script src="/components/platform/platform.js"></script>
<script src="/poly/scripts/poly_js.js"></script>
<link rel="import" href="components/core-scaffold/core-scaffold.html">
<link rel="import" href="components/core-menu/core-menu.html">
<link rel="import" href="components/core-menu/core-submenu.html">
<link rel="import" href="components/code-mirror/code-mirror.html">
<link rel="import" href="components/core-ajax/core-ajax.html">
<link rel="import" href="components/core-field/core-field.html">
<link rel="import" href="components/elements/poly-link.html">
</head>
<body unresolved touch-action="auto">
<style>
html, body {
height: 100%;
margin: 0;
}
body {
font-family: sans-serif;
}
core-scaffold {
position: absolute;
top: 0;
right: 0;
bottom: 0;
left: 0;
}
.content {
background-color: #fff;
height: 5000px;
padding: 20px;
}
/* some default styles for mode="cover" on core-scaffold */
core-scaffold[mode=cover]::shadow core-header-panel::shadow #mainContainer {
left: 120px;
}
core-scaffold[mode=cover] .content {
margin: 20px 100px 20px 0;
}
</style>
<polymer-element name="code-view" attributes="code, post_url, get_url, height">
<template>
<core-field>
<core-icon icon="file-upload" size="48"></core-icon>
<label>from:</label>
<input id="id_get_url" placeholder="source" style="width: 40%" value="{{get_url}}">
<core-icon-button icon="refresh" on-tap="{{load}}"></core-icon-button>
<core-icon icon="file-download" size="48"></core-icon>
<label>to:</label>
<input id="id_post_url" placeholder="destination" value="{{post_url}}" flex>
<core-icon-button icon="save" on-tap="{{save}}"></core-icon-button>
<core-icon-button icon="apps" on-tap="{{view}}"></core-icon-button>
</core-field>
<core-ajax id="request" url="{{get_url}}" handleAs="text" on-core-response="{{onResponse}}"></core-ajax>
<code-mirror id="editor" style="height: {{height}}" value="{{code}}"></code-mirror>
<form id="form" action="{{post_url}}" method="POST">
<textarea wrap="hard" name="content" type="text" hidden></textarea>
</form>
</template>
<script>
Polymer({
ready: function(event, response) {
if(this.get_url)
{
this.post_url = this.get_url.replace('/load/','/save/');
this.load();
}
},
onResponse: function(event, response) {
this.show(response.response);
},
load: function() {
this.$.request.go();
},
save: function()
{
var form = this.$.form;
var code = this.$.editor.mirror.getValue();
code = code.replace(/(\r\n|\n|\r)/gm,"\r");
form.content.value = code;
form.submit();
},
view: function() {
window.location = this.get_url;
},
show: function(text)
{
this.$.editor.mirror.setValue(text);
},
});
</script>
</polymer-element>
<polymer-element name="file-list" attributes="url">
<template>
<core-ajax id="request" handleAs="json" on-core-response="{{onResponse}}" url="{{hostname}}{{url}}"></core-ajax>
<template repeat="{{f in files}}">
<p>
<a onClick="edit('{{f}}');">{{f}}</a>
</p>
</template>
</template>
<script>
Polymer('file-list', {
ready: function() {
this.hostname = PolyPlease.Uri.site();
this.files = [];
this.refresh();
},
refresh: function() {
this.$.request.go();
},
onResponse: function(event, response) {
this.files = response.response;
},
});
</script>
</polymer-element>
<core-scaffold>
<core-header-panel navigation flex mode="seamed">
<core-toolbar style="background-color: #526E9C; color: #fff;">
<poly-link link=""><content/>PolyPlease?</poly-link>
</core-toolbar>
<core-menu selected="0" selectedindex="0" id="core_menu">
<core-submenu active label="Site" icon="settings" valueattr="name" id="core_submenu">
<core-item label="welcome poly" size="24" horizontal center layout onClick="show('view_poly_welcome')"></core-item>
<core-item label="welcome code" size="24" horizontal center layout onClick="show('view_poly_faq')"></core-item>
</core-submenu>
<core-submenu label="Meta" icon="settings" valueattr="name" id="core_submenu1">
<file-list url="please/get/files"/>
</core-submenu>
</core-menu>
</core-header-panel>
<code-view id="view"
get_url="[get_url]"
post_url=""
height="550px"
code="">[@content@]</code-view>
</core-scaffold>
<script>
function show(view_url)
{
var url = PolyPlease.Uri.please('load/'+view_url);
var v = document.getElementById('view');
v.get_url = url;
v.load();
}
</script>
</body>
</html>
| mit |
josephyi/taric | spec/operations/lol_status_spec.rb | 644 | require 'spec_helper'
describe Taric::Operation::LolStatus do
let(:client) {Taric.client(api_key:'test')}
describe '#shard_data' do
let (:url) {expand_template(Taric::Operation::LolStatus::SHARD.template_url)}
before {stub_get(url).to_return(body: fixture('shard.json'), headers: {content_type: 'application/json; charset=utf-8'})}
it 'requests the correct resource' do
client.shard_data
expect(a_get(url)).to have_been_made
end
it 'returns the requested result' do
shard = client.shard_data.body
expect(shard).to be_a Hash
expect(shard['name']).to eq('North America')
end
end
end | mit |
rufeltech/testing_server | src/main/java/ru/eltech/csa/siths/service/behaviour/IssueService.java | 329 | package ru.eltech.csa.siths.service.behaviour;
import ru.eltech.csa.siths.entity.node.Issue;
public interface IssueService {
public boolean isIssueExists(String publicId);
public boolean isIssueExists(Issue issue);
public Issue createIssue(Issue issue);
public Issue getIssueByPublicId(String publicId);
} | mit |
ByteSupreme/Micro-CMS-Symfony3 | app/AppKernel.php | 1908 | <?php
use Symfony\Component\HttpKernel\Kernel;
use Symfony\Component\Config\Loader\LoaderInterface;
class AppKernel extends Kernel
{
public function registerBundles()
{
$bundles = [
new Symfony\Bundle\FrameworkBundle\FrameworkBundle(),
new Symfony\Bundle\SecurityBundle\SecurityBundle(),
new Symfony\Bundle\TwigBundle\TwigBundle(),
new Symfony\Bundle\MonologBundle\MonologBundle(),
new Symfony\Bundle\SwiftmailerBundle\SwiftmailerBundle(),
new Doctrine\Bundle\DoctrineBundle\DoctrineBundle(),
new Sensio\Bundle\FrameworkExtraBundle\SensioFrameworkExtraBundle(),
new AdminBundle\AdminBundle(),
new FrontBundle\FrontBundle(),
];
if (in_array($this->getEnvironment(), ['dev', 'test'], true)) {
$bundles[] = new Symfony\Bundle\DebugBundle\DebugBundle();
$bundles[] = new Symfony\Bundle\WebProfilerBundle\WebProfilerBundle();
$bundles[] = new Sensio\Bundle\DistributionBundle\SensioDistributionBundle();
$bundles[] = new Doctrine\Bundle\FixturesBundle\DoctrineFixturesBundle();
if ('dev' === $this->getEnvironment()) {
$bundles[] = new Sensio\Bundle\GeneratorBundle\SensioGeneratorBundle();
$bundles[] = new Symfony\Bundle\WebServerBundle\WebServerBundle();
}
}
return $bundles;
}
public function getRootDir()
{
return __DIR__;
}
public function getCacheDir()
{
return dirname(__DIR__).'/var/cache/'.$this->getEnvironment();
}
public function getLogDir()
{
return dirname(__DIR__).'/var/logs';
}
public function registerContainerConfiguration(LoaderInterface $loader)
{
$loader->load($this->getRootDir().'/config/config_'.$this->getEnvironment().'.yml');
}
}
| mit |
Dormitory-System/Dormitory-System-Android | app/src/main/java/com/system/dormitory/dormitory_system_android/gcm/RegistrationIntentService.java | 2803 | package com.system.dormitory.dormitory_system_android.gcm;
import android.annotation.SuppressLint;
import android.app.IntentService;
import android.content.Intent;
import android.support.v4.content.LocalBroadcastManager;
import android.util.Log;
import com.google.android.gms.gcm.GoogleCloudMessaging;
import com.google.android.gms.iid.InstanceID;
import com.system.dormitory.dormitory_system_android.R;
import com.system.dormitory.dormitory_system_android.data.DataManager;
import com.system.dormitory.dormitory_system_android.helper.Helper_userData;
import java.io.IOException;
/**
* Created by BoWoon on 2016-06-12.
*/
public class RegistrationIntentService extends IntentService {
private static final String TAG = "RegistrationIntentService";
public RegistrationIntentService() {
super(TAG);
}
/**
* GCM์ ์ํ Instance ID์ ํ ํฐ์ ์์ฑํ์ฌ ๊ฐ์ ธ์จ๋ค.
*
* @param intent
*/
@SuppressLint("LongLogTag")
@Override
protected void onHandleIntent(Intent intent) {
// GCM Instance ID์ ํ ํฐ์ ๊ฐ์ ธ์ค๋ ์์
์ด ์์๋๋ฉด LocalBoardcast๋ก GENERATING ์ก์
์ ์๋ ค ProgressBar๊ฐ ๋์ํ๋๋ก ํ๋ค.
LocalBroadcastManager.getInstance(this)
.sendBroadcast(new Intent(QuickstartPreferences.REGISTRATION_GENERATING));
// GCM์ ์ํ Instance ID๋ฅผ ๊ฐ์ ธ์จ๋ค.
InstanceID instanceID = InstanceID.getInstance(this);
String token = null;
try {
synchronized (TAG) {
// GCM ์ฑ์ ๋ฑ๋กํ๊ณ ํ๋ํ ์ค์ ํ์ผ์ธ google-services.json์ ๊ธฐ๋ฐ์ผ๋ก SenderID๋ฅผ ์๋์ผ๋ก ๊ฐ์ ธ์จ๋ค.
String default_senderId = getString(R.string.gcm_defaultSenderId);
// GCM ๊ธฐ๋ณธ scope๋ "GCM"์ด๋ค.
String scope = GoogleCloudMessaging.INSTANCE_ID_SCOPE;
// Instance ID์ ํด๋นํ๋ ํ ํฐ์ ์์ฑํ์ฌ ๊ฐ์ ธ์จ๋ค.
token = instanceID.getToken(default_senderId, scope, null);
int sno = intent.getExtras().getInt("sno");
Log.i(TAG, "GCM Registration " + sno + " " +"Token: " + token);
Helper_userData.setGcmClientKey(token, sno);
}
} catch (IOException e) {
e.printStackTrace();
}
// GCM Instance ID์ ํด๋นํ๋ ํ ํฐ์ ํ๋ํ๋ฉด LocalBoardcast์ COMPLETE ์ก์
์ ์๋ฆฐ๋ค.
// ์ด๋ ํ ํฐ์ ํจ๊ป ๋๊ฒจ์ฃผ์ด์ UI์ ํ ํฐ ์ ๋ณด๋ฅผ ํ์ฉํ ์ ์๋๋ก ํ๋ค.
Intent registrationComplete = new Intent(QuickstartPreferences.REGISTRATION_COMPLETE);
registrationComplete.putExtra("token", token);
LocalBroadcastManager.getInstance(this).sendBroadcast(registrationComplete);
}
}
| mit |
mxhold/vimperor | spec/lib/type_coersion_spec.rb | 3813 | require 'spec_helper'
require_relative '../../lib/type_coersion'
describe ArrayExtensions::DeepToH do
describe '#deep_to_h' do
it 'converts deeply nested array into hash' do
module TestModule
using ArrayExtensions::DeepToH
def self.actual_hash
[[:a, [[:b, [[:c, :d]]]]]].deep_to_h
end
end
expected_hash = { a: { b: { c: :d } } }
expect(TestModule.actual_hash).to eql expected_hash
end
end
end
describe TypeCoersion do
describe '.coercer_for' do
it 'returns a coercer class for the given type' do
module TypeCoersion
class FooCoercer
end
end
expect(described_class.coercer_for(:foo)).to eql TypeCoersion::FooCoercer
end
end
end
describe TypeCoersion::HashCoercer do
describe '#coerce' do
it 'converts the values of a hash based on the provided config' do
config = {
bool: :boolean,
str: :string,
int: :integer,
deep: {
nested: {
hash: :boolean,
}
},
empty: :string,
}
hash = {
bool: 'true',
str: 123,
int: '123',
deep: {
nested: {
hash: 'false',
}
},
empty: '',
}
expected_hash = {
bool: true,
str: '123',
int: 123,
deep: {
nested: {
hash: false,
}
},
empty: nil,
}
coercer = described_class.new(config: config)
expect(coercer.coerce(hash)).to eql expected_hash
end
end
end
describe TypeCoersion::IntegerCoercer do
describe '.coerce' do
context 'non-nil value' do
it 'converts the value to an integer' do
expect(described_class.coerce('1')).to eql 1
end
end
context 'nil' do
it 'returns nil, not zero' do
expect(described_class.coerce(nil)).to eql nil
end
end
end
end
describe TypeCoersion::StringCoercer do
describe '.coerce' do
context 'non-nil string' do
it 'returns the original string' do
expect(described_class.coerce('foo')).to eql 'foo'
end
end
context 'integer' do
it 'returns the integer converted to a string' do
expect(described_class.coerce(1)).to eql '1'
end
end
context 'empty string' do
it 'returns nil' do
expect(described_class.coerce('')).to eql nil
end
end
context 'nil' do
it 'returns nil' do
expect(described_class.coerce(nil)).to eql nil
end
end
end
end
describe TypeCoersion::BooleanCoercer do
describe '.coerce' do
context 'true string' do
it 'returns true' do
expect(described_class.coerce('true')).to eql true
end
end
context '1 string' do
it 'returns true' do
expect(described_class.coerce('1')).to eql true
end
end
context '1 integer' do
it 'returns true' do
expect(described_class.coerce(1)).to eql true
end
end
context 'true' do
it 'returns true' do
expect(described_class.coerce(true)).to eql true
end
end
context 'false string' do
it 'returns false' do
expect(described_class.coerce('false')).to eql false
end
end
context '0 string' do
it 'returns false' do
expect(described_class.coerce('0')).to eql false
end
end
context '0 integer' do
it 'returns false' do
expect(described_class.coerce(0)).to eql false
end
end
context 'false' do
it 'returns false' do
expect(described_class.coerce(false)).to eql false
end
end
context 'nil' do
it 'returns nil' do
expect(described_class.coerce(nil)).to eql nil
end
end
end
end
| mit |
angelnetbd/angelnetbd | config/bootstrap.js | 1043 | /**
* Bootstrap
* (sails.config.bootstrap)
*
* An asynchronous bootstrap function that runs before your Sails app gets lifted.
* This gives you an opportunity to set up your data model, run jobs, or perform some special logic.
*
* For more information on bootstrapping your app, check out:
* http://sailsjs.org/#/documentation/reference/sails.config/sails.config.bootstrap.html
*/
module.exports.bootstrap = function (cb) {
// It's very important to trigger this callback method when you are finished
// with the bootstrap! (otherwise your server will never lift, since it's waiting on the bootstrap)
global.twitterShareMessage = "https://twitter.com/home?status=Check%20out%20this%20super%20fresh%20%40sails.js%20full%20auth%20template%20for%20your%20project!%20By%20%40icenodes%20%23nodejs%20%23startup%20https%3A%2F%2Fgithub.com%2Fbmustata%2Fsails-auth-super-templates";
global.facebookShareMessage = "https://www.facebook.com/sharer/sharer.php?u=http://sails-auth-super-templates.icenodes.com/";
cb();
};
| mit |
palkan/test-prof | lib/test_prof/factory_all_stub.rb | 740 | # frozen_string_literal: true
require "test_prof/factory_bot"
require "test_prof/factory_all_stub/factory_bot_patch"
module TestProf
# FactoryAllStub inject into FactoryBot to make
# all strategies be `build_stubbed` strategy.
module FactoryAllStub
LOCAL_NAME = :__factory_bot_stub_all__
class << self
def init
# Monkey-patch FactoryBot / FactoryGirl
TestProf::FactoryBot::FactoryRunner.prepend(FactoryBotPatch) if
defined?(TestProf::FactoryBot)
end
def enabled?
Thread.current[LOCAL_NAME] == true
end
def enable!
Thread.current[LOCAL_NAME] = true
end
def disable!
Thread.current[LOCAL_NAME] = false
end
end
end
end
| mit |
JakeAi/Dashboard | public/assets/js/ng/Modules/WebsiteModules/users/service.js | 341 | ๏ปฟangular.module( 'webUsers' )
.service( 'webUsers', class extends BaseWebsiteModuleService {
constructor($timeout, $http, $q, api2, webUsersConstants) {
'ngInject';
super( $timeout, $http, $q, api2 );
this.setConstants( webUsersConstants );
this.collection = [];
this.objects = 'users';
this.object = 'user';
}
} ); | mit |
QuikMod/QuikCore | src/main/java/com/github/quikmod/quikcore/core/QuikCore.java | 3938 | /*
*/
package com.github.quikmod.quikcore.core;
import com.github.quikmod.quikcore.command.QuikCommandManager;
import com.github.quikmod.quikcore.config.QuikConfig;
import com.github.quikmod.quikcore.lang.QuikTranslator;
import com.github.quikmod.quikcore.log.QuikLogManager;
import com.github.quikmod.quikcore.log.QuikLogger;
import com.github.quikmod.quikcore.config.QuikConfigAdapter;
import com.github.quikmod.quikcore.conversion.QuikConverterManager;
import com.github.quikmod.quikcore.injection.QuikInjector;
import com.github.quikmod.quikcore.injection.QuikInjectorManager;
import com.github.quikmod.quikcore.lang.QuikTranslationAdapter;
import com.github.quikmod.quikcore.log.QuikLogAdapter;
import com.github.quikmod.quikcore.network.QuikNetwork;
import com.github.quikmod.quikcore.network.QuikNetworkAdaptor;
import com.github.quikmod.quikcore.reflection.Quik;
import com.github.quikmod.quikcore.reflection.QuikDomain;
import com.github.quikmod.quikcore.reflection.QuikDomains;
import com.github.quikmod.quikcore.reflection.QuikReflector;
import com.github.quikmod.quikcore.reflection.QuikRegister;
/**
*
* @author RlonRyan
*/
@Quik
public final class QuikCore {
private static QuikConfig config;
private static QuikLogManager logger;
private static QuikTranslator translator;
private static QuikNetwork network;
private static final QuikConverterManager converters = new QuikConverterManager();
private static final QuikCommandManager commands = new QuikCommandManager();
private static final QuikInjectorManager injectors = new QuikInjectorManager();
private static final QuikReflector reflector = new QuikReflector();
private QuikCore() {
}
public static void init(
QuikLogAdapter logAdaptor,
QuikTranslationAdapter translatorAdaptor,
QuikConfigAdapter configAdaptor,
QuikNetworkAdaptor netAdaptor
) {
long start = System.currentTimeMillis();
QuikCore.logger = new QuikLogManager(logAdaptor);
QuikCore.translator = new QuikTranslator(translatorAdaptor);
QuikCore.config = new QuikConfig(configAdaptor);
QuikLogger log = QuikCore.getCoreLogger();
QuikCore.network = new QuikNetwork(netAdaptor);
QuikCore.reflector.performLoad();
long end = System.currentTimeMillis();
log.info("QuikCore Initialized! ({0} ms)", end - start);
log.info("Performing injections!");
start = System.currentTimeMillis();
QuikCore.injectors.performInjections();
end = System.currentTimeMillis();
log.info("Performed Injections! ({0} ms)", end - start);
log.info("Loading config!");
start = System.currentTimeMillis();
QuikCore.config.load();
end = System.currentTimeMillis();
log.info("Loaded config! ({0} ms)", end - start);
log.info("Saving config!");
start = System.currentTimeMillis();
QuikCore.config.save();
end = System.currentTimeMillis();
log.info("Saved config! ({0} ms)", end - start);
}
@QuikRegister
private static void registerClass(Class<?> clazz) {
QuikCore.injectors.registerInjectors(clazz);
QuikCore.injectors.registerInjectables(clazz);
QuikCore.converters.addConverters(clazz);
QuikCore.config.addConfigurable(clazz);
QuikCore.commands.addCommands(clazz);
QuikCore.network.registerMessage(clazz);
}
public static QuikLogger getCoreLogger() {
return getLogger("QuikCore");
}
@QuikInjector
@QuikDomain("")
public static QuikLogger getLogger(String source) {
return logger.getLogger(source);
}
public static QuikTranslator getTranslator() {
return translator;
}
public static QuikLogManager getLogManager() {
return logger;
}
public static QuikConverterManager getConverters() {
return converters;
}
public static QuikCommandManager getCommands() {
return commands;
}
public static QuikConfig getConfig() {
return config;
}
public static QuikDomains getDomains() {
return reflector.getDomains();
}
public static QuikInjectorManager getInjectorManager() {
return injectors;
}
}
| mit |
unger/Artportalen | Artportalen/Response/Web/SiteTypeEnum.cs | 306 | ๏ปฟusing System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Artportalen.Response.Web
{
public enum SiteTypeEnum
{
Ospecificerad = -1,
Privat = 0,
PublikDellokal = 1,
PublikSuperlokal = 2,
}
}
| mit |
jcamposanok/introsde-2016-assignment-2 | src/main/java/introsde/rest/ehealth/representations/PersonRepresentation.java | 3183 | package introsde.rest.ehealth.representations;
import com.fasterxml.jackson.annotation.JsonFormat;
import com.fasterxml.jackson.annotation.JsonIgnore;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.annotation.JsonRootName;
import introsde.rest.ehealth.models.HealthProfileItem;
import introsde.rest.ehealth.models.Person;
import introsde.rest.ehealth.util.DateParser;
import javax.persistence.*;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlElementWrapper;
import javax.xml.bind.annotation.XmlRootElement;
import javax.xml.bind.annotation.XmlTransient;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
@XmlRootElement(name = "person")
@JsonRootName("person")
public class PersonRepresentation {
private int personId;
private String lastname;
private String firstname;
@JsonFormat(shape = JsonFormat.Shape.STRING, pattern = DateParser.DEFAULT_FORMAT)
private Date birthdate;
private List<HealthProfileItemRepresentation> healthProfile;
public PersonRepresentation(Person p) {
personId = p.getPersonId();
lastname = p.getLastname();
firstname = p.getFirstname();
birthdate = p.getBirthdate();
setHealthProfile(p.getHealthProfile());
}
public PersonRepresentation() {
}
// Getters and setters
@XmlElement(name = "pid")
@JsonProperty("pid")
public int getPersonId() {
return personId;
}
public String getLastname() {
return lastname;
}
public String getFirstname() {
return firstname;
}
public Date getBirthdate() {
return birthdate;
}
@XmlTransient
@JsonIgnore
public List<HealthProfileItemRepresentation> getHealthProfile() {
return healthProfile;
}
@XmlElementWrapper(name = "healthProfile")
@XmlElement(name = "measure")
@JsonProperty("healthProfile")
public List<HealthProfileItemRepresentation> getCurrentHealthProfile() {
List<HealthProfileItemRepresentation> currentHealthProfile = new ArrayList<>();
if (healthProfile != null && healthProfile.size() > 0) {
for (HealthProfileItemRepresentation hp : healthProfile) {
if (hp.isValid()) {
currentHealthProfile.add(hp);
}
}
}
return currentHealthProfile;
}
// Setters
public void setPersonId(int personId) {
this.personId = personId;
}
public void setLastname(String lastname) {
this.lastname = lastname;
}
public void setFirstname(String firstname) {
this.firstname = firstname;
}
public void setBirthdate(Date birthdate) {
this.birthdate = birthdate;
}
public void setHealthProfile(List<HealthProfileItem> healthProfileItemList) {
healthProfile = new ArrayList<>();
if (healthProfileItemList != null && healthProfileItemList.size() > 0) {
for (HealthProfileItem i : healthProfileItemList) {
healthProfile.add(new HealthProfileItemRepresentation(i));
}
}
}
}
| mit |
jbatonnet/smartsync | SmartSync.OneDrive/OneDriveSdk/Requests/Generated/ItemContentRequestBuilder.cs | 2402 | // ------------------------------------------------------------------------------
// Copyright (c) 2015 Microsoft Corporation
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
// ------------------------------------------------------------------------------
// **NOTE** This file was generated by a tool and any changes will be overwritten.
namespace Microsoft.OneDrive.Sdk
{
using System.Collections.Generic;
/// <summary>
/// The type ItemContentRequestBuilder.
/// </summary>
public partial class ItemContentRequestBuilder : BaseRequestBuilder, IItemContentRequestBuilder
{
/// <summary>
/// Constructs a new ItemContentRequestBuilder.
/// </summary>
/// <param name="requestUrl">The URL for the built request.</param>
/// <param name="oneDriveClient">The <see cref="IOneDriveClient"/> for handling requests.</param>
public ItemContentRequestBuilder(
string requestUrl,
IOneDriveClient oneDriveClient)
: base(requestUrl, oneDriveClient)
{
}
/// <summary>
/// Builds the request.
/// </summary>
/// <returns>The built request.</returns>
public IItemContentRequest Request()
{
return new ItemContentRequest(this.RequestUrl, this.OneDriveClient, null);
}
}
}
| mit |
starweb/ongoing | src/Ongoing/GetInOrderStatusReports.php | 2142 | <?php
namespace Ongoing;
class GetInOrderStatusReports
{
/**
* @var string $GoodsOwnerCode
*/
protected $GoodsOwnerCode = null;
/**
* @var string $UserName
*/
protected $UserName = null;
/**
* @var string $Password
*/
protected $Password = null;
/**
* @var InOrderStatusReportsQuery $query
*/
protected $query = null;
/**
* @param string $GoodsOwnerCode
* @param string $UserName
* @param string $Password
* @param InOrderStatusReportsQuery $query
*/
public function __construct($GoodsOwnerCode, $UserName, $Password, $query)
{
$this->GoodsOwnerCode = $GoodsOwnerCode;
$this->UserName = $UserName;
$this->Password = $Password;
$this->query = $query;
}
/**
* @return string
*/
public function getGoodsOwnerCode()
{
return $this->GoodsOwnerCode;
}
/**
* @param string $GoodsOwnerCode
* @return \Ongoing\GetInOrderStatusReports
*/
public function setGoodsOwnerCode($GoodsOwnerCode)
{
$this->GoodsOwnerCode = $GoodsOwnerCode;
return $this;
}
/**
* @return string
*/
public function getUserName()
{
return $this->UserName;
}
/**
* @param string $UserName
* @return \Ongoing\GetInOrderStatusReports
*/
public function setUserName($UserName)
{
$this->UserName = $UserName;
return $this;
}
/**
* @return string
*/
public function getPassword()
{
return $this->Password;
}
/**
* @param string $Password
* @return \Ongoing\GetInOrderStatusReports
*/
public function setPassword($Password)
{
$this->Password = $Password;
return $this;
}
/**
* @return InOrderStatusReportsQuery
*/
public function getQuery()
{
return $this->query;
}
/**
* @param InOrderStatusReportsQuery $query
* @return \Ongoing\GetInOrderStatusReports
*/
public function setQuery($query)
{
$this->query = $query;
return $this;
}
}
| mit |
lsroudi/pythonTraining | quickTour/whileFibonacci.py | 78 | #!/usr/bin/python
a,b = 0,1
while a < 100 :
print(a)
b,a = a + b, b
| mit |
defano/hypertalk-java | src/main/java/com/defano/wyldcard/parts/util/MouseEventDispatcher.java | 9545 | package com.defano.wyldcard.parts.util;
import com.defano.wyldcard.parts.ContainerWrappedPart;
import com.defano.jmonet.canvas.JMonetCanvas;
import javax.swing.*;
import java.awt.*;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.awt.event.MouseMotionListener;
import java.util.HashMap;
import java.util.Map;
/**
* A hack to re-dispatch mouse events to parts (Swing components) in the background layer of a card
* that are obstructed by the foreground (card-layer) graphics canvas.
* <p>
* Swing does not support the concept of a component which is "transparent" to mouse events. That
* is, a paint canvas component that covers buttons and fields behind it--even if the canvas is
* graphically transparent--prevents mouse events from reaching the occluded components.
* <p>
* In order to get the card's foreground canvas to appear on top of parts in the background,
* and yet still allow the background parts to receive mouse clicks, drags, enters and exits, we
* have to capture mouse events on the foreground canvas then translate and re-dispatch them on the
* background parts. What a PITA.
*/
public class MouseEventDispatcher implements MouseListener, MouseMotionListener {
// Mapping of component hashCode to whether we think this mouse is inside its bounds
private final Map<Integer, Boolean> mouseWithinMap = new HashMap<>();
// Source component whose mouse events we're re-dispatching to components behind it
private Component source;
// Enumerator of parts behind the source
private ComponentEnumerator enumerator;
private MouseEventDispatcher(Component source, ComponentEnumerator enumerator) {
this.enumerator = enumerator;
this.source = source;
}
public static MouseEventDispatcher bindTo(Component source, ComponentEnumerator delegate) {
MouseEventDispatcher instance = new MouseEventDispatcher(source, delegate);
source.addMouseListener(instance);
source.addMouseMotionListener(instance);
return instance;
}
public void unbind() {
source.removeMouseListener(this);
source.removeMouseMotionListener(this);
this.source = null;
this.enumerator = null;
}
@Override
public void mouseClicked(MouseEvent e) {
delegateEvent(e);
}
@Override
public void mousePressed(MouseEvent e) {
delegateEvent(e);
}
@Override
public void mouseReleased(MouseEvent e) {
delegateEvent(e);
}
@Override
public void mouseEntered(MouseEvent e) {
delegateEvent(e);
}
@Override
public void mouseExited(MouseEvent e) {
delegateEvent(e);
}
@Override
public void mouseDragged(MouseEvent e) {
delegateEvent(e);
}
@Override
public void mouseMoved(MouseEvent e) {
delegateEvent(e);
}
/**
* Attempts to find a component behind the source at the event's location and, if found,
* translates the event and re-dispatches it to the found component.
*
* @param e The event to re-dispatch.
*/
private void delegateEvent(MouseEvent e) {
// Detect and send mouseEnter and mouseExit events
synthesizeChildEntryExitEvents(e);
Component c = findHit(e); // Find component behind source
if (c != null) {
// TODO: Canvas shouldn't behave unusually in this respect.
if (c instanceof JMonetCanvas) {
c.dispatchEvent(e);
}
// Obscured components will not automatically receive focus; force focus as needed
if (e.getID() == MouseEvent.MOUSE_CLICKED ||
e.getID() == MouseEvent.MOUSE_DRAGGED ||
e.getID() == MouseEvent.MOUSE_PRESSED) {
c.requestFocus();
}
// Translate and dispatch event
MouseEvent localEvent = SwingUtilities.convertMouseEvent(source, e, c);
c.dispatchEvent(localEvent);
}
}
/**
* Track and dispatch mouse-enter and mouse-exit events on the background parts.
* <p>
* This is a bit more complicated than first expected; we cannot simply translate the
* source component's mouseEnter/mouseExit events as those fire only when the
* mouse enters/exits the source, NOT when entering or exiting a component behind it.
*
* @param e The source's mouse event
*/
private void synthesizeChildEntryExitEvents(MouseEvent e) {
for (Component c : enumerator.getComponentsInZOrder()) {
if (c instanceof ContainerWrappedPart) {
c = ((ContainerWrappedPart) c).getWrappedComponent();
}
MouseEvent localEvent = SwingUtilities.convertMouseEvent(source, e, c);
if (didMouseEnter(c, e)) {
c.dispatchEvent(synthesizeEvent(c, localEvent, MouseEvent.MOUSE_ENTERED));
}
if (didMouseExit(c, e)) {
c.dispatchEvent(synthesizeEvent(c, localEvent, MouseEvent.MOUSE_EXITED));
}
}
}
/**
* Detect if the mouse has entered the given component.
*
* @param c The component which should be checked for mouse entry
* @param e The mouseMove event to track
* @return True if the mouse has entered the component, false otherwise.
*/
private boolean didMouseEnter(Component c, MouseEvent e) {
Point localPoint = SwingUtilities.convertPoint(source, e.getPoint(), c);
if (!isMouseWithin(c) && c.contains(localPoint)) {
mouseWithinMap.put(c.hashCode(), true);
return true;
}
return false;
}
/**
* Detect if the mouse has exited the given component.
*
* @param c The component which should be checked for mouse exit
* @param e The mouseMove event to track
* @return True if the mouse has exited the component, false otherwise.
*/
private boolean didMouseExit(Component c, MouseEvent e) {
Point localPoint = SwingUtilities.convertPoint(source, e.getPoint(), c);
if (isMouseWithin(c) && !c.contains(localPoint)) {
mouseWithinMap.put(c.hashCode(), false);
return true;
}
return false;
}
/**
* Determines if the mouse is currently inside the bounds of the given component based
* on the last mouseMove event that was dispatched.
*
* @param c The component to check
* @return True if the mouse is in the components bounds; false otherwise
*/
private boolean isMouseWithin(Component c) {
return mouseWithinMap.containsKey(c.hashCode()) && mouseWithinMap.get(c.hashCode());
}
/**
* Creates a copy of the given MouseEvent but with its event ID and source component
* replaced by the given arguments.
*
* @param source The source of the event to be created
* @param e The MouseEvent to copy
* @param newId The new event ID
* @return The new MouseEvent
*/
private MouseEvent synthesizeEvent(Component source, MouseEvent e, int newId) {
return new MouseEvent(source,
newId,
e.getWhen(),
e.getModifiers(),
e.getX(),
e.getY(),
e.getClickCount(),
e.isPopupTrigger(),
e.getButton());
}
/**
* Find the front-most background component which is underneath the point of the given MouseEvent. That is, the
* next component in the z-order behind this component.
*
* @param e The mouse event
* @return The component "hit" by the event or null if no component is underneath the event.
*/
private Component findHit(MouseEvent e) {
Component[] components = enumerator.getComponentsInZOrder();
for (int index = components.length - 1; index >= 0; index--) {
Component c = components[index];
Point hitPoint = SwingUtilities.convertPoint(e.getComponent(), e.getPoint(), c);
// Is anything underneath the event?
if (c.contains(hitPoint)) {
// Special case: found component is a container... uh oh
if (c instanceof Container) {
// Special case: Certain parts are implemented as containers; don't traverse these hierarchies.
if (c instanceof ContainerWrappedPart) {
return ((ContainerWrappedPart) c).getWrappedComponent();
}
// Special case: Give priority to scroll pane's viewport if it's hit
if (c instanceof JScrollPane) {
Component viewPortView = ((JScrollPane) c).getViewport().getView();
Point childHidPoint = SwingUtilities.convertPoint(e.getComponent(), e.getPoint(), c);
if (viewPortView.contains(childHidPoint)) {
return viewPortView;
}
}
for (Component child : ((Container) c).getComponents()) {
Point childHidPoint = SwingUtilities.convertPoint(e.getComponent(), e.getPoint(), child);
if (child.contains(childHidPoint)) {
return child;
}
}
}
return c;
}
}
return null;
}
} | mit |
plotly/python-api | packages/python/plotly/plotly/validators/scattermapbox/marker/colorbar/_y.py | 537 | import _plotly_utils.basevalidators
class YValidator(_plotly_utils.basevalidators.NumberValidator):
def __init__(
self, plotly_name="y", parent_name="scattermapbox.marker.colorbar", **kwargs
):
super(YValidator, self).__init__(
plotly_name=plotly_name,
parent_name=parent_name,
edit_type=kwargs.pop("edit_type", "calc"),
max=kwargs.pop("max", 3),
min=kwargs.pop("min", -2),
role=kwargs.pop("role", "style"),
**kwargs
)
| mit |
mono/cocos2d-xna | tests/tests/classes/tests/SpriteTest/SpriteChildrenAnchorPoint.cs | 3761 | using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Cocos2D;
namespace tests
{
public class SpriteChildrenAnchorPoint : SpriteTestDemo
{
public SpriteChildrenAnchorPoint()
{
CCSize s = CCDirector.SharedDirector.WinSize;
CCSpriteFrameCache.SharedSpriteFrameCache.AddSpriteFramesWithFile("animations/grossini.plist");
CCNode aParent;
CCSprite sprite1, sprite2, sprite3, sprite4, point;
//
// SpriteBatchNode
//
// parents
aParent = new CCNode ();
AddChild(aParent, 0);
// anchor (0,0)
sprite1 = new CCSprite("grossini_dance_08.png");
sprite1.Position = (new CCPoint(s.Width / 4, s.Height / 2));
sprite1.AnchorPoint = (new CCPoint(0, 0));
sprite2 = new CCSprite("grossini_dance_02.png");
sprite2.Position = (new CCPoint(20, 30));
sprite3 = new CCSprite("grossini_dance_03.png");
sprite3.Position = (new CCPoint(-20, 30));
sprite4 = new CCSprite("grossini_dance_04.png");
sprite4.Position = (new CCPoint(0, 0));
sprite4.Scale = 0.5f;
aParent.AddChild(sprite1);
sprite1.AddChild(sprite2, -2);
sprite1.AddChild(sprite3, -2);
sprite1.AddChild(sprite4, 3);
point = new CCSprite("Images/r1");
point.Scale = 0.25f;
point.Position = sprite1.Position;
AddChild(point, 10);
// anchor (0.5, 0.5)
sprite1 = new CCSprite("grossini_dance_08.png");
sprite1.Position = (new CCPoint(s.Width / 2, s.Height / 2));
sprite1.AnchorPoint = (new CCPoint(0.5f, 0.5f));
sprite2 = new CCSprite("grossini_dance_02.png");
sprite2.Position = (new CCPoint(20, 30));
sprite3 = new CCSprite("grossini_dance_03.png");
sprite3.Position = (new CCPoint(-20, 30));
sprite4 = new CCSprite("grossini_dance_04.png");
sprite4.Position = (new CCPoint(0, 0));
sprite4.Scale = 0.5f;
aParent.AddChild(sprite1);
sprite1.AddChild(sprite2, -2);
sprite1.AddChild(sprite3, -2);
sprite1.AddChild(sprite4, 3);
point = new CCSprite("Images/r1");
point.Scale = 0.25f;
point.Position = sprite1.Position;
AddChild(point, 10);
// anchor (1,1)
sprite1 = new CCSprite("grossini_dance_08.png");
sprite1.Position = (new CCPoint(s.Width / 2 + s.Width / 4, s.Height / 2));
sprite1.AnchorPoint = new CCPoint(1, 1);
sprite2 = new CCSprite("grossini_dance_02.png");
sprite2.Position = (new CCPoint(20, 30));
sprite3 = new CCSprite("grossini_dance_03.png");
sprite3.Position = (new CCPoint(-20, 30));
sprite4 = new CCSprite("grossini_dance_04.png");
sprite4.Position = (new CCPoint(0, 0));
sprite4.Scale = 0.5f;
aParent.AddChild(sprite1);
sprite1.AddChild(sprite2, -2);
sprite1.AddChild(sprite3, -2);
sprite1.AddChild(sprite4, 3);
point = new CCSprite("Images/r1");
point.Scale = 0.25f;
point.Position = sprite1.Position;
AddChild(point, 10);
}
public override void OnExit()
{
base.OnExit();
CCSpriteFrameCache.SharedSpriteFrameCache.RemoveUnusedSpriteFrames();
}
public override string title()
{
return "Sprite: children + anchor";
}
}
}
| mit |
rpoleski/MulensModel | examples/example_19_binary_source_binary_lens.py | 2311 | """
Example usage of the binary-lens binary-source model.
"""
import matplotlib.pyplot as plt
import os
import MulensModel as mm
t_0_1 = 5370.
t_0_2 = 5390.
u_0_1 = -0.15
u_0_2 = 0.2
rho_1 = 0.01
t_star_2 = 0.45
common = {'t_E': 25., 's': 1.1, 'q': 0.1, 'alpha': 10.}
parameters = {'t_0_1': t_0_1, 't_0_2': t_0_2, 'u_0_1': u_0_1, 'u_0_2': u_0_2,
'rho_1': rho_1, 't_star_2': t_star_2, **common}
parameters_1 = {'t_0': t_0_1, 'u_0': u_0_1, 'rho': rho_1, **common}
parameters_2 = {'t_0': t_0_2, 'u_0': u_0_2, 't_star': t_star_2, **common}
# plotting ranges:
t_start = 5362.
t_stop = 5400.
model = mm.Model(parameters)
model_1 = mm.Model(parameters_1)
model_2 = mm.Model(parameters_2)
model.set_magnification_methods([t_start, 'VBBL', t_stop])
model_1.set_magnification_methods([t_start, 'VBBL', t_stop])
model_2.set_magnification_methods([t_start, 'VBBL', t_stop])
# Make magnification plots:
plot_kwargs = {'t_start': t_start, 't_stop': t_stop}
model.plot_magnification(source_flux_ratio=1., label='flux ratio = 1',
**plot_kwargs)
model.plot_magnification(source_flux_ratio=5., label='flux ratio = 5',
**plot_kwargs)
model.plot_magnification(source_flux_ratio=0.2, label='flux ratio = 0.2',
**plot_kwargs)
model_1.plot_magnification(label='only source 1', ls='--', **plot_kwargs)
model_2.plot_magnification(label='only source 2', ls='--', **plot_kwargs)
plt.title('Binary-source binary-lens light curves')
plt.legend()
plt.show()
# Make trajectory plots:
model.plot_trajectory(caustics=True, label='both_sources', **plot_kwargs)
model_2.plot_trajectory(label='source 2', ls='--', lw=4, **plot_kwargs)
model_1.plot_trajectory(label='source 1', ls='--', lw=4, **plot_kwargs)
plt.title('Caustic and trajectories of both sources')
plt.legend()
plt.show()
# Combine it with a dataset (that doesn't show any caustic crossing),
# calculate chi^2, and make a plot of data and model:
file_name = os.path.join(mm.DATA_PATH, "photometry_files", "OB08092",
"phot_ob08092_O4.dat")
data = mm.MulensData(file_name=file_name)
event = mm.Event(datasets=data, model=model)
print("chi2 = ", event.get_chi2())
event.plot_data()
event.plot_model(c='red', **plot_kwargs)
plt.xlim(t_start, t_stop)
plt.show()
| mit |
CsharptutorialHungary/Peldak | Egyszeru-Peldak/pelda_string_numformat/Program.cs | 469 | ๏ปฟusing System;
namespace pelda_string_numformat
{
class Program
{
static void Main(string[] args)
{
Console.WriteLine("Pรฉnz: {0:C1}", 3148);
Console.WriteLine("Szรกzalรฉk: {0:P3}", 0.123456);
Console.WriteLine("รltalรกnos: {0:G}", 132354);
Console.WriteLine("Exponenciรกlis: {0:E}", 132354);
Console.WriteLine("Hexa: {0:X}", 255);
Console.ReadKey();
}
}
}
| mit |
congchinhqn/CapitalManagement | src/core/models/index.ts | 82 | ๏ปฟexport * from './base/base.model';
export * from './base/result-message.model'; | mit |
gforcedev/tgr-utils | js/urlutils.js | 259 | function getQueryVariable(variable) {
var query = window.location.search.substring(1);
var vars = query.split("&");
for (var i=0;i<vars.length;i++) {
var pair = vars[i].split("=");
if(pair[0] == variable){return pair[1];}
}
return(false);
}
| mit |
egoist/kanpai | src/prepare.ts | 3733 | import fs from "fs";
import path from "path";
import symbols from "log-symbols";
import figures from "figures";
import { execa } from "execa";
import commitsBetween from "commits-between";
import table from "text-table";
import * as colors from "colorette";
import semver from "semver";
import { writePackage } from "write-pkg";
import { ensureGit } from "./ensure-git";
import { config } from "./config";
import { updateChangeLog } from "./changelog";
import { getLatestTag } from "./git";
import { hr, runCommandWithSideEffects } from "./utils";
function failed(status = 1) {
process.exit(status);
}
function readPkg() {
const filepath = path.join(process.cwd(), "package.json");
if (!fs.existsSync(filepath)) {
throw new Error("Could not find package.json");
}
const content = fs.readFileSync(filepath, "utf8");
return {
path: filepath,
data: JSON.parse(content),
};
}
export async function prepare(
type: string,
options: {
anyBranch?: boolean;
skipTest?: boolean;
commitMessage?: string;
test?: string;
dryRun?: boolean;
channel?: string;
}
) {
const pkg = readPkg();
const kanpai = pkg.data.kanpai || {};
hr("CHECK GIT");
try {
await ensureGit({
anyBranch: options.anyBranch,
});
console.log("No conflicts!");
} catch (err: any) {
console.error(err.message);
failed();
}
const latestTag = await getLatestTag();
let defaultChangelog = "";
hr(latestTag ? `COMMITS` : `COMMITS SINCE ${latestTag}`);
const commits = await commitsBetween({ from: latestTag || undefined });
if (commits.length === 0) {
console.log(
`You haven't made any changes since last release (${latestTag}), aborted.`
);
failed();
}
console.log(
table(
commits.map((commit) => {
return [
`${figures.arrowRight} ${commit.subject}`,
colors.dim(commit.author.date.toString()),
];
})
)
);
defaultChangelog = commits.map((c) => `- ${c.subject}`).join("\n");
if (!latestTag) {
console.log(
"It seems to be your first time to publish a new release, not bad."
);
}
if (!options.skipTest) {
hr("TEST");
const defaultTest = kanpai.scripts && kanpai.scripts.kanpai;
const testCommand =
options.test || kanpai.test || defaultTest || config.get("test");
await execa("npm", ["run", testCommand], { stdio: "inherit" });
}
hr("VERSION");
const commitMessage = options.commitMessage || config.get("commitMessage");
const newVersion =
semver.valid(type) ||
semver.inc(
pkg.data.version,
type as any,
options.channel === "latest" ? "" : options.channel
);
if (!newVersion) {
console.error(
colors.red(`Could not bump version to ${type} from ${pkg.data.version}`)
);
return failed();
}
console.log(`Next version: ${newVersion}`);
// Update version in package.json
if (!options.dryRun) {
const newPkg = { ...pkg.data };
newPkg.version = newVersion;
await writePackage(pkg.path, newPkg);
}
// Update changelog file
if (!options.dryRun) {
updateChangeLog(newVersion, defaultChangelog);
}
// Commit and tag
await runCommandWithSideEffects(
"git",
["add", "package.json", "CHANGELOG.md"],
options.dryRun
);
await runCommandWithSideEffects(
"git",
["commit", "-m", commitMessage.replace("%s", newVersion)],
options.dryRun
);
await runCommandWithSideEffects(
"git",
["tag", `v${newVersion}`, `-m`, `v${newVersion}`],
options.dryRun
);
hr("PUSH");
await runCommandWithSideEffects(
"git",
["push", "--follow-tags"],
options.dryRun
);
console.log(`${symbols.success} Everything done!`);
}
| mit |
LimitedCoin/LimitedCoin | src/qt/locale/bitcoin_id_ID.ts | 112825 | <?xml version="1.0" ?><!DOCTYPE TS><TS language="id_ID" version="2.1">
<context>
<name>AboutDialog</name>
<message>
<location filename="../forms/aboutdialog.ui" line="+14"/>
<source>About LimitedCoin</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+39"/>
<source><b>LimitedCoin</b> version</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+41"/>
<source>Copyright ยฉ 2009-2014 The Bitcoin developers
Copyright ยฉ 2012-2014 The NovaCoin developers
Copyright ยฉ 2015 The LimitedCoin developers</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+15"/>
<source>
This is experimental software.
Distributed under the MIT/X11 software license, see the accompanying file COPYING or http://www.opensource.org/licenses/mit-license.php.
This product includes software developed by the OpenSSL Project for use in the OpenSSL Toolkit (http://www.openssl.org/) and cryptographic software written by Eric Young (eay@cryptsoft.com) and UPnP software written by Thomas Bernard.</source>
<translation type="unfinished"/>
</message>
</context>
<context>
<name>AddressBookPage</name>
<message>
<location filename="../forms/addressbookpage.ui" line="+14"/>
<source>Address Book</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+22"/>
<source>Double-click to edit address or label</source>
<translation>Klik-ganda untuk mengubah alamat atau label</translation>
</message>
<message>
<location line="+27"/>
<source>Create a new address</source>
<translation>Buat alamat baru</translation>
</message>
<message>
<location line="+14"/>
<source>Copy the currently selected address to the system clipboard</source>
<translation>Salin alamat yang dipilih ke clipboard</translation>
</message>
<message>
<location line="-11"/>
<source>&New Address</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-46"/>
<source>These are your LimitedCoin addresses for receiving payments. You may want to give a different one to each sender so you can keep track of who is paying you.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+60"/>
<source>&Copy Address</source>
<translation>&Salin Alamat</translation>
</message>
<message>
<location line="+11"/>
<source>Show &QR Code</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+11"/>
<source>Sign a message to prove you own a LimitedCoin address</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>Sign &Message</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+25"/>
<source>Delete the currently selected address from the list</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-14"/>
<source>Verify a message to ensure it was signed with a specified LimitedCoin address</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>&Verify Message</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+14"/>
<source>&Delete</source>
<translation>&Hapus</translation>
</message>
<message>
<location filename="../addressbookpage.cpp" line="+65"/>
<source>Copy &Label</source>
<translation>Salin &Label</translation>
</message>
<message>
<location line="+2"/>
<source>&Edit</source>
<translation>&Ubah</translation>
</message>
<message>
<location line="+250"/>
<source>Export Address Book Data</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Comma separated file (*.csv)</source>
<translation>File CSV (*.csv)</translation>
</message>
<message>
<location line="+13"/>
<source>Error exporting</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+0"/>
<source>Could not write to file %1.</source>
<translation type="unfinished"/>
</message>
</context>
<context>
<name>AddressTableModel</name>
<message>
<location filename="../addresstablemodel.cpp" line="+144"/>
<source>Label</source>
<translation>Label</translation>
</message>
<message>
<location line="+0"/>
<source>Address</source>
<translation>Alamat</translation>
</message>
<message>
<location line="+36"/>
<source>(no label)</source>
<translation>(tidak ada label)</translation>
</message>
</context>
<context>
<name>AskPassphraseDialog</name>
<message>
<location filename="../forms/askpassphrasedialog.ui" line="+26"/>
<source>Passphrase Dialog</source>
<translation>Dialog Kata kunci</translation>
</message>
<message>
<location line="+21"/>
<source>Enter passphrase</source>
<translation>Masukkan kata kunci</translation>
</message>
<message>
<location line="+14"/>
<source>New passphrase</source>
<translation>Kata kunci baru</translation>
</message>
<message>
<location line="+14"/>
<source>Repeat new passphrase</source>
<translation>Ulangi kata kunci baru</translation>
</message>
<message>
<location line="+33"/>
<source>Serves to disable the trivial sendmoney when OS account compromised. Provides no real security.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>For staking only</source>
<translation type="unfinished"/>
</message>
<message>
<location filename="../askpassphrasedialog.cpp" line="+35"/>
<source>Enter the new passphrase to the wallet.<br/>Please use a passphrase of <b>10 or more random characters</b>, or <b>eight or more words</b>.</source>
<translation>Masukkan kata kunci baru ke dompet.<br/>Mohon gunakan kata kunci dengan <b>10 karakter atau lebih dengan acak</b>, atau <b>delapan kata atau lebih</b>.</translation>
</message>
<message>
<location line="+1"/>
<source>Encrypt wallet</source>
<translation>Enkripsi dompet</translation>
</message>
<message>
<location line="+7"/>
<source>This operation needs your wallet passphrase to unlock the wallet.</source>
<translation>Operasi ini memerlukan kata kunci dompet Anda untuk membuka dompet ini.</translation>
</message>
<message>
<location line="+5"/>
<source>Unlock wallet</source>
<translation>Buka dompet</translation>
</message>
<message>
<location line="+3"/>
<source>This operation needs your wallet passphrase to decrypt the wallet.</source>
<translation>Operasi ini memerlukan kata kunci dompet Anda untuk mendekripsi dompet ini.</translation>
</message>
<message>
<location line="+5"/>
<source>Decrypt wallet</source>
<translation>Dekripsi dompet</translation>
</message>
<message>
<location line="+3"/>
<source>Change passphrase</source>
<translation>Ubah kata kunci</translation>
</message>
<message>
<location line="+1"/>
<source>Enter the old and new passphrase to the wallet.</source>
<translation>Masukkan kata kunci lama dan baru ke dompet ini.</translation>
</message>
<message>
<location line="+46"/>
<source>Confirm wallet encryption</source>
<translation>Konfirmasi enkripsi dompet</translation>
</message>
<message>
<location line="+1"/>
<source>Warning: If you encrypt your wallet and lose your passphrase, you will <b>LOSE ALL OF YOUR COINS</b>!</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+0"/>
<source>Are you sure you wish to encrypt your wallet?</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+15"/>
<source>IMPORTANT: Any previous backups you have made of your wallet file should be replaced with the newly generated, encrypted wallet file. For security reasons, previous backups of the unencrypted wallet file will become useless as soon as you start using the new, encrypted wallet.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+103"/>
<location line="+24"/>
<source>Warning: The Caps Lock key is on!</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-133"/>
<location line="+60"/>
<source>Wallet encrypted</source>
<translation>Dompet terenkripsi</translation>
</message>
<message>
<location line="-58"/>
<source>LimitedCoin will close now to finish the encryption process. Remember that encrypting your wallet cannot fully protect your coins from being stolen by malware infecting your computer.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+13"/>
<location line="+7"/>
<location line="+44"/>
<location line="+6"/>
<source>Wallet encryption failed</source>
<translation>Enkripsi dompet gagal</translation>
</message>
<message>
<location line="-56"/>
<source>Wallet encryption failed due to an internal error. Your wallet was not encrypted.</source>
<translation>Enkripsi dompet gagal karena kesalahan internal. Dompet Anda tidak dienkripsi.</translation>
</message>
<message>
<location line="+7"/>
<location line="+50"/>
<source>The supplied passphrases do not match.</source>
<translation>Kata kunci yang dimasukkan tidak cocok.</translation>
</message>
<message>
<location line="-38"/>
<source>Wallet unlock failed</source>
<translation>Gagal buka dompet</translation>
</message>
<message>
<location line="+1"/>
<location line="+12"/>
<location line="+19"/>
<source>The passphrase entered for the wallet decryption was incorrect.</source>
<translation>Kata kunci yang dimasukkan untuk dekripsi dompet tidak cocok.</translation>
</message>
<message>
<location line="-20"/>
<source>Wallet decryption failed</source>
<translation>Dekripsi dompet gagal</translation>
</message>
<message>
<location line="+14"/>
<source>Wallet passphrase was successfully changed.</source>
<translation type="unfinished"/>
</message>
</context>
<context>
<name>BitcoinGUI</name>
<message>
<location filename="../bitcoingui.cpp" line="+282"/>
<source>Sign &message...</source>
<translation>Pesan &penanda...</translation>
</message>
<message>
<location line="+251"/>
<source>Synchronizing with network...</source>
<translation>Sinkronisasi dengan jaringan...</translation>
</message>
<message>
<location line="-319"/>
<source>&Overview</source>
<translation>&Kilasan</translation>
</message>
<message>
<location line="+1"/>
<source>Show general overview of wallet</source>
<translation>Tampilkan kilasan umum dari dompet</translation>
</message>
<message>
<location line="+17"/>
<source>&Transactions</source>
<translation>&Transaksi</translation>
</message>
<message>
<location line="+1"/>
<source>Browse transaction history</source>
<translation>Jelajah sejarah transaksi</translation>
</message>
<message>
<location line="+5"/>
<source>&Address Book</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Edit the list of stored addresses and labels</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-13"/>
<source>&Receive coins</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Show the list of addresses for receiving payments</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-7"/>
<source>&Send coins</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+35"/>
<source>E&xit</source>
<translation>K&eluar</translation>
</message>
<message>
<location line="+1"/>
<source>Quit application</source>
<translation>Keluar dari aplikasi</translation>
</message>
<message>
<location line="+6"/>
<source>Show information about LimitedCoin</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+2"/>
<source>About &Qt</source>
<translation>Mengenai &Qt</translation>
</message>
<message>
<location line="+1"/>
<source>Show information about Qt</source>
<translation>Tampilkan informasi mengenai Qt</translation>
</message>
<message>
<location line="+2"/>
<source>&Options...</source>
<translation>&Pilihan...</translation>
</message>
<message>
<location line="+4"/>
<source>&Encrypt Wallet...</source>
<translation>%Enkripsi Dompet...</translation>
</message>
<message>
<location line="+3"/>
<source>&Backup Wallet...</source>
<translation>&Cadangkan Dompet...</translation>
</message>
<message>
<location line="+2"/>
<source>&Change Passphrase...</source>
<translation>&Ubah Kata Kunci...</translation>
</message>
<message numerus="yes">
<location line="+259"/>
<source>~%n block(s) remaining</source>
<translation type="unfinished"><numerusform></numerusform></translation>
</message>
<message>
<location line="+6"/>
<source>Downloaded %1 of %2 blocks of transaction history (%3% done).</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-256"/>
<source>&Export...</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-64"/>
<source>Send coins to a LimitedCoin address</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+47"/>
<source>Modify configuration options for LimitedCoin</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+18"/>
<source>Export the data in the current tab to a file</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-14"/>
<source>Encrypt or decrypt wallet</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>Backup wallet to another location</source>
<translation>Cadangkan dompet ke lokasi lain</translation>
</message>
<message>
<location line="+2"/>
<source>Change the passphrase used for wallet encryption</source>
<translation>Ubah kata kunci yang digunakan untuk enkripsi dompet</translation>
</message>
<message>
<location line="+10"/>
<source>&Debug window</source>
<translation>&Jendela Debug</translation>
</message>
<message>
<location line="+1"/>
<source>Open debugging and diagnostic console</source>
<translation>Buka konsol debug dan diagnosa</translation>
</message>
<message>
<location line="-5"/>
<source>&Verify message...</source>
<translation>&Verifikasi pesan...</translation>
</message>
<message>
<location line="-202"/>
<source>LimitedCoin</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+0"/>
<source>Wallet</source>
<translation>Dompet</translation>
</message>
<message>
<location line="+180"/>
<source>&About LimitedCoin</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+9"/>
<source>&Show / Hide</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+9"/>
<source>Unlock wallet</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>&Lock Wallet</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Lock wallet</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+35"/>
<source>&File</source>
<translation>&Berkas</translation>
</message>
<message>
<location line="+8"/>
<source>&Settings</source>
<translation>&Pengaturan</translation>
</message>
<message>
<location line="+8"/>
<source>&Help</source>
<translation>&Bantuan</translation>
</message>
<message>
<location line="+12"/>
<source>Tabs toolbar</source>
<translation>Baris tab</translation>
</message>
<message>
<location line="+8"/>
<source>Actions toolbar</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+13"/>
<location line="+9"/>
<source>[testnet]</source>
<translation>[testnet]</translation>
</message>
<message>
<location line="+0"/>
<location line="+60"/>
<source>LimitedCoin client</source>
<translation type="unfinished"/>
</message>
<message numerus="yes">
<location line="+75"/>
<source>%n active connection(s) to LimitedCoin network</source>
<translation type="unfinished"><numerusform></numerusform></translation>
</message>
<message>
<location line="+40"/>
<source>Downloaded %1 blocks of transaction history.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+413"/>
<source>Staking.<br>Your weight is %1<br>Network weight is %2<br>Expected time to earn reward is %3</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+6"/>
<source>Not staking because wallet is locked</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+2"/>
<source>Not staking because wallet is offline</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+2"/>
<source>Not staking because wallet is syncing</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+2"/>
<source>Not staking because you don't have mature coins</source>
<translation type="unfinished"/>
</message>
<message numerus="yes">
<location line="-403"/>
<source>%n second(s) ago</source>
<translation type="unfinished"><numerusform></numerusform></translation>
</message>
<message>
<location line="-312"/>
<source>About LimitedCoin card</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Show information about LimitedCoin card</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+18"/>
<source>&Unlock Wallet...</source>
<translation type="unfinished"/>
</message>
<message numerus="yes">
<location line="+297"/>
<source>%n minute(s) ago</source>
<translation type="unfinished"><numerusform></numerusform></translation>
</message>
<message numerus="yes">
<location line="+4"/>
<source>%n hour(s) ago</source>
<translation type="unfinished"><numerusform></numerusform></translation>
</message>
<message numerus="yes">
<location line="+4"/>
<source>%n day(s) ago</source>
<translation type="unfinished"><numerusform></numerusform></translation>
</message>
<message>
<location line="+6"/>
<source>Up to date</source>
<translation>Terbaru</translation>
</message>
<message>
<location line="+7"/>
<source>Catching up...</source>
<translation>Menyusul...</translation>
</message>
<message>
<location line="+10"/>
<source>Last received block was generated %1.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+59"/>
<source>This transaction is over the size limit. You can still send it for a fee of %1, which goes to the nodes that process your transaction and helps to support the network. Do you want to pay the fee?</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+5"/>
<source>Confirm transaction fee</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+27"/>
<source>Sent transaction</source>
<translation>Transaksi terkirim</translation>
</message>
<message>
<location line="+1"/>
<source>Incoming transaction</source>
<translation>Transaksi diterima</translation>
</message>
<message>
<location line="+1"/>
<source>Date: %1
Amount: %2
Type: %3
Address: %4
</source>
<translation>Tanggal: %1
Jumlah: %2
Jenis: %3
Alamat: %4
</translation>
</message>
<message>
<location line="+100"/>
<location line="+15"/>
<source>URI handling</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-15"/>
<location line="+15"/>
<source>URI can not be parsed! This can be caused by an invalid LimitedCoin address or malformed URI parameters.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+18"/>
<source>Wallet is <b>encrypted</b> and currently <b>unlocked</b></source>
<translation>Dompet saat ini <b>terenkripsi</b> dan <b>terbuka</b></translation>
</message>
<message>
<location line="+10"/>
<source>Wallet is <b>encrypted</b> and currently <b>locked</b></source>
<translation>Dompet saat ini <b>terenkripsi</b> dan <b>terkunci</b></translation>
</message>
<message>
<location line="+25"/>
<source>Backup Wallet</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+0"/>
<source>Wallet Data (*.dat)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>Backup Failed</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+0"/>
<source>There was an error trying to save the wallet data to the new location.</source>
<translation type="unfinished"/>
</message>
<message numerus="yes">
<location line="+76"/>
<source>%n second(s)</source>
<translation type="unfinished"><numerusform></numerusform></translation>
</message>
<message numerus="yes">
<location line="+4"/>
<source>%n minute(s)</source>
<translation type="unfinished"><numerusform></numerusform></translation>
</message>
<message numerus="yes">
<location line="+4"/>
<source>%n hour(s)</source>
<translation type="unfinished"><numerusform></numerusform></translation>
</message>
<message numerus="yes">
<location line="+4"/>
<source>%n day(s)</source>
<translation type="unfinished"><numerusform></numerusform></translation>
</message>
<message>
<location line="+18"/>
<source>Not staking</source>
<translation type="unfinished"/>
</message>
<message>
<location filename="../bitcoin.cpp" line="+109"/>
<source>A fatal error occurred. LimitedCoin can no longer continue safely and will quit.</source>
<translation type="unfinished"/>
</message>
</context>
<context>
<name>ClientModel</name>
<message>
<location filename="../clientmodel.cpp" line="+90"/>
<source>Network Alert</source>
<translation>Notifikasi Jaringan</translation>
</message>
</context>
<context>
<name>CoinControlDialog</name>
<message>
<location filename="../forms/coincontroldialog.ui" line="+14"/>
<source>Coin Control</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+31"/>
<source>Quantity:</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+32"/>
<source>Bytes:</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+48"/>
<source>Amount:</source>
<translation>Jumlah:</translation>
</message>
<message>
<location line="+32"/>
<source>Priority:</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+48"/>
<source>Fee:</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+35"/>
<source>Low Output:</source>
<translation type="unfinished"/>
</message>
<message>
<location filename="../coincontroldialog.cpp" line="+551"/>
<source>no</source>
<translation type="unfinished"/>
</message>
<message>
<location filename="../forms/coincontroldialog.ui" line="+51"/>
<source>After Fee:</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+35"/>
<source>Change:</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+69"/>
<source>(un)select all</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+13"/>
<source>Tree mode</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+16"/>
<source>List mode</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+45"/>
<source>Amount</source>
<translation>Jumlah</translation>
</message>
<message>
<location line="+5"/>
<source>Label</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+5"/>
<source>Address</source>
<translation>Alamat</translation>
</message>
<message>
<location line="+5"/>
<source>Date</source>
<translation>Tanggal</translation>
</message>
<message>
<location line="+5"/>
<source>Confirmations</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>Confirmed</source>
<translation>Terkonfirmasi</translation>
</message>
<message>
<location line="+5"/>
<source>Priority</source>
<translation type="unfinished"/>
</message>
<message>
<location filename="../coincontroldialog.cpp" line="-515"/>
<source>Copy address</source>
<translation>Salin alamat</translation>
</message>
<message>
<location line="+1"/>
<source>Copy label</source>
<translation>Salin label</translation>
</message>
<message>
<location line="+1"/>
<location line="+26"/>
<source>Copy amount</source>
<translation>Salin jumlah</translation>
</message>
<message>
<location line="-25"/>
<source>Copy transaction ID</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+24"/>
<source>Copy quantity</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+2"/>
<source>Copy fee</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Copy after fee</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Copy bytes</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Copy priority</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Copy low output</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Copy change</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+317"/>
<source>highest</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>high</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>medium-high</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>medium</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+4"/>
<source>low-medium</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>low</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>lowest</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+155"/>
<source>DUST</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+0"/>
<source>yes</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+10"/>
<source>This label turns red, if the transaction size is bigger than 10000 bytes.
This means a fee of at least %1 per kb is required.
Can vary +/- 1 Byte per input.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Transactions with higher priority get more likely into a block.
This label turns red, if the priority is smaller than "medium".
This means a fee of at least %1 per kb is required.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>This label turns red, if any recipient receives an amount smaller than %1.
This means a fee of at least %2 is required.
Amounts below 0.546 times the minimum relay fee are shown as DUST.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>This label turns red, if the change is smaller than %1.
This means a fee of at least %2 is required.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+37"/>
<location line="+66"/>
<source>(no label)</source>
<translation>(tidak ada label)</translation>
</message>
<message>
<location line="-9"/>
<source>change from %1 (%2)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>(change)</source>
<translation type="unfinished"/>
</message>
</context>
<context>
<name>EditAddressDialog</name>
<message>
<location filename="../forms/editaddressdialog.ui" line="+14"/>
<source>Edit Address</source>
<translation>Ubah Alamat</translation>
</message>
<message>
<location line="+11"/>
<source>&Label</source>
<translation>&Label</translation>
</message>
<message>
<location line="+10"/>
<source>The label associated with this address book entry</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+7"/>
<source>&Address</source>
<translation>&Alamat</translation>
</message>
<message>
<location line="+10"/>
<source>The address associated with this address book entry. This can only be modified for sending addresses.</source>
<translation type="unfinished"/>
</message>
<message>
<location filename="../editaddressdialog.cpp" line="+20"/>
<source>New receiving address</source>
<translation>Alamat menerima baru</translation>
</message>
<message>
<location line="+4"/>
<source>New sending address</source>
<translation>Alamat mengirim baru</translation>
</message>
<message>
<location line="+3"/>
<source>Edit receiving address</source>
<translation>Ubah alamat menerima</translation>
</message>
<message>
<location line="+4"/>
<source>Edit sending address</source>
<translation>Ubah alamat mengirim</translation>
</message>
<message>
<location line="+76"/>
<source>The entered address "%1" is already in the address book.</source>
<translation>Alamat yang dimasukkan "%1" sudah ada di dalam buku alamat.</translation>
</message>
<message>
<location line="-5"/>
<source>The entered address "%1" is not a valid LimitedCoin address.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+10"/>
<source>Could not unlock wallet.</source>
<translation>Tidak dapat membuka dompet.</translation>
</message>
<message>
<location line="+5"/>
<source>New key generation failed.</source>
<translation>Pembuatan kunci baru gagal.</translation>
</message>
</context>
<context>
<name>GUIUtil::HelpMessageBox</name>
<message>
<location filename="../guiutil.cpp" line="+420"/>
<location line="+12"/>
<source>limitedcoin-qt</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-12"/>
<source>version</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+2"/>
<source>Usage:</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>command-line options</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+4"/>
<source>UI options</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Set language, for example "de_DE" (default: system locale)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Start minimized</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Show splash screen on startup (default: 1)</source>
<translation type="unfinished"/>
</message>
</context>
<context>
<name>OptionsDialog</name>
<message>
<location filename="../forms/optionsdialog.ui" line="+14"/>
<source>Options</source>
<translation>Pilihan</translation>
</message>
<message>
<location line="+16"/>
<source>&Main</source>
<translation>&Utama</translation>
</message>
<message>
<location line="+6"/>
<source>Optional transaction fee per kB that helps make sure your transactions are processed quickly. Most transactions are 1 kB. Fee 0.01 recommended.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+15"/>
<source>Pay transaction &fee</source>
<translation>Bayar &biaya transaksi</translation>
</message>
<message>
<location line="+31"/>
<source>Reserved amount does not participate in staking and is therefore spendable at any time.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+15"/>
<source>Reserve</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+31"/>
<source>Automatically start LimitedCoin after logging in to the system.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>&Start LimitedCoin on system login</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+7"/>
<source>Detach block and address databases at shutdown. This means they can be moved to another data directory, but it slows down shutdown. The wallet is always detached.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>&Detach databases at shutdown</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+21"/>
<source>&Network</source>
<translation>&Jaringan</translation>
</message>
<message>
<location line="+6"/>
<source>Automatically open the LimitedCoin client port on the router. This only works when your router supports UPnP and it is enabled.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>Map port using &UPnP</source>
<translation>Petakan port dengan &UPnP</translation>
</message>
<message>
<location line="+7"/>
<source>Connect to the LimitedCoin network through a SOCKS proxy (e.g. when connecting through Tor).</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>&Connect through SOCKS proxy:</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+9"/>
<source>Proxy &IP:</source>
<translation>IP Proxy:</translation>
</message>
<message>
<location line="+19"/>
<source>IP address of the proxy (e.g. 127.0.0.1)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+7"/>
<source>&Port:</source>
<translation>&Port:</translation>
</message>
<message>
<location line="+19"/>
<source>Port of the proxy (e.g. 9050)</source>
<translation>Port proxy (cth. 9050)</translation>
</message>
<message>
<location line="+7"/>
<source>SOCKS &Version:</source>
<translation>Versi &SOCKS:</translation>
</message>
<message>
<location line="+13"/>
<source>SOCKS version of the proxy (e.g. 5)</source>
<translation>Versi SOCKS proxy (cth. 5)</translation>
</message>
<message>
<location line="+36"/>
<source>&Window</source>
<translation>&Jendela</translation>
</message>
<message>
<location line="+6"/>
<source>Show only a tray icon after minimizing the window.</source>
<translation>Hanya tampilkan ikon tray setelah meminilisasi jendela</translation>
</message>
<message>
<location line="+3"/>
<source>&Minimize to the tray instead of the taskbar</source>
<translation>&Meminilisasi ke tray daripada taskbar</translation>
</message>
<message>
<location line="+7"/>
<source>Minimize instead of exit the application when the window is closed. When this option is enabled, the application will be closed only after selecting Quit in the menu.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>M&inimize on close</source>
<translation>M&eminilisasi saat tutup</translation>
</message>
<message>
<location line="+21"/>
<source>&Display</source>
<translation>&Tampilan</translation>
</message>
<message>
<location line="+8"/>
<source>User Interface &language:</source>
<translation>&Bahasa Antarmuka Pengguna:</translation>
</message>
<message>
<location line="+13"/>
<source>The user interface language can be set here. This setting will take effect after restarting LimitedCoin.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+11"/>
<source>&Unit to show amounts in:</source>
<translation>&Unit untuk menunjukkan jumlah:</translation>
</message>
<message>
<location line="+13"/>
<source>Choose the default subdivision unit to show in the interface and when sending coins.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+9"/>
<source>Whether to show LimitedCoin addresses in the transaction list or not.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>&Display addresses in transaction list</source>
<translation>&Tampilkan alamat dalam daftar transaksi</translation>
</message>
<message>
<location line="+7"/>
<source>Whether to show coin control features or not.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>Display coin &control features (experts only!)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+71"/>
<source>&OK</source>
<translation>&YA</translation>
</message>
<message>
<location line="+7"/>
<source>&Cancel</source>
<translation>&Batal</translation>
</message>
<message>
<location line="+10"/>
<source>&Apply</source>
<translation type="unfinished"/>
</message>
<message>
<location filename="../optionsdialog.cpp" line="+55"/>
<source>default</source>
<translation>standar</translation>
</message>
<message>
<location line="+149"/>
<location line="+9"/>
<source>Warning</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-9"/>
<location line="+9"/>
<source>This setting will take effect after restarting LimitedCoin.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+29"/>
<source>The supplied proxy address is invalid.</source>
<translation>Alamat proxy yang diisi tidak valid.</translation>
</message>
</context>
<context>
<name>OverviewPage</name>
<message>
<location filename="../forms/overviewpage.ui" line="+14"/>
<source>Form</source>
<translation>Formulir</translation>
</message>
<message>
<location line="+33"/>
<location line="+231"/>
<source>The displayed information may be out of date. Your wallet automatically synchronizes with the LimitedCoin network after a connection is established, but this process has not completed yet.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-160"/>
<source>Stake:</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+29"/>
<source>Unconfirmed:</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-107"/>
<source>Wallet</source>
<translation>Dompet</translation>
</message>
<message>
<location line="+49"/>
<source>Spendable:</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+16"/>
<source>Your current spendable balance</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+71"/>
<source>Immature:</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+13"/>
<source>Mined balance that has not yet matured</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+20"/>
<source>Total:</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+16"/>
<source>Your current total balance</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+46"/>
<source><b>Recent transactions</b></source>
<translation><b>Transaksi sebelumnya</b></translation>
</message>
<message>
<location line="-108"/>
<source>Total of transactions that have yet to be confirmed, and do not yet count toward the current balance</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-29"/>
<source>Total of coins that was staked, and do not yet count toward the current balance</source>
<translation type="unfinished"/>
</message>
<message>
<location filename="../overviewpage.cpp" line="+113"/>
<location line="+1"/>
<source>out of sync</source>
<translation>tidak tersinkron</translation>
</message>
</context>
<context>
<name>QRCodeDialog</name>
<message>
<location filename="../forms/qrcodedialog.ui" line="+14"/>
<source>QR Code Dialog</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+59"/>
<source>Request Payment</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+56"/>
<source>Amount:</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-44"/>
<source>Label:</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+19"/>
<source>Message:</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+71"/>
<source>&Save As...</source>
<translation type="unfinished"/>
</message>
<message>
<location filename="../qrcodedialog.cpp" line="+62"/>
<source>Error encoding URI into QR Code.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+40"/>
<source>The entered amount is invalid, please check.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+23"/>
<source>Resulting URI too long, try to reduce the text for label / message.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+25"/>
<source>Save QR Code</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+0"/>
<source>PNG Images (*.png)</source>
<translation type="unfinished"/>
</message>
</context>
<context>
<name>RPCConsole</name>
<message>
<location filename="../forms/rpcconsole.ui" line="+46"/>
<source>Client name</source>
<translation>Nama Klien</translation>
</message>
<message>
<location line="+10"/>
<location line="+23"/>
<location line="+26"/>
<location line="+23"/>
<location line="+23"/>
<location line="+36"/>
<location line="+53"/>
<location line="+23"/>
<location line="+23"/>
<location filename="../rpcconsole.cpp" line="+348"/>
<source>N/A</source>
<translation>T/S</translation>
</message>
<message>
<location line="-217"/>
<source>Client version</source>
<translation>Versi Klien</translation>
</message>
<message>
<location line="-45"/>
<source>&Information</source>
<translation>&Informasi</translation>
</message>
<message>
<location line="+68"/>
<source>Using OpenSSL version</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+49"/>
<source>Startup time</source>
<translation>Waktu nyala</translation>
</message>
<message>
<location line="+29"/>
<source>Network</source>
<translation>Jaringan</translation>
</message>
<message>
<location line="+7"/>
<source>Number of connections</source>
<translation>Jumlah hubungan</translation>
</message>
<message>
<location line="+23"/>
<source>On testnet</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+23"/>
<source>Block chain</source>
<translation>Rantai blok</translation>
</message>
<message>
<location line="+7"/>
<source>Current number of blocks</source>
<translation>Jumlah blok terkini</translation>
</message>
<message>
<location line="+23"/>
<source>Estimated total blocks</source>
<translation>Perkiraan blok total</translation>
</message>
<message>
<location line="+23"/>
<source>Last block time</source>
<translation>Waktu blok terakhir</translation>
</message>
<message>
<location line="+52"/>
<source>&Open</source>
<translation>&Buka</translation>
</message>
<message>
<location line="+16"/>
<source>Command-line options</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+7"/>
<source>Show the limitedcoin-qt help message to get a list with possible LimitedCoin command-line options.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>&Show</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+24"/>
<source>&Console</source>
<translation>&Konsol</translation>
</message>
<message>
<location line="-260"/>
<source>Build date</source>
<translation>Tanggal pembuatan</translation>
</message>
<message>
<location line="-104"/>
<source>LimitedCoin - Debug window</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+25"/>
<source>LimitedCoin Core</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+279"/>
<source>Debug log file</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+7"/>
<source>Open the LimitedCoin debug log file from the current data directory. This can take a few seconds for large log files.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+102"/>
<source>Clear console</source>
<translation>Bersihkan konsol</translation>
</message>
<message>
<location filename="../rpcconsole.cpp" line="-33"/>
<source>Welcome to the LimitedCoin RPC console.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Use up and down arrows to navigate history, and <b>Ctrl-L</b> to clear screen.</source>
<translation>Gunakan panah keatas dan kebawah untuk menampilkan sejarah, dan <b>Ctrl-L</b> untuk bersihkan layar.</translation>
</message>
<message>
<location line="+1"/>
<source>Type <b>help</b> for an overview of available commands.</source>
<translation>Ketik <b>help</b> untuk menampilkan perintah tersedia.</translation>
</message>
</context>
<context>
<name>SendCoinsDialog</name>
<message>
<location filename="../forms/sendcoinsdialog.ui" line="+14"/>
<location filename="../sendcoinsdialog.cpp" line="+182"/>
<location line="+5"/>
<location line="+5"/>
<location line="+5"/>
<location line="+6"/>
<location line="+5"/>
<location line="+5"/>
<source>Send Coins</source>
<translation>Kirim Koin</translation>
</message>
<message>
<location line="+76"/>
<source>Coin Control Features</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+20"/>
<source>Inputs...</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+7"/>
<source>automatically selected</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+19"/>
<source>Insufficient funds!</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+77"/>
<source>Quantity:</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+22"/>
<location line="+35"/>
<source>0</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-19"/>
<source>Bytes:</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+51"/>
<source>Amount:</source>
<translation>Jumlah:</translation>
</message>
<message>
<location line="+22"/>
<location line="+86"/>
<location line="+86"/>
<location line="+32"/>
<source>0.00 hack</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-191"/>
<source>Priority:</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+19"/>
<source>medium</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+32"/>
<source>Fee:</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+35"/>
<source>Low Output:</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+19"/>
<source>no</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+32"/>
<source>After Fee:</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+35"/>
<source>Change</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+50"/>
<source>custom change address</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+106"/>
<source>Send to multiple recipients at once</source>
<translation>Kirim ke beberapa penerima sekaligus</translation>
</message>
<message>
<location line="+3"/>
<source>Add &Recipient</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+20"/>
<source>Remove all transaction fields</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>Clear &All</source>
<translation>Hapus %Semua</translation>
</message>
<message>
<location line="+28"/>
<source>Balance:</source>
<translation>Saldo:</translation>
</message>
<message>
<location line="+16"/>
<source>123.456 hack</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+31"/>
<source>Confirm the send action</source>
<translation>Konfirmasi aksi pengiriman</translation>
</message>
<message>
<location line="+3"/>
<source>S&end</source>
<translation type="unfinished"/>
</message>
<message>
<location filename="../sendcoinsdialog.cpp" line="-173"/>
<source>Enter a LimitedCoin address (e.g. LimitedCoinSamp1eAddressXXXXSST9Ap)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+15"/>
<source>Copy quantity</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Copy amount</source>
<translation>Salin jumlah</translation>
</message>
<message>
<location line="+1"/>
<source>Copy fee</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Copy after fee</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Copy bytes</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Copy priority</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Copy low output</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Copy change</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+86"/>
<source><b>%1</b> to %2 (%3)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+5"/>
<source>Confirm send coins</source>
<translation>Konfirmasi pengiriman koin</translation>
</message>
<message>
<location line="+1"/>
<source>Are you sure you want to send %1?</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+0"/>
<source> and </source>
<translation type="unfinished"/>
</message>
<message>
<location line="+29"/>
<source>The recipient address is not valid, please recheck.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+5"/>
<source>The amount to pay must be larger than 0.</source>
<translation>Jumlah yang dibayar harus lebih besar dari 0.</translation>
</message>
<message>
<location line="+5"/>
<source>The amount exceeds your balance.</source>
<translation>Jumlah melebihi saldo Anda.</translation>
</message>
<message>
<location line="+5"/>
<source>The total exceeds your balance when the %1 transaction fee is included.</source>
<translation>Kelebihan total saldo Anda ketika biaya transaksi %1 ditambahkan.</translation>
</message>
<message>
<location line="+6"/>
<source>Duplicate address found, can only send to each address once per send operation.</source>
<translation>Ditemukan alamat ganda, hanya dapat mengirim ke tiap alamat sekali per operasi pengiriman.</translation>
</message>
<message>
<location line="+5"/>
<source>Error: Transaction creation failed.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+5"/>
<source>Error: The transaction was rejected. This might happen if some of the coins in your wallet were already spent, such as if you used a copy of wallet.dat and coins were spent in the copy but not marked as spent here.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+251"/>
<source>WARNING: Invalid LimitedCoin address</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+13"/>
<source>(no label)</source>
<translation>(tidak ada label)</translation>
</message>
<message>
<location line="+4"/>
<source>WARNING: unknown change address</source>
<translation type="unfinished"/>
</message>
</context>
<context>
<name>SendCoinsEntry</name>
<message>
<location filename="../forms/sendcoinsentry.ui" line="+14"/>
<source>Form</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+15"/>
<source>A&mount:</source>
<translation>J&umlah:</translation>
</message>
<message>
<location line="+13"/>
<source>Pay &To:</source>
<translation>Kirim &Ke:</translation>
</message>
<message>
<location line="+24"/>
<location filename="../sendcoinsentry.cpp" line="+25"/>
<source>Enter a label for this address to add it to your address book</source>
<translation>Masukkan label bagi alamat ini untuk menambahkannya ke buku alamat Anda</translation>
</message>
<message>
<location line="+9"/>
<source>&Label:</source>
<translation>&Label:</translation>
</message>
<message>
<location line="+18"/>
<source>The address to send the payment to (e.g. LimitedCoinSamp1eAddressXXXXSST9Ap)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+10"/>
<source>Choose address from address book</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+10"/>
<source>Alt+A</source>
<translation>Alt+J</translation>
</message>
<message>
<location line="+7"/>
<source>Paste address from clipboard</source>
<translation>Tempel alamat dari salinan</translation>
</message>
<message>
<location line="+10"/>
<source>Alt+P</source>
<translation>Alt+B</translation>
</message>
<message>
<location line="+7"/>
<source>Remove this recipient</source>
<translation type="unfinished"/>
</message>
<message>
<location filename="../sendcoinsentry.cpp" line="+1"/>
<source>Enter a LimitedCoin address (e.g. LimitedCoinSamp1eAddressXXXXSST9Ap)</source>
<translation type="unfinished"/>
</message>
</context>
<context>
<name>SignVerifyMessageDialog</name>
<message>
<location filename="../forms/signverifymessagedialog.ui" line="+14"/>
<source>Signatures - Sign / Verify a Message</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+13"/>
<location line="+124"/>
<source>&Sign Message</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-118"/>
<source>You can sign messages with your addresses to prove you own them. Be careful not to sign anything vague, as phishing attacks may try to trick you into signing your identity over to them. Only sign fully-detailed statements you agree to.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+18"/>
<source>The address to sign the message with (e.g. LimitedCoinSamp1eAddressXXXXSST9Ap)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+10"/>
<location line="+203"/>
<source>Choose an address from the address book</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-193"/>
<location line="+203"/>
<source>Alt+A</source>
<translation>Alt+J</translation>
</message>
<message>
<location line="-193"/>
<source>Paste address from clipboard</source>
<translation>Tempel alamat dari salinan</translation>
</message>
<message>
<location line="+10"/>
<source>Alt+P</source>
<translation>Alt+B</translation>
</message>
<message>
<location line="+12"/>
<source>Enter the message you want to sign here</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+24"/>
<source>Copy the current signature to the system clipboard</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+21"/>
<source>Sign the message to prove you own this LimitedCoin address</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+17"/>
<source>Reset all sign message fields</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<location line="+146"/>
<source>Clear &All</source>
<translation>Hapus %Semua</translation>
</message>
<message>
<location line="-87"/>
<location line="+70"/>
<source>&Verify Message</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-64"/>
<source>Enter the signing address, message (ensure you copy line breaks, spaces, tabs, etc. exactly) and signature below to verify the message. Be careful not to read more into the signature than what is in the signed message itself, to avoid being tricked by a man-in-the-middle attack.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+21"/>
<source>The address the message was signed with (e.g. LimitedCoinSamp1eAddressXXXXSST9Ap)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+40"/>
<source>Verify the message to ensure it was signed with the specified LimitedCoin address</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+17"/>
<source>Reset all verify message fields</source>
<translation type="unfinished"/>
</message>
<message>
<location filename="../signverifymessagedialog.cpp" line="+27"/>
<location line="+3"/>
<source>Enter a LimitedCoin address (e.g. LimitedCoinSamp1eAddressXXXXSST9Ap)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-2"/>
<source>Click "Sign Message" to generate signature</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>Enter LimitedCoin signature</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+82"/>
<location line="+81"/>
<source>The entered address is invalid.</source>
<translation>Alamat yang dimasukkan tidak sesuai.</translation>
</message>
<message>
<location line="-81"/>
<location line="+8"/>
<location line="+73"/>
<location line="+8"/>
<source>Please check the address and try again.</source>
<translation>Silahkan periksa alamat dan coba lagi.</translation>
</message>
<message>
<location line="-81"/>
<location line="+81"/>
<source>The entered address does not refer to a key.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-73"/>
<source>Wallet unlock was cancelled.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+8"/>
<source>Private key for the entered address is not available.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+12"/>
<source>Message signing failed.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+5"/>
<source>Message signed.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+59"/>
<source>The signature could not be decoded.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+0"/>
<location line="+13"/>
<source>Please check the signature and try again.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+0"/>
<source>The signature did not match the message digest.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+7"/>
<source>Message verification failed.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+5"/>
<source>Message verified.</source>
<translation type="unfinished"/>
</message>
</context>
<context>
<name>TransactionDesc</name>
<message>
<location filename="../transactiondesc.cpp" line="+19"/>
<source>Open until %1</source>
<translation>Buka hingga %1</translation>
</message>
<message numerus="yes">
<location line="-2"/>
<source>Open for %n block(s)</source>
<translation type="unfinished"><numerusform></numerusform></translation>
</message>
<message>
<location line="+8"/>
<source>conflicted</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+2"/>
<source>%1/offline</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+2"/>
<source>%1/unconfirmed</source>
<translation>%1/tidak terkonfirmasi</translation>
</message>
<message>
<location line="+2"/>
<source>%1 confirmations</source>
<translation>%1 konfirmasi</translation>
</message>
<message>
<location line="+18"/>
<source>Status</source>
<translation>Status</translation>
</message>
<message numerus="yes">
<location line="+7"/>
<source>, broadcast through %n node(s)</source>
<translation type="unfinished"><numerusform></numerusform></translation>
</message>
<message>
<location line="+4"/>
<source>Date</source>
<translation>Tanggal</translation>
</message>
<message>
<location line="+7"/>
<source>Source</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+0"/>
<source>Generated</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+5"/>
<location line="+17"/>
<source>From</source>
<translation>Dari</translation>
</message>
<message>
<location line="+1"/>
<location line="+22"/>
<location line="+58"/>
<source>To</source>
<translation>Untuk</translation>
</message>
<message>
<location line="-77"/>
<location line="+2"/>
<source>own address</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-2"/>
<source>label</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+37"/>
<location line="+12"/>
<location line="+45"/>
<location line="+17"/>
<location line="+30"/>
<source>Credit</source>
<translation type="unfinished"/>
</message>
<message numerus="yes">
<location line="-102"/>
<source>matures in %n more block(s)</source>
<translation type="unfinished"><numerusform></numerusform></translation>
</message>
<message>
<location line="+2"/>
<source>not accepted</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+44"/>
<location line="+8"/>
<location line="+15"/>
<location line="+30"/>
<source>Debit</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-39"/>
<source>Transaction fee</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+16"/>
<source>Net amount</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+6"/>
<source>Message</source>
<translation>Pesan:</translation>
</message>
<message>
<location line="+2"/>
<source>Comment</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+2"/>
<source>Transaction ID</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>Generated coins must mature 510 blocks before they can be spent. When you generated this block, it was broadcast to the network to be added to the block chain. If it fails to get into the chain, its state will change to "not accepted" and it won't be spendable. This may occasionally happen if another node generates a block within a few seconds of yours.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+7"/>
<source>Debug information</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+8"/>
<source>Transaction</source>
<translation>Transaksi</translation>
</message>
<message>
<location line="+5"/>
<source>Inputs</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+23"/>
<source>Amount</source>
<translation>Jumlah</translation>
</message>
<message>
<location line="+1"/>
<source>true</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+0"/>
<source>false</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-211"/>
<source>, has not been successfully broadcast yet</source>
<translation>, belum berhasil disiarkan</translation>
</message>
<message>
<location line="+35"/>
<source>unknown</source>
<translation>tidak diketahui</translation>
</message>
</context>
<context>
<name>TransactionDescDialog</name>
<message>
<location filename="../forms/transactiondescdialog.ui" line="+14"/>
<source>Transaction details</source>
<translation>Rincian transaksi</translation>
</message>
<message>
<location line="+6"/>
<source>This pane shows a detailed description of the transaction</source>
<translation>Jendela ini menampilkan deskripsi rinci dari transaksi tersebut</translation>
</message>
</context>
<context>
<name>TransactionTableModel</name>
<message>
<location filename="../transactiontablemodel.cpp" line="+226"/>
<source>Date</source>
<translation>Tanggal</translation>
</message>
<message>
<location line="+0"/>
<source>Type</source>
<translation>Jenis</translation>
</message>
<message>
<location line="+0"/>
<source>Address</source>
<translation>Alamat</translation>
</message>
<message>
<location line="+0"/>
<source>Amount</source>
<translation>Jumlah</translation>
</message>
<message>
<location line="+60"/>
<source>Open until %1</source>
<translation>Buka hingga %1</translation>
</message>
<message>
<location line="+12"/>
<source>Confirmed (%1 confirmations)</source>
<translation>Terkonfirmasi (%1 konfirmasi)</translation>
</message>
<message numerus="yes">
<location line="-15"/>
<source>Open for %n more block(s)</source>
<translation type="unfinished"><numerusform></numerusform></translation>
</message>
<message>
<location line="+6"/>
<source>Offline</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>Unconfirmed</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>Confirming (%1 of %2 recommended confirmations)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+6"/>
<source>Conflicted</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>Immature (%1 confirmations, will be available after %2)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>This block was not received by any other nodes and will probably not be accepted!</source>
<translation>Blok ini tidak diterima oleh node lainnya dan kemungkinan tidak akan diterima!</translation>
</message>
<message>
<location line="+3"/>
<source>Generated but not accepted</source>
<translation>Terbuat tetapi tidak diterima</translation>
</message>
<message>
<location line="+42"/>
<source>Received with</source>
<translation>Diterima dengan</translation>
</message>
<message>
<location line="+2"/>
<source>Received from</source>
<translation>Diterima dari</translation>
</message>
<message>
<location line="+3"/>
<source>Sent to</source>
<translation>Terkirim ke</translation>
</message>
<message>
<location line="+2"/>
<source>Payment to yourself</source>
<translation>Pembayaran ke Anda sendiri</translation>
</message>
<message>
<location line="+2"/>
<source>Mined</source>
<translation>Tertambang</translation>
</message>
<message>
<location line="+38"/>
<source>(n/a)</source>
<translation>(t/s)</translation>
</message>
<message>
<location line="+190"/>
<source>Transaction status. Hover over this field to show number of confirmations.</source>
<translation>Status transaksi. Arahkan ke bagian ini untuk menampilkan jumlah konfrimasi.</translation>
</message>
<message>
<location line="+2"/>
<source>Date and time that the transaction was received.</source>
<translation>Tanggal dan waktu transaksi tersebut diterima.</translation>
</message>
<message>
<location line="+2"/>
<source>Type of transaction.</source>
<translation>Jenis transaksi.</translation>
</message>
<message>
<location line="+2"/>
<source>Destination address of transaction.</source>
<translation>Alamat tujuan dari transaksi.</translation>
</message>
<message>
<location line="+2"/>
<source>Amount removed from or added to balance.</source>
<translation>Jumlah terbuang dari atau ditambahkan ke saldo.</translation>
</message>
</context>
<context>
<name>TransactionView</name>
<message>
<location filename="../transactionview.cpp" line="+55"/>
<location line="+16"/>
<source>All</source>
<translation>Semua</translation>
</message>
<message>
<location line="-15"/>
<source>Today</source>
<translation>Hari ini</translation>
</message>
<message>
<location line="+1"/>
<source>This week</source>
<translation>Minggu ini</translation>
</message>
<message>
<location line="+1"/>
<source>This month</source>
<translation>Bulan ini</translation>
</message>
<message>
<location line="+1"/>
<source>Last month</source>
<translation>Bulan kemarin</translation>
</message>
<message>
<location line="+1"/>
<source>This year</source>
<translation>Tahun ini</translation>
</message>
<message>
<location line="+1"/>
<source>Range...</source>
<translation>Jarak...</translation>
</message>
<message>
<location line="+11"/>
<source>Received with</source>
<translation>DIterima dengan</translation>
</message>
<message>
<location line="+2"/>
<source>Sent to</source>
<translation>Terkirim ke</translation>
</message>
<message>
<location line="+2"/>
<source>To yourself</source>
<translation>Ke Anda sendiri</translation>
</message>
<message>
<location line="+1"/>
<source>Mined</source>
<translation>Ditambang</translation>
</message>
<message>
<location line="+1"/>
<source>Other</source>
<translation>Lainnya</translation>
</message>
<message>
<location line="+7"/>
<source>Enter address or label to search</source>
<translation>Masukkan alamat atau label untuk mencari</translation>
</message>
<message>
<location line="+7"/>
<source>Min amount</source>
<translation>Jumlah min</translation>
</message>
<message>
<location line="+34"/>
<source>Copy address</source>
<translation>Salin alamat</translation>
</message>
<message>
<location line="+1"/>
<source>Copy label</source>
<translation>Salin label</translation>
</message>
<message>
<location line="+1"/>
<source>Copy amount</source>
<translation>Salin jumlah</translation>
</message>
<message>
<location line="+1"/>
<source>Copy transaction ID</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Edit label</source>
<translation>Ubah label</translation>
</message>
<message>
<location line="+1"/>
<source>Show transaction details</source>
<translation>Tampilkan rincian transaksi</translation>
</message>
<message>
<location line="+144"/>
<source>Export Transaction Data</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Comma separated file (*.csv)</source>
<translation>Berkas CSV (*.csv)</translation>
</message>
<message>
<location line="+8"/>
<source>Confirmed</source>
<translation>Terkonfirmasi</translation>
</message>
<message>
<location line="+1"/>
<source>Date</source>
<translation>Tanggal</translation>
</message>
<message>
<location line="+1"/>
<source>Type</source>
<translation>Jenis</translation>
</message>
<message>
<location line="+1"/>
<source>Label</source>
<translation>Label</translation>
</message>
<message>
<location line="+1"/>
<source>Address</source>
<translation>Alamat</translation>
</message>
<message>
<location line="+1"/>
<source>Amount</source>
<translation>Jumlah</translation>
</message>
<message>
<location line="+1"/>
<source>ID</source>
<translation>ID</translation>
</message>
<message>
<location line="+4"/>
<source>Error exporting</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+0"/>
<source>Could not write to file %1.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+100"/>
<source>Range:</source>
<translation>Jarak:</translation>
</message>
<message>
<location line="+8"/>
<source>to</source>
<translation>ke</translation>
</message>
</context>
<context>
<name>WalletModel</name>
<message>
<location filename="../walletmodel.cpp" line="+206"/>
<source>Sending...</source>
<translation type="unfinished"/>
</message>
</context>
<context>
<name>bitcoin-core</name>
<message>
<location filename="../bitcoinstrings.cpp" line="+33"/>
<source>LimitedCoin version</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Usage:</source>
<translation>Penggunaan:</translation>
</message>
<message>
<location line="+1"/>
<source>Send command to -server or limitedcoind</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>List commands</source>
<translation>Daftar perintah</translation>
</message>
<message>
<location line="+1"/>
<source>Get help for a command</source>
<translation>Dapatkan bantuan untuk perintah</translation>
</message>
<message>
<location line="+2"/>
<source>Options:</source>
<translation>Pilihan:</translation>
</message>
<message>
<location line="+2"/>
<source>Specify configuration file (default: LimitedCoin.conf)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Specify pid file (default: limitedcoind.pid)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+2"/>
<source>Specify wallet file (within data directory)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-1"/>
<source>Specify data directory</source>
<translation>Tentukan direktori data</translation>
</message>
<message>
<location line="+2"/>
<source>Set database cache size in megabytes (default: 25)</source>
<translation>Atur ukuran tembolok dalam megabyte (standar: 25)</translation>
</message>
<message>
<location line="+1"/>
<source>Set database disk log size in megabytes (default: 100)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+6"/>
<source>Listen for connections on <port> (default: 15714 or testnet: 25714)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Maintain at most <n> connections to peers (default: 125)</source>
<translation>Mengatur hubungan paling banyak <n> ke peer (standar: 125)</translation>
</message>
<message>
<location line="+3"/>
<source>Connect to a node to retrieve peer addresses, and disconnect</source>
<translation>Hubungkan ke node untuk menerima alamat peer, dan putuskan</translation>
</message>
<message>
<location line="+1"/>
<source>Specify your own public address</source>
<translation>Tentukan alamat publik Anda sendiri</translation>
</message>
<message>
<location line="+5"/>
<source>Bind to given address. Use [host]:port notation for IPv6</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+2"/>
<source>Stake your coins to support network and gain reward (default: 1)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+5"/>
<source>Threshold for disconnecting misbehaving peers (default: 100)</source>
<translation>Batas untuk memutuskan peer buruk (standar: 100)</translation>
</message>
<message>
<location line="+1"/>
<source>Number of seconds to keep misbehaving peers from reconnecting (default: 86400)</source>
<translation>Jumlah kedua untuk menjaga peer buruk dari hubung-ulang (standar: 86400)</translation>
</message>
<message>
<location line="-44"/>
<source>An error occurred while setting up the RPC port %u for listening on IPv4: %s</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+51"/>
<source>Detach block and address databases. Increases shutdown time (default: 0)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+109"/>
<source>Error: The transaction was rejected. This might happen if some of the coins in your wallet were already spent, such as if you used a copy of wallet.dat and coins were spent in the copy but not marked as spent here.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-5"/>
<source>Error: This transaction requires a transaction fee of at least %s because of its amount, complexity, or use of recently received funds </source>
<translation type="unfinished"/>
</message>
<message>
<location line="-87"/>
<source>Listen for JSON-RPC connections on <port> (default: 15715 or testnet: 25715)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-11"/>
<source>Accept command line and JSON-RPC commands</source>
<translation>Menerima perintah baris perintah dan JSON-RPC</translation>
</message>
<message>
<location line="+101"/>
<source>Error: Transaction creation failed </source>
<translation type="unfinished"/>
</message>
<message>
<location line="-5"/>
<source>Error: Wallet locked, unable to create transaction </source>
<translation type="unfinished"/>
</message>
<message>
<location line="-8"/>
<source>Importing blockchain data file.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Importing bootstrap blockchain data file.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-88"/>
<source>Run in the background as a daemon and accept commands</source>
<translation>Berjalan dibelakang sebagai daemin dan menerima perintah</translation>
</message>
<message>
<location line="+1"/>
<source>Use the test network</source>
<translation>Gunakan jaringan uji</translation>
</message>
<message>
<location line="-24"/>
<source>Accept connections from outside (default: 1 if no -proxy or -connect)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-38"/>
<source>An error occurred while setting up the RPC port %u for listening on IPv6, falling back to IPv4: %s</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+117"/>
<source>Error initializing database environment %s! To recover, BACKUP THAT DIRECTORY, then remove everything from it except for wallet.dat.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-20"/>
<source>Set maximum size of high-priority/low-fee transactions in bytes (default: 27000)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+11"/>
<source>Warning: -paytxfee is set very high! This is the transaction fee you will pay if you send a transaction.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+61"/>
<source>Warning: Please check that your computer's date and time are correct! If your clock is wrong LimitedCoin will not work properly.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-31"/>
<source>Warning: error reading wallet.dat! All keys read correctly, but transaction data or address book entries might be missing or incorrect.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-18"/>
<source>Warning: wallet.dat corrupt, data salvaged! Original wallet.dat saved as wallet.{timestamp}.bak in %s; if your balance or transactions are incorrect you should restore from a backup.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-30"/>
<source>Attempt to recover private keys from a corrupt wallet.dat</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+4"/>
<source>Block creation options:</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-62"/>
<source>Connect only to the specified node(s)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+4"/>
<source>Discover own IP address (default: 1 when listening and no -externalip)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+94"/>
<source>Failed to listen on any port. Use -listen=0 if you want this.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-90"/>
<source>Find peers using DNS lookup (default: 1)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+5"/>
<source>Sync checkpoints policy (default: strict)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+83"/>
<source>Invalid -tor address: '%s'</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+4"/>
<source>Invalid amount for -reservebalance=<amount></source>
<translation type="unfinished"/>
</message>
<message>
<location line="-82"/>
<source>Maximum per-connection receive buffer, <n>*1000 bytes (default: 5000)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Maximum per-connection send buffer, <n>*1000 bytes (default: 1000)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-16"/>
<source>Only connect to nodes in network <net> (IPv4, IPv6 or Tor)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+28"/>
<source>Output extra debugging information. Implies all other -debug* options</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Output extra network debugging information</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Prepend debug output with timestamp</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+35"/>
<source>SSL options: (see the Bitcoin Wiki for SSL setup instructions)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-74"/>
<source>Select the version of socks proxy to use (4-5, default: 5)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+41"/>
<source>Send trace/debug info to console instead of debug.log file</source>
<translation>Kirim info lacak/debug ke konsol sebaliknya dari berkas debug.log</translation>
</message>
<message>
<location line="+1"/>
<source>Send trace/debug info to debugger</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+28"/>
<source>Set maximum block size in bytes (default: 250000)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-1"/>
<source>Set minimum block size in bytes (default: 0)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-29"/>
<source>Shrink debug.log file on client startup (default: 1 when no -debug)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-42"/>
<source>Specify connection timeout in milliseconds (default: 5000)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+109"/>
<source>Unable to sign checkpoint, wrong checkpointkey?
</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-80"/>
<source>Use UPnP to map the listening port (default: 0)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-1"/>
<source>Use UPnP to map the listening port (default: 1 when listening)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-25"/>
<source>Use proxy to reach tor hidden services (default: same as -proxy)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+42"/>
<source>Username for JSON-RPC connections</source>
<translation>Nama pengguna untuk hubungan JSON-RPC</translation>
</message>
<message>
<location line="+47"/>
<source>Verifying database integrity...</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+57"/>
<source>WARNING: syncronized checkpoint violation detected, but skipped!</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Warning: Disk space is low!</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-2"/>
<source>Warning: This version is obsolete, upgrade required!</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-48"/>
<source>wallet.dat corrupt, salvage failed</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-54"/>
<source>Password for JSON-RPC connections</source>
<translation>Kata sandi untuk hubungan JSON-RPC</translation>
</message>
<message>
<location line="-84"/>
<source>%s, you must set a rpcpassword in the configuration file:
%s
It is recommended you use the following random password:
rpcuser=LimitedCoinrpc
rpcpassword=%s
(you do not need to remember this password)
The username and password MUST NOT be the same.
If the file does not exist, create it with owner-readable-only file permissions.
It is also recommended to set alertnotify so you are notified of problems;
for example: alertnotify=echo %%s | mail -s "LimitedCoin Alert" admin@foo.com
</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+51"/>
<source>Find peers using internet relay chat (default: 0)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+5"/>
<source>Sync time with other nodes. Disable if time on your system is precise e.g. syncing with NTP (default: 1)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+15"/>
<source>When creating transactions, ignore inputs with value less than this (default: 0.01)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+16"/>
<source>Allow JSON-RPC connections from specified IP address</source>
<translation>Izinkan hubungan JSON-RPC dari alamat IP yang ditentukan</translation>
</message>
<message>
<location line="+1"/>
<source>Send commands to node running on <ip> (default: 127.0.0.1)</source>
<translation>Kirim perintah ke node berjalan pada <ip> (standar: 127.0.0.1)</translation>
</message>
<message>
<location line="+1"/>
<source>Execute command when the best block changes (%s in cmd is replaced by block hash)</source>
<translation>Menjalankan perintah ketika perubahan blok terbaik (%s dalam cmd digantikan oleh hash blok)</translation>
</message>
<message>
<location line="+3"/>
<source>Execute command when a wallet transaction changes (%s in cmd is replaced by TxID)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>Require a confirmations for change (default: 0)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Enforce transaction scripts to use canonical PUSH operators (default: 1)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+2"/>
<source>Execute command when a relevant alert is received (%s in cmd is replaced by message)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>Upgrade wallet to latest format</source>
<translation>Perbarui dompet ke format terbaru</translation>
</message>
<message>
<location line="+1"/>
<source>Set key pool size to <n> (default: 100)</source>
<translation>Kirim ukuran kolam kunci ke <n> (standar: 100)</translation>
</message>
<message>
<location line="+1"/>
<source>Rescan the block chain for missing wallet transactions</source>
<translation>Pindai ulang rantai-blok untuk transaksi dompet yang hilang</translation>
</message>
<message>
<location line="+2"/>
<source>How many blocks to check at startup (default: 2500, 0 = all)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>How thorough the block verification is (0-6, default: 1)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Imports blocks from external blk000?.dat file</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+8"/>
<source>Use OpenSSL (https) for JSON-RPC connections</source>
<translation>Gunakan OpenSSL (https) untuk hubungan JSON-RPC</translation>
</message>
<message>
<location line="+1"/>
<source>Server certificate file (default: server.cert)</source>
<translation>Berkas sertifikat server (standar: server.cert)</translation>
</message>
<message>
<location line="+1"/>
<source>Server private key (default: server.pem)</source>
<translation>Kunci pribadi server (standar: server.pem)</translation>
</message>
<message>
<location line="+1"/>
<source>Acceptable ciphers (default: TLSv1+HIGH:!SSLv2:!aNULL:!eNULL:!AH:!3DES:@STRENGTH)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+53"/>
<source>Error: Wallet unlocked for staking only, unable to create transaction.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+18"/>
<source>WARNING: Invalid checkpoint found! Displayed transactions may not be correct! You may need to upgrade, or notify developers.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-158"/>
<source>This help message</source>
<translation>Pesan bantuan ini</translation>
</message>
<message>
<location line="+95"/>
<source>Wallet %s resides outside data directory %s.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Cannot obtain a lock on data directory %s. LimitedCoin is probably already running.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-98"/>
<source>LimitedCoin</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+140"/>
<source>Unable to bind to %s on this computer (bind returned error %d, %s)</source>
<translation>Tidak dapat mengikat ke %s dengan komputer ini (ikatan gagal %d, %s)</translation>
</message>
<message>
<location line="-130"/>
<source>Connect through socks proxy</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>Allow DNS lookups for -addnode, -seednode and -connect</source>
<translation>Izinkan peninjauan DNS untuk -addnote, -seednode dan -connect</translation>
</message>
<message>
<location line="+122"/>
<source>Loading addresses...</source>
<translation>Memuat alamat...</translation>
</message>
<message>
<location line="-15"/>
<source>Error loading blkindex.dat</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+2"/>
<source>Error loading wallet.dat: Wallet corrupted</source>
<translation>Gagal memuat wallet.dat: Dompet rusak</translation>
</message>
<message>
<location line="+4"/>
<source>Error loading wallet.dat: Wallet requires newer version of LimitedCoin</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Wallet needed to be rewritten: restart LimitedCoin to complete</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Error loading wallet.dat</source>
<translation>Gagal memuat wallet.dat</translation>
</message>
<message>
<location line="-16"/>
<source>Invalid -proxy address: '%s'</source>
<translation>Alamat -proxy salah: '%s'</translation>
</message>
<message>
<location line="-1"/>
<source>Unknown network specified in -onlynet: '%s'</source>
<translation>Jaringan tidak diketahui yang ditentukan dalam -onlynet: '%s'</translation>
</message>
<message>
<location line="-1"/>
<source>Unknown -socks proxy version requested: %i</source>
<translation>Diminta versi proxy -socks tidak diketahui: %i</translation>
</message>
<message>
<location line="+4"/>
<source>Cannot resolve -bind address: '%s'</source>
<translation>Tidak dapat menyelesaikan alamat -bind: '%s'</translation>
</message>
<message>
<location line="+2"/>
<source>Cannot resolve -externalip address: '%s'</source>
<translation>Tidak dapat menyelesaikan alamat -externalip: '%s'</translation>
</message>
<message>
<location line="-24"/>
<source>Invalid amount for -paytxfee=<amount>: '%s'</source>
<translation>Jumlah salah untuk -paytxfee=<amount>: '%s'</translation>
</message>
<message>
<location line="+44"/>
<source>Error: could not start node</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+11"/>
<source>Sending...</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+5"/>
<source>Invalid amount</source>
<translation>Jumlah salah</translation>
</message>
<message>
<location line="+1"/>
<source>Insufficient funds</source>
<translation>Saldo tidak mencukupi</translation>
</message>
<message>
<location line="-34"/>
<source>Loading block index...</source>
<translation>Memuat indeks blok...</translation>
</message>
<message>
<location line="-103"/>
<source>Add a node to connect to and attempt to keep the connection open</source>
<translation>Tambahkan node untuk dihubungkan dan upaya untuk menjaga hubungan tetap terbuka</translation>
</message>
<message>
<location line="+122"/>
<source>Unable to bind to %s on this computer. LimitedCoin is probably already running.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-97"/>
<source>Fee per KB to add to transactions you send</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+55"/>
<source>Invalid amount for -mininput=<amount>: '%s'</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+25"/>
<source>Loading wallet...</source>
<translation>Memuat dompet...</translation>
</message>
<message>
<location line="+8"/>
<source>Cannot downgrade wallet</source>
<translation>Tidak dapat menurunkan versi dompet</translation>
</message>
<message>
<location line="+1"/>
<source>Cannot initialize keypool</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Cannot write default address</source>
<translation>Tidak dapat menyimpan alamat standar</translation>
</message>
<message>
<location line="+1"/>
<source>Rescanning...</source>
<translation>Memindai ulang...</translation>
</message>
<message>
<location line="+5"/>
<source>Done loading</source>
<translation>Memuat selesai</translation>
</message>
<message>
<location line="-167"/>
<source>To use the %s option</source>
<translation>Gunakan pilihan %s</translation>
</message>
<message>
<location line="+14"/>
<source>Error</source>
<translation>Gagal</translation>
</message>
<message>
<location line="+6"/>
<source>You must set rpcpassword=<password> in the configuration file:
%s
If the file does not exist, create it with owner-readable-only file permissions.</source>
<translation>Anda harus mengatur rpcpassword=<kata sandi> dalam berkas konfigurasi:
%s
Jika berkas tidak ada, buatlah dengan permisi berkas hanya-dapat-dibaca-oleh-pemilik.</translation>
</message>
</context>
</TS> | mit |
fusioncharts/jslink | src/lib.js | 16534 | /**
* This module contains all the helper and library functions that are required by various modules of `jslink`.
* @module lib
*/
var E = '',
SPC = ' ',
BLOCK = 'Block',
ASTERISK = '*',
PLURAL_SUFFIX = 's',
STRING = 'string',
OBJECT = 'object',
FUNCTION = 'function',
SLASH = '/',
DOTSLASH = './',
fs = require('fs'),
pathUtil = require('path'),
lib;
module.exports = lib = /** @lends module:lib */ {
/**
* Adds the character `s` to the contents of the `word` parameter. This method is helpful to show messages that are
* in tune with the value of a number.
*
* @param {number} num
* @param {string} word
* @returns {string}
*/
plural: function (num, word) {
return num + SPC + ((num > 1 || num < -1) && (word += PLURAL_SUFFIX), word);
},
/**
* Simple format function. Replaces construction of type โ`{<number>}`โ to the corresponding argument.
*
* @param {string} token
* @param {...string} params
* @returns {string}
*/
format: function (token, params) {
var args = Array.isArray(params) ? [0].concat(params) : arguments;
token && (typeof token === STRING) && args.length - 1 && (token = token.replace(/\{(\d+)\}/g, function (
str, i) {
return args[++i] === null ? E : args[i];
}));
return token || E;
},
/**
* Replaces a block of array of strings with a replacement array of string. In case replacement array is shorter,
* it fills with default character.
*
* @param {Array} array
* @param {string|Array} replacement
* @param {Array<number>} [loc]
* @param {string=} [defaultChar]
* @returns {Array}
*/
fillStringArray: function (array, replacement, loc, defaultChar) {
var i,
j,
ii,
jj;
// If replacement is a string then convert to an array.
if (!Array.isArray(replacement)) {
replacement = replacement && replacement.toString && replacement && replacement.toString().split(E) || [];
}
for (i = loc[0], ii = loc[1], j = 0, jj = replacement.length; i < ii; i++, j++) {
array[i] = (j < jj ? replacement[j] : (defaultChar || array[i]));
}
return array;
},
/**
* [trimStringArray description]
* @param {[type]} array [description]
* @param {Array<number>} loc
* @param {RegExp} regex
* @returns {Array}
*/
trimStringArray: function (array, loc, regex) {
var i,
ii;
// left trim
for (i = loc[0] - 1, ii = 0; i >= ii; i--) {
if ((regex || /[\s\r\n]/).test(array[i])) {
array[i] = E;
}
else {
break;
}
}
// right trim
for (i = loc[1] + 1, ii = array.length; i < ii; i++) {
if ((regex || /[\s\r\n]/).test(array[i])) {
array[i] = E;
}
else {
break;
}
}
return array;
},
/**
* Get string from string-like objects.
*
* @param {*} str
* @returns {string}
*
* @throws {TypeError} If the `str` parameter passed is `null` or `undefined` or does not have a `toString` method.
*/
stringLike: function (str) {
// Module name has to be valid and cannot be blank.
if (!(str ? typeof str.toString === FUNCTION : typeof str === STRING)) {
throw new TypeError('Not a valid string: ' + str);
}
// Sanitise the name for further processing - like trim it!
return str.toString().trim();
},
/**
* Copy all properties of source to sink.
*
* @param {object} sink
* @param {object} source
* @returns {object}
*/
copy: function (sink, source) {
for (var prop in source) {
sink[prop] = source[prop];
}
return sink;
},
/**
* Copies all new properties from source to sink.
*
* @param {object} sink
* @param {object} source
* @returns {object}
*/
fill: function (sink, source) {
for (var prop in source) {
!sink.hasOwnProperty(prop) && (sink[prop] = source[prop]);
}
return sink;
},
/**
* Converts an arguments array (usually from CLI) in format similar to Closure Compiler and returns an object of
* options.
*
* @param {Array} args
* @param {string=} [don] - The default option to which to append all stray options
* @returns {object}
*/
argsArray2Object: function (args, don) {
var out = {},
replacer,
arg;
// This function is sent to the .replace function on argument values in order extract its content as key=value
// pairs. Defined here to prevent repeated definition within loop.
replacer = function ($glob, $1, $2) {
// In case the value is undefined, we set it to boolean true
($2 === undefined) && ($2 = true);
// If the option already exists, push to the values array otherwise create a new values array. In case
// this option was discovered for the first time, we pust it as a single item of an array.
out.hasOwnProperty($1) && (out[$1].push ? out[$1] : (out[$1] = [out[$1]])).push($2) || (out[$1] =
$2);
};
// Loop through arguments and prepare options object.
while (arg = args.shift()) {
if (/^\-\-[^\-]*/g.test(arg)) {
arg.replace(/^\-\-([a-z]*)\=?([\s\S]*)?$/i, replacer);
}
// In case it is not an option object, we add it to default option name.
else if (don) {
out.hasOwnProperty(don) && (out[don].push ? out[don] : (out[don] = [out[don]])).push(arg) ||
(out[don] = arg);
}
}
return out;
},
/**
* Checks whether a path starts with or contains a hidden file or a folder.
*
* @param {string} source - The path of the file that needs to be validated.
* @returns {boolean} `true` if the source is blacklisted and otherwise `false`.
*/
isUnixHiddenPath: function (path) {
return (/(^|.\/)\.+[^\/\.]/g).test(path);
},
/**
* Tests whether a path is a directory or possibly a file reference.
*
* @param {string} path
* @returns {boolean}
*/
isUnixDirectory: function (path) {
return (/(^\.{1,2}$)|(\/$)/).test(path);
},
/**
* Return the JSON data stored in a file.
*
* @param {string} path Is always relative
* @returns {object}
*/
readJSONFromFile: function (path) {
try {
path = DOTSLASH + path;
return JSON.parse(fs.readFileSync(path));
}
catch (error) {
throw new Error(lib.format('Unable to read file: {0}\n{1}', path, error));
}
},
/**
* Iterate over an object and convert all string properties of the object into native boolean values.
*
* @param {object} obj
* @param {Array} properties
* @returns {object}
*/
parseJSONBooleans: function (obj, properties) {
// Check whether parameters are valid
if ((typeof obj === OBJECT) && Array.isArray(properties) && properties.length) {
properties.forEach(function (prop) {
if (obj.hasOwnProperty(prop)) {
obj[prop] = !(/^\s*false\s*$/ig.test(obj[prop]));
}
});
}
return obj;
},
/**
* Caches function call returns
* @param {[type]} f function whose arguments cannot contain Objects and the return value is dependent on the
* arguments
* @param {[type]} scope the scope in which the function should be executed
* @returns {[type]} a cached function f which returns the cached value for same arguments
*/
cacher: function (f, scope) {
function cachedfunction() {
var arg = Array.prototype.slice.call(arguments, 0),
args = arg.join('\u2400'),
cache = cachedfunction.cache = cachedfunction.cache || {},
count = cachedfunction.count = cachedfunction.count || [],
i,
ii;
if (cache.hasOwnProperty(args)) {
for (i = 0, ii = count.length; i < ii; i++) {
if (count[i] === args) {
count.push(count.splice(i, 1)[0]);
break;
}
}
return cache[args];
}
count.length >= 1e3 && delete cache[count.shift()];
count.push(args);
cache[args] = f.apply(scope, arg);
return cache[args];
}
return cachedfunction;
},
/**
* Generate a directive parsing Regular Expression from a directive name
*
* @param {string} directive
* @returns {RegExp}
*/
getDirectivePattern: function (directive) {
return new RegExp(lib.format('\\@{0}[\\s\\n\\r]+([^\\@\\r\\n]*)', directive), 'ig');
},
/**
* Takes in a comment AST block as parameter and returns whether it is a valid jsdoc block
* @param {object} comment
* @param {boolean} ignoreignore
*/
isJSDocBlock: function (comment, ignoreIgnore) {
return !(comment.type !== BLOCK || comment.value.charAt() !== ASTERISK ||
((!ignoreIgnore) && /\@ignore[\@\s\r\n]?/ig.test(comment.value)));
},
/**
* Returns the keys of an object in a specific order and optionally filtered by a type.
*
* @param {[object} object
* @param {Array<string>} reference
* @param {RegExp=} [type]
* @returns {Array}
*/
orderedKeys: function (object, reference, type) {
var order = [],
flag = {};
// If there is no object, there is no order!
if (typeof object !== OBJECT) {
throw new Error('Cannot prepare ordered key for non-object variables.');
}
// Validate type parameter
if (!type || (typeof type.test !== FUNCTION)) {
type = /./g;
}
// Concatenate object keys and reference. Reference first and the prepare the final order array.
([].concat(reference).concat(Object.keys(object))).map(function (key) {
// add to the order only if not duplicate and exists in object
if (object.hasOwnProperty(key) && !flag[key] && type.test(typeof object[key])) {
this.push(key);
flag[key] = true;
}
}, order);
return order;
},
/* jshint maxcomplexity: 15 */
/**
* @todo reduce complexity of these functions.
*/
/**
* Procures a writeable file.
*
* @param {string} path
* @param {string} defaultPath
* @param {boolean=} [overwrite]
* @param {boolean=} [nocreate]
* @param {boolean=} [clear]
* @returns {string}
*/
writeableFile: function (path, defaultPath, overwrite, nocreate, clear) {
var originalPath = path; // store it for future references.
// In case path comes from cli input and is equal to boolean true, then proceed with default.
if (path === true) {
originalPath = path = defaultPath;
}
// Validate parameters so as to ensure that the path and the alternative defaults can be processed.
if (!path || !defaultPath) {
throw new TypeError('Path cannot be blank.');
}
else if (lib.isUnixDirectory(path)) {
throw new TypeError(lib.format('Path "{0}" cannot be a directory.', path));
}
else if (lib.isUnixHiddenPath(path)) {
throw new TypeError(lib.format('Cannot output to hidden file "{0}".', path));
}
else if (lib.isUnixDirectory(defaultPath)) {
throw new TypeError('Path (default) cannot be a directory.');
}
// In case the output path is a directory, use the filename from default path.
if (lib.isUnixDirectory(path)) {
path += pathUtil.basename(defaultPath); // add file name if path is a directory
}
// Resolve the path to absolute reference
path = pathUtil.resolve(path.toString());
// If the path provided exists, the only check should be that it is a file and a not a directory. If its a
// directory, then append default file name;
if (fs.existsSync(path)) {
// In case the final file does point to an existing file, we need to check whether overwriting is permitted
// or not.
if (fs.statSync(path).isFile()) {
if (overwrite === false) {
throw new Error(lib.format('Cannot overwrite "{0}"', originalPath));
}
else if (clear) {
fs.writeFileSync(path, E);
}
}
// Otherwise... it is either a directory or the world's end!
else {
throw new TypeError(lib.format('The output path "{0}" does not point to a file.', originalPath));
}
}
// When file does not exist then we would need to create the directory tree (if provided and allowed)
else {
// Ensure that the path has a writeable folder (if permitted) till its parent directory.
lib.writeableFolder(pathUtil.dirname(path) + SLASH, pathUtil.dirname(defaultPath) + SLASH);
// We create the file so that it can be further used to write or append.
if (!nocreate) {
clear === true ? fs.writeFileSync(path, E) : fs.openSync(path, 'w');
}
}
return path; // the valid path
},
/**
* Takes in user provided path and returns a writeable path for the same.
*
* @param {string} path
* @param {string} default
* @returns {string}
*/
writeableFolder: function (path, defaultPath) {
var originalPath = path,
dirlist,
dir;
// In case path comes from cli input and is equal to boolean true, then proceed with default.
if (path === true) {
path = defaultPath;
}
// Validate parameters so as to ensure that the path and the alternative defaults can be processed.
if (!defaultPath) {
throw new TypeError('Path cannot be blank.');
}
else if (!path) {
path = defaultPath;
}
if (!lib.isUnixDirectory(path)) {
throw new TypeError(lib.format('Path "{0}" cannot be a file.'), path);
}
else if (lib.isUnixHiddenPath(path)) {
throw new TypeError(lib.format('Cannot output to hidden file "{0}".'), path);
}
else if (!lib.isUnixDirectory(defaultPath)) {
throw new TypeError('Path (default) cannot be a file.');
}
path = pathUtil.resolve(path.toString());
dirlist = [];
dir = path;
// Extract directories within the path that does not exist.
while (dir !== SLASH) {
if (fs.existsSync(dir)) {
// Check whether the last existing member of the dir tree is not a file.
if (!fs.statSync(dir).isDirectory()) {
throw new Error(lib.format('Cannot write to "{0}" since "{1}" is not a directory.',
originalPath, dir));
}
break;
}
dirlist.push(dir);
dir = pathUtil.dirname(dir);
}
// We now slowly create the directories recovered from the above loop.
while (dir = dirlist.pop()) {
fs.mkdirSync(dir); // let any error bubble.
}
return (/\/$/).test(path) ? path : path + SLASH;
},
/**
* This function outputs to console based on jslink global verbose mode
* @param {string} what - The message to log.
* @param {boolean=} [important=] - Show message even when not verbose but hide when quiet
*/
log: function (what, important) {
(important && !global.jslinkQuiet || global.jslinkVerbose) &&
(what = (typeof what === FUNCTION ? what() : what.toString())) && console.log(what);
}
};
| mit |
Prior99/coffee | lib/cookies.js | 1445 | /*
* Will set a new cookie to send in HTTP further on
*/
function setCookie(name, value, days)
{
if(days) //If an amount of days was specified the cookie will have a "best-before-date", if it exceeded, the cookie will be deleted
{
var date = new Date(); //Supplied time is relative to now
date.setTime(date.getTime() + (days * 24 * 60 * 60 * 1000)); //Calculate real time as GMTString
var expires = "; expires="+date.toGMTString();
}
else var expires = ""; //Else it will never expire
document.cookie = name + "=" + value + expires + "; path=/"; //Set cookie to DOM
}
/*
* Will return the value of the specified cookie
*/
function getCookie(name)
{
var nameEQ = name + "=";
var ca = document.cookie.split(';'); //Split at ; as the cookie ist store this way: "foo=blah;expiration;path=/foo/blah"
for(var i = 0;i < ca.length;i++) //Go through all elements in the array
{
var c = ca[i];
while (c.charAt(0) == ' ') c = c.substring(1, c.length); //Trim whitespaces
if(c.indexOf(nameEQ) == 0) {//If the value is empty after trimming or the original content, then it is a malformed cookie or a cookie without a value
return c.substring(nameEQ.length, c.length); //Only return if it is wellformed and has a value
}
}
return undefined; //If the cookie was not found
}
/*
* Will delete the specified cookie
* The cookie will no longer be transmitted via HTTP
*/
function deleteCookie(name)
{
setCookie(name, "", -1);
}
| mit |
eigenmethod/mol | row/demo/products/products.view.ts | 266 | namespace $.$$ {
export class $mol_row_demo_products extends $.$mol_row_demo_products {
products() {
return $mol_range2(id => this.Product(id), () => this.count())
}
@ $mol_mem_key
product_title(id: string) {
return $mol_stub_product_name()
}
}
}
| mit |
isaacseymour/prawn-svg | spec/prawn/svg/elements/style_spec.rb | 559 | require 'spec_helper'
describe Prawn::SVG::Elements::Style do
let(:svg) do
<<-SVG
<style>a
before>
x <![CDATA[ y
inside <>>
k ]]> j
after
z</style>
SVG
end
let(:document) { Prawn::SVG::Document.new(svg, [800, 600], {}) }
let(:element) { Prawn::SVG::Elements::Style.new(document, document.root, [], {}) }
it "correctly collects the style information in a <style> tag" do
expect(document.css_parser).to receive(:add_block!).with("a\n before>\n x y\n inside <>>\n k j\n after\nz")
element.process
end
end
| mit |
piotrek005/Library | vendor/sonata-project/admin-bundle/Tests/Form/FormMapperTest.php | 10043 | <?php
/*
* This file is part of the Sonata package.
*
* (c) Thomas Rabaix <thomas.rabaix@sonata-project.org>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Sonata\AdminBundle\Tests\Form;
use Sonata\AdminBundle\Form\FormMapper;
use Sonata\AdminBundle\Tests\Fixtures\Admin\CleanAdmin;
use Symfony\Component\Form\FormBuilder;
class FormMapperTest extends \PHPUnit_Framework_TestCase
{
/**
* @var \Sonata\AdminBundle\Builder\FormContractorInterface
*/
protected $contractor;
/**
* @var \Sonata\AdminBundle\Admin\AdminInterface
*/
protected $admin;
/**
* @var \Sonata\AdminBundle\Model\ModelManagerInterface
*/
protected $modelManager;
/**
* @var FormMapper
*/
protected $formMapper;
public function setUp()
{
$this->contractor = $this->getMock('Sonata\AdminBundle\Builder\FormContractorInterface');
$formFactory = $this->getMock('Symfony\Component\Form\FormFactoryInterface');
$eventDispatcher = $this->getMock('Symfony\Component\EventDispatcher\EventDispatcherInterface');
$formBuilder = new FormBuilder('test', 'stdClass', $eventDispatcher, $formFactory);
$this->admin = new CleanAdmin('code', 'class', 'controller');
$this->modelManager = $this->getMock('Sonata\AdminBundle\Model\ModelManagerInterface');
// php 5.3 BC
$fieldDescription = $this->getFieldDescriptionMock();
$this->modelManager->expects($this->any())
->method('getNewFieldDescriptionInstance')
->will($this->returnCallback(function($class, $name, array $options = array()) use ($fieldDescription) {
$fieldDescriptionClone = clone $fieldDescription;
$fieldDescriptionClone->setName($name);
$fieldDescriptionClone->setOptions($options);
return $fieldDescriptionClone;
}));
$this->admin->setModelManager($this->modelManager);
$labelTranslatorStrategy = $this->getMock('Sonata\AdminBundle\Translator\LabelTranslatorStrategyInterface');
$this->admin->setLabelTranslatorStrategy($labelTranslatorStrategy);
$this->formMapper = new FormMapper(
$this->contractor,
$formBuilder,
$this->admin
);
}
public function testWithNoOptions()
{
$this->formMapper->with('foobar');
$this->assertEquals(array('default' => array (
'collapsed' => false,
'class' => false,
'description' => false,
'translation_domain' => null,
'auto_created' => true,
'groups' => array('foobar'),
'tab' => true,
'name' => 'default'
)), $this->admin->getFormTabs());
$this->assertEquals(array('foobar' => array(
'collapsed' => false,
'class' => false,
'description' => false,
'translation_domain' => null,
'fields' => array (),
'name' => 'foobar'
)), $this->admin->getFormGroups());
}
public function testWithOptions()
{
$this->formMapper->with('foobar', array(
'translation_domain' => 'Foobar',
));
$this->assertEquals(array('foobar' => array(
'collapsed' => false,
'class' => false,
'description' => false,
'translation_domain' => 'Foobar',
'fields' => array (),
'name' => 'foobar'
)), $this->admin->getFormGroups());
$this->assertEquals(array('default' => array (
'collapsed' => false,
'class' => false,
'description' => false,
'translation_domain' => 'Foobar',
'auto_created' => true,
'groups' => array('foobar'),
'tab' => true,
'name' => 'default'
)), $this->admin->getFormTabs());
}
public function testWithFieldsCascadeTranslationDomain()
{
$this->contractor->expects($this->once())
->method('getDefaultOptions')
->will($this->returnValue(array()));
$this->formMapper->with('foobar', array(
'translation_domain' => 'Foobar'
))
->add('foo', 'bar')
->end();
$fieldDescription = $this->admin->getFormFieldDescription('foo');
$this->assertEquals('foo', $fieldDescription->getName());
$this->assertEquals('bar', $fieldDescription->getType());
$this->assertEquals('Foobar', $fieldDescription->getTranslationDomain());
$this->assertTrue($this->formMapper->has('foo'));
$this->assertEquals(array('default' => array (
'collapsed' => false,
'class' => false,
'description' => false,
'translation_domain' => 'Foobar',
'auto_created' => true,
'groups' => array ('foobar'),
'tab' => true,
'name' => 'default'
)), $this->admin->getFormTabs());
$this->assertEquals(array('foobar' => array(
'collapsed' => false,
'class' => false,
'description' => false,
'translation_domain' => 'Foobar',
'fields' => array(
'foo' => 'foo'
),
'name' => 'foobar'
)), $this->admin->getFormGroups());
}
public function testRemoveCascadeRemoveFieldFromFormGroup()
{
$this->formMapper->with('foo');
$this->formMapper->remove('foo');
}
public function testIfTrueApply()
{
$this->contractor->expects($this->once())
->method('getDefaultOptions')
->will($this->returnValue(array()));
$this->formMapper
->ifTrue(true)
->add('foo', 'bar')
->ifEnd()
;
$this->assertTrue($this->formMapper->has('foo'));
}
public function testIfTrueNotApply()
{
$this->formMapper
->ifTrue(false)
->add('foo', 'bar')
->ifEnd()
;
$this->assertFalse($this->formMapper->has('foo'));
}
public function testIfTrueCombination()
{
$this->contractor->expects($this->once())
->method('getDefaultOptions')
->will($this->returnValue(array()));
$this->formMapper
->ifTrue(false)
->add('foo', 'bar')
->ifEnd()
->add('baz', 'foobaz')
;
$this->assertFalse($this->formMapper->has('foo'));
$this->assertTrue($this->formMapper->has('baz'));
}
public function testIfFalseApply()
{
$this->contractor->expects($this->once())
->method('getDefaultOptions')
->will($this->returnValue(array()));
$this->formMapper
->ifFalse(false)
->add('foo', 'bar')
->ifEnd()
;
$this->assertTrue($this->formMapper->has('foo'));
}
public function testIfFalseNotApply()
{
$this->formMapper
->ifFalse(true)
->add('foo', 'bar')
->ifEnd()
;
$this->assertFalse($this->formMapper->has('foo'));
}
public function testIfFalseCombination()
{
$this->contractor->expects($this->once())
->method('getDefaultOptions')
->will($this->returnValue(array()));
$this->formMapper
->ifFalse(true)
->add('foo', 'bar')
->ifEnd()
->add('baz', 'foobaz')
;
$this->assertFalse($this->formMapper->has('foo'));
$this->assertTrue($this->formMapper->has('baz'));
}
/**
* @expectedException RuntimeException
* @expectedExceptionMessage Cannot nest ifTrue or ifFalse call
*/
public function testIfTrueNested()
{
$this->formMapper->ifTrue(true);
$this->formMapper->ifTrue(true);
}
/**
* @expectedException RuntimeException
* @expectedExceptionMessage Cannot nest ifTrue or ifFalse call
*/
public function testIfFalseNested()
{
$this->formMapper->ifFalse(false);
$this->formMapper->ifFalse(false);
}
/**
* @expectedException RuntimeException
* @expectedExceptionMessage Cannot nest ifTrue or ifFalse call
*/
public function testIfCombinationNested()
{
$this->formMapper->ifTrue(true);
$this->formMapper->ifFalse(false);
}
/**
* @expectedException RuntimeException
* @expectedExceptionMessage Cannot nest ifTrue or ifFalse call
*/
public function testIfFalseCombinationNested2()
{
$this->formMapper->ifFalse(false);
$this->formMapper->ifTrue(true);
}
/**
* @expectedException RuntimeException
* @expectedExceptionMessage Cannot nest ifTrue or ifFalse call
*/
public function testIfFalseCombinationNested3()
{
$this->formMapper->ifFalse(true);
$this->formMapper->ifTrue(false);
}
/**
* @expectedException RuntimeException
* @expectedExceptionMessage Cannot nest ifTrue or ifFalse call
*/
public function testIfFalseCombinationNested4()
{
$this->formMapper->ifTrue(false);
$this->formMapper->ifFalse(true);
}
private function getFieldDescriptionMock($name = null, $label = null, $translationDomain = null)
{
$fieldDescription = $this->getMockForAbstractClass('Sonata\AdminBundle\Admin\BaseFieldDescription');
if ($name !== null) {
$fieldDescription->setName($name);
}
if ($label !== null) {
$fieldDescription->setOption('label', $label);
}
if ($translationDomain !== null) {
$fieldDescription->setOption('translation_domain', $translationDomain);
}
return $fieldDescription;
}
}
| mit |
InversePalindrome/Memento-Mori | src/RoundNumber.cpp | 2238 | /*
Copyright (c) 2017 InversePalindrome
Memento Mori - RoundNumber.cpp
InversePalindrome.com
*/
#include "RoundNumber.hpp"
const std::array<std::pair<std::size_t, std::string>, 13u> RoundNumber::romanNumerals =
{
std::make_pair(1000, "M") , std::make_pair(900, "CM") , std::make_pair(500, "D"), std::make_pair(400, "CD"),
std::make_pair(100, "C"), std::make_pair(90, "XC"), std::make_pair(50, "L"), std::make_pair(40, "XL"),
std::make_pair(10, "X"), std::make_pair(9, "IX"), std::make_pair(5, "V"), std::make_pair(4, "IV"), std::make_pair(1, "I"), };
RoundNumber::RoundNumber(const sf::Font& font) :
RoundNumber(font, nullptr)
{
roundNumberText.setCharacterSize(100u);
}
RoundNumber::RoundNumber(const sf::Font& font, SystemManager* systemManager) :
systemManager(systemManager),
roundNumberText("I", font, 150u),
roundNumber(0u)
{
roundNumberText.setFillColor(sf::Color(176u, 7u, 7u, 255));
roundNumberText.setOutlineThickness(5.f);
roundNumberText.setOutlineColor(sf::Color::Black);
roundNumberText.setStyle(sf::Text::Bold);
roundNumberText.setPosition(sf::Vector2f(2350.f, 50.f));
}
void RoundNumber::update(std::size_t roundNumber)
{
if (this->roundNumber != roundNumber)
{
this->setRoundNumber(roundNumber);
this->systemManager->addEvent(this->systemManager->getEntityManager()->getPlayerID(), EntityEvent::RoundStarted);
}
}
void RoundNumber::setRoundNumber(std::size_t roundNumber)
{
this->roundNumber = roundNumber;
this->roundNumberText.setString(this->toRomanNumeral(roundNumber));
}
void RoundNumber::setPosition(sf::Vector2f position)
{
this->roundNumberText.setPosition(position);
}
void RoundNumber::draw(sf::RenderTarget& target, sf::RenderStates states) const
{
target.draw(this->roundNumberText);
}
std::string RoundNumber::toRomanNumeral(std::size_t roundNumber)
{
std::string romanNumeral;
for (auto& romanNumber : this->romanNumerals)
{
while (roundNumber >= romanNumber.first)
{
romanNumeral += romanNumber.second;
roundNumber -= romanNumber.first;
}
}
return romanNumeral;
} | mit |
richardschneider/club-server | lib/session/score.js | 4334 | import scorer from 'bridge-scorer';
import resolvers from '../../data/resolvers';
import { Board, Game, SessionPairResult } from '../../data/connectors';
const scorers = {
matchpoints (games) {
scorer.matchpoints(games);
let scoredGames = games.map(g => {
let game = g.game;
game.matchpointsNS = g.matchpointsNS.value;
game.matchpointsPercentageNS = g.matchpointsNS.percentage;
game.matchpointsEW = g.matchpointsEW.value;
game.matchpointsPercentageEW = g.matchpointsEW.percentage;
return game.save();
});
return Promise.all(scoredGames);
},
matchpointsACBL (games) {
scorer.matchpointsACBL(games);
let scoredGames = games.map(g => {
let game = g.game;
game.matchpointsNS = g.matchpointsNS.value;
game.matchpointsPercentageNS = g.matchpointsNS.percentage;
game.matchpointsEW = g.matchpointsEW.value;
game.matchpointsPercentageEW = g.matchpointsEW.percentage;
return game.save();
});
return Promise.all(scoredGames);
},
crossImps (games) {
scorer.crossImps(games);
let scoredGames = games.map(g => {
let game = g.game;
game.impsNS = g.impsNS.value;
game.impsEW = g.impsEW.value;
return game.save();
});
return Promise.all(scoredGames);
},
butler (games) {
scorer.butler(games);
let scoredGames = games.map(g => {
let game = g.game;
game.impsNS = g.impsNS.value;
game.impsEW = g.impsEW.value;
return game.save();
});
return Promise.all(scoredGames);
},
};
function scoreBoard (board, algorithm) {
return board
.getGames()
.then(games => {
let scoredGames = games.map(g => {
return {
game: g,
score: g.score,
contract: resolvers.Game.contract(g)
};
});
return scorers[algorithm](scoredGames);
});
}
function rankPairs(session) {
return Promise.resolve()
// Get all games for the session
.then(() => Game.findAll({include: [{ model: Board, where: { sessionId: session.id } }]}))
// Rank the pairs
.then(games => {
let pairs = {};
// Get the total for each pair
games.forEach(game => {
let nsId = `${session.id}-NS-${game.ns}`;
let ns = pairs[nsId] || { total: 0, played: 0, direction: 'NS' };
pairs[nsId] = ns;
ns.played += 1;
ns.total += game.matchpointsPercentageNS;
let ewId = `${session.id}-EW-${game.ew}`;
let ew = pairs[ewId] || { total: 0, played: 0, direction: 'EW' };
pairs[ewId] = ew;
ew.played += 1;
ew.total += game.matchpointsPercentageEW;
});
// Get score (total / games played) for each pair
for (var pairname in pairs) {
let pair = pairs[pairname];
pair.score = pair.total / pair.played;
}
// Rank NS pairs
let nsPairs = Object.getOwnPropertyNames(pairs)
.map(val => pairs[val])
.filter(pair => pair.direction === 'NS');
scorer.rank(nsPairs);
// Rank EW pairs
let ewPairs = Object.getOwnPropertyNames(pairs)
.map(val => pairs[val])
.filter(pair => pair.direction === 'EW');
scorer.rank(ewPairs);
// All pairs as an array
return Object.getOwnPropertyNames(pairs)
.map(val => {
let pair = pairs[val];
pair.id = val;
let rank = pair.rank;
pair.tied = rank.endsWith('=');
pair.rank = parseFloat(rank);
return pair;
});
})
// Update pair ranking
.then(pairs => {
return Promise.all(pairs.map(pair => {
return SessionPairResult.upsert({
id: pair.id,
rank: pair.rank,
tied: pair.tied,
score: pair.score,
scale: pair.scale
});
}));
})
;
}
function score(session, algorithm) {
if (!scorer[algorithm]) {
throw new Error(`Scoring ${algorithm} is not defined`);
}
if (!scorers[algorithm]) {
throw new Error(`Scoring ${algorithm} is NYI`);
}
return session
.getBoards()
.then(boards => Promise.all(boards.map(board => scoreBoard(board, algorithm))))
.then(() => rankPairs(session))
.then(() => session);
}
export default score;
| mit |
victronenergy/dbus-cgwacs | software/src/ac_sensor_settings_bridge.cpp | 2268 | #include <QsLog.h>
#include <velib/qt/v_busitems.h>
#include "ac_sensor_settings.h"
#include "ac_sensor_settings_bridge.h"
static const QString Service = "sub/com.victronenergy.settings";
static bool positionFromDBus(DBusBridge*, QVariant &v)
{
v = qVariantFromValue(static_cast<Position>(v.toInt()));
return true;
}
static bool positionToDBus(DBusBridge*, QVariant &v)
{
v = QVariant(static_cast<int>(v.value<Position>()));
return true;
}
AcSensorSettingsBridge::AcSensorSettingsBridge(AcSensorSettings *settings, QObject *parent) :
DBusBridge(Service, false, parent)
{
QString primaryId = QString("cgwacs_%1").arg(settings->serial());
QString secondaryId = QString("cgwacs_%1_S").arg(settings->serial());
QString primaryPath = QString("/Settings/Devices/%1").arg(primaryId);
QString secondaryPath = QString("/Settings/Devices/%1").arg(secondaryId);
consume(settings, "customName", QVariant(""),
primaryPath + "/CustomName", false);
consume(settings, "classAndVrmInstance",
primaryPath + "/ClassAndVrmInstance");
consume(settings, "isMultiPhase",
QVariant(static_cast<int>(settings->isMultiPhase())),
primaryPath + "/IsMultiphase", false);
consume(settings, "position", QVariant(0),
primaryPath + "/Position", false, positionFromDBus, positionToDBus);
consume(settings, "l1ReverseEnergy", 0.0, 0.0, 1e6,
primaryPath + "/L1ReverseEnergy", true);
consume(settings, "l2ReverseEnergy", 0.0, 0.0, 1e6,
primaryPath + "/L2ReverseEnergy", true);
consume(settings, "l3ReverseEnergy", 0.0, 0.0, 1e6,
primaryPath + "/L3ReverseEnergy", true);
consume(settings, "supportMultiphase", QVariant(static_cast<int>(settings->supportMultiphase())),
primaryPath + "/SupportMultiphase", false);
consume(settings, "l2ClassAndVrmInstance",
secondaryPath + "/ClassAndVrmInstance");
consume(settings, "l2CustomName", QVariant(""),
secondaryPath + "/CustomName", false);
consume(settings, "l2Position", QVariant(0),
secondaryPath + "/Position", false, positionFromDBus, positionToDBus);
consume(settings, "piggyEnabled", QVariant(0),
secondaryPath + "/Enabled", false);
// Allocate deviceinstances
initDeviceInstance(primaryId, "grid", MinDeviceInstance);
initDeviceInstance(secondaryId, "pvinverter", MinDeviceInstance);
}
| mit |
hypest/PrepaidTextAPI | src/org/hypest/prepaidtextapi/PrepaidTextAPI.java | 26103 |
package org.hypest.prepaidtextapi;
import java.util.ArrayList;
import java.util.List;
import java.util.Vector;
import org.hypest.prepaidtextapi.filters.NetworkOperatorDatum;
import org.hypest.prepaidtextapi.filters.NetworkOperatorDatum.NetworkOperator;
import org.hypest.prepaidtextapi.receivers.RestAlarm;
import org.hypest.prepaidtextapi.receivers.PrepaidTextAPIWidget;
import org.hypest.prepaidtextapi.services.ReportService;
import org.hypest.prepaidtextapi.utils.Misc;
import org.hypest.prepaidtextapi.utils.Misc.NOTIFICATION;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.PendingIntent;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.pm.PackageManager;
import android.content.pm.PackageManager.NameNotFoundException;
import android.content.pm.ResolveInfo;
import android.graphics.drawable.Drawable;
import android.net.Uri;
import android.os.Bundle;
import android.telephony.SmsManager;
import android.text.InputType;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ScrollView;
import android.widget.TextView;
import android.widget.Toast;
public class PrepaidTextAPI extends Activity implements Animation.AnimationListener {
public static final String PREFS_INFOCUS = "infocus";
public static final String PREFS_IN_CALL = "in_call";
public static final String PREFS_RINGING = "ringing";
public static final String PREFS_NOTIFICATION = "notification";
public static final String PREFS_SENDING = "sending";
public static final String PREFS_ALLPLUGINSSENT = "allpluginssent";
public static final String PREFS_FORCE_SMSC = "force_smsc";
public static final String PREFS_ON_CALL_END = "on_call_end";
public static final String PREFS_DO_REPORT = "do_report";
public static final String PREFS_REPORT_WIFI_ONLY = "report_wifi_only";
public static Activity _activity = null;
private static int _SentCount = 0;
private static final String SMS_SENT_UID = "SMS_SENT_UID";
private static final String ACTION_SMS_SENT = "ACTION_SMS_SENT";
private static final String ACTION_SMS_DELIVERED = "ACTION_SMS_DELIVERED";
public static final String ACTION_REST_ALARM = "ACTION_REST_ALARM";
private enum RESULT_CODES {
CODE_PREFERENCES,
}
PrepaidTextAPIPrefsFile prefs;
public static final String HYPEST_UPDATE_OWNUI_INTENT = "org.hypest.prepaidtextapi.UPDATE_OWNUI";
IntentFilter updateOwnUIIntentFilter;
Animation fadein_balance_end;
Animation fadeout_balance_end;
Animation fadein_bonus_end;
Animation fadeout_bonus_end;
Animation fadein_MBs_end;
Animation fadeout_MBs_end;
Animation fadein_balance_active;
Animation fadeout_balance_active;
Animation fadein_bonus_active;
Animation fadeout_bonus_active;
Animation fadein_MBs_active;
Animation fadeout_MBs_active;
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
_activity = this;
prefs = new PrepaidTextAPIPrefsFile(this);
setWholeView();
updateOwnUIIntentFilter = new IntentFilter();
updateOwnUIIntentFilter.addAction(HYPEST_UPDATE_OWNUI_INTENT);
fadein_balance_end = AnimationUtils.loadAnimation(this, R.anim.fadein);
fadein_bonus_end = AnimationUtils.loadAnimation(this, R.anim.fadein);
fadein_MBs_end = AnimationUtils.loadAnimation(this, R.anim.fadein);
fadein_balance_active = AnimationUtils.loadAnimation(this, R.anim.rotatefadein);
fadein_bonus_active = AnimationUtils.loadAnimation(this, R.anim.rotatefadein);
fadein_MBs_active = AnimationUtils.loadAnimation(this, R.anim.rotatefadein);
fadeout_balance_end = AnimationUtils.loadAnimation(this, R.anim.fadeout);
fadeout_bonus_end = AnimationUtils.loadAnimation(this, R.anim.fadeout);
fadeout_MBs_end = AnimationUtils.loadAnimation(this, R.anim.fadeout);
fadeout_balance_active = AnimationUtils.loadAnimation(this, R.anim.rotatefadeout);
fadeout_bonus_active = AnimationUtils.loadAnimation(this, R.anim.rotatefadeout);
fadeout_MBs_active = AnimationUtils.loadAnimation(this, R.anim.rotatefadeout);
// there seems to be a problem specifying the interpolator in the xml,
// so setting it manually...
fadein_balance_active.setInterpolator(getApplicationContext(), R.anim.linearinterpol);
fadein_bonus_active.setInterpolator(getApplicationContext(), R.anim.linearinterpol);
fadein_MBs_active.setInterpolator(getApplicationContext(), R.anim.linearinterpol);
fadein_balance_end.setAnimationListener(this);
fadeout_balance_end.setAnimationListener(this);
fadein_bonus_end.setAnimationListener(this);
fadeout_bonus_end.setAnimationListener(this);
fadein_MBs_end.setAnimationListener(this);
fadeout_MBs_end.setAnimationListener(this);
fadein_balance_active.setAnimationListener(this);
fadeout_balance_active.setAnimationListener(this);
fadein_bonus_active.setAnimationListener(this);
fadeout_bonus_active.setAnimationListener(this);
fadein_MBs_active.setAnimationListener(this);
fadeout_MBs_active.setAnimationListener(this);
if (inAutoRefresh()) {
if (prefs.getBoolean("launch_update", false)) {
Button sendButton = (Button) findViewById(R.id.ButtonSend);
sendButton.setEnabled(false);
sendButton.setText(getString(R.string.auto_update_in_progress));
onRefreshClick();
}
}
}
BroadcastReceiver smsSendingListener = new BroadcastReceiver() {
@Override
public void onReceive(Context ctx, Intent intent) {
switch (getResultCode()) {
case Activity.RESULT_OK:
// Toast.makeText(getBaseContext(), "SMS sent",
// Toast.LENGTH_SHORT).show();
break;
case SmsManager.RESULT_ERROR_GENERIC_FAILURE:
Toast.makeText(getBaseContext(), "SMS sending: Generic failure",
Toast.LENGTH_SHORT).show();
break;
case SmsManager.RESULT_ERROR_NO_SERVICE:
Toast.makeText(getBaseContext(), "SMS sending: No service", Toast.LENGTH_SHORT)
.show();
break;
case SmsManager.RESULT_ERROR_NULL_PDU:
Toast.makeText(getBaseContext(), "SMS sending: Null PDU", Toast.LENGTH_SHORT)
.show();
break;
case SmsManager.RESULT_ERROR_RADIO_OFF:
Toast.makeText(getBaseContext(), "SMS sending: Radio off", Toast.LENGTH_SHORT)
.show();
break;
}
}
};
BroadcastReceiver smsDeliveryListener = new BroadcastReceiver() {
@Override
public void onReceive(Context ctx, Intent intent) {
switch (getResultCode()) {
case Activity.RESULT_OK:
// Toast.makeText(getBaseContext(), "SMS delivered",
// Toast.LENGTH_SHORT).show();
break;
case Activity.RESULT_CANCELED:
Toast.makeText(getBaseContext(), "SMS not delivered!", Toast.LENGTH_SHORT)
.show();
break;
}
}
};
private void registerSMSListeners() {
registerReceiver(smsSendingListener, new IntentFilter(ACTION_SMS_SENT));
registerReceiver(smsDeliveryListener, new IntentFilter(ACTION_SMS_DELIVERED));
}
private void unregisterSMSListeners() {
unregisterReceiver(smsSendingListener);
unregisterReceiver(smsDeliveryListener);
}
public boolean inAutoRefresh() {
Intent ca = this.getIntent();
if (ca == null) {
return false;
}
String action = ca.getAction();
if (action == null) {
return false;
}
if (prefs == null) {
return false;
}
int flags = ca.getFlags();
if (((flags & Intent.FLAG_ACTIVITY_LAUNCHED_FROM_HISTORY) == 0)
&& (action.contains("ACTION_REFRESH"))
&& (prefs.getBoolean("launch_update", false))) {
return true;
} else {
return false;
}
}
private void setWholeView() {
LayoutInflater li = LayoutInflater.from(this);
View whole = li.inflate(R.layout.main, null);
ScrollView sv = (ScrollView) whole.findViewById(R.id.ScrollView01);
LinearLayout lin = (LinearLayout) (whole.findViewById(R.id.LinearLayout_body));
Vector<NetworkOperatorDatum> nets = NetworkOperatorDatum.getEnabledOnly(this, prefs);
int count = 0;
for (NetworkOperatorDatum net : nets) {
View child = net.MainView();
ViewGroup vg = (ViewGroup) (child.getParent());
if (vg != null)
vg.removeView(child);
lin.addView(child, count);
count += 1;// 2;
net.setScrollView(sv);
}
Button sendButton = (Button) whole.findViewById(R.id.ButtonSend);
sendButton.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
onRefreshClick();
}
});
View reportButton = whole.findViewById(R.id.Button_Report);
reportButton.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
ReportSmsList.viewReport(PrepaidTextAPI.this);
}
});
setContentView(whole);
sendButton.requestFocus();
}
private void onRefreshClick() {
NetworkOperator net = NetworkOperatorDatum.getNetworkOperator(this);
switch (net) {
case Cosmote:
doForceRefresh();
break;
case Offline:
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setMessage(
getString(R.string.network_offline_info))
.setTitle(getString(R.string.network_offline))
.setCancelable(true)
.setNegativeButton(getString(android.R.string.cancel),
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog,
int id) {
dialog.cancel();
}
});
AlertDialog alert = builder.create();
alert.show();
break;
default:
builder = new AlertDialog.Builder(this);
builder.setMessage(
getString(R.string.network_foreign))
.setTitle(getString(R.string.warning))
.setIcon(R.drawable.ic_bullet_key_permission)
.setCancelable(true)
.setNegativeButton(getString(android.R.string.cancel),
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog,
int id) {
dialog.cancel();
}
});
builder.setPositiveButton(getString(R.string.button_send),
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog,
int id) {
doForceRefresh();
}
});
alert = builder.create();
alert.show();
break;
}
}
private void doForceRefresh() {
doRefresh(true);
}
private void doRefresh(Boolean forceRefresh) {
Button sendButton = (Button) findViewById(R.id.ButtonSend);
sendButton.setEnabled(false);
prefs.putBoolean(PREFS_SENDING, true);
prefs.putBoolean(PREFS_ALLPLUGINSSENT, false);
prefs.commit();
new Thread(sendSMSsRunable).start();
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.menu, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
AlertDialog.Builder builder;
AlertDialog alert;
// Handle item selection
switch (item.getItemId()) {
case R.id.about:
builder = new AlertDialog.Builder(this);
try {
builder.setTitle(getString(R.string.app_name) + " v"
+ getPackageManager().getPackageInfo(getPackageName(), 0).versionName);
} catch (NameNotFoundException e) {
e.printStackTrace();
}
builder.setMessage(getString(R.string.about))
.setCancelable(true)
.setPositiveButton("http://hypest.org",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog,
int id) {
Intent web = new Intent(
Intent.ACTION_VIEW,
Uri.parse("http://hypest.org/PrepaidTextAPI"));
startActivity(web);
}
})
.setNegativeButton(getString(R.string.button_back),
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog,
int id) {
dialog.cancel();
}
});
alert = builder.create();
alert.show();
return true;
case R.id.preferences:
Intent settingsActivity = new Intent().setClass(this, PrepaidTextAPI_Prefs.class);
startActivityForResult(settingsActivity, RESULT_CODES.CODE_PREFERENCES.ordinal());
return true;
case R.id.renewal:
NetworkOperator net = NetworkOperatorDatum.getNetworkOperator(this);
switch (net) {
case Cosmote:
renewal();
break;
case Offline:
builder = new AlertDialog.Builder(this);
builder.setMessage(
getString(R.string.network_offline_info))
.setTitle(getString(R.string.network_offline))
.setCancelable(true)
.setNegativeButton(getString(R.string.button_back),
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog,
int id) {
dialog.cancel();
}
});
alert = builder.create();
alert.show();
break;
default:
builder = new AlertDialog.Builder(this);
builder.setMessage(
getString(R.string.network_foreign))
.setTitle(getString(R.string.warning))
.setIcon(R.drawable.ic_bullet_key_permission)
.setCancelable(true)
.setPositiveButton(getString(R.string.button_send),
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
renewal();
}
})
.setNegativeButton(getString(android.R.string.cancel),
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
dialog.cancel();
}
});
alert = builder.create();
alert.show();
break;
}
return true;
case R.id.forceupdate:
onRefreshClick();
return true;
default:
return super.onOptionsItemSelected(item);
}
}
private void renewal() {
AlertDialog.Builder renewal_number = new AlertDialog.Builder(this);
// Set an EditText view to get user input
final EditText input = new EditText(this);
input.setInputType(InputType.TYPE_CLASS_NUMBER);
renewal_number.setView(input);
renewal_number.setTitle(getString(R.string.renewal_title));
renewal_number.setMessage(getString(R.string.renewal_info));
renewal_number.setPositiveButton(getString(R.string.button_send),
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
String value = input.getText().toString();
sendSMS("<put your network number for renewal here", value,
prefs.getBoolean(PrepaidTextAPI.PREFS_FORCE_SMSC, true));
}
});
renewal_number.setNegativeButton(getString(android.R.string.cancel),
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
dialog.cancel();
}
});
renewal_number.show();
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
switch (RESULT_CODES.values()[requestCode]) {
case CODE_PREFERENCES:
NetworkOperatorDatum.unregisterAllInstances();
NetworkOperatorDatum.regather(this, prefs);
NetworkOperatorDatum.registerAllInstances(this);
setWholeView();
updateUI();
PrepaidTextAPIWidget.doUpdate(this);
ReportService.initiate(this);
break;
}
}
@Override
protected void onResume() {
_activity = this;
registerSMSListeners();
registerReceiver(updateIntentReceiver, updateOwnUIIntentFilter);
NetworkOperatorDatum.registerAllInstances(this);
prefs.putBoolean(PrepaidTextAPI.PREFS_INFOCUS, true);
prefs.commit();
updateUI();
Misc.notify_cancel(NOTIFICATION.UPDATE, this);
PrepaidTextAPIWidget.doUpdate(this);
super.onResume();
}
@Override
protected void onPause() {
unregisterSMSListeners();
unregisterReceiver(updateIntentReceiver);
prefs.putBoolean(PrepaidTextAPI.PREFS_INFOCUS, false);
prefs.putBoolean(PrepaidTextAPI.PREFS_SENDING, false);
prefs.commit();
NetworkOperatorDatum.unregisterAllInstances();
RestAlarm.CancelAlarm(this);
RestAlarm.SetAlarm(this);
_activity = null;
super.onPause();
}
@Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
if (keyCode == KeyEvent.KEYCODE_BACK) {
if (NetworkOperatorDatum.closeAllExtras()) {
return true;
}
}
return super.onKeyDown(keyCode, event);
}
private void updateOwnUI() {
Boolean sending = prefs.getBoolean(PREFS_SENDING, false);
if (!sending) {
Button sendButton = (Button) findViewById(R.id.ButtonSend);
sendButton.setEnabled(true);
} else {
Button sendButton = (Button) findViewById(R.id.ButtonSend);
sendButton.setEnabled(false);
}
}
private void updateUI() {
Vector<NetworkOperatorDatum> nets = NetworkOperatorDatum.getEnabledOnly(this, prefs);
for (NetworkOperatorDatum net : nets) {
net.updateUI();
}
updateOwnUI();
}
public static void updateOwnUIAsync(Context aContext) {
Intent i = new Intent();
i.setAction(HYPEST_UPDATE_OWNUI_INTENT);
aContext.sendBroadcast(i);
}
private Runnable updateOwnUIRunnable = new Runnable() {
@Override
public void run() {
updateOwnUI();
}
};
private BroadcastReceiver updateIntentReceiver = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
runOnUiThread(updateOwnUIRunnable);
}
};
public void doRunNetworkRefresh() {
NetworkOperatorDatum.runNetworkRefresh(this);
}
private Runnable sendSMSsRunable = new Runnable() {
@Override
public void run() {
doRunNetworkRefresh();
}
};
public static void sendSMS(String phoneNumber, String message, Boolean forceSMSC) {
_SentCount++;
PendingIntent sentPendingIntent = null;
PendingIntent deliveredPendingIntent = null;
if (PrepaidTextAPI._activity != null) {
Intent sentIntent = new Intent();
sentIntent.putExtra(SMS_SENT_UID, _SentCount);
sentIntent.setAction(ACTION_SMS_SENT);
Intent deliverIntent = new Intent();
deliverIntent.putExtra(SMS_SENT_UID, _SentCount);
deliverIntent.setAction(ACTION_SMS_DELIVERED);
sentPendingIntent = PendingIntent.getBroadcast(PrepaidTextAPI._activity, 0, sentIntent,
PendingIntent.FLAG_UPDATE_CURRENT);
deliveredPendingIntent = PendingIntent.getBroadcast(PrepaidTextAPI._activity, 0,
deliverIntent, PendingIntent.FLAG_UPDATE_CURRENT);
}
ArrayList<PendingIntent> sentintents = new ArrayList<PendingIntent>();
ArrayList<PendingIntent> deliveredintents = new ArrayList<PendingIntent>();
sentintents.add(sentPendingIntent);
deliveredintents.add(deliveredPendingIntent);
SmsManager sms = SmsManager.getDefault();
ArrayList<String> smsparts = sms.divideMessage(message);
sms.sendMultipartTextMessage(phoneNumber, (forceSMSC ? "<SMS center number>" : null),
smsparts, sentintents, deliveredintents);
}
@Override
public void onAnimationEnd(Animation animation) {
}
@Override
public void onAnimationRepeat(Animation animation) {
}
@Override
public void onAnimationStart(Animation animation) {
}
protected class EmailClientAdapter extends ArrayAdapter<ResolveInfo> {
public List<ResolveInfo> items;
public EmailClientAdapter(Context context, List<ResolveInfo> items) {
super(context, R.layout.email_client_item, items);
this.items = items;
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
View v = convertView;
if (v == null) {
LayoutInflater vi = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
v = vi.inflate(R.layout.email_client_item, null);
}
final PackageManager pm = getPackageManager();
ResolveInfo o = items.get(position);
if (o != null) {
TextView tt = (TextView) v.findViewById(R.id.label);
ImageView icon = (ImageView) v.findViewById(R.id.icon);
if (tt != null) {
tt.setText(pm.getApplicationLabel(o.activityInfo.applicationInfo));
}
if (icon != null) {
Drawable d = pm.getApplicationIcon(o.activityInfo.applicationInfo);
if (d != null) {
icon.setImageDrawable(d);
} else {
icon.setImageResource(R.drawable.empty);
}
}
}
return v;
}
}
}
| mit |
jls713/jfactors | flattened/process_data.py | 2570 | ## Produce Table 5 of SEG (2016)
## ============================================================================
import numpy as np
import pandas as pd
import sys
import os.path
sys.path.append('/home/jls/work/data/jfactors/spherical/')
from J_D_table import posh_latex_names
## ============================================================================
def load_files(name):
''' Load in three sample files for dwarf <name> '''
name='triaxial_results/'+name
if os.path.isfile(name+'_nop') and os.path.isfile(name+'_ma') and os.path.isfile(name+'_sj'):
return np.genfromtxt(name+'_nop'),np.genfromtxt(name+'_ma'),np.genfromtxt(name+'_sj')
else:
return None,None,None
def write(l):
''' Output median and \pm 1\sigma errors for correction factors in ascii
form '''
l = l.T[4]
return r'$%0.2f^{+%0.2f}_{-%0.2f}$'%(np.median(l),np.percentile(l,84.1)-np.median(l),np.median(l)-np.percentile(l,15.9))
def write_ascii(l):
''' Output median and \pm 1\sigma errors for correction factors in latex
form '''
l = l.T[4]
return '%0.2f %0.2f %0.2f '%(np.median(l),np.percentile(l,84.1)-np.median(l),np.median(l)-np.percentile(l,15.9))
## ============================================================================
## 1. Read in data file and write headers to tables
data = pd.read_csv('../data/data.dat',sep=' ')
ff = open('corr_triax_table.dat','w')
ffa = open('corr_triax_table_ascii.dat','w')
ff.write('\\begin{tabular}{lcccc}\n')
ff.write('\\hline\n\\hline\n')
ff.write('Name & Ellipticity & $\mathcal{F}_{\mathrm{J},U}$& $\mathcal{F}_{\mathrm{J},R}$& $\mathcal{F}_{\mathrm{J},T}$\\\\ \n')
ff.write('\\hline\n')
## 2. Loop over dwarfs and compute median and \pm 1 \sigma for correction factors
for i in data.ellip.argsort():
d,e,f=load_files(data.Name[i])
ellip_string='&$%0.2f^{+%0.2f}_{-%0.2f}$&'%(data.ellip[i],data.ellip_e1[i],data.ellip_e2[i])
if(data.ellip_e1[i]!=data.ellip_e1[i]):
ellip_string='&$<%0.2f$&'%(data.ellip[i])
if(d==None):
ff.write(posh_latex_names[data['Name'][i]]+ellip_string+'NaN&NaN&NaN\\\\\n')
ffa.write(data['Name'][i]+' %0.2f %0.2f %0.2f '%(data.ellip[i],data.ellip_e1[i],data.ellip_e2[i])+'NaN '*9+'\n')
else:
ff.write(posh_latex_names[data['Name'][i]]+ellip_string
+write(d)+'&'+write(e)+'&'+write(f)+'\\\\\n')
ffa.write(data['Name'][i]+' %0.2f %0.2f %0.2f '%(data.ellip[i],data.ellip_e1[i],data.ellip_e2[i])+write_ascii(d)+write_ascii(e)+write_ascii(f)+'\n')
ff.write('\\hline\n\\end{tabular}\n')
ff.close()
ffa.close()
## ============================================================================
| mit |
Greenplugin/yandex-pdd | src/DomainManager.php | 4278 | <?php
/**
* Created by PhpStorm.
* User: GreenPlugin
* Date: 10.01.17
* Time: 0:57
*/
namespace YandexPDD;
use YandexPDD\Entity\DomainCollectionResponse;
use YandexPDD\Entity\DomainConnectionResponse;
use YandexPDD\Entity\DomainCountryResponse;
use YandexPDD\Entity\DomainDetailsResponse;
use YandexPDD\Entity\DomainLogoResponse;
use YandexPDD\Entity\DomainStatusResponse;
use YandexPDD\Entity\SimpleResponse;
/**
* Class DomainManager
* @package YandexPDD
*/
class DomainManager extends AbstractBaseManager
{
// TODO [GreenPlugin]: fill all responses to self;
// TODO [GreenPlugin]: fix setDomainLogo method
const HOST = 'https://pddimp.yandex.ru/api2/admin/domain';
/**
* @param int $page = 1
* @param int $count = 20
* @param string $direction = asc
*
* @return DomainCollectionResponse
*/
public function get($page = 1, $count = 20, $direction = 'asc')
{
return $this->getQuery(sprintf(
"%s/domains?page=%d&on_page=%d&direction=%s",
self::HOST,
$page,
$count,
$direction),
new DomainCollectionResponse()
);
}
/**
* @param string $domain
*
* @return DomainConnectionResponse
*/
public function register($domain = null)
{
$domain = $domain ? $domain : $this->domain;
return $this->postQuery(
sprintf("%s/register", self::HOST),
['domain' => $domain],
new DomainConnectionResponse()
);
}
/**
* @param string $domain
*
* @return mixed|\Psr\Http\Message\ResponseInterface
*/
public function remove($domain = null)
{
$domain = $domain ? $domain : $this->domain;
return $this->postQuery(
sprintf("%s/delete", self::HOST),
['domain' => $domain],
new SimpleResponse()
);
}
/**
* @param string $domain
*
* @return null|DomainStatusResponse
*/
public function getStatus($domain = null)
{
$domain = $domain ? $domain : $this->domain;
return $this->getQuery(
sprintf("%s/registration_status?domain=%s", self::HOST, $domain),
new DomainStatusResponse()
);
}
/**
* @param string $domain
*
* @return DomainDetailsResponse|null
*/
public function getDetails($domain = null)
{
$domain = $domain ? $domain : $this->domain;
return $this->getQuery(
sprintf("%s/details?domain=%s", self::HOST, $domain),
new DomainDetailsResponse()
);
}
/**
* @param string $country in ISO-3166-1 https://ru.wikipedia.org/wiki/ISO_3166-1
* @param string $domain
*
* @return DomainCountryResponse|null
*/
public function setCountry($country, $domain = null)
{
$domain = $domain ? $domain : $this->domain;
return $this->postQuery(
sprintf("%s/settings/set_country", self::HOST),
[
'domain' => $domain,
'country' => $country
],
new DomainCountryResponse()
);
}
/**
* @param string $domain
* @param string $path
*
* @return mixed|\Psr\Http\Message\ResponseInterface
*/
public function setDomainLogo($path, $domain = null)
{
$domain = $domain ? $domain : $this->domain;
$mime = mime_content_type($path);
$file = file_get_contents($path);
$result = $this->client->request(
'POST',
sprintf("%s/logo/set", self::HOST),
[
'multipart' => [
[
'name'=> 'domain',
'contents' => $domain
],
[
'name' => 'file',
'filename' => 'logo',
'contents' => $file,
'headers' => [
'Content-Type' => $mime,
],
]
],
'headers' => ['PddToken' => $this->apiKey],
'http_errors' => $this->debug,
]
);
return $this->processResponse($result, new SimpleResponse());
}
/**
* @param string $domain
*
* @return mixed|\Psr\Http\Message\ResponseInterface
*/
public function getDomainLogo($domain = null)
{
$domain = $domain ? $domain : $this->domain;
return $this->getQuery(sprintf("%s/logo/check?domain=%s", self::HOST, $domain), new DomainLogoResponse());
}
/**
* @param $domain
*
* @return mixed|\Psr\Http\Message\ResponseInterface
*/
public function removeDomainLogo($domain = null)
{
$domain = $domain ? $domain : $this->domain;
return $this->postQuery(sprintf("%s/logo/del", self::HOST), ['domain' => $domain], new SimpleResponse());
}
/**
* @return null|DomainCollectionResponse|DomainConnectionResponse
*/
public function getResponse()
{
return $this->response;
}
} | mit |
thoas/picfit | vendor/github.com/thoas/go-funk/utils.go | 987 | package funk
import "reflect"
func equal(expected, actual interface{}) bool {
if expected == nil || actual == nil {
return expected == actual
}
return reflect.DeepEqual(expected, actual)
}
func sliceElem(rtype reflect.Type) reflect.Type {
for {
if rtype.Kind() != reflect.Slice && rtype.Kind() != reflect.Array {
return rtype
}
rtype = rtype.Elem()
}
}
func redirectValue(value reflect.Value) reflect.Value {
for {
if !value.IsValid() || value.Kind() != reflect.Ptr {
return value
}
res := reflect.Indirect(value)
// Test for a circular type.
if res.Kind() == reflect.Ptr && value.Pointer() == res.Pointer() {
return value
}
value = res
}
}
func makeSlice(value reflect.Value, values ...int) reflect.Value {
sliceType := sliceElem(value.Type())
size := value.Len()
cap := size
if len(values) > 0 {
size = values[0]
}
if len(values) > 1 {
cap = values[1]
}
return reflect.MakeSlice(reflect.SliceOf(sliceType), size, cap)
}
| mit |
redarmy30/Eurobot-2017 | NewCommunication/main_file.py | 16741 | import driver
import time
from hokuyolx import HokuyoLX
import logging
import signal
import npParticle as pf
import numpy as np
from multiprocessing import Process, Queue, Value,Array
from multiprocessing.queues import Queue as QueueType
lvl = logging.INFO
logging.basicConfig(filename='Eurobot.log', filemode='w', format='%(levelname)s:%(asctime)s %(message)s',
datefmt='%m/%d/%Y %I:%M:%S %p', level=lvl)
console = logging.StreamHandler()
console.setLevel(lvl)
# set a format which is simpler for console use
formatter = logging.Formatter('%(levelname)s: %(message)s')
console.setFormatter(formatter)
# add the handler to the root logger
logging.getLogger('').addHandler(console)
logger = logging.getLogger(__name__)
obstacles=[]
class Robot:
def __init__(self, lidar_on=True,small=True):
sensors_number=6
self.sensor_range = 20
self.collision_avoidance = False
if small:
self.sensors_map= {0: (0, np.pi/3), 1: (np.pi/4, np.pi*7/12), 2: (np.pi*0.5, np.pi*1.5), 3: (17/12.*np.pi, 7/4.*np.pi), 4: (5/3.*np.pi,2*np.pi), 5: [(7/4.*np.pi,2*np.pi),(0,np.pi*1/4.)]} # can be problem with 2pi and 0
self.lidar_on = lidar_on
self.map = np.load('npmap.npy')
if lidar_on:
logging.debug('lidar is connected')
# add check for lidar connection
try:
self.lidar = HokuyoLX(tsync=False)
self.lidar.convert_time = False
except:
self.lidar_on = False
logging.warning('lidar is not connected')
#self.x = 170 # mm
#self.y = 150 # mm
#self.angle = 0.0 # pi
if small:
self.coords = Array('d',[850, 170, 0])
else:
self.coords = Array('d', [170, 170, 0])
self.localisation = Value('b', True)
self.input_queue = Queue()
self.loc_queue = Queue()
self.fsm_queue = Queue()
self.PF = pf.ParticleFilter(particles=1500, sense_noise=25, distance_noise=20, angle_noise=0.3, in_x=self.coords[0],
in_y=self.coords[1], in_angle=self.coords[2],input_queue=self.input_queue, out_queue=self.loc_queue)
# driver process
self.dr = driver.Driver(self.input_queue,self.fsm_queue,self.loc_queue)
p = Process(target=self.dr.run)
p.start()
p2 = Process(target=self.PF.localisation,args=(self.localisation,self.coords,self.get_raw_lidar))
logging.info(self.send_command('echo','ECHO'))
logging.info(self.send_command('setCoordinates',[self.coords[0] / 1000., self.coords[1] / 1000., self.coords[2]]))
p2.start()
time.sleep(0.1)
def send_command(self,name,params=None):
self.input_queue.put({'source': 'fsm','cmd': name,'params': params})
return self.fsm_queue.get()
def get_raw_lidar(self):
# return np.load('scan.npy')[::-1]
timestamp, scan = self.lidar.get_intens()
return scan
# return scan[::-1] our robot(old)
def check_lidar(self):
try:
state = self.lidar.laser_state()
except:
self.lidar_on = False
logging.warning('Lidar off')
def go_to_coord_rotation(self, parameters): # parameters [x,y,angle,speed]
if self.PF.warning:
time.sleep(1)
pm = [self.coords[0]/1000.,self.coords[1]/1000.,float(self.coords[2]),parameters[0] / 1000., parameters[1] / 1000., float(parameters[2]), parameters[3]]
x = parameters[0] - self.coords[0]
y = parameters[1] - self.coords[1]
sm = x+y
logging.info(self.send_command('go_to_with_corrections',pm))
# After movement
stamp = time.time()
time.sleep(0.100001) # sleep because of STM interruptions (Maybe add force interrupt in STM)
while not self.send_command('is_point_was_reached')['data']:
time.sleep(0.05)
if self.collision_avoidance:
direction = (float(x) / sm, float(y) / sm)
if self.check_collisions(direction):
self.send_command('stopAllMotors')
# check untill ok and then move!
# add Collision Avoidance there
if (time.time() - stamp) > 30:
return False # Error, need to handle somehow (Localize and add new point maybe)
if self.localisation.value == 0:
self.PF.move_particles([parameters[0]-self.coords[0],parameters[1]-self.coords[1],parameters[2]-self.coords[2]])
self.coords[0] = parameters[0]
self.coords[1] = parameters[1]
self.coords[2] = parameters[2]
logging.info('point reached')
return True
def check_collisions(self, direction):
angle = np.arctan2(direction[1],direction[0]) % (np.pi*2)
sensor_angle = (angle-self.coords[2]) %(np.pi*2)
#### switch on sensor_angle
collisions = [0,0,0,0,1]
for index,i in enumerate(collisions):
if i and sensor_angle<=self.sensors_map[index][1] and sensor_angle>=self.sensors_map[index][0]:
logging.info("Collision at index "+str(index))
if self.check_map(direction):
continue
return True
return False
def receive_sensors_data(self):
data = self.send_command('sensors_data')
answer = []
for i in range(6):
answer.append((data & (1 << i)) != 0)
return answer
def check_map(self,direction): # probably can be optimized However O(1)
for i in range(0,self.sensor_range,2):
for dx in range(-2,2):
for dy in range(-2,2):
x = int(self.coords[0]/10+direction[0]*i+dx)
y = int(self.coords[1]/10+direction[1]*i+dy)
if x > pf.WORLD_X/10 or x < 0 or y > pf.WORLD_Y/10 or y < 0:
return True
# Or maybe Continue
if self.map[x][y]:
return True
return False
def go_last(self,parameters):
while abs(parameters[0]-self.coords[0]) > 10 or abs(parameters[1]-self.coords[1]) > 10:
print 'calibrate'
self.go_to_coord_rotation(parameters)
def take_cylinder(self): # approx time = 2
self.send_command('take_cylinder')
time.sleep(4)
def store_cylinder(self): # approx time = 0.5
self.send_command('store_cylinder')
time.sleep(0.5)
def drop_cylinder(self): # approx time = 1
self.send_command('drop_cylinder')
time.sleep(1)
def left_ball_down(self):
self.send_command('left_ball_down')
time.sleep(1)
def left_ball_up(self):
self.send_command('left_ball_up')
time.sleep(1)
def left_ball_drop(self):
self.send_command('left_ball_drop')
time.sleep(1)
def right_ball_down(self):
self.send_command('right_ball_down')
time.sleep(1)
def right_ball_up(self):
self.send_command('right_ball_up')
time.sleep(1)
def right_ball_drop(self):
self.send_command('right_ball_drop')
time.sleep(1)
def funny(self):
self.send_command('funny')
time.sleep(1)
############################################################################
######## HIGH LEVEL FUNCTIONS ##############################################
############################################################################
def demo(self, speed=1):
"""robot Demo, go to coord and take cylinder"""
signal.signal(signal.SIGALRM, self.funny_action)
signal.alarm(90)
# TODO take cylinder
angle = np.pi
parameters = [850, 150, angle, speed]
self.go_to_coord_rotation(parameters)
parameters = [1000, 500, angle, speed]
self.go_to_coord_rotation(parameters)
parameters = [1000, 700, angle, speed]
self.go_to_coord_rotation(parameters)
parameters = [650, 1350, angle, speed]
self.go_to_coord_rotation(parameters)
parameters = [250, 1350, angle, speed]
self.go_to_coord_rotation(parameters)
parameters = [300, 1350, angle, speed]
self.go_to_coord_rotation(parameters)
def demo_r(self, speed=1):
"""robot Demo, go to coord and take cylinder"""
# TODO take cylinder
angle = np.pi
parameters = [650, 1350, angle, speed]
self.go_to_coord_rotation(parameters)
parameters = [1000, 700, angle, speed]
self.go_to_coord_rotation(parameters)
parameters = [1000, 500, angle, speed]
self.go_to_coord_rotation(parameters)
parameters = [850, 250, angle, speed]
self.go_to_coord_rotation(parameters)
angle = 0.0
parameters = [170, 150, angle, speed]
self.go_to_coord_rotation(parameters)
def test_trajectory(self,speed=1):
angle =3*np.pi / 2.
parameters = [700, 150, angle, speed]
self.go_to_coord_rotation(parameters)
parameters = [1150, 190, angle, speed]
self.go_to_coord_rotation(parameters)
parameters = [1150, 1000, angle, speed]
self.go_to_coord_rotation(parameters)
parameters = [1350, 1570, angle, speed]
self.go_to_coord_rotation(parameters)
parameters = [1350, 1500, angle, speed]
self.go_to_coord_rotation(parameters)
parameters = [1350, 1400, angle, speed]
self.go_to_coord_rotation(parameters)
parameters = [1350, 1300, angle, speed]
self.go_to_coord_rotation(parameters)
######
parameters = [900, 1200, angle, speed]
self.go_to_coord_rotation(parameters)
parameters = [900, 1200, angle, speed]
self.go_to_coord_rotation(parameters)
parameters = [250, 1350, angle, speed]
self.go_to_coord_rotation(parameters)
########
parameters = [1150, 1200, angle, speed]
self.go_to_coord_rotation(parameters)
parameters = [1300, 1550, angle, speed]
self.go_to_coord_rotation(parameters)
parameters = [1270, 1500, angle, speed]
self.go_to_coord_rotation(parameters)
parameters = [1250, 1500, angle, speed]
self.go_to_coord_rotation(parameters)
parameters = [1200, 1450, angle, speed]
self.go_to_coord_rotation(parameters)
parameters = [1200, 1500, angle, speed]
self.go_to_coord_rotation(parameters)
parameters = [1250, 1550, angle, speed]
self.go_to_coord_rotation(parameters)
parameters = [1300, 1600, angle, speed]
self.go_to_coord_rotation(parameters)
parameters = [900, 150, angle, speed]
self.go_to_coord_rotation(parameters)
parameters = [170, 150, angle, speed]
self.go_to_coord_rotation(parameters)
return
def simpliest_trajectory(self,speed=1):
angle =3*np.pi / 2.
#1 area 2: after seesaw
parameters = [700, 150, angle, speed]
self.go_to_coord_rotation(parameters)
#2 back rocket stand to take
parameters = [1150, 190, angle, speed]
self.go_to_coord_rotation(parameters)
#3 back rocket pass big robot
parameters = [1250, 190, angle, speed]
self.go_to_coord_rotation(parameters)
time.sleep(1)
#4 back rocket stand to take
parameters = [1150, 190, angle, speed]
self.go_to_coord_rotation(parameters)
#########
#5 between adjust
parameters = [1250, 1200, angle, speed]
self.go_to_coord_rotation(parameters)
#6 1 lunar module
parameters = [1350, 1600, angle, speed]
self.go_to_coord_rotation(parameters)
#7 2nd lunar module
parameters = [1300, 1550, angle, speed]
self.go_to_coord_rotation(parameters)
#8 3rd lunar module
parameters = [1280, 1530, angle, speed]
self.go_to_coord_rotation(parameters)
#9 last module
parameters = [1250, 1500, angle, speed]
self.go_to_coord_rotation(parameters)
#10 between adjust
parameters = [1080, 1300, angle, speed]
self.go_to_coord_rotation(parameters)
#11 lateral rocket stand to take
parameters = [250, 1350, angle, speed]
self.go_to_coord_rotation(parameters)
self.go_last(parameters)
####
#12 between adjustment: back 20
parameters = [270, 1350, angle, speed]
self.go_to_coord_rotation(parameters)
#13 1st module
parameters = [270, 1150, angle, speed]
self.go_to_coord_rotation(parameters)
#14 2nd module
parameters = [270, 1050, angle, speed]
self.go_to_coord_rotation(parameters)
#15 3rd module take + rbg detect
parameters = [270, 950, angle, speed]
self.go_to_coord_rotation(parameters)
#16 2th module take + rbg detect
parameters = [270, 1050, angle, speed]
self.go_to_coord_rotation(parameters)
#17 1t module take + rbg detect
parameters = [270, 1150, angle, speed]
self.go_to_coord_rotation(parameters)
######
## funny action
parameters = [270, 1150, 0, speed]
self.go_to_coord_rotation(parameters)
parameters = [270, 1150, angle, speed]
self.go_to_coord_rotation(parameters)
parameters = [270, 1150, 0, speed]
self.go_to_coord_rotation(parameters)
def big_robot_trajectory(self,speed=1):
angle = np.pi*0.1
self.left_ball_up()
self.localisation.value = False
parameters = [900, 150, angle, speed]
self.go_to_coord_rotation(parameters)
self.localisation.value = True
angle = np.pi/2
parameters = [950, 400, angle, speed]
self.go_to_coord_rotation(parameters)
parameters = [950, 1000, angle, speed]
self.go_to_coord_rotation(parameters)
angle = 0.0
parameters = [250, 1750, angle, speed]
self.go_to_coord_rotation(parameters)
self.left_ball_down()
self.left_ball_up()
def big_robot_trajectory_r(self,speed=1):
angle = np.pi/2
parameters = [900, 1000, angle, speed]
self.go_to_coord_rotation(parameters)
parameters = [950, 400, angle, speed]
self.go_to_coord_rotation(parameters)
parameters = [950, 250, angle, speed]
self.go_to_coord_rotation(parameters)
angle = np.pi * 0.1
self.localisation.value = False
parameters = [170, 180, angle, speed]
self.go_to_coord_rotation(parameters)
self.localisation.value = True
self.left_ball_drop()
self.funny()
def first_cylinder(self,speed=1):
angle = np.pi
############### take cylinder
parameters = [700, 160, angle, speed]
self.go_to_coord_rotation(parameters)
parameters = [1135, 400, angle, speed]
self.go_to_coord_rotation(parameters)
angle = np.pi*3/2.
parameters = [1135, 400, angle, speed]
self.go_to_coord_rotation(parameters)
parameters = [1135, 300, angle, speed]
self.go_to_coord_rotation(parameters)
parameters = [1135, 220, angle, speed]
self.go_to_coord_rotation(parameters)
self.take_cylinder()
#self.store_cylinder()
##############
parameters = [1135, 400, angle, speed]
self.go_to_coord_rotation(parameters)
self.drop_cylinder()
return
self.go_to_coord_rotation(parameters)
parameters = [1150, 200, angle, speed]
angle = np.pi
self.go_to_coord_rotation(parameters)
parameters = [1150, 200, angle, speed]
self.go_to_coord_rotation(parameters)
parameters = [400, 800, angle, speed]
self.go_to_coord_rotation(parameters)
parameters = [200, 800, angle, speed]
self.go_last(parameters)
self.go_to_coord_rotation(parameters)
parameters = [120, 800, angle, speed]
self.drop_cylinder()
def funny_action(self, signum, frame):
print 'Main functionaly is off'
print 'FUNNNY ACTION'
def test():
rb = Robot(True)
#rb.take_cylinder()
#rb.first_cylinder()
i = 0
while i<10:
#rb.big_robot_trajectory(4)
#rb.big_robot_trajectory_r(4)
rb.demo(4)
rb.demo_r(4)
i+=1
def tst_time():
rb = Robot(True)
stamp = time.time()
for i in range(100):
command = {'source': 'fsm', 'cmd': 'echo', 'params': 'ECHO'}
rb.dr.process_cmd(command)
print time.time()-stamp
test()
| mit |
garysharp/EduHub.Data | src/EduHub.Data/Entities/KEMADataSet.cs | 15491 | using System;
using System.CodeDom.Compiler;
using System.Collections.Generic;
using System.Data;
using System.Data.SqlClient;
using System.Globalization;
using System.Linq;
using System.Text;
namespace EduHub.Data.Entities
{
/// <summary>
/// CSEF Receipt details Data Set
/// </summary>
[GeneratedCode("EduHub Data", "0.9")]
public sealed partial class KEMADataSet : EduHubDataSet<KEMA>
{
/// <inheritdoc />
public override string Name { get { return "KEMA"; } }
/// <inheritdoc />
public override bool SupportsEntityLastModified { get { return true; } }
internal KEMADataSet(EduHubContext Context)
: base(Context)
{
Index_TID = new Lazy<Dictionary<int, KEMA>>(() => this.ToDictionary(i => i.TID));
}
/// <summary>
/// Matches CSV file headers to actions, used to deserialize <see cref="KEMA" />
/// </summary>
/// <param name="Headers">The CSV column headers</param>
/// <returns>An array of actions which deserialize <see cref="KEMA" /> fields for each CSV column header</returns>
internal override Action<KEMA, string>[] BuildMapper(IReadOnlyList<string> Headers)
{
var mapper = new Action<KEMA, string>[Headers.Count];
for (var i = 0; i < Headers.Count; i++) {
switch (Headers[i]) {
case "TID":
mapper[i] = (e, v) => e.TID = int.Parse(v);
break;
case "FAMILY_KEY":
mapper[i] = (e, v) => e.FAMILY_KEY = v;
break;
case "STREGISTRATION":
mapper[i] = (e, v) => e.STREGISTRATION = v;
break;
case "EMA_PERIOD":
mapper[i] = (e, v) => e.EMA_PERIOD = v;
break;
case "EMA_TRAMT":
mapper[i] = (e, v) => e.EMA_TRAMT = v == null ? (decimal?)null : decimal.Parse(v);
break;
case "DELETE_FLAG":
mapper[i] = (e, v) => e.DELETE_FLAG = v;
break;
case "LW_DATE":
mapper[i] = (e, v) => e.LW_DATE = v == null ? (DateTime?)null : DateTime.ParseExact(v, "d/MM/yyyy h:mm:ss tt", CultureInfo.InvariantCulture);
break;
case "LW_TIME":
mapper[i] = (e, v) => e.LW_TIME = v == null ? (short?)null : short.Parse(v);
break;
case "LW_USER":
mapper[i] = (e, v) => e.LW_USER = v;
break;
default:
mapper[i] = MapperNoOp;
break;
}
}
return mapper;
}
/// <summary>
/// Merges <see cref="KEMA" /> delta entities
/// </summary>
/// <param name="Entities">Iterator for base <see cref="KEMA" /> entities</param>
/// <param name="DeltaEntities">List of delta <see cref="KEMA" /> entities</param>
/// <returns>A merged <see cref="IEnumerable{KEMA}"/> of entities</returns>
internal override IEnumerable<KEMA> ApplyDeltaEntities(IEnumerable<KEMA> Entities, List<KEMA> DeltaEntities)
{
HashSet<int> Index_TID = new HashSet<int>(DeltaEntities.Select(i => i.TID));
using (var deltaIterator = DeltaEntities.GetEnumerator())
{
using (var entityIterator = Entities.GetEnumerator())
{
while (deltaIterator.MoveNext())
{
var deltaClusteredKey = deltaIterator.Current.TID;
bool yieldEntity = false;
while (entityIterator.MoveNext())
{
var entity = entityIterator.Current;
bool overwritten = Index_TID.Remove(entity.TID);
if (entity.TID.CompareTo(deltaClusteredKey) <= 0)
{
if (!overwritten)
{
yield return entity;
}
}
else
{
yieldEntity = !overwritten;
break;
}
}
yield return deltaIterator.Current;
if (yieldEntity)
{
yield return entityIterator.Current;
}
}
while (entityIterator.MoveNext())
{
yield return entityIterator.Current;
}
}
}
}
#region Index Fields
private Lazy<Dictionary<int, KEMA>> Index_TID;
#endregion
#region Index Methods
/// <summary>
/// Find KEMA by TID field
/// </summary>
/// <param name="TID">TID value used to find KEMA</param>
/// <returns>Related KEMA entity</returns>
/// <exception cref="ArgumentOutOfRangeException">No match was found</exception>
public KEMA FindByTID(int TID)
{
return Index_TID.Value[TID];
}
/// <summary>
/// Attempt to find KEMA by TID field
/// </summary>
/// <param name="TID">TID value used to find KEMA</param>
/// <param name="Value">Related KEMA entity</param>
/// <returns>True if the related KEMA entity is found</returns>
/// <exception cref="ArgumentOutOfRangeException">No match was found</exception>
public bool TryFindByTID(int TID, out KEMA Value)
{
return Index_TID.Value.TryGetValue(TID, out Value);
}
/// <summary>
/// Attempt to find KEMA by TID field
/// </summary>
/// <param name="TID">TID value used to find KEMA</param>
/// <returns>Related KEMA entity, or null if not found</returns>
/// <exception cref="ArgumentOutOfRangeException">No match was found</exception>
public KEMA TryFindByTID(int TID)
{
KEMA value;
if (Index_TID.Value.TryGetValue(TID, out value))
{
return value;
}
else
{
return null;
}
}
#endregion
#region SQL Integration
/// <summary>
/// Returns a <see cref="SqlCommand"/> which checks for the existence of a KEMA table, and if not found, creates the table and associated indexes.
/// </summary>
/// <param name="SqlConnection">The <see cref="SqlConnection"/> to be associated with the <see cref="SqlCommand"/></param>
public override SqlCommand GetSqlCreateTableCommand(SqlConnection SqlConnection)
{
return new SqlCommand(
connection: SqlConnection,
cmdText:
@"IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[dbo].[KEMA]') AND OBJECTPROPERTY(id, N'IsUserTable') = 1)
BEGIN
CREATE TABLE [dbo].[KEMA](
[TID] int IDENTITY NOT NULL,
[FAMILY_KEY] varchar(10) NULL,
[STREGISTRATION] varchar(15) NULL,
[EMA_PERIOD] varchar(1) NULL,
[EMA_TRAMT] money NULL,
[DELETE_FLAG] varchar(1) NULL,
[LW_DATE] datetime NULL,
[LW_TIME] smallint NULL,
[LW_USER] varchar(128) NULL,
CONSTRAINT [KEMA_Index_TID] PRIMARY KEY CLUSTERED (
[TID] ASC
)
);
END");
}
/// <summary>
/// Returns null as <see cref="KEMADataSet"/> has no non-clustered indexes.
/// </summary>
/// <param name="SqlConnection">The <see cref="SqlConnection"/> to be associated with the <see cref="SqlCommand"/></param>
/// <returns>null</returns>
public override SqlCommand GetSqlDisableIndexesCommand(SqlConnection SqlConnection)
{
return null;
}
/// <summary>
/// Returns null as <see cref="KEMADataSet"/> has no non-clustered indexes.
/// </summary>
/// <param name="SqlConnection">The <see cref="SqlConnection"/> to be associated with the <see cref="SqlCommand"/></param>
/// <returns>null</returns>
public override SqlCommand GetSqlRebuildIndexesCommand(SqlConnection SqlConnection)
{
return null;
}
/// <summary>
/// Returns a <see cref="SqlCommand"/> which deletes the <see cref="KEMA"/> entities passed
/// </summary>
/// <param name="SqlConnection">The <see cref="SqlConnection"/> to be associated with the <see cref="SqlCommand"/></param>
/// <param name="Entities">The <see cref="KEMA"/> entities to be deleted</param>
public override SqlCommand GetSqlDeleteCommand(SqlConnection SqlConnection, IEnumerable<KEMA> Entities)
{
SqlCommand command = new SqlCommand();
int parameterIndex = 0;
StringBuilder builder = new StringBuilder();
List<int> Index_TID = new List<int>();
foreach (var entity in Entities)
{
Index_TID.Add(entity.TID);
}
builder.AppendLine("DELETE [dbo].[KEMA] WHERE");
// Index_TID
builder.Append("[TID] IN (");
for (int index = 0; index < Index_TID.Count; index++)
{
if (index != 0)
builder.Append(", ");
// TID
var parameterTID = $"@p{parameterIndex++}";
builder.Append(parameterTID);
command.Parameters.Add(parameterTID, SqlDbType.Int).Value = Index_TID[index];
}
builder.Append(");");
command.Connection = SqlConnection;
command.CommandText = builder.ToString();
return command;
}
/// <summary>
/// Provides a <see cref="IDataReader"/> for the KEMA data set
/// </summary>
/// <returns>A <see cref="IDataReader"/> for the KEMA data set</returns>
public override EduHubDataSetDataReader<KEMA> GetDataSetDataReader()
{
return new KEMADataReader(Load());
}
/// <summary>
/// Provides a <see cref="IDataReader"/> for the KEMA data set
/// </summary>
/// <returns>A <see cref="IDataReader"/> for the KEMA data set</returns>
public override EduHubDataSetDataReader<KEMA> GetDataSetDataReader(List<KEMA> Entities)
{
return new KEMADataReader(new EduHubDataSetLoadedReader<KEMA>(this, Entities));
}
// Modest implementation to primarily support SqlBulkCopy
private class KEMADataReader : EduHubDataSetDataReader<KEMA>
{
public KEMADataReader(IEduHubDataSetReader<KEMA> Reader)
: base (Reader)
{
}
public override int FieldCount { get { return 9; } }
public override object GetValue(int i)
{
switch (i)
{
case 0: // TID
return Current.TID;
case 1: // FAMILY_KEY
return Current.FAMILY_KEY;
case 2: // STREGISTRATION
return Current.STREGISTRATION;
case 3: // EMA_PERIOD
return Current.EMA_PERIOD;
case 4: // EMA_TRAMT
return Current.EMA_TRAMT;
case 5: // DELETE_FLAG
return Current.DELETE_FLAG;
case 6: // LW_DATE
return Current.LW_DATE;
case 7: // LW_TIME
return Current.LW_TIME;
case 8: // LW_USER
return Current.LW_USER;
default:
throw new ArgumentOutOfRangeException(nameof(i));
}
}
public override bool IsDBNull(int i)
{
switch (i)
{
case 1: // FAMILY_KEY
return Current.FAMILY_KEY == null;
case 2: // STREGISTRATION
return Current.STREGISTRATION == null;
case 3: // EMA_PERIOD
return Current.EMA_PERIOD == null;
case 4: // EMA_TRAMT
return Current.EMA_TRAMT == null;
case 5: // DELETE_FLAG
return Current.DELETE_FLAG == null;
case 6: // LW_DATE
return Current.LW_DATE == null;
case 7: // LW_TIME
return Current.LW_TIME == null;
case 8: // LW_USER
return Current.LW_USER == null;
default:
return false;
}
}
public override string GetName(int ordinal)
{
switch (ordinal)
{
case 0: // TID
return "TID";
case 1: // FAMILY_KEY
return "FAMILY_KEY";
case 2: // STREGISTRATION
return "STREGISTRATION";
case 3: // EMA_PERIOD
return "EMA_PERIOD";
case 4: // EMA_TRAMT
return "EMA_TRAMT";
case 5: // DELETE_FLAG
return "DELETE_FLAG";
case 6: // LW_DATE
return "LW_DATE";
case 7: // LW_TIME
return "LW_TIME";
case 8: // LW_USER
return "LW_USER";
default:
throw new ArgumentOutOfRangeException(nameof(ordinal));
}
}
public override int GetOrdinal(string name)
{
switch (name)
{
case "TID":
return 0;
case "FAMILY_KEY":
return 1;
case "STREGISTRATION":
return 2;
case "EMA_PERIOD":
return 3;
case "EMA_TRAMT":
return 4;
case "DELETE_FLAG":
return 5;
case "LW_DATE":
return 6;
case "LW_TIME":
return 7;
case "LW_USER":
return 8;
default:
throw new ArgumentOutOfRangeException(nameof(name));
}
}
}
#endregion
}
}
| mit |
regb/scala-game-library | desktop-native/src/main/scala/sgl/native/NativeSystemProvider.scala | 1421 | package sgl
package native
import sgl.util._
import java.net.URI
import java.awt.Desktop
import scala.concurrent.ExecutionContext
import scala.language.implicitConversions
trait NativeSystemProvider extends SystemProvider with PartsResourcePathProvider {
object NativeSystem extends System {
override def exit(): Unit = {
sys.exit()
}
override def currentTimeMillis: Long = java.lang.System.currentTimeMillis
override def nanoTime: Long = java.lang.System.nanoTime
override def loadText(path: ResourcePath): Loader[Array[String]] = {
???
//val is = getClass.getClassLoader.getResourceAsStream(path)
//scala.io.Source.fromInputStream(is).getLines
}
override def loadBinary(path: ResourcePath): Loader[Array[Byte]] = {
???
}
override def openWebpage(uri: URI): Unit = {
???
}
}
override val System = NativeSystem
// TODO: This is not really a root as we start with a first part ("assets"). We
// should instead add the assets prefix at the time when we convert the parts to
// a path. For now, it's a fine hack to get something working though.
override val ResourcesRoot: ResourcePath = PartsResourcePath(Vector("assets"))
// TODO: Add support for multi dpi in loadImage (so do not always use drawable-mdpi).
override val MultiDPIResourcesRoot: ResourcePath = PartsResourcePath(Vector("assets", "drawable-mdpi"))
}
| mit |
DataDog/java-dogstatsd-client | src/main/java/com/timgroup/statsd/StatsDSender.java | 4270 | package com.timgroup.statsd;
import java.io.IOException;
import java.net.SocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.DatagramChannel;
import java.nio.channels.WritableByteChannel;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.Callable;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ThreadFactory;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;
public class StatsDSender {
private final WritableByteChannel clientChannel;
private final StatsDClientErrorHandler handler;
private final BufferPool pool;
private final BlockingQueue<ByteBuffer> buffers;
private static final int WAIT_SLEEP_MS = 10; // 10 ms would be a 100HZ slice
protected final ThreadFactory threadFactory;
protected final Thread[] workers;
private final CountDownLatch endSignal;
private volatile boolean shutdown;
private volatile Telemetry telemetry;
StatsDSender(final WritableByteChannel clientChannel,
final StatsDClientErrorHandler handler, BufferPool pool, BlockingQueue<ByteBuffer> buffers,
final int workers, final ThreadFactory threadFactory) {
this.pool = pool;
this.buffers = buffers;
this.handler = handler;
this.threadFactory = threadFactory;
this.workers = new Thread[workers];
this.clientChannel = clientChannel;
this.endSignal = new CountDownLatch(workers);
}
public void setTelemetry(final Telemetry telemetry) {
this.telemetry = telemetry;
}
public Telemetry getTelemetry() {
return telemetry;
}
void startWorkers(final String namePrefix) {
// each task is a busy loop taking up one thread, so keep it simple and use an array of threads
for (int i = 0 ; i < workers.length ; i++) {
workers[i] = threadFactory.newThread(new Runnable() {
public void run() {
try {
sendLoop();
} finally {
endSignal.countDown();
}
}
});
workers[i].setName(namePrefix + (i + 1));
workers[i].start();
}
}
void sendLoop() {
ByteBuffer buffer = null;
Telemetry telemetry = getTelemetry(); // attribute snapshot to harness CPU cache
while (!(buffers.isEmpty() && shutdown)) {
int sizeOfBuffer = 0;
try {
if (buffer != null) {
pool.put(buffer);
}
buffer = buffers.poll(WAIT_SLEEP_MS, TimeUnit.MILLISECONDS);
if (buffer == null) {
continue;
}
sizeOfBuffer = buffer.position();
buffer.flip();
final int sentBytes = clientChannel.write(buffer);
buffer.clear();
if (sizeOfBuffer != sentBytes) {
throw new IOException(
String.format("Could not send stat %s entirely to %s. Only sent %d out of %d bytes",
buffer,
clientChannel,
sentBytes,
sizeOfBuffer));
}
if (telemetry != null) {
telemetry.incrBytesSent(sizeOfBuffer);
telemetry.incrPacketSent(1);
}
} catch (final InterruptedException e) {
if (shutdown) {
break;
}
} catch (final Exception e) {
if (telemetry != null) {
telemetry.incrBytesDropped(sizeOfBuffer);
telemetry.incrPacketDropped(1);
}
handler.handle(e);
}
}
}
void shutdown(boolean blocking) throws InterruptedException {
shutdown = true;
if (blocking) {
endSignal.await();
} else {
for (int i = 0 ; i < workers.length ; i++) {
workers[i].interrupt();
}
}
}
}
| mit |
chronos38/lupus-core | Source/BlackWolf.Lupus.System/UnixLibrary.cpp | 1984 | /**
* Copyright (C) 2014 David Wolf <d.wolf@live.at>
*
* This file is part of Lupus.
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
#ifndef _MSC_VER
#include "Library.h"
#include <dlfcn.h>
#include <cstdio>
namespace Lupus {
namespace System {
Library::Library(String path)
{
if (!(mHandle = force_cast<uintptr_t>(dlopen(path.ToUTF8().c_str(), RTLD_NOW)))) {
// TODO: Information eintragen sobald String::Format implementiert ist.
throw io_error();
}
}
Library::~Library()
{
if (mHandle) {
dlclose(force_cast<void*>(mHandle));
mHandle = 0;
}
}
void* Library::GetFunctionHandle(String name)
{
if (!mHandle) {
return nullptr;
}
return dlsym(force_cast<void*>(mHandle), name.ToUTF8().c_str());
}
}
}
#endif
| mit |
BuieConnect/BuieConnect-Android | app/src/main/java/me/arkanayan/buieconnect/services/MyGCMListenerService.java | 3483 | package me.arkanayan.buieconnect.services;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.media.RingtoneManager;
import android.net.Uri;
import android.os.Bundle;
import android.support.v4.app.NotificationCompat;
import android.util.Log;
import com.crashlytics.android.answers.Answers;
import com.crashlytics.android.answers.CustomEvent;
import com.google.gson.Gson;
import co.mobiwise.fastgcm.GCMListenerService;
import in.uncod.android.bypass.Bypass;
import me.arkanayan.buieconnect.R;
import me.arkanayan.buieconnect.activities.MainActivity;
import me.arkanayan.buieconnect.activities.NoticeDetailActivity;
import me.arkanayan.buieconnect.models.Notice;
import me.arkanayan.buieconnect.utils.App;
public class MyGCMListenerService extends GCMListenerService {
private final String TAG = this.getClass().getSimpleName();
@Override
public void onMessageReceived(String from, Bundle data) {
super.onMessageReceived(from, data);
if (data.getString("type").equals("notice")) {
Gson gson = new Gson();
Notice notice = gson.fromJson(data.getString("data"), Notice.class);
/* Log.d(TAG, "***Bundle Keys****");
for (String key : data.keySet()) {
Log.d(TAG, key + " : " + data.get(key));
}*/
// analytics
Answers.getInstance().logCustom(new CustomEvent("GCM Notice received")
.putCustomAttribute("From", from)
.putCustomAttribute("Notice Id", notice.getId())
);
/* String message = notice.getMessage();
String title = notice.getTitle();*/
// sends notification
sendNotification(notice);
}
}
/**
* Shows a simple notification
* @param notice GCM message Received
*/
private void sendNotification(Notice notice) {
Intent backIntent = new Intent(this, MainActivity.class);
backIntent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK);
Intent intent = NoticeDetailActivity.getInstance(this, notice);
/* PendingIntent pendingIntent = PendingIntent.getActivity(this, 0 ,
intent, PendingIntent.FLAG_ONE_SHOT);*/
PendingIntent pendingIntent = PendingIntent.getActivities(this, 0,
new Intent[]{backIntent, intent}, PendingIntent.FLAG_ONE_SHOT);
Bypass bypass = new Bypass(this);
CharSequence message = bypass.markdownToSpannable(notice.getMessage());
Bitmap largeIcon = BitmapFactory.decodeResource(getResources(), R.drawable.buie_splash);
Uri defaultSoundUri = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(this)
.setLargeIcon(largeIcon)
.setSmallIcon(R.mipmap.ic_launcher)
.setContentTitle(notice.getTitle())
.setContentText(message)
.setAutoCancel(true)
.setSound(defaultSoundUri)
.setContentIntent(pendingIntent);
NotificationManager notificationManager =
(NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
notificationManager.notify(0, notificationBuilder.build());
}
}
| mit |
lreimer/secure-programming-101 | secpro-webapp/src/main/java/de/qaware/campus/secpro/web/passwords/SecurePasswords.java | 3832 | /*
* The MIT License (MIT)
*
* Copyright (c) 2015 QAware GmbH, Munich, Germany
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package de.qaware.campus.secpro.web.passwords;
import de.qaware.commons.crypto.*;
import org.apache.commons.codec.binary.Base64;
import org.apache.deltaspike.core.api.config.ConfigProperty;
import javax.annotation.PostConstruct;
import javax.enterprise.context.ApplicationScoped;
import javax.inject.Inject;
/**
* A simple class to encrypt and decrypt secure passwords using the master
* password managed by the Glassfish password alias.
*
* @author mario-leander.reimer
*/
@ApplicationScoped
public class SecurePasswords {
private static final int ITERATIONS = 42;
@Inject
private MasterPassword masterPassword;
private Salt salt;
@Inject
@ConfigProperty(name = "secure.password")
private String securePassword;
/**
* Default constructor.
*/
public SecurePasswords() {
}
/**
* Manually inject the master password instance.
*
* @param masterPassword the master password
*/
SecurePasswords(MasterPassword masterPassword) {
this.masterPassword = masterPassword;
}
@PostConstruct
public void initialize() {
String saltBase64 = Base64.encodeBase64String(new byte[]{'s', 'a', 'l', 't'});
salt = Salt.fromBase64(saltBase64);
}
/**
* Returns the decrypted secure password property.
*
* @return the decrypted password
*/
public String getDecryptedSecurePassword() {
return decrypt(securePassword);
}
/**
* Encrypt the given plaintext string using the master password.
*
* @param plaintext the plain text password
* @return the Base64 encoded encrypted password.
*/
public String encrypt(String plaintext) {
try {
Key key = getKey();
Ciphertext ciphertext = CryptoUtil.encrypt(key, Plaintext.fromString(plaintext));
return ciphertext.toBase64();
} catch (CryptoException e) {
throw new SecurityException(e);
}
}
/**
* Decrypt the given ciphertext string into the plaintext original.
*
* @param ciphertext the ciphertext
* @return the decrypted string
*/
public String decrypt(String ciphertext) {
try {
Key key = getKey();
Plaintext decoded = CryptoUtil.decrypt(key, Ciphertext.fromBase64(ciphertext));
return decoded.asUtf8String();
} catch (CryptoException e) {
throw new SecurityException(e);
}
}
private Key getKey() throws CryptoException {
char[] password = masterPassword.toString().toCharArray();
return Key.fromPassword(password, salt, ITERATIONS);
}
}
| mit |
digital-york/researchdatayork | config/initializers/active_fedora_noid.rb | 174 | ActiveFedora::Base.translate_uri_to_id = ActiveFedora::Noid.config.translate_uri_to_id
ActiveFedora::Base.translate_id_to_uri = ActiveFedora::Noid.config.translate_id_to_uri
| mit |
Mistchenko/Dockers | ap/ws/ws/settings.py | 5009 | import os
# from logging.handlers import SysLogHandler
BASE_DIR = os.path.dirname(os.path.dirname(__file__))
SECRET_KEY = 'k0zg0kibq7lv3$vcodk0*6g&nq8yzgue_wfxvai%k1yy@5=myd'
DEBUG = True
TEMPLATE_DEBUG = True
ALLOWED_HOSTS = ['0.0.0.0']
# Application definition
INSTALLED_APPS = (
# 'django.contrib.admin',
# 'django.contrib.auth',
# 'django.contrib.contenttypes',
# 'django.contrib.sessions',
# 'django.contrib.messages',
# 'django.contrib.staticfiles',
'app',
)
MIDDLEWARE_CLASSES = (
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.common.CommonMiddleware',
# 'django.middleware.csrf.CsrfViewMiddleware',
# 'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware',
)
ROOT_URLCONF = 'ws.urls'
WSGI_APPLICATION = 'ws.wsgi.application'
DATABASES = {
'default': {
# 'ENGINE': 'django.db.backends.sqlite3',
# 'NAME': os.path.join(BASE_DIR, 'db.sqlite3'),
}
}
LANGUAGE_CODE = 'en-us'
TIME_ZONE = 'UTC'
USE_I18N = True
USE_L10N = True
USE_TZ = True
STATIC_URL = '/static/'
# XLSX = True # Excel format '.xlsx'
XLSX = False # Excel 98 format '.xls'
# ---------------------------------------------------------------------------------------------
# HOST_NAME = 'dev'
# WS_LOG_FORMAT = '{0}:[%(asctime)s] - %(levelname)s - %(message)s'.format(HOST_NAME)
# PING_LOG_FORMAT = '{0}:[%(asctime)s] - %(message)s'.format(HOST_NAME)
# LOG_DATE_FORMAT = '%a %b %d %H:%M:%S %Y'
#
#
# LOGGING = {
# 'version': 1,
# 'disable_existing_loggers': True,
# 'formatters': {
# 'rootFormatter': {
# 'format': WS_LOG_FORMAT,
# 'datefmt': LOG_DATE_FORMAT,
# },
# 'pingFormatter': {
# 'format': PING_LOG_FORMAT,
# 'datefmt': LOG_DATE_FORMAT,
# },
# 'samlFormatter': {
# 'format': WS_LOG_FORMAT,
# 'datefmt': LOG_DATE_FORMAT,
# },
# },
# 'handlers': {
# 'rootHandler': {
# 'level': 'INFO',
# 'class': 'logging.handlers.SysLogHandler',
# 'address': '/dev/log',
# 'formatter': 'rootFormatter',
# 'facility': SysLogHandler.LOG_LOCAL2,
# },
# 'pingHandler': {
# 'level': 'INFO',
# 'class': 'logging.handlers.SysLogHandler',
# 'address': '/dev/log',
# 'formatter': 'pingFormatter',
# 'facility': SysLogHandler.LOG_LOCAL3,
# },
# 'samlHandler': {
# 'level': 'DEBUG',
# 'class': 'logging.handlers.SysLogHandler',
# 'address': '/dev/log',
# 'formatter': 'samlFormatter',
# 'facility': SysLogHandler.LOG_LOCAL6,
# },
# 'null': {
# 'level': 'DEBUG',
# 'class': 'django.utils.log.NullHandler',
# }
# },
# 'loggers': {
# '': {
# 'handlers': ['rootHandler'],
# 'level': 'INFO',
# 'propagate': True,
# },
# 'ping': {
# 'handlers': ['pingHandler'],
# 'level': 'INFO',
# 'propagate': False,
# },
# 'saml': {
# 'handlers': ['samlHandler'],
# 'level': 'DEBUG',
# 'propagate': False,
# },
# 'djangosaml2': {
# 'handlers': ['samlHandler'],
# 'level': 'DEBUG',
# },
# 'saml2': {
# 'handlers': ['samlHandler'],
# 'level': 'DEBUG',
# },
# 'factory': {
# 'level': 'ERROR',
# 'propagate': False
# }
# }
# }
#
# LOG_TEMPLATES = {"GENERAL": "Service:'{service}' Reply:'{code}' Time:'{response_time}' StartTime:'{start_time}' ClientID:'{client_id}' Request:'{parameters}'",
# "LOGIN": "Service:'{service}' Report: session with SID='{sid}' opened for user with UID='{uid}',LDAP_UID='{ldap_uid}',DisplayName='{display_name}',Host='%s'" % HOST_NAME,
# "CUSTOMER": "Service:'{service}' Report: Customer='{customer}',SID='{sid}'",
# "REPORT": "Service:'{service}' basefilename: {filename} fullpath: {path}",
# "DOWNLOAD": "Service:'{service}' Report: UID='{ldap_uid}' downloaded {type} files, filename='{filename}'",
# "TABLEAU": "Service:'{service}' Report: UID='{ldap_uid}', tableau url='{url}'",
# "ERROR": "Service:'{service}' [{code}] {message} Details: '{details}'",
# "LDAP": "Message:'using '{server}' ldap server'",
# "PING": "Report: Host={host},Customer={customer},SID={sid},LDAP_UID={ldap_uid},info={info}",
# "SEARCH": "Message: sphinx found non-existing claims: {claims}",
# "CLIENT_ID": "Message: client ID '{client_id}' does not match the expected format"}
| mit |
geota/hadesmem | include/memory/hadesmem/region_list.hpp | 4978 | // Copyright (C) 2010-2015 Joshua Boyce
// See the file COPYING for copying permission.
#pragma once
#include <iterator>
#include <memory>
#include <utility>
#include <windows.h>
#include <hadesmem/config.hpp>
#include <hadesmem/detail/assert.hpp>
#include <hadesmem/detail/optional.hpp>
#include <hadesmem/detail/query_region.hpp>
#include <hadesmem/detail/trace.hpp>
#include <hadesmem/error.hpp>
#include <hadesmem/process.hpp>
#include <hadesmem/protect.hpp>
#include <hadesmem/region.hpp>
namespace hadesmem
{
// RegionIterator satisfies the requirements of an input iterator
// (C++ Standard, 24.2.1, Input Iterators [input.iterators]).
template <typename RegionT>
class RegionIterator : public std::iterator<std::input_iterator_tag, RegionT>
{
public:
using BaseIteratorT = std::iterator<std::input_iterator_tag, RegionT>;
using value_type = typename BaseIteratorT::value_type;
using difference_type = typename BaseIteratorT::difference_type;
using pointer = typename BaseIteratorT::pointer;
using reference = typename BaseIteratorT::reference;
using iterator_category = typename BaseIteratorT::iterator_category;
HADESMEM_DETAIL_CONSTEXPR RegionIterator() HADESMEM_DETAIL_NOEXCEPT
{
}
explicit RegionIterator(Process const& process)
{
try
{
impl_ = std::make_shared<Impl>(process);
}
catch (hadesmem::Error const& e)
{
// VirtualQuery can fail with ERROR_ACCESS_DENIED for 'zombie' processes.
auto const last_error_ptr =
boost::get_error_info<hadesmem::ErrorCodeWinLast>(e);
if (!last_error_ptr || *last_error_ptr != ERROR_ACCESS_DENIED)
{
throw;
}
}
}
explicit RegionIterator(Process&& process) = delete;
#if defined(HADESMEM_DETAIL_NO_RVALUE_REFERENCES_V3)
RegionIterator(RegionIterator const&) = default;
RegionIterator& operator=(RegionIterator const&) = default;
RegionIterator(RegionIterator&& other) HADESMEM_DETAIL_NOEXCEPT
: impl_{std::move(other.impl_)}
{
}
RegionIterator& operator=(RegionIterator&& other) HADESMEM_DETAIL_NOEXCEPT
{
impl_ = std::move(other.impl_);
return *this;
}
#endif // #if defined(HADESMEM_DETAIL_NO_RVALUE_REFERENCES_V3)
reference operator*() const HADESMEM_DETAIL_NOEXCEPT
{
HADESMEM_DETAIL_ASSERT(impl_.get());
return *impl_->region_;
}
pointer operator->() const HADESMEM_DETAIL_NOEXCEPT
{
HADESMEM_DETAIL_ASSERT(impl_.get());
return &*impl_->region_;
}
RegionIterator& operator++()
{
HADESMEM_DETAIL_ASSERT(impl_.get());
void const* const base = impl_->region_->GetBase();
SIZE_T const size = impl_->region_->GetSize();
auto const next = static_cast<char const* const>(base) + size;
MEMORY_BASIC_INFORMATION mbi{};
try
{
mbi = detail::Query(*impl_->process_, next);
}
catch (hadesmem::Error const& e)
{
auto const last_error_ptr =
boost::get_error_info<hadesmem::ErrorCodeWinLast>(e);
if (!last_error_ptr || *last_error_ptr != ERROR_INVALID_PARAMETER)
{
throw;
}
impl_.reset();
return *this;
}
impl_->region_ = Region{*impl_->process_, mbi};
return *this;
}
RegionIterator operator++(int)
{
RegionIterator const iter{*this};
++*this;
return iter;
}
bool operator==(RegionIterator const& other) const HADESMEM_DETAIL_NOEXCEPT
{
return impl_ == other.impl_;
}
bool operator!=(RegionIterator const& other) const HADESMEM_DETAIL_NOEXCEPT
{
return !(*this == other);
}
private:
struct Impl
{
explicit Impl(Process const& process) HADESMEM_DETAIL_NOEXCEPT
: process_{&process}
{
MEMORY_BASIC_INFORMATION const mbi = detail::Query(process, nullptr);
region_ = Region{process, mbi};
}
Process const* process_;
hadesmem::detail::Optional<Region> region_;
};
// Shallow copy semantics, as required by InputIterator.
std::shared_ptr<Impl> impl_;
};
class RegionList
{
public:
using value_type = Region;
using iterator = RegionIterator<Region>;
using const_iterator = RegionIterator<Region const>;
explicit RegionList(Process const& process) : process_{&process}
{
}
explicit RegionList(Process&& process) = delete;
iterator begin()
{
return iterator(*process_);
}
const_iterator begin() const
{
return const_iterator(*process_);
}
const_iterator cbegin() const
{
return const_iterator(*process_);
}
iterator end() HADESMEM_DETAIL_NOEXCEPT
{
return iterator();
}
const_iterator end() const HADESMEM_DETAIL_NOEXCEPT
{
return const_iterator();
}
const_iterator cend() const HADESMEM_DETAIL_NOEXCEPT
{
return const_iterator();
}
private:
Process const* process_;
};
}
| mit |
mpalourdio/SpringBootTemplate | src/main/java/com/mpalourdio/springboottemplate/rsa/exceptions/EncryptException.java | 351 | package com.mpalourdio.springboottemplate.rsa.exceptions;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.ResponseStatus;
@ResponseStatus(value = HttpStatus.BAD_REQUEST)
public class EncryptException extends RuntimeException {
public EncryptException(String message) {
super(message);
}
}
| mit |
mikecann/Unity-Parse-Helpers | Editor/Tests/TestModels.cs | 1604 | ๏ปฟusing Parse;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using UnityParseHelpers;
namespace UnityParseHelpersTests
{
public interface IFather
{
string Name { get; }
Child Son { get; set; }
IChild Daughter { get; set; }
}
[ParseClassName("Father")]
public class Father : ParseObject, IFather
{
public int AField;
public Child AProperty { get; set; }
public int AMethod() { return 0; }
[ParseFieldName("name")]
public string Name { get; set; }
[ParseFieldName("son")]
public Child Son { get; set; }
[ParseFieldName("daughter")]
[ParseFieldType(typeof(Child))]
public IChild Daughter { get; set; }
[ParseFieldName("children")]
[ParseFieldType(typeof(Child))]
public List<IChild> Children { get; set; }
}
public interface IChild
{
string Name { get; }
int Age { get; set; }
IChild Brother { get; set; }
IChild Sister { get; set; }
void Shout();
}
[ParseClassName("Child")]
public class Child : ParseObject, IChild
{
public int Age { get; set; }
[ParseFieldName("name")]
public string Name { get; set; }
[ParseFieldName("brother")]
public IChild Brother { get; set; }
[ParseFieldName("sister")]
[ParseFieldType(typeof(Child))]
public IChild Sister { get; set; }
public void Shout() { Console.WriteLine("Raaar!"); }
}
}
| mit |
ChannelElementsTeam/channel-web-client | public/src/core/db-service.js | 5038 | class DbService {
constructor() {
this.DB_NAME = "channels-web-client";
this.DB_VERSION = 1;
this.STORE_COMPONENTS = "components";
this.STORE_PINNED = "pinnedcards";
this.MODE_READWRITE = "readwrite";
this.MODE_READ = "readonly";
this.db = null;
}
open() {
return new Promise((resolve, reject) => {
if (this.db) {
resolve();
return;
}
const request = indexedDB.open(this.DB_NAME, this.DB_VERSION);
request.onerror = (event) => {
console.error("Failed to load DB: ", event);
reject(new Error("Error loading database: " + (event.message || event)));
};
request.onsuccess = (event) => {
this.db = request.result;
resolve();
};
request.onupgradeneeded = (event) => {
const db = event.target.result;
db.onerror = (event) => {
console.log("Failed to load database: ", event);
};
if (!db.objectStoreNames.contains(this.STORE_COMPONENTS)) {
const store = db.createObjectStore(this.STORE_COMPONENTS, { keyPath: "source" });
}
if (!db.objectStoreNames.contains(this.STORE_PINNED)) {
const store = db.createObjectStore(this.STORE_PINNED, { keyPath: "channel" });
}
};
});
}
getStore(name, mode) {
const tx = this.db.transaction(name, mode);
return tx.objectStore(name);
}
saveComponent(component) {
return this.open().then(() => {
return new Promise((resolve, reject) => {
const store = this.getStore(this.STORE_COMPONENTS, this.MODE_READWRITE);
try {
const request = store.put(component);
request.onerror = (event) => {
console.error("Error saving component to db: ", event);
reject(new Error("Error saving component: " + event));
};
request.onsuccess = (event) => {
resolve();
};
} catch (ex) {
reject(ex);
}
});
});
}
getComponent(source) {
return this.open().then(() => {
return new Promise((resolve, reject) => {
const store = this.getStore(this.STORE_COMPONENTS, this.MODE_READ);
const request = store.get(source);
request.onerror = (event) => {
console.error("Failed to load component from DB: ", event);
reject(new Error("Failed to load component: " + event));
};
request.onsuccess = (event) => {
resolve(request.result);
};
});
});
}
savePinnedCards(channel, cardList) {
return this.open().then(() => {
return new Promise((resolve, reject) => {
const store = this.getStore(this.STORE_PINNED, this.MODE_READWRITE);
try {
const request = store.put({
channel: channel,
cardList: cardList
});
request.onerror = (event) => {
console.error("Error saving pinned card list to db: ", event);
reject(new Error("Error saving pinned card list: " + event));
};
request.onsuccess = (event) => {
resolve();
};
} catch (ex) {
reject(ex);
}
});
});
}
getPinnedCards(channel) {
return this.open().then(() => {
return new Promise((resolve, reject) => {
const store = this.getStore(this.STORE_PINNED, this.MODE_READ);
const request = store.get(channel);
request.onerror = (event) => {
console.error("Failed to load pinned cards from DB: ", event);
reject(new Error("Failed to load pinned cards: " + event));
};
request.onsuccess = (event) => {
resolve(request.result ? (request.result.cardList || []) : []);
};
});
});
}
getAllComponents() {
return this.open().then(() => {
return new Promise((resolve, reject) => {
const store = this.getStore(this.STORE_COMPONENTS, this.MODE_READ);
const request = store.openCursor();
const result = [];
request.onerror = (event) => {
console.error("Failed to open components cursor: ", event);
reject(new Error("Failed to open components cursor: " + event));
};
request.onsuccess = (event) => {
const cursor = event.target.result;
if (cursor) {
result.push(cursor.value);
cursor.continue();
} else {
resolve(result);
}
};
});
});
}
getLocal(key, json) {
if (window.localStorage) {
var stored = window.localStorage.getItem(key) || "";
if (json) {
if (stored) {
return JSON.parse(stored);
}
return null;
}
return stored;
}
return null;
}
setLocal(key, value) {
if (window.localStorage) {
if (typeof value === "string") {
window.localStorage.setItem(key, value);
} else {
window.localStorage.setItem(key, JSON.stringify(value));
}
}
}
} | mit |
ling7334/Novel-crawler | usrlib.py | 13928 | #encoding:UTF-8
#from threading import Thread
import pickle
from configparser import ConfigParser
from os import (path,makedirs,listdir)
from urllib import (request,parse)
from flask import jsonify
from bs4 import BeautifulSoup
HEADERS = {
'User-Agent' : 'Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/54.0.2840.71 Safari/537.36'
}
DIRDICT = {'novellist' : './novel/list.dat',\
'noveldata' : lambda novelname : './novel/' + novelname + '/info.dat',\
'chapter_name' : lambda novelname : './novel/' + novelname + '/chapter_name.dat',\
'chapter_link' : lambda novelname : './novel/' + novelname + '/chapter_link.dat',\
'chapter' : lambda novelname,index :'./novel/' + novelname + '/' + repr(index) + '.txt'}
CONFIG = ConfigParser()
CONFIG.read('./config.ini',encoding='utf8')
def Get_ID():
'''่ทๅๆ็ดข็ฝ็ซ่ฎพ็ฝฎ็IDๅ่กจ'''
ID = list()
for item in CONFIG.sections():
ID.append(item)
return ID
def Search_By_ID(novelname, id):
'''่ทๅๅฐ่ฏดไฟกๆฏ๏ผ็ฎๅฝ๏ผ้กต
novelname๏ผๅฐ่ฏดๅ
id๏ผ็ฝ็ซ่ฎพ็ฝฎID
'''
opts = CONFIG[id]
__searchdata = {}
__searchdata[opts['keyword']] = novelname #ๆๅปบๆ็ดขๅ
ณ้ฎ่ฏ
url = opts["slink"] + parse.urlencode(__searchdata, encoding='GBK') #ๅ
ณ้ฎ่ฏURL็ผ็
req = request.Request(url, None, HEADERS)
try:
data = request.urlopen(req).read() #่ฏปๅๆ็ดข้กต้ขๅ
ๅฎน
except:
return -1 #็ฝ็ซๆ ๆณ่ฟๆฅ
soup = BeautifulSoup(data, "html.parser") #ๆๅปบBSๆฐๆฎ
string = 'soup.' + opts["novel_link"]
try:
url = eval(string) #่ทๅๅฐ่ฏด้กต้ข้พๆฅ
except:
return -2
if not url.startswith('http'):
url = opts["url"] + url #ๆๅปบๅฐ่ฏด้กต้ข้พๆฅ
# try:
# data = request.urlopen(url).read() #่ฏปๅๅฐ่ฏดไฟกๆฏ้กต้ขๅ
ๅฎน
# except:
# return -1 #ๅฐ่ฏดไฟกๆฏ้กต้ขๆ ๆณ่ฟๆฅ
return url
def Get_Novel_Info(url,id):
'''่ทๅๅฐ่ฏดไฟกๆฏ
url๏ผๅฐ่ฏดไฟกๆฏ๏ผ็ฎๅฝ๏ผ้กต
id๏ผ็ฝ็ซID'''
opts = CONFIG[id]
noveldata = {}
req = request.Request(url, None, HEADERS)
try:
data = request.urlopen(req).read() #่ฏปๅๅฐ่ฏด้กต้ขๅ
ๅฎน
except:
return -1 #ๅฐ่ฏด้กต้ขๆ ๆณ่ฟๆฅ
soup = BeautifulSoup(data,"html.parser") #ๆๅปบBSๆฐๆฎ
# print(data)
#--------------------------------------------------ๆๅๅฐ่ฏดไฟกๆฏ
noveldata['homepage'] = opts['url']
noveldata['infolink'] = url
noveldata['id'] = opts['id']
noveldata['website'] = opts['name']
string = 'soup.'+ opts['title']
# print(string)
try:
noveldata['title'] = eval(string)
except:
# print(url,data)
return -1
try:
string = 'soup.'+opts['content_link']
string = eval(string)
if not string.startswith('http'):
string = noveldata['homepage'] + string
noveldata['content_link'] = eval(string)
except:
pass
try:
string = 'soup.'+opts['description']
noveldata['description'] = eval(string)
except:
pass
try:
string = 'soup.'+opts['category']
noveldata['category'] = eval(string)
except:
pass
try:
string = 'soup.'+opts['author']
noveldata['author'] = eval(string)
except:
pass
try:
string = 'soup.'+opts['status']
noveldata['status'] = eval(string)
except:
pass
try:
string = 'soup.'+opts['update']
noveldata['update'] = eval(string)
except:
pass
try:
string = 'soup.'+opts['latest']
noveldata['latest'] = eval(string)
except:
pass
try:
string = 'soup.'+opts['image']
except:
pass
string = eval(string)
if not string.startswith('http'):
string = noveldata['homepage'] + string
noveldata['image'] = string
# #--------------------------------------------------ๅๅปบๅฐ่ฏดๆไปถๅคน
# filename = './novel/' + noveldata['title'] + '/'
# if not path.exists(filename):
# makedirs(filename)
# #--------------------------------------------------ๅๅ
ฅๅฐ่ฏดไฟกๆฏ
# filename = './novel/' + noveldata['title'] + '/' + 'info.dat'
# pickle.dump(noveldata, open(filename, "wb"))
# #--------------------------------------------------ๅๅ
ฅๅฐ่ฏดๅ่กจ
# filename = './novel/' + 'list.dat'
# novel_list = list()
# for item in listdir('./novel/'):
# if path.isfile('./novel/'+item+'info.dat'):
# novel_list.append(item)
# pickle.dump(novel_list, open(filename, "wb"))
return noveldata
def Save_Content(noveldata):
"""ไป้ขๅฎ็ฝ็ซไธ่ฝฝ็ซ ่ๅ่กจ
noveldata:ๅฐ่ฏดไฟกๆฏๅญๅ
ธ
"""
chapter_name=[]
chapter_link=[]
opts = CONFIG[noveldata['id']]
if 'content_link' in noveldata:
url = noveldata['content_link']
else:
url = noveldata['infolink']
req = request.Request(url, None, HEADERS)
try:
data = request.urlopen(req).read() #่ฏปๅ็ฎๅฝ้กต้ขๅ
ๅฎน
except:
return -1 #็ฎๅฝ้กต้ขๆ ๆณ่ฟๆฅ
soup = BeautifulSoup(data,"html.parser") #ๆๅปบBSๆฐๆฎ
#--------------------------------------------------ๆๅๅฐ่ฏด็ซ ่ๅ่กจ
string = 'soup.'+opts['chapter_list']
for chapter_list in eval(string):
string = eval(opts['chapter_name'])
string = str(string)
chapter_name.append(string)
link = eval(opts['chapter_link'])
if not link.startswith('http'):
if ((link.split("/")[0] == '') & (len(link.split("/")) <= 2)) | (len(link.split("/")) <= 1):
chapter_url = url + link
else:
chapter_url = opts['url'] + eval(opts['chapter_link'])
else:
chapter_url = link
chapter_link.append(chapter_url)
#--------------------------------------------------ๅๅปบๅฐ่ฏดๆไปถๅคน
if not path.exists('./novel/' + noveldata['title'] + '/'):
makedirs('./novel/' + noveldata['title'] + '/')
#--------------------------------------------------ๅๅ
ฅๅฐ่ฏดไฟกๆฏ
pickle.dump(noveldata, open(DIRDICT['noveldata'](noveldata['title']), "wb"))
#--------------------------------------------------ๅๅ
ฅๅฐ่ฏดๅ่กจ
novel_list = []
for novelname in listdir('./novel/'):
if path.isfile(DIRDICT['noveldata'](novelname)):
novel_list.append(novelname)
pickle.dump(novel_list, open(DIRDICT['novellist'], "wb"))
#--------------------------------------------------ๅๅ
ฅๅฐ่ฏด็ฎๅฝ
pickle.dump(chapter_name, open(DIRDICT['chapter_name'](noveldata['title']), "wb"))
pickle.dump(chapter_link, open(DIRDICT['chapter_link'](noveldata['title']), "wb"))
#--------------------------------------------------ๅๅ
ฅๅฐ่ฏด็ซ ่
# if end == -1:
# end = len(self.chapter_link)
# for i in range(start,end):
# data=request.urlopen(self.chapter_link[i]).read() #่ฏปๅ็ซ ่ๅ
ๅฎน
# soup = BeautifulSoup(data,"html.parser") #ๆๅปบBSๆฐๆฎ
# text = eval('soup.'+self.opts['text'])
# filename = './novel/' + self.noveldata['title'] + '/' + repr(i) + '.txt'
# fo = open(filename, "wb")
# fo.write(text.encode('utf8'))
# fo.close()
return True
def Get_New_Chapter_List(noveldata):
'''ไป้ขๅฎ็ฝ้กตๆดๆฐ็ซ ่ๅ่กจ
noveldata๏ผๅฐ่ฏดไฟกๆฏๅญๅ
ธ'''
update_noveldata ={}
chapter_name=[]
chapter_link=[]
update_chapter_name =[]
rt=[]
t={}
if 'content_link' in noveldata:
url = noveldata['content_link']
else:
url = noveldata['infolink']
update_noveldata = Get_Novel_Info(url,noveldata['id'])
if update_noveldata == -1:
return '-1'
if update_noveldata['latest'] == noveldata['latest']:
return '0'
opts = CONFIG[noveldata['id']]
chapter_name = pickle.load(open(DIRDICT['chapter_name'](noveldata['title']), "rb"))
req = request.Request(url, None, HEADERS)
try:
data = request.urlopen(req).read() #่ฏปๅ็ฎๅฝ้กต้ขๅ
ๅฎน
except:
return '-1' #็ฎๅฝ้กต้ขๆ ๆณ่ฟๆฅ
soup = BeautifulSoup(data,"html.parser") #ๆๅปบBSๆฐๆฎ
#--------------------------------------------------ๆๅๅฐ่ฏด็ซ ่ๅ่กจ
comstr = 'soup.'+opts['chapter_list']
for chapter_list in eval(comstr):
string = eval(opts['chapter_name'])
string = str(string)
update_chapter_name.append(string)
link = eval(opts['chapter_link'])
if not link.startswith('http'):
if ((link.split("/")[0] == '') & (len(link.split("/")) <= 2)) | (len(link.split("/")) <= 1):
chapter_url = url + link
else:
chapter_url = opts['url'] + eval(opts['chapter_link'])
else:
chapter_url = link
chapter_link.append(chapter_url)
for chapter in update_chapter_name:
if not chapter in chapter_name:
rt.append({"index": update_chapter_name.index(chapter), "name": chapter})
if 'lastread' in noveldata:
update_noveldata['lastread'] = noveldata['lastread']
pickle.dump(update_noveldata, open(DIRDICT['noveldata'](noveldata['title']), "wb"))
#--------------------------------------------------ๅๅ
ฅๅฐ่ฏด็ฎๅฝ
pickle.dump(update_chapter_name, open(DIRDICT['chapter_name'](noveldata['title']), "wb"))
pickle.dump(chapter_link, open(DIRDICT['chapter_link'](noveldata['title']), "wb"))
#t['list'] = rt
return jsonify({'list':rt})
def escape(txt,space):
'''ๅฐtxtๆๆฌไธญ็็ฉบๆ ผใ&ใ<ใ>ใ๏ผ"๏ผใ๏ผ'๏ผ่ฝฌๅๆๅฏนๅบ็็ๅญ็ฌฆๅฎไฝ๏ผไปฅๆนไพฟๅจhtmlไธๆพ็คบ'''
txt = txt.replace('&','&')
txt = txt.replace(' ',' ')
txt = txt.replace('<','<')
txt = txt.replace('>','>')
txt = txt.replace('"','"')
txt = txt.replace('\'',''')
txt = txt.replace('\r',space*'<br />')
txt = txt.replace('\n',space*'<br />')
return txt
def Load_Novel_List():
'''่ฝฝๅ
ฅๅฐ่ฏดๅ่กจ'''
try:
return pickle.load(open(DIRDICT['novellist'], "rb"))
except:
print("ๅฐ่ฏดๅ่กจๆชๅๅปบ")
return None
def Load_Novel_Data(novelname):
'''่ฝฝๅ
ฅๅฐ่ฏดไฟกๆฏ
novelname๏ผๅฐ่ฏดๅ
'''
try:
return pickle.load(open(DIRDICT['noveldata'](novelname), "rb"))
except:
print("ๆชๆพๅฐ่ฏฅๅฐ่ฏด")
return None
def Load_Chapter_List(novelname):
'''่ฝฝๅ
ฅๅฐ่ฏด็ซ ่ๅ่กจ
novelname๏ผๅฐ่ฏดๅ'''
try:
return pickle.load(open(DIRDICT['chapter_name'](novelname), "rb"))
except:
print("ๆชๆพๅฐ็ซ ่ๅ่กจ")
return None
def Load_Chapter(novelname,index):
'''่ฝฝๅ
ฅๆฌๅฐ็ซ ่ๅ
ๅฎน
novelname๏ผๅฐ่ฏดๅ
index๏ผ็ซ ่ๆ ๅฟไฝ
'''
if path.isfile(DIRDICT['chapter'](novelname,index)):
return open(DIRDICT['chapter'](novelname,index),encoding='utf8').read()
else:
return -1
def Search_Chapter(novelname,index):
'''ไป้ขๅฎ็ฝ็ซไธ่ฝฝๆๅฎ็ซ ่
novelname๏ผๅฐ่ฏดๅ
index๏ผ็ซ ่ๆ ๅฟไฝ
'''
noveldata = {}
chapter_link = []
try:
noveldata = pickle.load(open(DIRDICT['noveldata'](novelname), "rb"))
chapter_link = pickle.load(open(DIRDICT['chapter_link'](novelname), "rb"))
except:
return -1
#่ฝฝๅ
ฅ็ฝ็ซ่ฎพ็ฝฎ
opts = CONFIG[noveldata['id']]
try:
req = request.Request(chapter_link[index], None, HEADERS)
data = request.urlopen(req).read() #่ฏปๅ็ซ ่ๅ
ๅฎน
except:
return -2
soup = BeautifulSoup(data,"html.parser") #ๆๅปบBSๆฐๆฎ
comstr = 'soup.'+ opts['text']
text = eval(comstr)
return text
def Get_Chapter(novelname,index):
'''ๅฐ่ฏไปๆฌๅฐไธ็ฝ็ซ่ฝฝๅ
ฅ็ซ ่
novelname๏ผๅฐ่ฏดๅ
index๏ผ็ซ ่ๆ ๅฟไฝ
'''
text = Load_Chapter(novelname,index)
if text == -1:
text = Search_Chapter(novelname,index)
if text == -1:
return 'ๆชๆพๅฐ็ซ ่ไฟกๆฏ๏ผ'
elif text == -2:
return 'ๆชๆพๅฐ็ซ ่๏ผ'
else:
open(DIRDICT['chapter'](novelname,index), "wb").write(text.encode('utf8'))
return text
if __name__ == "__main__":
# print(Search_By_ID('ๆ่พฐไนไธป','xs111'))
opts = CONFIG['bqg5200']
__searchdata = {}
__searchdata[opts['keyword']] = 'ๅฏปๆพ่ตฐไธข็่ฐๅจ'
url = opts["slink"] + parse.urlencode(__searchdata)
print(url)
req = request.Request(url, None, HEADERS)
data = request.urlopen(req).read()
print(data)
pass | mit |
psjava/psjava | src/test/java/org/psjava/ds/array/MutableArrayUsingBooleanArrayTest.java | 368 | package org.psjava.ds.array;
import org.junit.Test;
import static org.junit.Assert.*;
public class MutableArrayUsingBooleanArrayTest {
@Test
public void test() {
MutableArray<Boolean> a = MutableArrayUsingBooleanArray.wrap(new boolean[]{true, false, false});
a.set(1, true);
assertEquals("(true,true,false)", a.toString());
}
} | mit |
Azure/azure-sdk-for-python | sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2018_09_01/models/_monitor_management_client_enums.py | 2147 | # coding=utf-8
# --------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See License.txt in the project root for license information.
# Code generated by Microsoft (R) AutoRest Code Generator.
# Changes may cause incorrect behavior and will be lost if the code is regenerated.
# --------------------------------------------------------------------------
from enum import Enum, EnumMeta
from six import with_metaclass
class _CaseInsensitiveEnumMeta(EnumMeta):
def __getitem__(self, name):
return super().__getitem__(name.upper())
def __getattr__(cls, name):
"""Return the enum member matching `name`
We use __getattr__ instead of descriptors or inserting into the enum
class' __dict__ in order to support `name` and `value` being both
properties for enum members (which live in the class' __dict__) and
enum members themselves.
"""
try:
return cls._member_map_[name.upper()]
except KeyError:
raise AttributeError(name)
class ErrorType(with_metaclass(_CaseInsensitiveEnumMeta, str, Enum)):
"""The error type of the baseline.
"""
ZERO = "0"
ONE = "1"
TWO = "2"
THREE = "3"
FOUR = "4"
ONE_HUNDRED = "100"
TWO_HUNDRED = "200"
class PredictionResultType(with_metaclass(_CaseInsensitiveEnumMeta, str, Enum)):
"""The prediction result type of the baseline.
"""
ZERO = "0"
ONE = "1"
TWO = "2"
class ReceiverStatus(with_metaclass(_CaseInsensitiveEnumMeta, str, Enum)):
"""Indicates the status of the receiver. Receivers that are not Enabled will not receive any
communications.
"""
NOT_SPECIFIED = "NotSpecified"
ENABLED = "Enabled"
DISABLED = "Disabled"
class ResultType(with_metaclass(_CaseInsensitiveEnumMeta, str, Enum)):
DATA = "Data"
METADATA = "Metadata"
class Sensitivity(with_metaclass(_CaseInsensitiveEnumMeta, str, Enum)):
"""The sensitivity of the baseline.
"""
LOW = "Low"
MEDIUM = "Medium"
HIGH = "High"
| mit |
joren/recipes | app/models/user.rb | 114 | class User < ActiveRecord::Base
authenticates_with_sorcery!
has_many :recipes
def to_s
name
end
end
| mit |
Invenietis/CK-CodeGen | CK.CodeGen/ICodePart{T}.cs | 702 | using System;
using System.Text;
namespace CK.CodeGen
{
/// <summary>
/// A code part enables any <see cref="INamedScope"/> to be segmented
/// in as many parts as needed.
/// </summary>
/// <remarks>
/// This generic interface doesn't extend the non generic <see cref="ICodePart"/>: each
/// typed code part (<see cref="ITypeScope"/>) can create its own typed part (<see cref="ITypeScopePart"/>)
/// that needs to be bound to the primary part owner.
/// </remarks>
public interface ICodePart<T> : ICodeWriter where T : INamedScope
{
/// <summary>
/// Gets the owner of this part.
/// </summary>
T PartOwner { get; }
}
}
| mit |
aboutlo/gulp-starter-kit | app/js/views/LoginView.js | 1985 | 'use strict';
var $ = require('jquery');
var _ = require('underscore');
var Backbone = require('backbone');
Backbone.$ = $;
var UserActions = require('../actions/UserActions');
var config = require('../config');
var SessionStore = require('../stores/SessionStore');
var MainView = Backbone.View.extend({
template: require('../templates/login.tpl'),
templateItemError: require('../templates/ItemError.tpl'),
tagName:'section',
className:'login',
id:'loginForm',
events:{
'keyup .login__email, .login__password': 'validateForm',
'submit form': 'onSubmit'
},
initialize: function(){
this.listenTo(SessionStore,'change',this.render);
this.debouncedValidate = _.debounce(this.isValid.bind(this), 250);
this.$el.html(this.template(config));
this.delegateEvents();
this.$errors = this.$el.find('.login__errors');
this.$login = this.$el.find('.login__button');
},
isValid:function(){
var validated = SessionStore.validate(this.getData());
validated ?
this.$login.attr('disabled', false)
:
this.$login.attr('disabled', true);
return validated;
},
validateForm: function(e){
e.preventDefault();
this.debouncedValidate();
},
getData: function(){
return {
username: this.$el.find('input[name="username"]').val(),
password: this.$el.find('input[name="password"]').val()
};
},
onSubmit: function(e){
e.preventDefault();
var username = this.$el.find('input[name="username"]').val();
var password = this.$el.find('input[name="password"]').val();
var credentials = this.getData();
if (SessionStore.validate(credentials)) {
UserActions.authenticate(credentials);
}
},
render: function(){
this.$errors.empty();
_.each(SessionStore.getErrors(),function(error){
this.$errors.append(this.templateItemError({error:error}));
},this);
return this;
}
});
module.exports = MainView;
| mit |
CupOfTea696/WordPress-Lib | src/Foundation/Bootstrap/ReadConfiguration.php | 4245 | <?php
namespace CupOfTea\WordPress\Foundation\Bootstrap;
use Illuminate\Config\Repository;
use Symfony\Component\Finder\Finder;
use Symfony\Component\Finder\SplFileInfo;
use Illuminate\Contracts\Container\Container;
use Illuminate\Contracts\Config\Repository as RepositoryContract;
class ReadConfiguration
{
/**
* Bootstrap the given application.
*
* @param \Illuminate\Contracts\Foundation\Application $app
* @return void
*/
public function bootstrap(Container $app)
{
$items = [];
$app->instance('config', $config = new Repository($items));
// Next we will spin through all of the configuration files in the configuration
// directory and load each one into the repository. This will make all of the
// options available to the developer for use in various parts of this app.
$this->loadConfigurationFiles($app, $config);
mb_internal_encoding('UTF-8');
}
/**
* Load the configuration items from all of the files.
*
* @param \Illuminate\Contracts\Foundation\Application $app
* @param \Illuminate\Contracts\Config\Repository $config
* @return void
*/
protected function loadConfigurationFiles(Container $app, RepositoryContract $config)
{
foreach ($this->getConfigurationFiles($app) as $key => $path) {
$config->set($key, require $path);
}
foreach ($this->getThemeConfigurationFiles($app) as $key => $path) {
if ($config->has($key)) {
$values = require $path;
$config->set($key, array_merge($config->get($key), $values));
} else {
$config->set($key, require $path);
}
}
}
/**
* Get all of the configuration files for the application.
*
* @param \Illuminate\Contracts\Foundation\Application $app
* @return array
*/
protected function getConfigurationFiles(Container $app)
{
$files = [];
foreach (Finder::create()->files()->name('*.php')->in($app->configPath()) as $file) {
$nesting = $this->getConfigurationNesting($file);
$files[$nesting . basename($file->getRealPath(), '.php')] = $file->getRealPath();
}
return $files;
}
/**
* Get all of the configuration files for the theme.
*
* @param \Illuminate\Contracts\Foundation\Application $app
* @return array
*/
protected function getThemeConfigurationFiles(Container $app)
{
$files = [];
$config_path = $app->make('config')->get('theme.config_path', realpath($app->make('wp.theme')->getRoot()) . '/config');
if (file_exists($config_path) && is_dir($config_path)) {
foreach (Finder::create()->files()->name('*.php')->in($config_path) as $file) {
$nesting = $this->getThemeConfigurationNesting($file, $config_path);
$files[$nesting . basename($file->getRealPath(), '.php')] = $file->getRealPath();
}
}
return $files;
}
/**
* Get the configuration file nesting path.
*
* @param \Symfony\Component\Finder\SplFileInfo $file
* @return string
*/
private function getConfigurationNesting(SplFileInfo $file)
{
$directory = dirname($file->getRealPath());
if ($tree = trim(str_replace(config_path(), '', $directory), DIRECTORY_SEPARATOR)) {
$tree = str_replace(DIRECTORY_SEPARATOR, '.', $tree) . '.';
}
return $tree;
}
/**
* Get the theme configuration file nesting path.
*
* @param \Symfony\Component\Finder\SplFileInfo $file
* @return string
*/
private function getThemeConfigurationNesting(SplFileInfo $file, $config_path)
{
$directory = dirname($file->getRealPath());
if ($tree = trim(str_replace($config_path, '', $directory), DIRECTORY_SEPARATOR)) {
$tree = str_replace(DIRECTORY_SEPARATOR, '.', $tree) . '.';
}
return $tree;
}
}
| mit |
bang88/ant-console | src/stores/BaseStore.js | 785 | import assign from 'object-assign';
import {EventEmitter} from 'events';
const CHANGE_EVENT = 'change';
/**
* create store
* @param spec
*/
export function createStore(spec) {
const emitter = new EventEmitter();
emitter.setMaxListeners(0);
const store = assign({
emitChange() {
emitter.emit(CHANGE_EVENT);
},
addChangeListener(callback) {
emitter.on(CHANGE_EVENT, callback);
},
removeChangeListener(callback) {
emitter.removeListener(CHANGE_EVENT, callback);
}
}, spec);
//auto bind
for (var key in store) {
if (store.hasOwnProperty(key) && typeof key === 'function') {
store[key] = store[key].bind(store);
}
}
return store;
}
| mit |
qudou/xmlplus | example/docs/08-searching/07/index.js | 706 | xmlplus("xp", function (xp, $_, t) {
$_().imports({
Index: {
xml: "<div id='index'>first\
<button id='foo'>foo</button>\
<button id='bar'>bar</button>last\
</div>",
fun: function (sys, items, opts) {
console.log(sys.foo.next().text()); // bar
console.log(sys.bar.prev().text()); // foo
console.log(sys.index.prev(), sys.index.next()); // undefined undefined
console.log(sys.foo.prev(3).text()); // first
console.log(sys.bar.next(3).text()); // last
}
}
});
}); | mit |
sergei1152/CraneBoom.js | scripts/Node.js | 5404 | var ForceLine=require('./ForceLine'); //node deligates forceline
var Node = fabric.util.createClass(fabric.Circle, {
type: 'node',
initialize: function(options) {
if (!options) {
options = {};
}
this.callSuper('initialize', options);
//settings default values of the most important properties
this.set({
showCoords: false,
left: options.left || -100,
top: options.top || -100,
strokeWidth: options.strokeWidth || 5,
radius: options.radius || 12,
fill: options.fill || '#FFFFFF',
stroke: options.stroke || '#666',
selectable: options.selectable || true,
hasControls: false,
hasBorders: false,
label: options.label || '',
maximum_shear_stress: null,
support: options.support || false, //if the node is a support (and thus is a floor beam as well)
floor_beam: options.floor_beam || false, //if the node is a floor beam
external_force: [0,0], //the reaction forces acting on the floor beam
connected_members: [] //the members that are connected to the floor beam
});
},
toObject: function() {
return {
support: this.get('support'),
floor_beam: this.get('floor_beam'),
left: this.get('left'),
top: this.get('top'),
};
},
_render: function(ctx) {
this.callSuper('_render', ctx);
ctx.font = '15px Arial';
ctx.fillStyle = 'hsla(87, 100%, 24%, 1)'; //color of the font
if (this.showCoords) {
// ctx.fillRect(-10, yOff, 150, 22); //will show a white rectangle background around the coordinates of the node
ctx.fillText('('+Math.round(this.left*100)/100+', ' +Math.round(this.top*100)/100+')', 12,18);
}
else{
ctx.fillText(this.label,12,18);
}
}
});
//for the import, takes in a json singleton representing a node and applies it to the current node object
Node.prototype.copyProp=function(nodeObj) {
this.top = nodeObj.top;
this.left = nodeObj.left;
this.support = nodeObj.support;
this.floor_beam = nodeObj.floor_beam;
if (this.floor_beam) {
this.lockMovementY = true;
} else {
this.lockMovementY = false;
}
if (this.support) {
this.stroke = '#F41313';
this.lockMovementX=true;
} else if (this.floor_beam) {
this.stroke = '#000000';
this.lockMovementX=false;
} //else default
};
module.exports=Node;
var E=require('./EntityController'); //since the entity controller is only required for the prototypes
//Moves the connected members of the node to its position
Node.prototype.moveMembers = function(canvas) {
for (var i = 0; i < this.connected_members.length; i++) {
if (this.connected_members[i].start_node == this) { //if the start of the member is connected to the this
this.connected_members[i].set({
x1: this.left,
y1: this.top
});
} else if (this.connected_members[i].end_node == this) { //if the end of the member is connected to the this
this.connected_members[i].set({
x2: this.left,
y2: this.top
});
}
//Re-adding the members to avoing weird glitchiness (if canvas object available)
if(canvas){
canvas.remove(this.connected_members[i]);
canvas.add(this.connected_members[i]);
canvas.sendToBack(this.connected_members[i]); //sending the connected members to the back of the canvas
}
}
};
Node.prototype.setShearStress=function(stress){
this.maximum_shear_stress=stress || 0;
this.label=stress.toFixed(1)+'MPa';
var percentMax=stress*100/E.node_maximum_shear_stress;
if(percentMax>100){ //if the force exceeded maximum tensile force
this.stroke='hsla(65, 100%, 60%, 1)';
}
else{
this.stroke='hsla(360, '+(percentMax*0.8+20)+'%,50%, 1)';
}
}
//set the reaction force of the node
Node.prototype.setForce=function(x,y,canvas){
this.external_force[0]=x || 0;
this.external_force[1]=y || 0;
roundedX=Math.round(x*100)/100;
roundedY=Math.round(y*100)/100;
if(this.forceLineX && this.forceLineY){ //if a force line already exists
this.forceLineX.set({
x1: this.left,
y1: this.top,
label: Math.abs(roundedX)+'N',
x2: this.left+roundedX*10,
y2: this.top
});
this.forceLineY.set({
x1: this.left,
y1: this.top,
label: Math.abs(roundedY)+'N',
x2: this.left,
y2: this.top-30*roundedY
});
}
else { //if the forceline doesnt yet exist
this.forceLineX=new ForceLine({
x1: this.left,
y1: this.top,
label: Math.abs(roundedX)+'N',
x2: this.left+roundedX*10,
y2: this.top
});
this.forceLineY=new ForceLine({
x1: this.left,
y1: this.top,
label: Math.abs(roundedY)+'N',
x2: this.left,
y2: this.top-30*roundedY
});
canvas.add(this.forceLineX);
canvas.add(this.forceLineY);
}
}; | mit |
gszathmari/wpbiff | setup.py | 1227 | from setuptools import setup, find_packages
from codecs import open
from os import path
here = path.abspath(path.dirname(__file__))
with open(path.join(here, 'README.rst'), encoding='utf-8') as f:
long_description = f.read()
setup(
name="wpbiff",
version="0.1.1",
author="Gabor Szathmari",
author_email="gszathmari@gmail.com",
packages=find_packages(exclude=['contrib', 'docs', 'tests*']),
include_package_data=True,
url="https://github.com/gszathmari/wpbiff",
license="MIT",
platforms = ["Linux"],
description="Wordpress Two-Factor Authentication Brute-forcer",
long_description=long_description,
entry_points='''
[console_scripts]
wpbiff=wpbiff.cli:main
''',
install_requires=[
"click",
"colorama",
"progressbar",
"requests"
],
classifiers=[
'Development Status :: 4 - Beta',
'License :: OSI Approved :: MIT License',
'Topic :: Security',
'Intended Audience :: Other Audience',
'Programming Language :: Python :: 2 :: Only',
'Programming Language :: Python :: 2.6',
'Programming Language :: Python :: 2.7',
],
keywords='security password',
)
| mit |
mcodegeeks/OpenKODE-Framework | 04_Sample/Galaga/Source/ScrMainMenu.cpp | 4313 | ๏ปฟ/* --------------------------------------------------------------------------
*
* File ScrMainMenu.cpp
* Description Main Menu Screen
* Author Kyoung-Cheol Kim
* Contact redfreek2c@gmail.com
*
* --------------------------------------------------------------------------
*
* Copyright (c) 2010-2013 XMSoft. All rights reserved.
*
* --------------------------------------------------------------------------
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library in the file COPYING.LIB;
* if not, write to the Free Software Foundation, Inc.,
* 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA
*
* -------------------------------------------------------------------------- */
#include "Precompiled.h"
#include "ScrMainMenu.h"
#include "ScrMainGame.h"
#include "GameState.h"
KDbool CScrMainMenu::init ( KDvoid )
{
// ๋ ์ด์ด๋ฅผ ์ด๊ธฐํ ํ๋ค.
if ( !CCLayer::initWithVisibleViewport ( ) )
{
return KD_FALSE;
}
// ํ์ฌ ๋ ์ด์ด ์ฌ์ด์ฆ๋ฅผ ๊ฐ์ ธ์จ๋ค.
CCSize tLyrSize = this->getContentSize ( );
CCSize tSize = ccsz;
// ๋๋ฒ๊ทธ์ฉ ๋ฐฐ๊ฒฝ
// this->addChild ( CCLayerColor::create ( ccc4 ( 255, 0, 0, 128 ), tLyrSize ) );
// ์ฐ์๋จ ์ข
๋ฃ ๋ฒํผ
CCMenuItemImage* pClose = CCMenuItemImage::create
(
"Images/CloseNormal.png",
"Images/CloseSelected.png",
this, menu_selector ( CScrMainMenu::onExit )
);
this->addChild ( CCMenu::createWithItem ( pClose ), 1 );
tSize = pClose->getContentSize ( );
pClose->setPosition ( this, kCCAlignmentTopRight, ccp ( 20, 20 ) );
// pClose->setPosition ( ccp ( tLyrSize.cx - tSize.cx / 2 - 20, tLyrSize.cy - tSize.cx / 2 - 20 ) );
// ํ์ดํ ๋ ์ด๋ธ ์์ฑ
CCLabelTTF* pTitle = CCLabelTTF::create ( GSTAT->getText ( eTxtTitle ), "Font/NanumGothicBold.ttf", 40 );
this->addChild ( pTitle );
pTitle->setColor ( ccYELLOW );
pTitle->setPositionWithParent ( kCCAlignmentTop, ccp ( 0, 50 ) );
// ์ค๋ช
Label ์์ฑ
CCLabelTTF* pDesc = CCLabelTTF::create( "Press the airplane !!!!", "Font/NanumGothicBold.ttf", 25 );
this->addChild( pDesc );
pDesc->setPosition ( ccpMid ( tLyrSize ) );
// ์ค๋ช
Label์ด ๊ณ์ํด์ ๊น๋นก๊ฑฐ๋ฆฌ๋๋ก ์ค์
pDesc->runAction ( CCRepeatForever::create ( CCBlink::create ( 1.0f, 1 ) ) );
// ๋นํ๊ธฐ ๋ฌถ์ ํ
์ค์ณ ์์ฑ
CCTexture2D* pTexture = CCTextureCache::sharedTextureCache ( )->addImage ( "Images/galagasheet.png" );
// ํ๋จ์ ๋นํ๊ธฐ ์์ฑ
CCSprite* pAirPlane = CCSprite::createWithTexture ( pTexture, ccr ( 184, 55, 15, 17 ) );
this->addChild ( pAirPlane );
pAirPlane->setScale ( 2 );
pAirPlane->setPositionWithParent ( kCCAlignmentBottom, ccp ( 0, 50 ) );
m_pAirPlane = pAirPlane;
// ๋ ์ด์ด ํฐ์น ๋ชจ๋ ์ผ๊ธฐ
this->setTouchEnabled ( KD_TRUE );
return KD_TRUE;
}
KDvoid CScrMainMenu::ccTouchesEnded ( CCSet* pTouches, CCEvent* pEvent )
{
CCTouch* pTouch = (CCTouch*) pTouches->anyObject ( );
CCPoint tPoint = m_pAirPlane->convertTouchToNodeSpace ( pTouch );
CCRect tAirRect = m_pAirPlane->boundingBox ( );
tAirRect.origin.x = 0; //-tAirRect.size.cx * 2;
tAirRect.origin.y = 0; //-tAirRect.size.cy * 2;
// tAirRect.size.cx *= 2;
// tAirRect.size.cy *= 2;
if ( tAirRect.containsPoint ( tPoint ) )
{
CCLOG ( "Airplane OK" );
// ๊ฒ์ ํ๋ฉด์ผ๋ก ์ ํ
GSTAT->setScene ( eScrMainGame, eTranSlideIn );
}
// ํ๋จ์ ํฐ์น ๋์ ์ฝ๋ ์์
for ( CCSetIterator it = pTouches->begin ( ); it != pTouches->end ( ); it++ )
{
pTouch = (CCTouch*) ( *it );
}
}
KDvoid CScrMainMenu::onExit ( CCObject* pSender )
{
CCDirector::sharedDirector ( )->end ( );
}
| mit |
ap--/python-seabreeze | src/libseabreeze/src/vendors/OceanOptics/protocols/obp/exchanges/OBPGetI2CMasterNumberOfBusesExchange.cpp | 2106 | /***************************************************//**
* @file OBPGetI2CMasterNumberOfBusesExchange.cpp
* @date May 2017
* @author Ocean Optics, Inc.
*
* LICENSE:
*
* SeaBreeze Copyright (C) 2017, Ocean Optics Inc
*
* Permission is hereby granted, free of charge, to any person obtaining
* a copy of this software and associated documentation files (the
* "Software"), to deal in the Software without restriction, including
* without limitation the rights to use, copy, modify, merge, publish,
* distribute, sublicense, and/or sell copies of the Software, and to
* permit persons to whom the Software is furnished to do so, subject
* to the following conditions:
*
* The above copyright notice and this permission notice shall be included
* in all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
* CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*******************************************************/
#include "common/globals.h"
#include "vendors/OceanOptics/protocols/obp/exchanges/OBPGetI2CMasterNumberOfBusesExchange.h"
#include "vendors/OceanOptics/protocols/obp/constants/OBPMessageTypes.h"
#include "vendors/OceanOptics/protocols/obp/hints/OBPControlHint.h"
using namespace seabreeze;
using namespace seabreeze::oceanBinaryProtocol;
OBPGetI2CMasterNumberOfBusesExchange::OBPGetI2CMasterNumberOfBusesExchange() {
this->messageType = OBPMessageTypes::OBP_GET_I2C_MASTER_BUS_COUNT;
this->hints->push_back(new OBPControlHint());
this->payload.resize(sizeof(unsigned char));
this->payload[0] = 0; /* default state of device on startup */
}
OBPGetI2CMasterNumberOfBusesExchange::~OBPGetI2CMasterNumberOfBusesExchange() {
}
| mit |
mentholi/giosgapps-todo-example | src/todo/serializers.py | 380 | from swampdragon.serializers.model_serializer import ModelSerializer
class TodoListSerializer(ModelSerializer):
class Meta:
model = 'todo.TodoList'
publish_fields = ('name', 'description')
class TodoItemSerializer(ModelSerializer):
class Meta:
model = 'todo.TodoItem'
publish_fields = ('done', 'text')
update_fields = ('done', ) | mit |
zedam/portfolio | node_modules/browser-sync/lib/logger.js | 4635 | "use strict";
var messages = require("./messages");
var utils = require("./utils");
var _ = require("lodash");
var template = "{cyan:[}%s{cyan:] }";
var logger = require("eazy-logger").Logger({
prefix: template.replace("%s", "BS"),
useLevelPrefixes: false
});
module.exports.logger = logger;
/**
* @param name
* @returns {*}
*/
module.exports.getLogger = function (name) {
return logger.clone(function (config) {
config.prefix = config.prefix + template.replace("%s", name);
return config;
});
};
/**
* Logging Callbacks
*/
module.exports.callbacks = {
/**
* Log when file-watching has started
* @param options
* @param data
*/
"file:watching": function (options, data) {
if (Object.keys(data).length) {
logger.info("Watching files...");
}
},
/**
* Log when a file changes
* @param options
* @param data
*/
"file:reload": function (options, data) {
if (data.log) {
var path = utils.resolveRelativeFilePath(data.path, data.cwd);
logger.info("{cyan:File changed: {magenta:%s", path);
}
},
/**
*
*/
"service:exit": function () {
logger.debug("Exiting...");
},
/**
*
*/
"browser:reload": function () {
logger.info("{cyan:Reloading Browsers...");
},
/**
* @param options
* @param data
*/
"config:error": function (options, data) {
logger.setOnce("useLevelPrefixes", true).error(data.msg);
},
/**
* @param options
* @param data
*/
"config:warn": function (options, data) {
logger.setOnce("useLevelPrefixes", true).warn(data.msg);
},
/**
* @param options
* @param data
*/
"stream:changed": function (options, data) {
var changed = data.changed;
logger.info("{cyan:%s file%s changed} ({magenta:%s})",
changed.length,
changed.length > 1 ? "s" : "",
changed.join(", ")
);
},
/**
* Client connected logging
* @param options
* @param data
*/
"client:connected": function (options, data) {
var uaString = utils.getUaString(data.ua);
var msg = "{cyan:Browser Connected: {magenta:%s, version: %s}";
var method = "info";
if (!options.logConnections) {
method = "debug";
}
logger.log(method, msg,
uaString.name,
uaString.version
);
},
/**
* Main logging when the service is running
* @param options
* @param data
*/
"service:running": function (options, data) {
var type = data.type;
var baseDir = options.server.baseDir;
var proxy = options.proxy;
if (type === "server") {
logUrls(options.urls);
if (baseDir) {
if (Array.isArray(baseDir)) {
_.each(baseDir, serveFiles);
} else {
serveFiles(baseDir);
}
}
}
if (type === "proxy") {
logger.info("Proxying: {cyan:%s}", proxy.target);
logger.info("Now you can access your site through the following addresses:");
logUrls(options.urls);
}
if (type === "snippet" && options.logSnippet) {
logger.info(
"Copy the following snippet into your website, " +
"just before the closing {cyan:</body>} tag"
);
logger.unprefixed("info",
messages.scriptTags(options.port, options)
);
}
function serveFiles (base) {
logger.info("Serving files from: {magenta:%s}", base);
}
function logUrls (urls) {
_.each(urls, function (value, key) {
logger.info("%s URL: {magenta:%s}",
utils.ucfirst(key),
value);
});
}
}
};
/**
* Plugin interface - only to be called once to register all events
*/
module.exports.plugin = function (emitter, options) {
// Should set logger level here!
if (options.logLevel === "silent") {
logger.mute(true);
} else {
logger.setLevel(options.logLevel);
}
if (options.logPrefix && _.isString(options.logPrefix)) {
logger.setPrefix(template.replace("%s", options.logPrefix));
}
_.each(exports.callbacks, function (func, event) {
emitter.on(event, func.bind(this, options));
});
return logger;
};
| mit |
Concatapult/pult | modules/less/config.js | 1146 | var lib = require('../../lib')
module.exports = {
maxCLIArgs: 0,
pultModuleDeps: [],
pultModuleConflicts: [],
get: function get (vfs, baseConfig, moduleArgs) {
var serverConfig = lib.clone(baseConfig.server)
serverConfig.routerPipeline.unshift('./style-bundles.js')
//
// Inject link tag into main html file
//
var isSpa = baseConfig.package.addedPultModules.includes('spa')
var isMarko = baseConfig.package.addedPultModules.includes('marko')
if ( isSpa || isMarko ) {
var htmlPath = baseConfig.projectRoot + (
isSpa ? '/client/public/index.html' : '/client/pages/_layouts/main.marko'
)
var html = vfs.read(htmlPath)
var spaces = html.match(/( *)<\/head>/)[1]
var result = html.replace(
'</head>',
` <link rel="stylesheet" type="text/css" href="/app-bundle.css">\n${ spaces }</head>`
)
vfs.write(htmlPath, result)
}
var config = {
dependencies: {
"node-less-endpoint": "0.x",
},
server: serverConfig,
}
config.installs = Object.keys(config.dependencies)
return config
}
}
| mit |
ycabon/presentations | 2018-user-conference/arcgis-js-api-road-ahead/demos/gamepad/api-snapshot/esri/widgets/LayerList/nls/vi/LayerList.js | 543 | // All material copyright ESRI, All Rights Reserved, unless otherwise specified.
// See https://js.arcgis.com/4.8/esri/copyright.txt for details.
//>>built
define({widgetLabel:"Danh s\u00e1ch L\u1edbp",noItemsToDisplay:"Hi\u1ec7n kh\u00f4ng c\u00f3 m\u1ee5c n\u00e0o \u0111\u1ec3 hi\u1ec3n th\u1ecb.",layerInvisibleAtScale:"Kh\u00f4ng hi\u1ec3n th\u1ecb \u1edf t\u1ef7 l\u1ec7 hi\u1ec7n t\u1ea1i",layerError:"\u0110\u00e3 x\u1ea3y ra l\u1ed7i khi t\u1ea3i l\u1edbp n\u00e0y",untitledLayer:"L\u1edbp ch\u01b0a c\u00f3 ti\u00eau \u0111\u1ec1"}); | mit |
Harkamal/webcam_image_capture | test/dummy/config/routes.rb | 100 | Rails.application.routes.draw do
mount WebcamImageCapture::Engine => "/webcam_image_capture"
end
| mit |
SerafimArts/gitter-api | src/Support/Observer.php | 793 | <?php
/**
* This file is part of GitterApi package.
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
declare(strict_types=1);
namespace Gitter\Support;
/**
* Class Observer
* @package Gitter\Support
*/
class Observer
{
/**
* @var array|\Closure[]
*/
private $subscribers = [];
/**
* @param \Closure $closure
* @return Observer
*/
public function subscribe(\Closure $closure): Observer
{
$this->subscribers[] = $closure;
return $this;
}
/**
* @param $data
* @return void
*/
public function fire($data)
{
foreach ($this->subscribers as $subscriber) {
$subscriber($data);
}
}
}
| mit |
arxanas/drafts.ninja | public/src/components/game.js | 3970 | import App from '../app'
import {Zones} from '../cards'
import Chat from './chat'
import Cols from './cols'
import Grid from './grid'
import DeckSettings from './deck-settings'
import GameSettings from './game-settings'
import {LBox} from './checkbox'
let d = React.DOM
export default React.createClass({
componentWillMount() {
App.state.players = []
App.send('join', this.props.id)
},
componentDidMount() {
this.timer = window.setInterval(decrement, 1e3)
},
componentWillUnmount() {
window.clearInterval(this.timer)
},
componentWillReceiveProps({id}) {
if (this.props.id === id)
return
App.send('join', id)
},
render() {
return d.div({ className: 'container' },
d.audio({ id: 'beep', src: '/media/beep.wav' }),
d.div({ className: 'game' },
d.div({ className: 'game-controls' },
d.div({ className: 'game-status' }, this.Players(), this.Start()),
DeckSettings(),
GameSettings()),
this.Cards()),
Chat())
},
Cards() {
if (Object.keys(Zones.pack).length)
let pack = Grid({ zones: ['pack'] })
let component = App.state.cols ? Cols : Grid
let pool = component({ zones: ['main', 'side', 'junk'] })
return [pack, pool]
},
Start() {
if (App.state.didGameStart || !App.state.isHost)
return
let startControls = d.div({},
d.div({}, `Format: ${App.state.format}`),
LBox('addBots', 'bots'),
d.div({},
d.label({},
d.input({
type: 'checkbox',
checkedLink: App.link('useTimer'),
}), ' use '),
d.label({},
d.input({
className: 'number',
disabled: !App.state.useTimer,
min: 0,
max: 60,
step: 5,
type: 'number',
valueLink: App.link('timerLength'),
}), '-second timer')),
d.div({},
d.button({ onClick: App._emit('start') }, 'Start game')))
return d.fieldset({ className: 'start-controls fieldset' },
d.legend({ className: 'legend game-legend' }, 'Start game'),
d.span({}, startControls))
},
Players() {
let rows = App.state.players.map(row)
let columns = [
d.th({}, '#'),
d.th({}, ''), // connection status
d.th({}, 'name'),
d.th({}, 'packs'),
d.th({}, 'time'),
d.th({}, 'cock'),
d.th({}, 'mws'),
]
if (App.state.isHost)
columns.push(d.th({})) // kick
let playersTable = d.table({ id: 'players' },
d.thead({},
d.tr({}, ...columns)),
d.tbody({},
rows))
return d.fieldset({ className: 'fieldset' },
d.legend({ className: 'legend game-legend' }, 'Players'),
playersTable)
}
})
function row(p, i) {
let {players, self} = App.state
let {length} = players
if (length % 2 === 0)
let opp = (self + length/2) % length
let className
= i === self ? 'self'
: i === opp ? 'opp'
: null
let connectionStatusIndicator
= p.isBot ? d.span({
className: 'icon-bot',
title: 'This player is a bot.',
})
: p.isConnected ? d.span({
className: 'icon-connected',
title: 'This player is currently connected to the server.',
})
: d.span({
className: 'icon-disconnected',
title: 'This player is currently disconnected from the server.',
})
let columns = [
d.td({}, i + 1),
d.td({}, connectionStatusIndicator),
d.td({}, p.name),
d.td({}, p.packs),
d.td({}, p.time),
d.td({}, p.hash && p.hash.cock),
d.td({}, p.hash && p.hash.mws),
]
if (App.state.isHost)
if (i !== self && !p.isBot)
columns.push(d.td({}, d.button({
onClick: ()=> App.send('kick', i),
}, 'kick')))
else
columns.push(d.td({}))
return d.tr({ className }, ...columns)
}
function decrement() {
for (let p of App.state.players)
if (p.time)
p.time--
App.update()
}
| mit |
jayanthkoushik/torch-gel | gel/ridgepaths.py | 2301 | """ridgepaths.py: solution paths for ridge regression."""
import torch
import tqdm
def ridge_paths(X, y, support, lambdas, summ_fun, verbose=False):
"""Solve ridge ridgression for a sequence of regularization values,
and return the summary for each.
The multiple solutions are obtained efficiently using the Woodbury identity.
With X (p x m) representing the feature matrix, and y (m x 1) the outcomes,
the ridge solution is given by
b = (X@X' + l*I)^{-1}@X@y
where l is the regularization coefficient. This can be reduced to
(1/l)*(X@y - X@V(e + l*I)^{-1}@(X@V)'@X@y)
where V@e@V' is the eigendecomposition of X'@X. Since (e + l*I) is a
diagonal matrix, its inverse can be performed efficiently simply by taking
the reciprocal of the diagonal elements. Then, (X@V)'@X@y is a vector; so it
can be multiplied by (e + l*I)^{-1} just by scalar multiplication.
Arguments:
X: pxm tensor of features (where m is the number of samples);
X should be centered (each row should have mean 0).
y: tensor (length m vector) of outcomes.
support: LongTensor vector of features to use. This vector should
contain indices. It can also be None to indicate empty support.
X should already be indexed using support. This argument is simply
passed to the summary function.
lambdas: list of regularization values for which to solve the problem.
summ_fun: a function that takes (support, b) and returns an arbitrary
summary.
verbose: enable/disable the progress bar.
The function returns a dictionary mapping lambda values to their summaries.
"""
summaries = {}
if support is None:
# Nothing to do.
for l in tqdm.tqdm(
lambdas, desc="Solving ridge regressions", disable=not verbose
):
summaries[l] = summ_fun(None, None)
return summaries
# Setup.
_, S, V = torch.svd(X)
e = S ** 2
p = X @ y
Q = X @ V
r = Q.t() @ p # (X@V)'@X@y
# Main loop.
for l in tqdm.tqdm(lambdas, desc="Solving ridge regressions", disable=not verbose):
b = (1.0 / l) * (p - Q @ (r / (e + l)))
summaries[l] = summ_fun(support, b)
return summaries
| mit |