text:
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
  <component name="ChangeListManager">
    <list default="true" id="edcbf0d3-8e05-457c-aa6e-44b8585b4562" name="Default" comment="">
      <change type="DELETED" beforePath="$PROJECT_DIR$/.tmp/concat/scripts/modules.js" afterPath="" />
      <change type="DELETED" beforePath="$PROJECT_DIR$/.tmp/concat/scripts/plugins.js" afterPath="" />
      <change type="DELETED" beforePath="$PROJECT_DIR$/.tmp/concat/scripts/scripts.js" afterPath="" />
      <change type="DELETED" beforePath="$PROJECT_DIR$/.tmp/concat/styles/main.css" afterPath="" />
      <change type="MODIFICATION" beforePath="$PROJECT_DIR$/.sass-cache/85386f123d38015a7ecaececd6ae0aef6448c03a/main.scssc" afterPath="$PROJECT_DIR$/.sass-cache/85386f123d38015a7ecaececd6ae0aef6448c03a/main.scssc" />
      <change type="MODIFICATION" beforePath="$PROJECT_DIR$/app/index.html" afterPath="$PROJECT_DIR$/app/index.html" />
      <change type="MODIFICATION" beforePath="$PROJECT_DIR$/.tmp/styles/main.css" afterPath="$PROJECT_DIR$/.tmp/styles/main.css" />
      <change type="MODIFICATION" beforePath="$PROJECT_DIR$/app/styles/main.scss" afterPath="$PROJECT_DIR$/app/styles/main.scss" />
    </list>
    <ignored path="christmas.iws" />
    <ignored path=".idea/workspace.xml" />
    <option name="TRACKING_ENABLED" value="true" />
    <option name="SHOW_DIALOG" value="false" />
    <option name="HIGHLIGHT_CONFLICTS" value="true" />
    <option name="HIGHLIGHT_NON_ACTIVE_CHANGELIST" value="false" />
    <option name="LAST_RESOLUTION" value="IGNORE" />
  </component>
  <component name="ChangesViewManager" flattened_view="true" show_ignored="false" />
  <component name="CreatePatchCommitExecutor">
    <option name="PATCH_PATH" value="" />
  </component>
  <component name="DaemonCodeAnalyzer">
    <disable_hints />
  </component>
  <component name="ExecutionTargetManager" SELECTED_TARGET="default_target" />
  <component name="FavoritesManager">
    <favorites_list name="christmas" />
  </component>
  <component name="FileEditorManager">
    <splitter split-orientation="horizontal" split-proportion="0.5">
      <split-first>
        <leaf>
          <file leaf-file-name="main.js" pinned="false" current="true" current-in-tab="true">
            <entry file="file://$PROJECT_DIR$/app/scripts/controllers/main.js">
              <provider selected="true" editor-type-id="text-editor">
                <state line="36" column="0" selection-start="1076" selection-end="1076" vertical-scroll-proportion="0.804769" vertical-offset="0" max-vertical-offset="1680">
                  <folding />
                </state>
              </provider>
            </entry>
          </file>
          <file leaf-file-name="classie.js" pinned="false" current="false" current-in-tab="false">
            <entry file="file://$PROJECT_DIR$/dist/assets/modal/js/classie.js">
              <provider selected="true" editor-type-id="text-editor">
                <state line="0" column="0" selection-start="0" selection-end="0" vertical-scroll-proportion="0.0" vertical-offset="0" max-vertical-offset="1170">
                  <folding />
                </state>
              </provider>
            </entry>
          </file>
          <file leaf-file-name="main.scss" pinned="false" current="false" current-in-tab="false">
            <entry file="file://$PROJECT_DIR$/app/styles/main.scss">
              <provider selected="true" editor-type-id="text-editor">
                <state line="113" column="16" selection-start="2001" selection-end="2001" vertical-scroll-proportion="-6.9054055" vertical-offset="1184" max-vertical-offset="3360">
                  <folding />
                </state>
              </provider>
            </entry>
          </file>
          <file leaf-file-name="index.html" pinned="false" current="false" current-in-tab="false">
            <entry file="file://$PROJECT_DIR$/app/index.html">
              <provider selected="true" editor-type-id="text-editor">
                <state line="11" column="59" selection-start="567" selection-end="567" vertical-scroll-proportion="-6.875" vertical-offset="0" max-vertical-offset="1845">
                  <folding />
                </state>
              </provider>
            </entry>
          </file>
          <file leaf-file-name="load.js" pinned="false" current="false" current-in-tab="false">
            <entry file="file://$PROJECT_DIR$/app/scripts/controllers/load.js">
              <provider selected="true" editor-type-id="text-editor">
                <state line="7" column="32" selection-start="243" selection-end="243" vertical-scroll-proportion="0.0" vertical-offset="105" max-vertical-offset="270">
                  <folding />
                </state>
              </provider>
            </entry>
          </file>
          <file leaf-file-name="app.js" pinned="false" current="false" current-in-tab="false">
            <entry file="file://$PROJECT_DIR$/app/scripts/app.js">
              <provider selected="true" editor-type-id="text-editor">
                <state line="27" column="0" selection-start="565" selection-end="565" vertical-scroll-proportion="0.0" vertical-offset="0" max-vertical-offset="555">
                  <folding />
                </state>
              </provider>
            </entry>
          </file>
          <file leaf-file-name="admin.js" pinned="false" current="false" current-in-tab="false">
            <entry file="file://$PROJECT_DIR$/app/scripts/controllers/admin.js">
              <provider selected="true" editor-type-id="text-editor">
                <state line="12" column="34" selection-start="381" selection-end="381" vertical-scroll-proportion="0.0" vertical-offset="0" max-vertical-offset="600">
                  <folding />
                </state>
              </provider>
            </entry>
          </file>
        </leaf>
      </split-first>
      <split-second>
        <leaf>
          <file leaf-file-name="main.html" pinned="false" current="false" current-in-tab="true">
            <entry file="file://$PROJECT_DIR$/app/views/main.html">
              <provider selected="true" editor-type-id="text-editor">
                <state line="36" column="0" selection-start="1286" selection-end="1286" vertical-scroll-proportion="0.75446427" vertical-offset="33" max-vertical-offset="705">
                  <folding />
                </state>
              </provider>
            </entry>
          </file>
          <file leaf-file-name="default.css" pinned="false" current="false" current-in-tab="false">
            <entry file="file://$PROJECT_DIR$/app/assets/modal/css/default.css">
              <provider selected="true" editor-type-id="text-editor">
                <state line="0" column="0" selection-start="0" selection-end="0" vertical-scroll-proportion="0.0" vertical-offset="0" max-vertical-offset="90">
                  <folding />
                </state>
              </provider>
            </entry>
          </file>
          <file leaf-file-name="admin.html" pinned="false" current="false" current-in-tab="false">
            <entry file="file://$PROJECT_DIR$/app/views/admin.html">
              <provider selected="true" editor-type-id="text-editor">
                <state line="11" column="30" selection-start="429" selection-end="429" vertical-scroll-proportion="-6.875" vertical-offset="0" max-vertical-offset="390">
                  <folding />
                </state>
              </provider>
            </entry>
          </file>
          <file leaf-file-name="auth.js" pinned="false" current="false" current-in-tab="false">
            <entry file="file://$PROJECT_DIR$/app/scripts/services/auth.js">
              <provider selected="true" editor-type-id="text-editor">
                <state line="12" column="41" selection-start="237" selection-end="237" vertical-scroll-proportion="0.0" vertical-offset="0" max-vertical-offset="645">
                  <folding />
                </state>
              </provider>
            </entry>
          </file>
        </leaf>
      </split-second>
    </splitter>
  </component>
  <component name="FindManager">
    <FindUsagesManager>
      <setting name="OPEN_NEW_TAB" value="false" />
    </FindUsagesManager>
  </component>
  <component name="Git.Settings">
    <option name="RECENT_GIT_ROOT_PATH" value="$PROJECT_DIR$" />
  </component>
  <component name="GitLogSettings">
    <option name="myDateState">
      <MyDateState />
    </option>
  </component>
  <component name="IdeDocumentHistory">
    <option name="changedFiles">
      <list>
        <option value="$PROJECT_DIR$/test/spec/controllers/main.js" />
        <option value="$PROJECT_DIR$/karma.conf.js" />
        <option value="$PROJECT_DIR$/Gruntfile.js" />
        <option value="$PROJECT_DIR$/app/assets/modal/css/default.css" />
        <option value="$PROJECT_DIR$/app/assets/modal/js/modalEffects.js" />
        <option value="$PROJECT_DIR$/app/assets/modal/css/component.css" />
        <option value="$PROJECT_DIR$/app/scripts/controllers/load.js" />
        <option value="$PROJECT_DIR$/app/scripts/controllers/admin.js" />
        <option value="$PROJECT_DIR$/app/views/admin.html" />
        <option value="$PROJECT_DIR$/app/scripts/services/auth.js" />
        <option value="$PROJECT_DIR$/app/scripts/app.js" />
        <option value="$PROJECT_DIR$/app/views/main.html" />
        <option value="$PROJECT_DIR$/app/scripts/controllers/main.js" />
        <option value="$PROJECT_DIR$/app/styles/main.scss" />
        <option value="$PROJECT_DIR$/app/index.html" />
      </list>
    </option>
  </component>
  <component name="ProjectFrameBounds">
    <option name="width" value="1680" />
    <option name="height" value="1050" />
  </component>
  <component name="ProjectLevelVcsManager" settingsEditedManually="false">
    <OptionsSetting value="true" id="Add" />
    <OptionsSetting value="true" id="Remove" />
    <OptionsSetting value="true" id="Checkout" />
    <OptionsSetting value="true" id="Update" />
    <OptionsSetting value="true" id="Status" />
    <OptionsSetting value="true" id="Edit" />
    <ConfirmationsSetting value="0" id="Add" />
    <ConfirmationsSetting value="0" id="Remove" />
  </component>
  <component name="ProjectReloadState">
    <option name="STATE" value="0" />
  </component>
  <component name="ProjectView">
    <navigator currentView="ProjectPane" proportions="" version="1" splitterProportion="0.5">
      <flattenPackages />
      <showMembers />
      <showModules />
      <showLibraryContents />
      <hideEmptyPackages />
      <abbreviatePackageNames />
      <autoscrollToSource />
      <autoscrollFromSource />
      <sortByType />
    </navigator>
    <panes>
      <pane id="ProjectPane">
        <subPane>
          <PATH>
            <PATH_ELEMENT>
              <option name="myItemId" value="christmas" />
              <option name="myItemType" value="com.intellij.ide.projectView.impl.nodes.ProjectViewProjectNode" />
            </PATH_ELEMENT>
          </PATH>
          <PATH>
            <PATH_ELEMENT>
              <option name="myItemId" value="christmas" />
              <option name="myItemType" value="com.intellij.ide.projectView.impl.nodes.ProjectViewProjectNode" />
            </PATH_ELEMENT>
            <PATH_ELEMENT>
              <option name="myItemId" value="christmas" />
              <option name="myItemType" value="com.intellij.ide.projectView.impl.nodes.PsiDirectoryNode" />
            </PATH_ELEMENT>
          </PATH>
          <PATH>
            <PATH_ELEMENT>
              <option name="myItemId" value="christmas" />
              <option name="myItemType" value="com.intellij.ide.projectView.impl.nodes.ProjectViewProjectNode" />
            </PATH_ELEMENT>
            <PATH_ELEMENT>
              <option name="myItemId" value="christmas" />
              <option name="myItemType" value="com.intellij.ide.projectView.impl.nodes.PsiDirectoryNode" />
            </PATH_ELEMENT>
            <PATH_ELEMENT>
              <option name="myItemId" value="app" />
              <option name="myItemType" value="com.intellij.ide.projectView.impl.nodes.PsiDirectoryNode" />
            </PATH_ELEMENT>
          </PATH>
          <PATH>
            <PATH_ELEMENT>
              <option name="myItemId" value="christmas" />
              <option name="myItemType" value="com.intellij.ide.projectView.impl.nodes.ProjectViewProjectNode" />
            </PATH_ELEMENT>
            <PATH_ELEMENT>
              <option name="myItemId" value="christmas" />
              <option name="myItemType" value="com.intellij.ide.projectView.impl.nodes.PsiDirectoryNode" />
            </PATH_ELEMENT>
            <PATH_ELEMENT>
              <option name="myItemId" value="app" />
              <option name="myItemType" value="com.intellij.ide.projectView.impl.nodes.PsiDirectoryNode" />
            </PATH_ELEMENT>
            <PATH_ELEMENT>
              <option name="myItemId" value="styles" />
              <option name="myItemType" value="com.intellij.ide.projectView.impl.nodes.PsiDirectoryNode" />
            </PATH_ELEMENT>
          </PATH>
        </subPane>
      </pane>
      <pane id="Scope" />
    </panes>
  </component>
  <component name="PropertiesComponent">
    <property name="GoToFile.includeJavaFiles" value="false" />
    <property name="WebServerToolWindowFactoryState" value="false" />
    <property name="FullScreen" value="true" />
  </component>
  <component name="RecentsManager">
    <key name="CopyFile.RECENT_KEYS">
      <recent name="$PROJECT_DIR$/dist" />
    </key>
  </component>
  <component name="RunManager">
    <configuration default="true" type="DartCommandLineRunConfigurationType" factoryName="Dart Command Line Application">
      <option name="VMOptions" />
      <option name="arguments" />
      <option name="filePath" />
      <option name="name" value="Dart" />
      <option name="saveOutputToFile" value="false" />
      <option name="showConsoleOnStdErr" value="false" />
      <option name="showConsoleOnStdOut" value="false" />
      <method />
    </configuration>
    <configuration default="true" type="DartUnitRunConfigurationType" factoryName="DartUnit">
      <option name="VMOptions" />
      <option name="arguments" />
      <option name="filePath" />
      <option name="scope" value="ALL" />
      <option name="testName" />
      <method />
    </configuration>
    <configuration default="true" type="JavaScriptTestRunnerKarma" factoryName="Karma" singleton="true" config-file="">
      <envs />
      <method />
    </configuration>
    <configuration default="true" type="JavascriptDebugType" factoryName="JavaScript Debug" singleton="true">
      <method />
    </configuration>
    <configuration default="true" type="NodeJSConfigurationType" factoryName="Node.js" working-dir="">
      <browser start="false" url="" with-js-debugger="false" />
      <method />
    </configuration>
    <list size="0" />
  </component>
  <component name="ShelveChangesManager" show_recycled="false" />
  <component name="TaskManager">
    <task active="true" id="Default" summary="Default task">
      <changelist id="edcbf0d3-8e05-457c-aa6e-44b8585b4562" name="Default" comment="" />
      <created>1384695052398</created>
      <updated>1384695052398</updated>
    </task>
    <servers />
  </component>
  <component name="ToolWindowManager">
    <frame x="0" y="0" width="1680" height="1050" extended-state="0" />
    <editor active="false" />
    <layout>
      <window_info id="Changes" active="false" anchor="bottom" auto_hide="false" internal_type="DOCKED" type="DOCKED" visible="false" weight="0.33" sideWeight="0.5" order="7" side_tool="false" content_ui="tabs" />
      <window_info id="Terminal" active="true" anchor="bottom" auto_hide="false" internal_type="DOCKED" type="DOCKED" visible="true" weight="0.22584033" sideWeight="0.5" order="7" side_tool="false" content_ui="tabs" />
      <window_info id="TODO" active="false" anchor="bottom" auto_hide="false" internal_type="DOCKED" type="DOCKED" visible="false" weight="0.33" sideWeight="0.5" order="6" side_tool="false" content_ui="tabs" />
      <window_info id="Structure" active="false" anchor="left" auto_hide="false" internal_type="DOCKED" type="DOCKED" visible="false" weight="0.25" sideWeight="0.5" order="1" side_tool="false" content_ui="tabs" />
      <window_info id="Project" active="false" anchor="left" auto_hide="false" internal_type="DOCKED" type="DOCKED" visible="true" weight="0.13940857" sideWeight="0.77415967" order="0" side_tool="false" content_ui="combo" />
      <window_info id="Debug" active="false" anchor="bottom" auto_hide="false" internal_type="DOCKED" type="DOCKED" visible="false" weight="0.4" sideWeight="0.5" order="3" side_tool="false" content_ui="tabs" />
      <window_info id="Favorites" active="false" anchor="left" auto_hide="false" internal_type="DOCKED" type="DOCKED" visible="false" weight="0.33" sideWeight="0.5" order="2" side_tool="true" content_ui="tabs" />
      <window_info id="Event Log" active="false" anchor="bottom" auto_hide="false" internal_type="DOCKED" type="DOCKED" visible="false" weight="0.33" sideWeight="0.5" order="7" side_tool="true" content_ui="tabs" />
      <window_info id="Run" active="false" anchor="bottom" auto_hide="false" internal_type="DOCKED" type="DOCKED" visible="false" weight="0.33" sideWeight="0.5" order="2" side_tool="false" content_ui="tabs" />
      <window_info id="Version Control" active="false" anchor="bottom" auto_hide="false" internal_type="DOCKED" type="DOCKED" visible="false" weight="0.33" sideWeight="0.5" order="7" side_tool="false" content_ui="tabs" />
      <window_info id="Cvs" active="false" anchor="bottom" auto_hide="false" internal_type="DOCKED" type="DOCKED" visible="false" weight="0.25" sideWeight="0.5" order="4" side_tool="false" content_ui="tabs" />
      <window_info id="Message" active="false" anchor="bottom" auto_hide="false" internal_type="DOCKED" type="DOCKED" visible="false" weight="0.33" sideWeight="0.5" order="0" side_tool="false" content_ui="tabs" />
      <window_info id="Ant Build" active="false" anchor="right" auto_hide="false" internal_type="DOCKED" type="DOCKED" visible="false" weight="0.25" sideWeight="0.5" order="1" side_tool="false" content_ui="tabs" />
      <window_info id="Find" active="false" anchor="bottom" auto_hide="false" internal_type="DOCKED" type="DOCKED" visible="false" weight="0.33" sideWeight="0.5" order="1" side_tool="false" content_ui="tabs" />
      <window_info id="Commander" active="false" anchor="right" auto_hide="false" internal_type="SLIDING" type="SLIDING" visible="false" weight="0.4" sideWeight="0.5" order="0" side_tool="false" content_ui="tabs" />
      <window_info id="Hierarchy" active="false" anchor="right" auto_hide="false" internal_type="DOCKED" type="DOCKED" visible="false" weight="0.25" sideWeight="0.5" order="2" side_tool="false" content_ui="combo" />
      <window_info id="Inspection" active="false" anchor="bottom" auto_hide="false" internal_type="DOCKED" type="DOCKED" visible="false" weight="0.4" sideWeight="0.5" order="5" side_tool="false" content_ui="tabs" />
    </layout>
  </component>
  <component name="VcsContentAnnotationSettings">
    <option name="myLimit" value="2678400000" />
  </component>
  <component name="VcsManagerConfiguration">
    <option name="myTodoPanelSettings">
      <TodoPanelSettings />
    </option>
  </component>
  <component name="XDebuggerManager">
    <breakpoint-manager />
  </component>
  <component name="editorHistoryManager">
    <entry file="file://$PROJECT_DIR$/app/assets/modal/js/cssParser.js">
      <provider selected="true" editor-type-id="text-editor">
        <state line="0" column="0" selection-start="0" selection-end="0" vertical-scroll-proportion="0.0" vertical-offset="0" max-vertical-offset="81825">
          <folding>
            <element signature="n#!!doc" expanded="false" />
          </folding>
        </state>
      </provider>
    </entry>
    <entry file="file://$PROJECT_DIR$/app/assets/modal/js/css-filters-polyfill.js">
      <provider selected="true" editor-type-id="text-editor">
        <state line="6" column="16" selection-start="149" selection-end="149" vertical-scroll-proportion="0.0" vertical-offset="0" max-vertical-offset="11865" />
      </provider>
    </entry>
    <entry file="file://$PROJECT_DIR$/app/assets/modal/css/default.css">
      <provider selected="true" editor-type-id="text-editor">
        <state line="0" column="0" selection-start="0" selection-end="0" vertical-scroll-proportion="0.0" vertical-offset="0" max-vertical-offset="2835">
          <folding />
        </state>
      </provider>
    </entry>
    <entry file="file://$PROJECT_DIR$/app/assets/modal/js/classie.js">
      <provider selected="true" editor-type-id="text-editor">
        <state line="0" column="0" selection-start="0" selection-end="0" vertical-scroll-proportion="0.0" vertical-offset="0" max-vertical-offset="1290">
          <folding>
            <element signature="n#!!doc" expanded="false" />
          </folding>
        </state>
      </provider>
    </entry>
    <entry file="file://$PROJECT_DIR$/app/assets/modal/css/component.css">
      <provider selected="true" editor-type-id="text-editor">
        <state line="21" column="0" selection-start="459" selection-end="459" vertical-scroll-proportion="0.42473918" vertical-offset="30" max-vertical-offset="11070">
          <folding />
        </state>
      </provider>
    </entry>
    <entry file="file://$PROJECT_DIR$/app/assets/modal/js/modalEffects.js">
      <provider selected="true" editor-type-id="text-editor">
        <state line="0" column="0" selection-start="0" selection-end="0" vertical-scroll-proportion="0.0" vertical-offset="0" max-vertical-offset="709" />
      </provider>
    </entry>
    <entry file="file://$PROJECT_DIR$/app/scripts/controllers/load.js">
      <provider selected="true" editor-type-id="text-editor">
        <state line="7" column="32" selection-start="243" selection-end="243" vertical-scroll-proportion="0.0" vertical-offset="0" max-vertical-offset="270">
          <folding />
        </state>
      </provider>
    </entry>
    <entry file="file://$PROJECT_DIR$/app/views/admin.html">
      <provider selected="true" editor-type-id="text-editor">
        <state line="11" column="30" selection-start="429" selection-end="429" vertical-scroll-proportion="-6.875" vertical-offset="0" max-vertical-offset="390">
          <folding />
        </state>
      </provider>
    </entry>
    <entry file="file://$PROJECT_DIR$/app/scripts/services/auth.js">
      <provider selected="true" editor-type-id="text-editor">
        <state line="12" column="41" selection-start="237" selection-end="237" vertical-scroll-proportion="0.0" vertical-offset="0" max-vertical-offset="645">
          <folding />
        </state>
      </provider>
    </entry>
    <entry file="file://$PROJECT_DIR$/app/scripts/controllers/admin.js">
      <provider selected="true" editor-type-id="text-editor">
        <state line="12" column="34" selection-start="381" selection-end="381" vertical-scroll-proportion="0.0" vertical-offset="0" max-vertical-offset="600">
          <folding />
        </state>
      </provider>
    </entry>
    <entry file="file://$PROJECT_DIR$/app/scripts/app.js">
      <provider selected="true" editor-type-id="text-editor">
        <state line="27" column="0" selection-start="565" selection-end="565" vertical-scroll-proportion="0.0" vertical-offset="0" max-vertical-offset="555">
          <folding />
        </state>
      </provider>
    </entry>
    <entry file="file://$PROJECT_DIR$/app/views/main.html">
      <provider selected="true" editor-type-id="text-editor">
        <state line="36" column="0" selection-start="1286" selection-end="1286" vertical-scroll-proportion="0.75446427" vertical-offset="33" max-vertical-offset="705">
          <folding />
        </state>
      </provider>
    </entry>
    <entry file="file://$PROJECT_DIR$/dist/assets/modal/js/classie.js">
      <provider selected="true" editor-type-id="text-editor">
        <state line="0" column="0" selection-start="0" selection-end="0" vertical-scroll-proportion="0.0" vertical-offset="0" max-vertical-offset="1170">
          <folding />
        </state>
      </provider>
    </entry>
    <entry file="file://$PROJECT_DIR$/app/styles/main.scss">
      <provider selected="true" editor-type-id="text-editor">
        <state line="113" column="16" selection-start="2001" selection-end="2001" vertical-scroll-proportion="-6.9054055" vertical-offset="1184" max-vertical-offset="3360">
          <folding />
        </state>
      </provider>
    </entry>
    <entry file="file://$PROJECT_DIR$/app/index.html">
      <provider selected="true" editor-type-id="text-editor">
        <state line="11" column="59" selection-start="567" selection-end="567" vertical-scroll-proportion="-6.875" vertical-offset="0" max-vertical-offset="1845">
          <folding />
        </state>
      </provider>
    </entry>
    <entry file="file://$PROJECT_DIR$/app/scripts/controllers/main.js">
      <provider selected="true" editor-type-id="text-editor">
        <state line="36" column="0" selection-start="1076" selection-end="1076" vertical-scroll-proportion="0.804769" vertical-offset="0" max-vertical-offset="1680">
          <folding />
        </state>
      </provider>
    </entry>
  </component>
</project>


text:
from .log import LoggerFactory

# Global logger for this part
logger = LoggerFactory.create_logger('dashboard')

class DashboardManager(object):
    def __init__(self):
        self.dashboards = {}

    def import_dashboard(self, o, fname, gname, mod_time=0, pack_name='', pack_level=''):
        o['pack_name'] = pack_name
        o['pack_level'] = pack_level
        self.dashboards[gname.split('/')[-1]] = o

dashboarder = None

def get_dashboarder():
    global dashboarder
    if dashboarder is None:
        logger.debug('Lazy creation of the dashboarder class')
        dashboarder = DashboardManager()
    return dashboarder

redpajama_set_name: RedPajamaGithub


text:
package com.dremio.datastore.format;

import java.util.Arrays;
import java.util.Objects;

import com.dremio.datastore.format.compound.KeyPair;
import com.dremio.datastore.format.compound.KeyTriple;

/**
 * Tests for expected classes returned from {@link Format#getRepresentedClass()}
 */
public class WrappedCompoundFormats {
  /**
   * Wraps a KeyPair object.
   */
  public static class KeyPairStringContainer {
    private final KeyPair<String, String> containedObject;

    public KeyPairStringContainer(KeyPair<String, String> containedObject) {
      this.containedObject = containedObject;
    }

    public KeyPair<String,String> getContainedObject() {
      return containedObject;
    }

    @Override
    public boolean equals(Object obj) {
      return Objects.deepEquals(this, obj);
    }

    @Override
    public int hashCode() {
      return Objects.hash(containedObject);
    }
  }

  /**
   * Wraps a KeyTriple object.
   */
  public static class KeyTripleStringContainer {
    private final KeyTriple<String, String, String> containedObject;

    public KeyTripleStringContainer(KeyTriple<String, String, String> containedObject) {
      this.containedObject = containedObject;
    }

    public KeyTriple<String,String, String> getContainedObject() {
      return containedObject;
    }

    @Override
    public boolean equals(Object obj) {
      return Objects.deepEquals(this, obj);
    }

    @Override
    public int hashCode() {
      return Objects.hash(containedObject);
    }
  }

  /**
   * Wraps a KeyPair object.
   */
  public static class KeyPairBytesContainer {
    private final KeyPair<byte[], byte[]> containedObject;

    public KeyPairBytesContainer(KeyPair<byte[], byte[]> containedObject) {
      this.containedObject = containedObject;
    }

    public KeyPair<byte[],byte[]> getContainedObject() {
      return containedObject;
    }

    @Override
    public boolean equals(Object obj) {
      return Objects.deepEquals(this, obj);
    }

    @Override
    public int hashCode() {
      return Arrays.deepHashCode(containedObject.toArray());
    }
  }

  /**
   * Wraps a KeyTriple object.
   */
  public static class KeyTripleBytesContainer {
    private final KeyTriple<byte[], byte[], byte[]> containedObject;

    public KeyTripleBytesContainer(KeyTriple<byte[], byte[], byte[]> containedObject) {
      this.containedObject = containedObject;
    }

    public KeyTriple<byte[],byte[], byte[]> getContainedObject() {
      return containedObject;
    }

    @Override
    public boolean equals(Object obj) {
      return Objects.deepEquals(this, obj);
    }

    @Override
    public int hashCode() {
      return Arrays.deepHashCode(containedObject.toArray());
    }
  }
}


text:
package cherry.gallery.web.basic.ex30;

import lombok.EqualsAndHashCode;
import lombok.Getter;
import lombok.Setter;
import lombok.ToString;

@Getter
@Setter
@EqualsAndHashCode(callSuper = true)
@ToString(callSuper = true)
public class BasicEx30Form extends BasicEx30FormBase {

	private static final long serialVersionUID = 1L;

}


text:
<?php

class Ui_UploadController extends IMDT_Controller_Abstract {

    public function postAction() {
        $this->_disableViewAndLayout();
        $upload_handler = new JQueryUploader_UploadHandler(null, false);
        $response = $upload_handler->post(false);

        $newResponse = array();
        foreach ($response as $key => $value) {
            $newResponse[$key] = $value;
        }

        $newFiles = $newResponse['files'];

        foreach ($newFiles as $indice => &$file) {
            $fileName = $_FILES['files']['name'][$indice];
            $file->displayName = $fileName;
        }

        echo json_encode($newResponse);
    }

}


text:
layout: post
category: blog
title: "Converting goto"
tag : codeing
published: true
author: Lee Elenbaas
---
I am working on a task I thought have passed from the world:
Converting "goto" code to functional programming.
And I am doing it in modern Javascript code.

This was covered by articles over 20 years ago, see http://ieeexplore.ieee.org/xpl/articleDetails.jsp?tp=&arnumber=126773&url=http%3A%2F%2Fieeexplore.ieee.org%2Fxpls%2Fabs_all.jsp%3Farnumber%3D126773

The basics are the normal loops, conditionals, break and continue.

# Conversion rules

* If you have a goto that jumps forward can be replaced by a simple if on the code it jumps over.

* A goto that jump backwards is converted to loop. either a do-while loop, or an infinite loop.

* Several jumps forward with overlapping skipped code can be made using flags, each goto condition will set the appropriate flags, and the code execution will depend on the flags.

* Multiple jumps backward can be replaced by a single infinite loop, and appropriate flags.

In general, it is best to understand what the code tries to do. There is usually a better way then just make it work with the new tools.


text:
package io.druid.segment.transform;

import io.druid.data.input.InputRow;
import io.druid.data.input.impl.ParseSpec;
import io.druid.data.input.impl.StringInputRowParser;

import javax.annotation.Nullable;
import java.nio.ByteBuffer;
import java.util.List;
import java.util.stream.Collectors;

public class TransformingStringInputRowParser extends StringInputRowParser
{
  private final TransformSpec transformSpec;
  private final Transformer transformer;

  public TransformingStringInputRowParser(
      final ParseSpec parseSpec,
      final String encoding,
      final TransformSpec transformSpec
  )
  {
    super(parseSpec, encoding);
    this.transformSpec = transformSpec;
    this.transformer = transformSpec.toTransformer();
  }

  @Override
  public List<InputRow> parseBatch(final ByteBuffer input)
  {
    return super.parseBatch(input).stream().map(transformer::transform).collect(Collectors.toList());
  }

  @Nullable
  @Override
  public InputRow parse(@Nullable final String input)
  {
    return transformer.transform(super.parse(input));
  }

  @Override
  public StringInputRowParser withParseSpec(final ParseSpec parseSpec)
  {
    return new TransformingStringInputRowParser(parseSpec, getEncoding(), transformSpec);
  }

  public TransformSpec getTransformSpec()
  {
    return transformSpec;
  }
}


text:
layout: post
title: GMCH Chandigarh Medical Lab Technician posts last date 9th Sep 2015
date: 2015-08-17 19:33
comments: true
tags:  Chandigarh  College  Hospital  Laboratory  Medical  Online  Technician
archive: false
---
Online applications are invited for filling up the following posts consolidated contract basis :

- Medical Lab Technician : 06 posts (UR-4, SC-1, ST-1), Pay : Rs. 33700/- on consolidated basis, Age : 18-25 years

**How to Apply** : Apply Online at GMCH website on or before 09/09/2015.

Please visit <http://gmch.gov.in/jobs.aspx>   for detailed information  and  online application format.


text:
package com.obidea.semantika.knowledgebase;

import java.util.ArrayList;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import com.obidea.semantika.expression.base.IAtom;
import com.obidea.semantika.expression.base.IConstant;
import com.obidea.semantika.expression.base.IExpressionObject;
import com.obidea.semantika.expression.base.IFunction;
import com.obidea.semantika.expression.base.ISignature;
import com.obidea.semantika.expression.base.ITerm;
import com.obidea.semantika.expression.base.IUriReference;
import com.obidea.semantika.expression.base.IVariable;
import com.obidea.semantika.expression.base.TermUtils;
import com.obidea.semantika.mapping.IUriTemplate;
import com.obidea.semantika.mapping.MappingObjectFactory;
import com.obidea.semantika.util.Serializer;

public class Unifier
{
   public static TermSubstitutionBinding findSubstitution(IAtom a1, IAtom a2) throws UnificationException
   {
      TermSubstitutionBinding theta = TermSubstitutionBinding.createEmptyBinding();
      findSubstitution(a1, a2, theta);
      return theta;
   }

   public static TermSubstitutionBinding findSubstitution(ITerm t1, ITerm t2) throws UnificationException
   {
      TermSubstitutionBinding theta = TermSubstitutionBinding.createEmptyBinding();
      findSubstitution(t1, t2, theta);
      return theta;
   }

   public static void findSubstitution(IAtom a1, IAtom a2, TermSubstitutionBinding substitution) throws UnificationException
   {
      /*
       * The fastest way to ignore finding the unifier is to compare both atoms syntactically. This
       * checking will throw UnificationException if the two atoms are not similar.
       */
      checkSyntacticalUnification(a1, a2);
      IAtom ac1 = copy(a1);
      IAtom ac2 = copy(a2);
      for (int i = 0; i < a1.getArity(); i++) {
         final ITerm t1 = ac1.getTerm(i);
         final ITerm t2 = ac2.getTerm(i);
         findSubstitution(t1, t2, substitution);
         ac1.apply(substitution);
         ac2.apply(substitution);
      }
      checkOverflowUnification(ac1, ac2);
   }

   public static void findSubstitution(ITerm t1, ITerm t2, TermSubstitutionBinding substitution) throws UnificationException
   {
      if (t1.equals(t2)) {
         return; // if both terms are equal then ignore them.
      }

      if (t1 instanceof IConstant && t2 instanceof IConstant) {
         findSubstitution(TermUtils.asConstant(t1), TermUtils.asConstant(t2), substitution);
      }
      if (t1 instanceof IFunction && t2 instanceof IFunction) {
         findSubstitution(TermUtils.asFunction(t1), TermUtils.asFunction(t2), substitution);
      }

      if (t1 instanceof IUriTemplate && t2 instanceof IUriReference) {
         findSubstitution((IUriTemplate) t1, TermUtils.asUriReference(t2), substitution);
      }
      if (t1 instanceof IUriReference && t2 instanceof IUriTemplate) {
         findSubstitution((IUriTemplate) t2, TermUtils.asUriReference(t1), substitution);
      }

      // Create a substitution unifier between variable and term
      TermSubstitutionBinding sigma = TermSubstitutionBinding.createEmptyBinding();
      if (t2 instanceof IVariable) {
         sigma.put(TermUtils.asVariable(t2), t1);
      }
      else if (t1 instanceof IVariable) {
         sigma.put(TermUtils.asVariable(t1), t2);
      }

      // Do substitution unifier composition.
      substitution.compose(sigma);
   }

   public static void findSubstitution(IConstant c1, IConstant c2, TermSubstitutionBinding substitution) throws UnificationException
   {
      if (!c1.equals(c2)) {
         String message = String.format("Constants are not equal \"%s\" and \"%s\"", c1.getLexicalValue(), c2.getLexicalValue()); //$NON-NLS-1$
         throw new UnificationException(message);
      }
   }

   public static void findSubstitution(IFunction f1, IFunction f2, TermSubstitutionBinding substitution) throws UnificationException
   {
      /*
       * The fastest way to ignore finding the unifier is to compare both functions syntactically. This
       * checking will throw UnificationException if the two functions are not similar.
       */
      checkSyntacticalUnification(f1, f2);
      IFunction fc1 = TermUtils.copy(f1);
      IFunction fc2 = TermUtils.copy(f2);
      for (int i = 0; i < fc1.getArity(); i++) {
         final ITerm p1 = fc1.getParameter(i);
         final ITerm p2 = fc2.getParameter(i);
         findSubstitution(p1, p2, substitution);
         fc1.apply(substitution);
         fc2.apply(substitution);
      }
      checkOverflowUnification(fc1, fc2);
   }

   public static void findSubstitution(IUriTemplate uriTemplate, IUriReference uriReference, TermSubstitutionBinding substitution) throws UnificationException
   {
      String templateString = uriTemplate.getTemplateString();
      String templateRegex = templateString.replaceAll("\\{\\d+\\}", "(.*)"); //$NON-NLS-1$
      Pattern templatePattern = Pattern.compile(templateRegex);

      List<ITerm> parameters = new ArrayList<ITerm>();
      Matcher m = templatePattern.matcher(uriReference.getLexicalValue());
      if (m.matches()) {
         for (int i = 1; i <= m.groupCount(); i++) {
            String value = m.group(i); // value comes from pattern matching
            String datatype = uriTemplate.getParameter(i-1).getDatatype(); // datatype comes from template function
            parameters.add(TermUtils.makeTypedLiteral(value, datatype)); //$NON-NLS-1$
         }
      }
      IUriTemplate u2 = MappingObjectFactory.getInstance().createUriTemplate(templateString, parameters);
      findSubstitution(uriTemplate, u2, substitution);
   }

   private static void checkSyntacticalUnification(ISignature s1, ISignature s2) throws UnificationException
   {
      if (!s1.isEquivalent(s2)) {
         throw new UnificationException("Signatures are not equal"); //$NON-NLS-1$
      }
   }

   private static void checkOverflowUnification(IExpressionObject a1, IExpressionObject a2) throws UnificationException
   {
      try {
         a1.toString();
         a2.toString();
      }
      catch (StackOverflowError e) {
         throw new UnificationException("Infinite loop in unification", e); //$NON-NLS-1$
      }
   }

   private static IAtom copy(IAtom atom)
   {
      return (IAtom) Serializer.copy(atom);
   }
}


text:
from django.conf import settings
from django.db import models

class AppToAppPermission(models.Model):
    requester = models.ForeignKey(settings.OAUTH2_PROVIDER_APPLICATION_MODEL,
                                  db_index=True, related_name='+', on_delete=models.CASCADE)
    target = models.ForeignKey(settings.OAUTH2_PROVIDER_APPLICATION_MODEL,
                               db_index=True, related_name='+', on_delete=models.CASCADE)

    def __str__(self):
        return "%s -> %s" % (self.requester, self.target)


text:
class Api::ApiController < ApplicationController

	private
	  	# Devise methods overwrites
		def current_user
			if request.headers['Authorization'] != ""
					@current_user ||= User.find_by(auth_token: request.headers['Authorization'])
			end
		end

		def authenticate_with_token!
			render json: { errors: "Not authenticated" },
		    	status: :unauthorized unless current_user.present?
			end
		end


text:
package pro.taskana.monitor.internal.reports;

import java.time.Instant;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.List;
import java.util.stream.Collectors;

import pro.taskana.common.api.TaskanaRole;
import pro.taskana.common.api.exceptions.InvalidArgumentException;
import pro.taskana.common.api.exceptions.NotAuthorizedException;
import pro.taskana.common.internal.InternalTaskanaEngine;
import pro.taskana.monitor.api.SelectedItem;
import pro.taskana.monitor.api.TaskTimestamp;
import pro.taskana.monitor.api.reports.Report;
import pro.taskana.monitor.api.reports.TimestampReport;
import pro.taskana.monitor.api.reports.TimestampReport.Builder;
import pro.taskana.monitor.api.reports.header.TimeIntervalColumnHeader;
import pro.taskana.monitor.api.reports.item.TimestampQueryItem;
import pro.taskana.monitor.internal.MonitorMapper;
import pro.taskana.monitor.internal.preprocessor.DaysToWorkingDaysReportPreProcessor;
import pro.taskana.task.api.TaskState;

/** The implementation of {@linkplain TimestampReport.Builder}. */
public class TimestampReportBuilderImpl
    extends TimeIntervalReportBuilderImpl<Builder, TimestampQueryItem, TimeIntervalColumnHeader>
    implements TimestampReport.Builder {

  private List<TaskTimestamp> status =
      Arrays.asList(TaskTimestamp.CREATED, TaskTimestamp.COMPLETED);

  public TimestampReportBuilderImpl(
      InternalTaskanaEngine taskanaEngine, MonitorMapper monitorMapper) {
    super(taskanaEngine, monitorMapper);
  }

  @Override
  public TimestampReport.Builder stateIn(List<TaskState> states) {
    throw new UnsupportedOperationException(
        "The states have no influence regarding this report. Use withTimestamps instead");
  }

  @Override
  public List<String> listTaskIdsForSelectedItems(
      List<SelectedItem> selectedItems, TaskTimestamp timestamp) {
    throw new UnsupportedOperationException();
  }

  @Override
  public TimestampReport.Builder withTimestamps(List<TaskTimestamp> taskTimestamps) {
    this.status = new ArrayList<>(taskTimestamps);
    return _this();
  }

  @Override
  public Report<TimestampQueryItem, TimeIntervalColumnHeader> buildReport(TaskTimestamp timestamp)
      throws NotAuthorizedException, InvalidArgumentException {
    return buildReport();
  }

  @Override
  public TimestampReport buildReport() throws NotAuthorizedException, InvalidArgumentException {
    this.taskanaEngine.getEngine().checkRoleMembership(TaskanaRole.MONITOR, TaskanaRole.ADMIN);
    try {
      this.taskanaEngine.openConnection();
      TimestampReport report = new TimestampReport(columnHeaders);
      List<TimestampQueryItem> items =
          status.stream()
              // This can also be implemented into a single sql query which combines all statuses
              // with the union operator. That would reduce the readability of the sql template.
              // That's why "the loop" is done outside mybatis.
              .map(this::getTasksCountForStatusGroupedByOrgLevel)
              .flatMap(Collection::stream)
              .collect(Collectors.toList());

      report.addItems(
          items,
          new DaysToWorkingDaysReportPreProcessor<>(columnHeaders, converter, inWorkingDays));
      return report;
    } finally {
      this.taskanaEngine.returnConnection();
    }
  }

  @Override
  protected TimestampReport.Builder _this() {
    return this;
  }

  @Override
  protected String determineGroupedBy() {
    throw new UnsupportedOperationException();
  }

  private List<TimestampQueryItem> getTasksCountForStatusGroupedByOrgLevel(TaskTimestamp s) {
    return monitorMapper.getTasksCountForStatusGroupedByOrgLevel(Instant.now(), s, this);
  }
}


text:
@interface SOKRSA : NSObject

@property (nonatomic) size_t maxPlainLen;

- (instancetype _Nullable)initWithDERData:(NSData * _Nonnull)keyData;

// Encrypt with a public key. Data will only be decryptable with the corresponsing private key.
- (NSData * _Nullable) encryptWithData:(NSData * _Nonnull)content;

// Decryption can be done with openssl, but we didn't find a way to do it so far with
//  CommonCrypto library build into iOS.

@end


text:
'use strict';

/**
 * @class
 * Initializes a new instance of the ComputeNodeListResult class.
 * @constructor
 * @summary The result of listing the compute nodes in a pool.
 *
 * @member {string} [odatanextLink]
 *
 */
class ComputeNodeListResult extends Array {
  constructor() {
    super();
  }

  /**
   * Defines the metadata of ComputeNodeListResult
   *
   * @returns {object} metadata of ComputeNodeListResult
   *
   */
  mapper() {
    return {
      required: false,
      serializedName: 'ComputeNodeListResult',
      type: {
        name: 'Composite',
        className: 'ComputeNodeListResult',
        modelProperties: {
          value: {
            required: false,
            serializedName: '',
            type: {
              name: 'Sequence',
              element: {
                  required: false,
                  serializedName: 'ComputeNodeElementType',
                  type: {
                    name: 'Composite',
                    className: 'ComputeNode'
                  }
              }
            }
          },
          odatanextLink: {
            required: false,
            serializedName: 'odata\\.nextLink',
            type: {
              name: 'String'
            }
          }
        }
      }
    };
  }
}

module.exports = ComputeNodeListResult;


text:
var countImage = [];
countImage[0] = 0;
document.getElementById('button').style.visibility="hidden";
function parseRSS() {
        var form = document.forms[0];
        var select = form.elements.url;
        var urlSelected;
        for (var i = 0; i < select.options.length; i++) {
            var option = select.options[i];
            if(option.selected) {
                urlSelected = option.value;
            }
        }
        parseXML(urlSelected);
    }

    function parseXML(url) {
        $.ajax({
            type: 'GET',
            url: url,
            dataType: 'xml',
            error: function(xhr) {
                alert('Failed to parse feed');
            },
            success: function(xml) {
                var channel = $('entry', xml).eq(0);
                var items = [];
                $('entry', xml).each( function() {
                    var item = {};
                    item.title = $(this).find('title').eq(0).text();
                    item.id = $(this).find('id').eq(0).text();
                    item.published = $(this).find('published').eq(0).text();
                    item.updated = $(this).find('updated').eq(0).text();
                    item.authorName = $(this).find('name').text();
                    item.authorUri = $(this).find('uri').text();
                    item.content= $(this).find('content').text();
                    items.push(item);
                    console.dir(item);
                });
                buildRSS(items);
            }
        });
    }

    function buildRSS(temp) {
        var items = temp;
        console.log(items.length);
        var table = document.getElementById('rss');
        table.setAttribute('width','auto');
        table.setAttribute('border','1');
        for (var i = 0; i < items.length; i++) {
            var newRow = table.insertRow(i);
            var newCell0 = newRow.insertCell(0);
            newCell0.width = window.innerWidth;
            var date = new Date(items[i].published);
            newCell0.innerHTML = "" + items[i].title + "" + "
" + date + "
" + items[i].content;
        }
        getImages();
        document.getElementById('button').style.visibility="visible";
}

function getImages() {
    var imagesDoc = document.querySelectorAll('img');
    countImage.push(imagesDoc.length);
    var x = {};
    var images = [];
    for (var i = 0; i < countImage[countImage.length - 1] - countImage[countImage.length - 2]; i++) {
        var image = {};
        image.title = imagesDoc[i].alt;
        image.uri = imagesDoc[i].src;
        images.push(image);
    }
    x.images = images;
    localStorage.setItem("images", JSON.stringify(x.images));
}

function goToGallery() {
    window.open('file:///Users/admin/Desktop/JS/rssReader/photoGallery/index.html');
}


text:
using content::BrowserThread;
using net::URLFetcher;
using variations::VariationsService;

namespace {

const char kPopularSitesURLFormat[] =
    "https://www.gstatic.com/chrome/ntp/suggested_sites_%s_%s.json";
const char kPopularSitesDefaultCountryCode[] = "DEFAULT";
const char kPopularSitesDefaultVersion[] = "5";
const char kPopularSitesLocalFilename[] = "suggested_sites.json";
const int kPopularSitesRedownloadIntervalHours = 24;

const char kPopularSitesLastDownloadPref[] = "popular_sites_last_download";
const char kPopularSitesCountryPref[] = "popular_sites_country";
const char kPopularSitesVersionPref[] = "popular_sites_version";

// Extract the country from the default search engine if the default search
// engine is Google.
std::string GetDefaultSearchEngineCountryCode(
    const TemplateURLService* template_url_service) {
  DCHECK(template_url_service);

  base::CommandLine* cmd_line = base::CommandLine::ForCurrentProcess();
  if (!cmd_line->HasSwitch(
          ntp_tiles::switches::kEnableNTPSearchEngineCountryDetection))
    return std::string();

  const TemplateURL* default_provider =
      template_url_service->GetDefaultSearchProvider();
  // It's possible to not have a default provider in the case that the default
  // search engine is defined by policy.
  if (default_provider) {
    bool is_google_search_engine =
        TemplateURLPrepopulateData::GetEngineType(
            *default_provider, template_url_service->search_terms_data()) ==
        SearchEngineType::SEARCH_ENGINE_GOOGLE;

    if (is_google_search_engine) {
      GURL search_url = default_provider->GenerateSearchURL(
          template_url_service->search_terms_data());
      return google_util::GetGoogleCountryCode(search_url);
    }
  }

  return std::string();
}

// Determine the country code to use. In order of precedence:
// - The explicit "override country" pref set by the user.
// - The country code from the field trial config (variation parameter).
// - The Google country code if Google is the default search engine (and the
//   "--enable-ntp-search-engine-country-detection" switch is present).
// - The country provided by the VariationsService.
// - A default fallback.
std::string GetCountryToUse(const PrefService* prefs,
                            const TemplateURLService* template_url_service,
                            VariationsService* variations_service,
                            const std::string& variation_param_country) {
  std::string country_code =
      prefs->GetString(ntp_tiles::prefs::kPopularSitesOverrideCountry);

  if (country_code.empty())
    country_code = variation_param_country;

  if (country_code.empty())
    country_code = GetDefaultSearchEngineCountryCode(template_url_service);

  if (country_code.empty() && variations_service)
    country_code = variations_service->GetStoredPermanentCountry();

  if (country_code.empty())
    country_code = kPopularSitesDefaultCountryCode;

  return base::ToUpperASCII(country_code);
}

// Determine the version to use. In order of precedence:
// - The explicit "override version" pref set by the user.
// - The version from the field trial config (variation parameter).
// - A default fallback.
std::string GetVersionToUse(const PrefService* prefs,
                            const std::string& variation_param_version) {
  std::string version =
      prefs->GetString(ntp_tiles::prefs::kPopularSitesOverrideVersion);

  if (version.empty())
    version = variation_param_version;

  if (version.empty())
    version = kPopularSitesDefaultVersion;

  return version;
}

std::unique_ptr<std::vector<PopularSites::Site>> ParseJson(
    const std::string& json) {
  std::unique_ptr<base::Value> value =
      base::JSONReader::Read(json, base::JSON_ALLOW_TRAILING_COMMAS);
  base::ListValue* list;
  if (!value || !value->GetAsList(&list)) {
    DLOG(WARNING) << "Failed parsing json";
    return nullptr;
  }

  std::unique_ptr<std::vector<PopularSites::Site>> sites(
      new std::vector<PopularSites::Site>);
  for (size_t i = 0; i < list->GetSize(); i++) {
    base::DictionaryValue* item;
    if (!list->GetDictionary(i, &item))
      continue;
    base::string16 title;
    std::string url;
    if (!item->GetString("title", &title) || !item->GetString("url", &url))
      continue;
    std::string favicon_url;
    item->GetString("favicon_url", &favicon_url);
    std::string thumbnail_url;
    item->GetString("thumbnail_url", &thumbnail_url);
    std::string large_icon_url;
    item->GetString("large_icon_url", &large_icon_url);

    sites->push_back(PopularSites::Site(title, GURL(url), GURL(favicon_url),
                                        GURL(large_icon_url),
                                        GURL(thumbnail_url)));
  }

  return sites;
}

}  // namespace

base::FilePath ChromePopularSites::GetDirectory() {
  base::FilePath dir;
  PathService::Get(chrome::DIR_USER_DATA, &dir);
  return dir;  // empty if PathService::Get() failed.
}

PopularSites::Site::Site(const base::string16& title,
                         const GURL& url,
                         const GURL& favicon_url,
                         const GURL& large_icon_url,
                         const GURL& thumbnail_url)
    : title(title),
      url(url),
      favicon_url(favicon_url),
      large_icon_url(large_icon_url),
      thumbnail_url(thumbnail_url) {}

PopularSites::Site::Site(const Site& other) = default;

PopularSites::Site::~Site() {}

PopularSites::PopularSites(PrefService* prefs,
                           const TemplateURLService* template_url_service,
                           VariationsService* variations_service,
                           net::URLRequestContextGetter* download_context,
                           const base::FilePath& directory,
                           const std::string& variation_param_country,
                           const std::string& variation_param_version,
                           bool force_download,
                           const FinishedCallback& callback)
    : PopularSites(prefs,
                   download_context,
                   directory,
                   GetCountryToUse(prefs,
                                   template_url_service,
                                   variations_service,
                                   variation_param_country),
                   GetVersionToUse(prefs, variation_param_version),
                   GURL(),
                   force_download,
                   callback) {}

PopularSites::PopularSites(PrefService* prefs,
                           net::URLRequestContextGetter* download_context,
                           const base::FilePath& directory,
                           const GURL& url,
                           const FinishedCallback& callback)
    : PopularSites(prefs,
                   download_context,
                   directory,
                   std::string(),
                   std::string(),
                   url,
                   true,
                   callback) {}

PopularSites::~PopularSites() {}

std::string PopularSites::GetCountry() const {
  return prefs_->GetString(kPopularSitesCountryPref);
}

std::string PopularSites::GetVersion() const {
  return prefs_->GetString(kPopularSitesVersionPref);
}

// static
void PopularSites::RegisterProfilePrefs(
    user_prefs::PrefRegistrySyncable* user_prefs) {
  user_prefs->RegisterStringPref(ntp_tiles::prefs::kPopularSitesOverrideCountry,
                                 std::string());
  user_prefs->RegisterStringPref(ntp_tiles::prefs::kPopularSitesOverrideVersion,
                                 std::string());

  user_prefs->RegisterInt64Pref(kPopularSitesLastDownloadPref, 0);
  user_prefs->RegisterStringPref(kPopularSitesCountryPref, std::string());
  user_prefs->RegisterStringPref(kPopularSitesVersionPref, std::string());
}

PopularSites::PopularSites(PrefService* prefs,
                          net::URLRequestContextGetter* download_context,
                           const base::FilePath& directory,
                           const std::string& country,
                           const std::string& version,
                           const GURL& override_url,
                           bool force_download,
                           const FinishedCallback& callback)
    : callback_(callback),
      is_fallback_(false),
      pending_country_(country),
      pending_version_(version),
      local_path_(directory.empty()
                      ? base::FilePath()
                      : directory.AppendASCII(kPopularSitesLocalFilename)),
      prefs_(prefs),
      download_context_(download_context),
      runner_(
          BrowserThread::GetBlockingPool()->GetTaskRunnerWithShutdownBehavior(
              base::SequencedWorkerPool::CONTINUE_ON_SHUTDOWN)),
      weak_ptr_factory_(this) {
  DCHECK_CURRENTLY_ON(BrowserThread::UI);
  const base::Time last_download_time = base::Time::FromInternalValue(
      prefs_->GetInt64(kPopularSitesLastDownloadPref));
  const base::TimeDelta time_since_last_download =
      base::Time::Now() - last_download_time;
  const base::TimeDelta redownload_interval =
      base::TimeDelta::FromHours(kPopularSitesRedownloadIntervalHours);
  const bool download_time_is_future = base::Time::Now() < last_download_time;
  const bool country_changed = GetCountry() != pending_country_;
  const bool version_changed = GetVersion() != pending_version_;

  const GURL url =
      override_url.is_valid() ? override_url : GetPopularSitesURL();

  // No valid path to save to. Immediately post failure.
  if (local_path_.empty()) {
    BrowserThread::PostTask(BrowserThread::UI, FROM_HERE,
                            base::Bind(callback_, false));
    return;
  }

  // Download forced, or we need to download a new file.
  if (force_download || download_time_is_future ||
      (time_since_last_download > redownload_interval) || country_changed ||
      version_changed) {
    FetchPopularSites(url);
    return;
  }

  std::unique_ptr<std::string> file_data(new std::string);
  std::string* file_data_ptr = file_data.get();
  base::PostTaskAndReplyWithResult(
      runner_.get(), FROM_HERE,
      base::Bind(&base::ReadFileToString, local_path_, file_data_ptr),
      base::Bind(&PopularSites::OnReadFileDone, weak_ptr_factory_.GetWeakPtr(),
                 url, base::Passed(std::move(file_data))));
}

GURL PopularSites::GetPopularSitesURL() const {
  return GURL(base::StringPrintf(kPopularSitesURLFormat,
                                 pending_country_.c_str(),
                                 pending_version_.c_str()));
}

void PopularSites::OnReadFileDone(const GURL& url,
                                  std::unique_ptr<std::string> data,
                                  bool success) {
  if (success) {
    ParseSiteList(*data);
  } else {
    // File didn't exist, or couldn't be read for some other reason.
    FetchPopularSites(url);
  }
}

void PopularSites::FetchPopularSites(const GURL& url) {
  fetcher_ = URLFetcher::Create(url, URLFetcher::GET, this);
  fetcher_->SetRequestContext(download_context_);
  fetcher_->SetLoadFlags(net::LOAD_DO_NOT_SEND_COOKIES |
                         net::LOAD_DO_NOT_SAVE_COOKIES);
  fetcher_->SetAutomaticallyRetryOnNetworkChanges(1);
  fetcher_->Start();
}

void PopularSites::OnURLFetchComplete(const net::URLFetcher* source) {
  DCHECK_EQ(fetcher_.get(), source);
  std::unique_ptr<net::URLFetcher> free_fetcher = std::move(fetcher_);

  std::string sketchy_json;
  if (!(source->GetStatus().is_success() &&
        source->GetResponseCode() == net::HTTP_OK &&
        source->GetResponseAsString(&sketchy_json))) {
    OnDownloadFailed();
    return;
  }

  safe_json::JsonSanitizer::Sanitize(
      sketchy_json, base::Bind(&PopularSites::OnJsonSanitized,
                               weak_ptr_factory_.GetWeakPtr()),
      base::Bind(&PopularSites::OnJsonSanitizationFailed,
                 weak_ptr_factory_.GetWeakPtr()));
}

void PopularSites::OnJsonSanitized(const std::string& valid_minified_json) {
  base::PostTaskAndReplyWithResult(
      runner_.get(), FROM_HERE,
      base::Bind(&base::ImportantFileWriter::WriteFileAtomically, local_path_,
                 valid_minified_json),
      base::Bind(&PopularSites::OnFileWriteDone, weak_ptr_factory_.GetWeakPtr(),
                 valid_minified_json));
}

void PopularSites::OnJsonSanitizationFailed(const std::string& error_message) {
  DLOG(WARNING) << "JSON sanitization failed: " << error_message;
  OnDownloadFailed();
}

void PopularSites::OnFileWriteDone(const std::string& json, bool success) {
  if (success) {
    prefs_->SetInt64(kPopularSitesLastDownloadPref,
                     base::Time::Now().ToInternalValue());
    prefs_->SetString(kPopularSitesCountryPref, pending_country_);
    prefs_->SetString(kPopularSitesVersionPref, pending_version_);
    ParseSiteList(json);
  } else {
    DLOG(WARNING) << "Could not write file to "
                  << local_path_.LossyDisplayName();
    OnDownloadFailed();
  }
}

void PopularSites::ParseSiteList(const std::string& json) {
  base::PostTaskAndReplyWithResult(
      runner_.get(), FROM_HERE, base::Bind(&ParseJson, json),
      base::Bind(&PopularSites::OnJsonParsed, weak_ptr_factory_.GetWeakPtr()));
}

void PopularSites::OnJsonParsed(std::unique_ptr<std::vector<Site>> sites) {
  if (sites)
    sites_.swap(*sites);
  else
    sites_.clear();
  callback_.Run(!!sites);
}

void PopularSites::OnDownloadFailed() {
  if (!is_fallback_) {
    DLOG(WARNING) << "Download country site list failed";
    is_fallback_ = true;
    pending_country_ = kPopularSitesDefaultCountryCode;
    pending_version_ = kPopularSitesDefaultVersion;
    FetchPopularSites(GetPopularSitesURL());
  } else {
    DLOG(WARNING) << "Download fallback site list failed";
    callback_.Run(false);
  }
}


text:
Imports System.Collections.ObjectModel
Imports System.Collections.Generic
Imports System.Text.RegularExpressions
Imports System.ServiceModel
Imports log4net

''' <summary>
''' Class containing the processing commands.
''' </summary>
''' <remarks></remarks>
Module Process

    Private ReadOnly Log As ILog = LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod.DeclaringType)

    Private Const COMMAND_MONITOR_ALL As String = "all"
    Private Const COMMAND_MONITOR_STAR As String = "*"

    ''' <summary>
    ''' Runs a local or remote monitors process command by name.
    ''' </summary>
    ''' <param name="app">SiphonConsole. The main console instance.</param>
    ''' <param name="args">String. The arguments passed to the process command.</param>
    ''' <remarks></remarks>
    Public Sub Run(ByVal app As SiphonConsole, ByVal args() As String)
        If args.Count > 1 Then
            Dim endpoint As String = args(0).Trim
            Dim monitor As String = args(1).Trim

            If Regex.IsMatch(endpoint, "\A(http|\\\\)") Then
                Try
                    Using client As New SiphonServiceAdministration.SiphonServiceAdministrationClient
                        client.Endpoint.Address = New EndpointAddress(endpoint)
                        client.Process(monitor)
                    End Using
                Catch ex As Exception
                    Log.Error(ex.Message)
                    Log.Debug(ex.StackTrace)

                    Environment.ExitCode = 1
                End Try
            Else
                Log.InfoFormat("Running monitor {0} on endpoint {1}", monitor, endpoint)

                Try
                    Using client As New SiphonServiceAdministration.SiphonServiceAdministrationClient(endpoint)
                        client.Process(monitor)
                    End Using
                Catch ex As Exception
                    Log.Error(ex.Message)
                    Log.Debug(ex.StackTrace)

                    Environment.ExitCode = 1
                End Try
            End If
        ElseIf args.Count = 1 Then
            Dim name As String = args(0).Trim

            If name.ToLower = COMMAND_MONITOR_ALL Or name.ToLower = COMMAND_MONITOR_STAR Then
                If app.Monitors.Count > 0 Then
                    For Each monitor As IDataMonitor In app.Monitors
                        Log.InfoFormat("Running monitor {0}", monitor.Name)
                        monitor.Process()
                    Next
                Else
                    Log.Error("No monitors are configured")
                    Environment.ExitCode = 1
                End If
            Else
                If app.Monitors.Count > 0 Then
                    Dim query As IEnumerable(Of IDataMonitor) = From monitor In app.Monitors Where monitor.Name.Trim.ToLower = name.ToLower

                    If query.Count = 0 Then
                        Log.ErrorFormat("Could not find monitor {0}", name)
                        Environment.ExitCode = 1
                    Else
                        Log.InfoFormat("Running monitor {0}", query.First.Name)

                        query.First.Process()
                    End If
                Else
                    Log.Error("No monitors are configured")
                    Environment.ExitCode = 1
                End If
            End If
        Else
            Environment.ExitCode = 1
            Log.Error("No arguments were supplied")
        End If
    End Sub

End Module


text:
import unittest

from hecuba import config, StorageDict
from hecuba.IStorage import IStorage

class PersistentDict(StorageDict):
    '''
    @TypeSpec dict<<key:int>, value:double>
    '''

class IStorageTests(unittest.TestCase):
    @classmethod
    def setUpClass(cls):
        cls.old = config.execution_name
        config.NUM_TEST = 0 # HACK a new attribute to have a global counter
    @classmethod
    def tearDownClass(cls):
        config.execution_name = cls.old
        del config.NUM_TEST

    # Create a new keyspace per test
    def setUp(self):
        config.NUM_TEST = config.NUM_TEST + 1
        self.current_ksp = "IStorageTests{}".format(config.NUM_TEST).lower()
        config.execution_name = self.current_ksp

    def tearDown(self):
        #config.session.execute("DROP KEYSPACE IF EXISTS {}".format(self.current_ksp))
        pass

    def stop_persistent_method_test(self):
        key = 123
        value = 456
        name = 'istorage_pers'

        base_dict = PersistentDict()

        def check_stop_pers():
            assert (isinstance(base_dict, IStorage))
            base_dict.stop_persistent()

        self.assertRaises(RuntimeError, check_stop_pers)
        # PyCOMPSs requires uuid of type str

        base_dict.make_persistent(name)

        base_dict[key] = value

        base_dict.stop_persistent()

        self.assertIsNone(base_dict.storage_id)
        self.assertIsNone(base_dict.storage_id)

        self.assertRaises(RuntimeError, check_stop_pers)

        base_dict.make_persistent(name)

        self.assertEqual(base_dict[key], value)

        base_dict.stop_persistent()

        self.assertRaises(RuntimeError, check_stop_pers)

        external_dict = PersistentDict(name)
        self.assertEqual(external_dict[key], value)

    def delete_persistent_method_test(self):
        key = 123
        value = 456
        name = 'istorage_pers'

        base_dict = PersistentDict()

        def check_stop_pers():
            assert (isinstance(base_dict, IStorage))
            base_dict.stop_persistent()

        def check_del_pers():
            assert (isinstance(base_dict, IStorage))
            base_dict.delete_persistent()

        self.assertRaises(RuntimeError, check_del_pers)
        # PyCOMPSs requires uuid of type str

        base_dict.make_persistent(name)

        base_dict[key] = value

        base_dict.delete_persistent()

        self.assertIsNone(base_dict.storage_id)
        self.assertIsNone(base_dict.storage_id)

        self.assertRaises(RuntimeError, check_del_pers)
        self.assertRaises(RuntimeError, check_stop_pers)

        base_dict.make_persistent(name)

        def get_key():
            res = base_dict[key]

        self.assertRaises(KeyError, get_key)

        base_dict.delete_persistent()

        self.assertRaises(RuntimeError, check_del_pers)
        self.assertRaises(RuntimeError, check_stop_pers)

        external_dict = PersistentDict(name)

        def get_key_ext():
            res = external_dict[key]

        self.assertRaises(KeyError, get_key_ext)

if __name__ == '__main__':
    unittest.main()


text:
layout: page
title: Page Not Found
permalink: /404.html
nocomments: true
public: false
---

Page not found :(


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace _7.Cake_Ingredients
{
    class Program
    {
        static void Main(string[] args)
        {
            string input = "";
            int counter = 0;
            while (true)
            {
                input = Console.ReadLine();
                if (input == "Bake!")
                {
                    Console.WriteLine($"Preparing cake with {counter} ingredients.");
                    break;
                }
                Console.WriteLine($"Adding ingredient {input}.");
                counter++;
            }

        }
    }
}


text:
require 'open-uri'
require 'nokogiri'
require 'time'
require_relative 'nyc_today/version'
require_relative 'nyc_today/cli'
require_relative 'nyc_today/event'
require_relative 'nyc_today/scraper'

module NycToday
end


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Data.Entity.Core;
using System.ComponentModel.DataAnnotations;

namespace Timeclock.Models
{
    public class Shift
    {
        [Key]
        public int Id { get; set; }
        public DateTimeOffset ClockIn { get; set; }
        public DateTimeOffset ClockOut { get; set; }
        public double HoursWorked { get; set; }
        public string Notes { get; set; }
        public double OvertimeHours1 { get; set; }
        public double OvertimeHours2 { get; set; }
        public double HolidayHours { get; set; }
        public double PTOHours { get; set; }
        public double VacationHours { get; set; }
        public string Log { get; set; }
    }
}


text:
/***************************************************************************
File: mvLesion.hh
Abstract:  Lesion groups in Computer Assisted Polyp Detection (CAPD)
Created: 03/2002

(C) 2002 by Wake Forest University School of Medicine

Last Revision ($Revision: 1.4 $)
by $Author: hongli $ on $Date: 2003/10/02 19:44:22 $
***************************************************************************/

#ifndef _mvLesion_hh_
#define _mvLesion_hh_
#include <fstream>
#include <cstdio>

#include <stdio.h>
#include <stdlib.h>
#include <sys/types.h>
#include <constant.h>
#include "Vertex_with_Features.hh"
class mvLesion;
#include "Colon.hh"
#include "nrjacobi.hh"

/**
* a class for lesion
*/
class mvLesion {
  public:
	/// the colon where the lesion comes from
    Colon * colon;
    ///lesion id
    int16_t id;
    ///lesion rank
    int16_t rank;
    /// a list of vertices that represent the lesion on the surface
    std::slist<Vertex_with_Features *> vertexList;
    /// filtering flag
    int filtered;
//    mvVertex center;
//    mvIndex centerIndex;
//    mvVertex centroid;
//    mvNormal normal;

	///normal direction of the lesion
    mvVec3f normal;
    mvVec3f center;

    /// center vertex of the lesion
    Vertex_with_Features * vCenter;

    float rating;
    float ratio;
    float maxRadius;
    float minRadius;
    float height;
    float convexity;
    float curvature;
    float area;
    float blength; //boundary length
    float thickness;
    float max_thickness;
    float volumeSize;
    float isoplanicity;

    ///criteria
    float min_area;
    float max_radius;
    float size_ratio;
    float min_radius;
    float max_ratio;
    float min_elongation;

/// fitting surface and Geomatric Transformation Matrix
    double a,b,c;
    double Ay, Az;
    double TranX[16]; /* 4 by 4*/
  public:

  /// a constructor
    mvLesion(void) {
      colon=NULL;
      id = -1;
      rank = -1;
      filtered = 0;
 //     centerIndex = -1;
      rating = 0.0f;
      height = 0.0f;
      convexity = 0.0f;
      curvature = 0.0f;
      area = 0.0f;
      blength = 0.0f;
      volumeSize = 0.0f;
      isoplanicity = 0.0f;
      ratio = 0;

      //initialize the criteria
     min_area = MIN_AREA;
     size_ratio = SIZE_RATIO;
     max_radius = MAX_RADIUS;
     min_radius = MIN_RADIUS;
     max_ratio = MAX_RATIO;
     min_elongation = MIN_ELONGATION;

    }
	///a destructor
    ~mvLesion(void) {
      id = -1;
//      filtered = FILTER_NONE;
    }

    	///test the lesion is too small or not
    int undersize()
    	{
	if(area < min_area) return true;
	//if(area < 100) return area < 0.9 * Pi * maxRadius * minRadius;
	return 0;
	}

    	///test the lesion is too big wrt the radius or not
    int oversize()
    	{
	return area > Pi * maxRadius * minRadius * size_ratio;
	}

    	///test the lesion is a noise or not
    int spike()
    	{
	if(fabs(minRadius) < min_radius || fabs(maxRadius) < min_radius)
		return true;
	else
		return false;
	}

    	///test the lesion is on fold or not
    int onfold()
    	{
	if(fabs(minRadius)/fabs(maxRadius) > max_ratio || fabs(minRadius) > max_radius)
		return true;

	if(isoplanicity * area < 2.84) return true;

	return false;
	}
    	///test the lesion is elongated or not
    int elongation();

    	///output the lesion to oogl file
    void write_oogl(float r, float g, float b);
    	///Calculate the normal direction
    void setBLength();
    void setNormal();
    	///Calculate the center vertex
    void setCenter();
    	///Calculate the Volume size the lesion covers
    void setVolumeSize();
    	///Calculate the lesion radius
    void setRadius();
    	///Set up the detection criteria
    void setCriteria(float ma, float sizer, float maxr, float minr, float maxratio, float minelg)
    	{
    	if( ma != -1) min_area = ma;
    	if( sizer != -1) size_ratio = sizer;
    	if( maxr != -1) max_radius = maxr;
    	if( minr != -1) min_radius = minr;
    	if( maxratio != -1) max_ratio = maxratio;
    	if( minelg != -1) min_elongation = minelg;
	}

};

#endif


text:
package mariculture.core.util;

public interface IHasClickableButton {
    public void handleButtonClick(int id);
}


text:
import optparse
import logging
import pymongo
import time
import random

from ubernear.util import signal_handler
from ubernear import event_location
from ubernear.util.config import (
    collections,
    )
from ubernear.util import mongo

log = logging.getLogger(__name__)

@signal_handler
def main():
    parser = optparse.OptionParser(
        usage='%prog [OPTS]',
        )
    parser.add_option(
        '-v', '--verbose',
        help='Verbose mode [default %default]',
        action="store_true", dest="verbose"
        )
    parser.add_option(
        '--db-config',
        help=('Path to the file with information on how to '
              'retrieve and store data in the database'
              ),
        metavar='PATH',
        )
    parser.add_option(
        '-a', '--process-all',
        help=('Process all events that have not expired '
              'instead of just those that have not been '
              'processed [default %default]'
              ),
        action="store_true", dest="process_all"
        )
    parser.set_defaults(
        verbose=False,
        process_all=False,
        )

    options, args = parser.parse_args()
    if args:
        parser.error('Wrong number of arguments.')

    if options.db_config is None:
        parser.error('Missing option --db-config=.')

    logging.basicConfig(
        level=logging.DEBUG if options.verbose else logging.INFO,
        format='%(asctime)s.%(msecs)03d %(name)s: %(levelname)s: %(message)s',
        datefmt='%Y-%m-%dT%H:%M:%S',
        )

    coll = collections(options.db_config)
    events_coll = coll['events-collection']
    places_coll = coll['places-collection']
    database = coll['database']

    indices = [
        {'match.ubernear.location': pymongo.GEO2D},
        ]
    mongo.create_indices(
        collection=events_coll,
        indices=indices,
        )

    log.info('Start...')

    log.info('Setting events\' locations...')
    found_work = event_location.locate(
        events_coll=events_coll,
        places_coll=places_coll,
        database=database,
        process_all=options.process_all,
        )

    if not found_work:
        minutes = 15
        delay = random.randint(60*minutes-1, 60*minutes+1)
        log.info(
            'Did not find any work. '
            'Sleeping about {minutes} minutes...'.format(
                minutes=minutes,
                )
            )
        time.sleep(delay)

    log.info('End')


text:
namespace SoftUni.WebServer.Http.Requests
{
    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Net;
    using Cookies;
    using Enums;
    using Exceptions;
    using Headers;
    using Interfaces;
    using Session;
    using SoftUni.WebServer.Common;

    public class HttpRequest : IHttpRequest
    {
        private const int HttpRequestLinePartsLength = 3; // Method; URL; HTTP version
        private const string HttpVersion = "HTTP/1.1";
        private const string HeaderSeparator = ": ";
        private const string QueryStringSeparator = "?";
        private const string UrlParameterSeparator = "&";
        private const string UrlKeyValueSeparator = "=";

        private const string CookieSeparator = ";";
        private const string CookieKeyValueSeparator = "=";

        private string requestString;

        public HttpRequest(string requestString)
        {
            this.requestString = requestString;

            this.UrlParameters = new Dictionary<string, string>();
            this.QueryParameters = new Dictionary<string, string>();
            this.Headers = new HttpHeaderCollection();
            this.Cookies = new HttpCookieCollection();
            this.FormData = new Dictionary<string, string>();

            this.ParseRequest(requestString);
        }

        public HttpRequestMethod Method { get; private set; }

        public string Url { get; private set; }

        public string Path { get; private set; }

        public IDictionary<string, string> UrlParameters { get; private set; }

        public IDictionary<string, string> QueryParameters { get; private set; }

        public IHttpHeaderCollection Headers { get; private set; }

        public IHttpCookieCollection Cookies { get; private set; }

        public IHttpSession Session { get; set; }

        public IDictionary<string, string> FormData { get; private set; }

        public void AddUrlParameter(string key, string value)
        {
            Validation.EnsureNotNullOrEmptyString(key, nameof(key));
            Validation.EnsureNotNullOrEmptyString(value, nameof(value));

            this.UrlParameters.Add(key, value);
        }

        public override string ToString() => this.requestString;

        private void ParseRequest(string requestString)
        {
            string[] requestLines = requestString.Split(Environment.NewLine, StringSplitOptions.None);
            if (!requestLines.Any())
            {
                throw new BadRequestException();
            }

            string[] requestLineParts = requestLines[0]
                .Trim()
                .Split(" ", StringSplitOptions.RemoveEmptyEntries);

            if (requestLineParts.Length != HttpRequestLinePartsLength ||
                requestLineParts[HttpRequestLinePartsLength - 1].ToLower() != HttpVersion.ToLower())
            {
                throw new BadRequestException();
            }

            this.Method = this.ParseRequestMethod(requestLineParts[0]);
            this.Url = requestLineParts[1];
            this.Path = requestLineParts[1].Split(new[] { '?', '#' }, StringSplitOptions.RemoveEmptyEntries)[0];

            var headerLines = requestLines
                .Skip(1)
                .TakeWhile(line => !string.IsNullOrEmpty(line));
            this.ParseHeaders(headerLines);
            this.ParseCookies();
            this.ParseParameters(this.Url);

            if (this.Method == HttpRequestMethod.Post)
            {
                this.FormData = this.ParseFormData(requestLines[requestLines.Length - 1]);
            }

            this.InitializeSession();
        }

        private HttpRequestMethod ParseRequestMethod(string method)
        {
            HttpRequestMethod methodResult;
            bool parsingSuccess = Enum.TryParse<HttpRequestMethod>(method, true, out methodResult);
            if (!parsingSuccess)
            {
                throw new BadRequestException("The request method is invalid or not supported.");
            }

            return methodResult;
        }

        private void ParseHeaders(IEnumerable<string> headerLines)
        {
            foreach (string headerLine in headerLines)
            {
                string[] headerParts = headerLine.Split(HeaderSeparator);
                if (headerParts.Length != 2)
                {
                    throw new BadRequestException();
                }

                this.Headers.Add(new HttpHeader(headerParts[0], headerParts[1].Trim()));
            }

            if (!this.Headers.ContainsKey(HttpHeader.Host))
            {
                throw new BadRequestException("The headers must specify a host.");
            }
        }

        private void ParseCookies()
        {
            if (this.Headers.ContainsKey(HttpHeader.Cookie))
            {
                string allCookiesString = this.Headers.Get(HttpHeader.Cookie).Value;
                string[] cookies = allCookiesString.Split(CookieSeparator, StringSplitOptions.RemoveEmptyEntries);
                foreach (var cookie in cookies)
                {
                    string[] cookieParts = cookie.Split(CookieKeyValueSeparator, StringSplitOptions.RemoveEmptyEntries);
                    if (cookieParts.Length != 2)
                    {
                        throw new BadRequestException();
                    }

                    string key = cookieParts[0];
                    string value = cookieParts[1];
                    this.Cookies.Add(new HttpCookie(key, value, isNew: false));
                }
            }
        }

        private void ParseParameters(string url)
        {
            if (url.IndexOf(QueryStringSeparator) < 0)
            {
                return;
            }

            string query = url.Split(QueryStringSeparator, 2)[1];
            this.QueryParameters = this.ParseQuery(query);
        }

        private IDictionary<string, string> ParseQuery(string query)
        {
            var queryParameters = new Dictionary<string, string>();
            string[] keyValuePairs = query.Split(UrlParameterSeparator, StringSplitOptions.RemoveEmptyEntries);
            foreach (var keyValuePair in keyValuePairs)
            {
                string[] keyAndValue = keyValuePair.Split(UrlKeyValueSeparator, StringSplitOptions.RemoveEmptyEntries);
                if (keyAndValue.Length != 2)
                {
                    continue;
                }

                string key = WebUtility.UrlDecode(keyAndValue[0]);
                string value = WebUtility.UrlDecode(keyAndValue[1]);
                queryParameters[key] = value;
            }

            return queryParameters;
        }

        private IDictionary<string, string> ParseFormData(string query)
        {
            if (this.Method == HttpRequestMethod.Get)
            {
                return new Dictionary<string, string>();
            }

            return this.ParseQuery(query);
        }

        private void InitializeSession()
        {
            if (this.Cookies.ContainsKey(SessionStore.SessionCookieKey))
            {
                var cookie = this.Cookies.Get(SessionStore.SessionCookieKey);
                string sessionId = cookie.Value;
                this.Session = SessionStore.GetSession(sessionId);
            }
        }
    }
}


text:
package org.vasttrafik.wso2.carbon.apimgt.portal.api.annotations;

import javax.ws.rs.NameBinding;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;

/**
 * @author Daniel Oskarsson <daniel.oskarsson@gmail.com>
 */
@NameBinding
@Retention(RetentionPolicy.RUNTIME)
public @interface Status {
    int OK = 200;
    int CREATED = 201;
    int value();
}


text:
title: 'Combination Sum III - Medium - L'
date: 2021-03-25
permalink: /dsa/2019/03/blog-post-18/
tags:
  - Data Structures
  - Algorithms
  - Leetcode
  - C++
  - Medium
  - L
---

# Question
- https://leetcode.com/problems/combination-sum-iii/

Find all valid combinations of k numbers that sum up to n such that the following conditions are true:

    Only numbers 1 through 9 are used.
    Each number is used at most once.

Return a list of all possible valid combinations. The list must not contain the same combination twice, and the combinations may be returned in any order.

# Approach

- BackTracking

# Solution
```
class Solution {
public:
    vector<vector<int>>res;
    vector<int>temp;
    void find(int i,int k,int n)
    {
        if(k==0)
        {
            if(n==0)
            {
                res.push_back(temp);
            }
            return;
        }
        for(int j=i;j<=9;j++)
        {
            if(j<=n)
            {
                temp.push_back(j);
                find(j+1,k-1,n-j);
                temp.pop_back();
            }
        }
    }
    vector<vector<int>> combinationSum3(int k, int n)
    {
        find(1,k,n);
        return res;
    }
};
```


text:
using System.Collections.Generic;

namespace Zirpl.Spotify.MetadataApi
{
    public class TrackSearchResult
    {
        public TrackSearchResult()
        {
            Tracks = new List<Track>();
        }

        public SearchResultInfo Info { get; set; }
        public List<Track> Tracks { get; set; }
    }
}


text:
#include <string.h>

__BEGIN_C

/** @file
 * @brief KLIBC implementation of memcpy
 */

extern void c_panic(const char*, const char*) __attribute__((__noreturn__));

void* memcpy(void *dest, const void *src, size_t n) {
    c_panic("NOT_IMPLEMENTED", "Function not implemented");
    return (void*) 0x0;
}

__END_C


text:
namespace google {
namespace ddex {

    MessageParser::MessageParser() {};
    MessageParser::~MessageParser() {};

    void MessageParser::parse(std::istream& xml_istream, google::protobuf::Message* message) {
        pugi::xml_document doc;
        pugi::xml_parse_result result = doc.load(xml_istream);

        pugi::xml_node root = MessageParser::getRootNode(doc);
        MessageParser::mergeMessage(root, message);

        std::cout << "Result description : " << result.description() << std::endl;
        std::cout << "Final message: " << std::endl << message->DebugString() << std::endl;
    }

    pugi::xml_node MessageParser::getRootNode(pugi::xml_document& doc) {
        return doc.first_child();
    }

    void MessageParser::mergeMessage(pugi::xml_node& node, google::protobuf::Message* message) {
        const google::protobuf::Descriptor* desc = message->GetDescriptor();

        nestParserGeneratedXmlTags(node, desc);
        nestNodeAttributes(node);

        for (pugi::xml_node child : node.children()) {
            std::string name = camelToSnake(child.name());
            const google::protobuf::FieldDescriptor* fieldDescriptor = desc->FindFieldByName(name);
            if (fieldDescriptor != nullptr) {
                if (fieldDescriptor->is_repeated()) {
                    handleRepeated(child, message, fieldDescriptor);
                } else {
                    handleSingle(child, message, fieldDescriptor);
                }
            }
        }
    }

    void MessageParser::handleRepeated(
            pugi::xml_node& node,
            google::protobuf::Message* message,
            const google::protobuf::FieldDescriptor* fieldDescriptor) {
        pugi::xml_text node_value = node.text();

        const google::protobuf::Reflection* ref = message->GetReflection();
        google::protobuf::FieldDescriptor::CppType cpp_type = fieldDescriptor->cpp_type();
        if (cpp_type == google::protobuf::FieldDescriptor::CppType::CPPTYPE_INT32) {
            ref->AddInt32(message, fieldDescriptor, ((google::protobuf::int32)node_value.as_int()));
        }
        if (cpp_type == google::protobuf::FieldDescriptor::CppType::CPPTYPE_INT64) {
            ref->AddInt64(message, fieldDescriptor, ((google::protobuf::int64)node_value.as_llong()));
        }
        if (cpp_type == google::protobuf::FieldDescriptor::CppType::CPPTYPE_UINT32) {
            ref->AddUInt32(message, fieldDescriptor, ((google::protobuf::uint32)node_value.as_uint()));
        }
        if (cpp_type == google::protobuf::FieldDescriptor::CppType::CPPTYPE_UINT64) {
            ref->AddUInt64(message, fieldDescriptor, ((google::protobuf::uint64)node_value.as_ullong()));
        }
        if (cpp_type == google::protobuf::FieldDescriptor::CppType::CPPTYPE_DOUBLE) {
            ref->AddDouble(message, fieldDescriptor, node_value.as_double());
        }
        if (cpp_type == google::protobuf::FieldDescriptor::CppType::CPPTYPE_FLOAT) {
            ref->AddFloat(message, fieldDescriptor, node_value.as_float());
        }
        if (cpp_type == google::protobuf::FieldDescriptor::CppType::CPPTYPE_BOOL) {
            ref->AddBool(message, fieldDescriptor, node_value.as_bool());
        }
        if (cpp_type == google::protobuf::FieldDescriptor::CppType::CPPTYPE_STRING) {
            ref->AddString(message, fieldDescriptor, node_value.as_string());
        }
        if (cpp_type == google::protobuf::FieldDescriptor::CppType::CPPTYPE_MESSAGE) {
            MessageParser::mergeMessage(node, ref->AddMessage(message, fieldDescriptor));
        }
        if (cpp_type == google::protobuf::FieldDescriptor::CppType::CPPTYPE_ENUM) {
            // ERROR
        }
    }

    void MessageParser::handleSingle(
            pugi::xml_node& node,
            google::protobuf::Message* message,
            const google::protobuf::FieldDescriptor* fieldDescriptor)
    {
        pugi::xml_text node_value = node.text();
        const google::protobuf::Reflection* ref = message->GetReflection();
        google::protobuf::FieldDescriptor::CppType cpp_type = fieldDescriptor->cpp_type();

        if (cpp_type == google::protobuf::FieldDescriptor::CppType::CPPTYPE_INT32) {
            ref->SetInt32(message, fieldDescriptor, ((google::protobuf::int32)node_value.as_int()));
        }
        if (cpp_type == google::protobuf::FieldDescriptor::CppType::CPPTYPE_INT64) {
            ref->SetInt64(message, fieldDescriptor, ((google::protobuf::int64)node_value.as_llong()));
        }
        if (cpp_type == google::protobuf::FieldDescriptor::CppType::CPPTYPE_UINT32) {
            ref->SetUInt32(message, fieldDescriptor, ((google::protobuf::uint32)node_value.as_uint()));
        }
        if (cpp_type == google::protobuf::FieldDescriptor::CppType::CPPTYPE_UINT64) {
            ref->SetUInt64(message, fieldDescriptor, ((google::protobuf::uint64)node_value.as_ullong()));
        }
        if (cpp_type == google::protobuf::FieldDescriptor::CppType::CPPTYPE_DOUBLE) {
            ref->SetDouble(message, fieldDescriptor, node_value.as_double());
        }
        if (cpp_type == google::protobuf::FieldDescriptor::CppType::CPPTYPE_FLOAT) {
            ref->SetFloat(message, fieldDescriptor, node_value.as_float());
        }
        if (cpp_type == google::protobuf::FieldDescriptor::CppType::CPPTYPE_BOOL) {
            ref->SetBool(message, fieldDescriptor, node_value.as_bool());
        }
        if (cpp_type == google::protobuf::FieldDescriptor::CppType::CPPTYPE_STRING) {
            ref->SetString(message, fieldDescriptor, node_value.as_string());
        }
        if (cpp_type == google::protobuf::FieldDescriptor::CppType::CPPTYPE_MESSAGE) {
            MessageParser::mergeMessage(node, ref->MutableMessage(message, fieldDescriptor));
        }
        if (cpp_type == google::protobuf::FieldDescriptor::CppType::CPPTYPE_ENUM) {
            // ERROR
        }
    }

    void MessageParser::nestNodeAttributes(pugi::xml_node& node) {
        while (node.first_attribute() != NULL) {
            // MUST RENAME THE NODES TO BE IN GUAVA FORMAT CAMEL AND ALSO IGNORE CONTAINS ":"
            pugi::xml_attribute attr = node.first_attribute();
            std::string attribute_name(attr.name());

            if (attribute_name.find(":") == std::string::npos) {
                pugi::xml_node new_node = node.append_child(attr.name());
                new_node.text().set(attr.value());
            }
            node.remove_attribute(attr);
        }
    }

    void MessageParser::nestParserGeneratedXmlTags(pugi::xml_node& node, const google::protobuf::Descriptor* desc) {
        if (desc == NULL) {
            return;
        }

        std::string parserGeneratedTag = "";
        if (desc->FindFieldByName("ext_value") != NULL) {
            parserGeneratedTag = "ext_value";
        } else if (desc->FindFieldByName("enum_value") != NULL) {
            parserGeneratedTag = "enum_value";
        } else if (desc->FindFieldByName("auto_value") != NULL) {
            parserGeneratedTag = "auto_value";
        }

        if (parserGeneratedTag != "") {
            std::string curVal = node.text().as_string();
            node.set_value("");
            pugi::xml_node new_node = node.append_child(parserGeneratedTag.c_str());
            new_node.text().set(curVal.c_str());
        }
    }

    std::string MessageParser::camelToSnake(const std::string& in) {
        std::string snake_string = "";
        for (std::string::size_type i = 0; i < in.size(); i++) {
            char c = in[i];
            if (isupper(c)) {
                if (i != 0) snake_string += "_";
                snake_string += tolower(c);
            } else {
                snake_string += c;
            }
        }
        return snake_string;
}
}}


text:
package analyser

import "github.com/orktes/orlang/ast"

type Closure struct {
	FunctionDeclaration *ast.FunctionDeclaration
	Env                 []ScopeItem
}


text:
/******************************************************************************
  This source file is part of the Avogadro project.
  This source code is released under the 3-Clause BSD License, (see "LICENSE").
******************************************************************************/

#ifndef AVOGADRO_QTPLUGINS_MONGOCHEMWIDGET_H
#define AVOGADRO_QTPLUGINS_MONGOCHEMWIDGET_H

#include <QScopedPointer>
#include <QSharedPointer>
#include <QWidget>

namespace Ui {
class MongoChemWidget;
}

class QNetworkAccessManager;
class QNetworkReply;

namespace Avogadro {

namespace QtPlugins {

class ConfigDialog;
class ListMoleculesModel;
class MongoChem;
class SubmitCalculationDialog;

class MongoChemWidget : public QWidget
{
  Q_OBJECT

public:
  explicit MongoChemWidget(MongoChem* plugin, QWidget* parent = nullptr);
  ~MongoChemWidget() override;

private slots:
  void showConfig();
  void finishAuthentication(const QVariant& results);
  void search();
  void finishSearch(const QVariant& results);
  void downloadSelectedMolecule();
  void finishDownloadMolecule(const QVariant& results);
  void uploadMolecule();
  void finishUploadMolecule(const QVariant& results);
  void uploadGeometry(const QString& moleculeId);
  void finishUploadGeometry(const QVariant& results);
  void submitCalculation();
  void finishSubmitCalculation(const QVariantMap& results);
  void finishWatchCalculation(const QByteArray& cjson);
  void error(const QString& message, QNetworkReply* reply = nullptr);

  void readSettings();
  void writeSettings();

private:
  void setupConnections();
  void authenticate();
  int selectedRow();

  MongoChem* m_plugin;

  QString m_girderUrl = "http://localhost:8080/api/v1";
  QString m_apiKey;
  QString m_girderToken;

  QScopedPointer<Ui::MongoChemWidget> m_ui;
  QSharedPointer<QNetworkAccessManager> m_networkManager;
  QScopedPointer<ConfigDialog> m_configDialog;
  QScopedPointer<ListMoleculesModel> m_listMoleculesModel;
  QScopedPointer<SubmitCalculationDialog> m_submitCalculationDialog;
};

} // namespace QtPlugins
} // namespace Avogadro

#endif // AVOGADRO_QTPLUGINS_MONGOCHEMWIDGET_H