text:
title: Translate Hour of Code
nav: translate_nav
---

# Translating the Hour of Code
The majority of our translations are done through CrowdIn, a localization management platform. It is free to join and any volunteer can immediately contribute to the project by providing translations. There are currently three projects open for translations:

* [Code.org Project](https://crowdin.com/project/codeorg) - For the Code.org site and all Code Studio tutorials. Learn more [here](https://code.org/translate/tutorials).
* [Hour of Code Project](https://crowdin.com/project/hour-of-code) - For the HourofCode.com site. Learn more below.
* [Curriculum Project](https://crowdin.com/project/lesson-plans) - For teacher lesson plans that accompany our courses. Learn more [here](https://code.org/translate/curriculum).

Please complete translations for these projects in the above order of priority. If you have completed translations (at least 75% of the project is complete) and do not see your language in the drop down menu, please send a report to translations@code.org.

## What do I translate first?
1. Please translate our [Star Wars tutorial](/translate/starwars) and our [Minecraft tutorial](/translate/mc) first.
1. Then in the [Hour of Code Project](https://crowdin.com/project/hour-of-code), complete in the following order:
  * hourofcode.com homepage
  * thanks.md
  * everything in how-to folder
  * everything in prizes folder
  * everything in promote folder

## Where can I find context for translations?
All of the markdown files are the same as the URL path. For example, you can find the context for promote/index.md at [hourofcode.com/promote](https://hourofcode.com/promote). The country resources page will only be visible for all non-US sites, i.e. [hourofcode.com/uk/promote/country-resources](https://hourofcode.com/uk/promote/country-resources).

The files folder contains the text for handouts and posters. The pdfs are not automatically generated, we are only collecting translations and hope to convert into pdfs soon. If you can manually localize and create these resources, please email translations@code.org for the complete assets.

## How to Use CrowdIn

<embed src="/files/crowdin.swf" width=800 height=550 />

Watch the [demo video](/files/crowdin.swf) in full screen.

## Strings that may still change

As we prepare for the Hour of Code, we may change messaging every few weeks. For example, we will focus on gathering signups for the first few months, then during the Hour of Code direct people to the tutorials. Please complete the project and check in every week for small changes to strings that may need re-translating.

## How translations are selected

Members of the project are either a translator or proofreader. A translator can provide translations, while a proofreader can both provide translations as well as select the best translation to be used on the site.

The final translation that appears on our site is selected as follows:

1. A proofreader selects the best translation.
2. If there is no translation selected by a proofreader, translators vote on the best translation and the translation with the most votes is selected.
3. if votes are tied, the most recent translation will be selected.


text:
"""
defines all "built-in" classes that implement declarations compare
functionality according to some criteria
"""

import re
from . import class_declaration

class matcher_base_t(object):

    """matcher_base_t class defines interface for classes that will implement
       compare functionality according to some criteria.
    """

    def __init__(self):
        object.__init__(self)

    def __call__(self, decl):
        raise NotImplementedError(
            "matcher must always implement the __call__() method.")

    def __invert__(self):
        """not-operator (~)"""
        return not_matcher_t(self)

    def __and__(self, other):
        """and-operator (&)"""
        return and_matcher_t([self, other])

    def __or__(self, other):
        """or-operator (|)"""
        return or_matcher_t([self, other])

    def __str__(self):
        return "base class for all matchers"

class and_matcher_t(matcher_base_t):

    """
    Combine several other matchers with "&" (and) operator.

    For example: find all private functions with name XXX

    .. code-block:: python

       matcher = access_type_matcher_t( 'private' ) & \
           calldef_matcher_t( name='XXX' )
    """

    def __init__(self, matchers):
        matcher_base_t.__init__(self)
        self.matchers = matchers

    def __call__(self, decl):
        for matcher in self.matchers:
            if not matcher(decl):
                return False
        return True

    def __str__(self):
        return " & ".join(["(%s)" % str(x) for x in self.matchers])

class or_matcher_t(matcher_base_t):

    """Combine several other matchers with "|" (or) operator.

    For example: find all functions and variables with name 'XXX'

    .. code-block:: python

       matcher = variable_matcher_t( name='XXX' ) | \
           calldef_matcher_t( name='XXX' )

    """

    def __init__(self, matchers):
        matcher_base_t.__init__(self)
        self.matchers = matchers

    def __call__(self, decl):
        for matcher in self.matchers:
            if matcher(decl):
                return True
        return False

    def __str__(self):
        return " | ".join(["(%s)" % str(x) for x in self.matchers])

class not_matcher_t(matcher_base_t):

    """
    return the inverse result of a matcher

    For example: find all public and protected declarations

    .. code-block:: python

       matcher = ~access_type_matcher_t( 'private' )
    """

    def __init__(self, matcher):
        matcher_base_t.__init__(self)
        self.matcher = matcher

    def __call__(self, decl):
        return not self.matcher(decl)

    def __str__(self):
        return "~(%s)" % str(self.matcher)

class regex_matcher_t(matcher_base_t):

    """
    Instance of this class will match declaration using regular expression.
    User should supply a function that will extract from declaration desired
    information as string. Later, this matcher will match that string using
    user regular expression.
    """

    def __init__(self, regex, function=None):
        """
        :param regex: regular expression
        :type regex: string, an instance of this class will compile it for you

        :param function: function that will be called to get an information
                         from declaration as string. As input this function
                         takes single argument - reference to a declaration.
                         Return value should be string. If function is None,
                         then the matcher will use declaration name.

        """
        matcher_base_t.__init__(self)
        self.regex = re.compile(regex)
        self.function = function
        if self.function is None:
            self.function = lambda decl: decl.name

    def __call__(self, decl):
        text = self.function(decl)
        return bool(self.regex.match(text))

    def __str__(self):
        return '(regex=%s)' % self.regex

class custom_matcher_t(matcher_base_t):

    """
    Instance of this class will match declaration by user custom criteria.
    """

    def __init__(self, function):
        """
        :param function: callable, that takes single argument -
                         declaration instance should return True or False
        """
        matcher_base_t.__init__(self)
        self.function = function

    def __call__(self, decl):
        return bool(self.function(decl))

    def __str__(self):
        return '(user criteria)'

class access_type_matcher_t(matcher_base_t):

    """
    Instance of this class will match declaration by its access type: public,
    private or protected. If declarations does not have access type, for
    example free function, then `False` will be returned.
    """

    def __init__(self, access_type):
        """
        :param access_type: declaration access type, could be "public",
        "private", "protected"
        :type access_type: :class: `str`
        """
        matcher_base_t.__init__(self)
        self.access_type = access_type

    def __call__(self, decl):
        if not isinstance(decl.parent, class_declaration.class_t):
            return False
        return (
            self.access_type == decl.parent.find_out_member_access_type(decl)
        )

    def __str__(self):
        return '(access type=%s)' % self.access_type

class virtuality_type_matcher_t(matcher_base_t):

    """
    Instance of this class will match declaration by its virtual type: not
    virtual, virtual or pure virtual. If declarations does not have "virtual"
    property, for example free function, then `False` will be returned.
    """

    def __init__(self, virtuality_type):
        """
        :param access_type: declaration access type
        :type access_type: :class:VIRTUALITY_TYPES defines few constants for
        your convenience.
        """
        matcher_base_t.__init__(self)
        self.virtuality_type = virtuality_type

    def __call__(self, decl):
        if not isinstance(decl.parent, class_declaration.class_t):
            return False
        return self.virtuality_type == decl.virtuality

    def __str__(self):
        return '(virtuality type=%s)' % self.virtuality_type

redpajama_set_name: RedPajamaGithub


text:
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
  <component name="ArtifactsWorkspaceSettings">
    <artifacts-to-build>
      <artifact name="GeigerCounter:jar" />
    </artifacts-to-build>
  </component>
  <component name="ChangeListManager">
    <list default="true" id="fc47e3c0-a8ae-4fcb-b006-1899155244bc" name="Default" comment="">
      <change type="MODIFICATION" beforePath="$PROJECT_DIR$/.idea/workspace.xml" afterPath="$PROJECT_DIR$/.idea/workspace.xml" />
    </list>
    <ignored path="GeigerCounter.iws" />
    <ignored path=".idea/workspace.xml" />
    <file path="/Dummy.txt" changelist="fc47e3c0-a8ae-4fcb-b006-1899155244bc" time="1390792290994" ignored="false" />
    <file path="/GeigerCounter.java" changelist="fc47e3c0-a8ae-4fcb-b006-1899155244bc" time="1390536284305" ignored="false" />
    <file path="/BackendHandler.java" changelist="fc47e3c0-a8ae-4fcb-b006-1899155244bc" time="1389116927897" ignored="false" />
    <file path="/ZapListener.java" changelist="fc47e3c0-a8ae-4fcb-b006-1899155244bc" time="1389117146111" ignored="false" />
    <file path="/ZapReader.java" changelist="fc47e3c0-a8ae-4fcb-b006-1899155244bc" time="1390536129079" ignored="false" />
    <file path="/ZapRecorder.java" changelist="fc47e3c0-a8ae-4fcb-b006-1899155244bc" time="1390794842602" ignored="false" />
    <file path="/fragment.java" changelist="fc47e3c0-a8ae-4fcb-b006-1899155244bc" time="1389921928295" ignored="false" />
    <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="DebuggerManager">
    <ui_properties default_suspend_policy="SuspendAll" default_condition_enabled="true" />
    <breakpoint_any default_suspend_policy="SuspendAll" default_condition_enabled="true">
      <breakpoint>
        <option name="NOTIFY_CAUGHT" value="true" />
        <option name="NOTIFY_UNCAUGHT" value="true" />
        <option name="ENABLED" value="false" />
        <option name="LOG_ENABLED" value="false" />
        <option name="LOG_EXPRESSION_ENABLED" value="false" />
        <option name="REMOVE_AFTER_HIT" value="false" />
        <option name="SUSPEND_POLICY" value="SuspendAll" />
        <option name="SUSPEND" value="true" />
        <option name="COUNT_FILTER_ENABLED" value="false" />
        <option name="COUNT_FILTER" value="0" />
        <option name="CONDITION_ENABLED" value="true" />
        <option name="CLASS_FILTERS_ENABLED" value="false" />
        <option name="INSTANCE_FILTERS_ENABLED" value="false" />
        <option name="CONDITION" value="" />
        <option name="LOG_MESSAGE" value="" />
      </breakpoint>
      <breakpoint>
        <option name="NOTIFY_CAUGHT" value="true" />
        <option name="NOTIFY_UNCAUGHT" value="true" />
        <option name="ENABLED" value="false" />
        <option name="LOG_ENABLED" value="false" />
        <option name="LOG_EXPRESSION_ENABLED" value="false" />
        <option name="REMOVE_AFTER_HIT" value="false" />
        <option name="SUSPEND_POLICY" value="SuspendAll" />
        <option name="SUSPEND" value="true" />
        <option name="COUNT_FILTER_ENABLED" value="false" />
        <option name="COUNT_FILTER" value="0" />
        <option name="CONDITION_ENABLED" value="true" />
        <option name="CLASS_FILTERS_ENABLED" value="false" />
        <option name="INSTANCE_FILTERS_ENABLED" value="false" />
        <option name="CONDITION" value="" />
        <option name="LOG_MESSAGE" value="" />
      </breakpoint>
    </breakpoint_any>
    <breakpoint_rules />
    <ui_properties />
  </component>
  <component name="ExecutionTargetManager" SELECTED_TARGET="default_target" />
  <component name="FavoritesManager">
    <favorites_list name="GeigerCounter" />
  </component>
  <component name="FileEditorManager">
    <leaf>
      <file leaf-file-name="GeigerCounter.java" pinned="false" current="false" current-in-tab="false">
        <entry file="file://$PROJECT_DIR$/src/com/boztalay/geigercounter/GeigerCounter.java">
          <provider selected="true" editor-type-id="text-editor">
            <state line="13" column="30" selection-start="392" selection-end="392" vertical-scroll-proportion="0.0">
              <folding />
            </state>
          </provider>
        </entry>
      </file>
      <file leaf-file-name="ZapReader.java" pinned="false" current="false" current-in-tab="false">
        <entry file="file://$PROJECT_DIR$/src/com/boztalay/geigercounter/ZapReader.java">
          <provider selected="true" editor-type-id="text-editor">
            <state line="10" column="51" selection-start="340" selection-end="340" vertical-scroll-proportion="0.0">
              <folding />
            </state>
          </provider>
        </entry>
      </file>
      <file leaf-file-name="ZapRecorder.java" pinned="false" current="true" current-in-tab="true">
        <entry file="file://$PROJECT_DIR$/src/com/boztalay/geigercounter/ZapRecorder.java">
          <provider selected="true" editor-type-id="text-editor">
            <state line="49" column="62" selection-start="1896" selection-end="1896" vertical-scroll-proportion="0.44146687">
              <folding>
                <element signature="imports" expanded="true" />
                <element signature="e#758#885#0" expanded="true" />
                <element signature="e#874#875#0" expanded="true" />
              </folding>
            </state>
          </provider>
        </entry>
      </file>
    </leaf>
  </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$/src/com/boztalay/geigercounter/BackendHandler.java" />
        <option value="$PROJECT_DIR$/src/com/boztalay/geigercounter/ZapListener.java" />
        <option value="$PROJECT_DIR$/src/com/boztalay/geigercounter/GeigerCounter.java" />
        <option value="$PROJECT_DIR$/src/com/boztalay/geigercounter/ZapReader.java" />
        <option value="$PROJECT_DIR$/src/com/boztalay/geigercounter/ZapRecorder.java" />
      </list>
    </option>
  </component>
  <component name="ProjectFrameBounds">
    <option name="x" value="1744" />
    <option name="y" value="-4" />
    <option name="width" value="1857" />
    <option name="height" value="1085" />
  </component>
  <component name="ProjectInspectionProfilesVisibleTreeState">
    <entry key="Project Default">
      <profile-state>
        <expanded-state>
          <State>
            <id />
          </State>
          <State>
            <id>Abstraction issues</id>
          </State>
          <State>
            <id>Android Lint</id>
          </State>
          <State>
            <id>Assignment issues</id>
          </State>
          <State>
            <id>Class metrics</id>
          </State>
          <State>
            <id>Class structure</id>
          </State>
          <State>
            <id>Code maturity issues</id>
          </State>
          <State>
            <id>Code style issues</id>
          </State>
          <State>
            <id>Compiler issues</id>
          </State>
          <State>
            <id>Declaration redundancy</id>
          </State>
          <State>
            <id>Encapsulation issues</id>
          </State>
          <State>
            <id>Error handling</id>
          </State>
          <State>
            <id>Finalization issues</id>
          </State>
          <State>
            <id>GPath inspectionsGroovy</id>
          </State>
          <State>
            <id>Groovy</id>
          </State>
          <State>
            <id>Imports</id>
          </State>
          <State>
            <id>Inheritance issues</id>
          </State>
          <State>
            <id>Internationalization issues</id>
          </State>
          <State>
            <id>J2ME issues</id>
          </State>
          <State>
            <id>JUnit issues</id>
          </State>
          <State>
            <id>Java language level issues</id>
          </State>
          <State>
            <id>Java language level migration aids</id>
          </State>
          <State>
            <id>JavaBeans issues</id>
          </State>
          <State>
            <id>JavaFX</id>
          </State>
          <State>
            <id>Javadoc issues</id>
          </State>
          <State>
            <id>Language Injection</id>
          </State>
          <State>
            <id>Logging issues</id>
          </State>
          <State>
            <id>Memory issues</id>
          </State>
          <State>
            <id>Method metrics</id>
          </State>
          <State>
            <id>Naming ConventionsGroovy</id>
          </State>
          <State>
            <id>Naming conventions</id>
          </State>
          <State>
            <id>Numeric issues</id>
          </State>
          <State>
            <id>Performance issues</id>
          </State>
          <State>
            <id>Plugin DevKit</id>
          </State>
          <State>
            <id>Portability issues</id>
          </State>
          <State>
            <id>Probable bugs</id>
          </State>
          <State>
            <id>Probable bugsGroovy</id>
          </State>
          <State>
            <id>Properties Files</id>
          </State>
          <State>
            <id>Resource management issues</id>
          </State>
          <State>
            <id>Security issues</id>
          </State>
          <State>
            <id>Serialization issues</id>
          </State>
          <State>
            <id>StyleGroovy</id>
          </State>
          <State>
            <id>TestNG</id>
          </State>
          <State>
            <id>Threading issues</id>
          </State>
          <State>
            <id>Threading issuesGroovy</id>
          </State>
          <State>
            <id>Visibility issues</id>
          </State>
        </expanded-state>
      </profile-state>
    </entry>
  </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="2" 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="GeigerCounter" />
              <option name="myItemType" value="com.intellij.ide.projectView.impl.nodes.ProjectViewProjectNode" />
            </PATH_ELEMENT>
          </PATH>
          <PATH>
            <PATH_ELEMENT>
              <option name="myItemId" value="GeigerCounter" />
              <option name="myItemType" value="com.intellij.ide.projectView.impl.nodes.ProjectViewProjectNode" />
            </PATH_ELEMENT>
            <PATH_ELEMENT>
              <option name="myItemId" value="GeigerCounter" />
              <option name="myItemType" value="com.intellij.ide.projectView.impl.nodes.PsiDirectoryNode" />
            </PATH_ELEMENT>
          </PATH>
          <PATH>
            <PATH_ELEMENT>
              <option name="myItemId" value="GeigerCounter" />
              <option name="myItemType" value="com.intellij.ide.projectView.impl.nodes.ProjectViewProjectNode" />
            </PATH_ELEMENT>
            <PATH_ELEMENT>
              <option name="myItemId" value="GeigerCounter" />
              <option name="myItemType" value="com.intellij.ide.projectView.impl.nodes.PsiDirectoryNode" />
            </PATH_ELEMENT>
            <PATH_ELEMENT>
              <option name="myItemId" value="src" />
              <option name="myItemType" value="com.intellij.ide.projectView.impl.nodes.PsiDirectoryNode" />
            </PATH_ELEMENT>
          </PATH>
          <PATH>
            <PATH_ELEMENT>
              <option name="myItemId" value="GeigerCounter" />
              <option name="myItemType" value="com.intellij.ide.projectView.impl.nodes.ProjectViewProjectNode" />
            </PATH_ELEMENT>
            <PATH_ELEMENT>
              <option name="myItemId" value="GeigerCounter" />
              <option name="myItemType" value="com.intellij.ide.projectView.impl.nodes.PsiDirectoryNode" />
            </PATH_ELEMENT>
            <PATH_ELEMENT>
              <option name="myItemId" value="src" />
              <option name="myItemType" value="com.intellij.ide.projectView.impl.nodes.PsiDirectoryNode" />
            </PATH_ELEMENT>
            <PATH_ELEMENT>
              <option name="myItemId" value="geigercounter" />
              <option name="myItemType" value="com.intellij.ide.projectView.impl.nodes.PsiDirectoryNode" />
            </PATH_ELEMENT>
          </PATH>
        </subPane>
      </pane>
      <pane id="Scope" />
      <pane id="PackagesPane" />
    </panes>
  </component>
  <component name="PropertiesComponent">
    <property name="GoToFile.includeJavaFiles" value="false" />
    <property name="project.structure.last.edited" value="Artifacts" />
    <property name="project.structure.proportion" value="0.15" />
    <property name="options.splitter.main.proportions" value="0.3" />
    <property name="recentsLimit" value="5" />
    <property name="MemberChooser.sorted" value="false" />
    <property name="options.lastSelected" value="reference.projectsettings.compiler.javacompiler" />
    <property name="last_opened_file_path" value="$PROJECT_DIR$/libs/Parse-1.3.9-javadoc" />
    <property name="project.structure.side.proportion" value="0.2" />
    <property name="MemberChooser.copyJavadoc" value="false" />
    <property name="GoToClass.toSaveIncludeLibraries" value="false" />
    <property name="FullScreen" value="true" />
    <property name="MemberChooser.showClasses" value="true" />
    <property name="GoToClass.includeLibraries" value="false" />
    <property name="options.searchVisible" value="true" />
    <property name="options.splitter.details.proportions" value="0.2" />
    <property name="dynamic.classpath" value="false" />
  </component>
  <component name="RecentsManager">
    <key name="CopyFile.RECENT_KEYS">
      <recent name="$PROJECT_DIR$/libs" />
      <recent name="$PROJECT_DIR$/res" />
    </key>
    <key name="MoveFile.RECENT_KEYS">
      <recent name="$PROJECT_DIR$/libs" />
      <recent name="$PROJECT_DIR$" />
      <recent name="$PROJECT_DIR$/libdocs" />
    </key>
  </component>
  <component name="RunManager" selected="Application.GeigerCounter">
    <configuration default="false" name="GeigerCounter" type="Application" factoryName="Application" temporary="true">
      <option name="MAIN_CLASS_NAME" value="com.boztalay.geigercounter.GeigerCounter" />
      <option name="VM_PARAMETERS" />
      <option name="PROGRAM_PARAMETERS" />
      <option name="WORKING_DIRECTORY" value="$PROJECT_DIR$" />
      <option name="ALTERNATIVE_JRE_PATH_ENABLED" value="false" />
      <option name="ALTERNATIVE_JRE_PATH" />
      <option name="ENABLE_SWING_INSPECTOR" value="false" />
      <option name="ENV_VARIABLES" />
      <option name="PASS_PARENT_ENVS" value="true" />
      <module name="GeigerCounter" />
      <envs />
      <RunnerSettings RunnerId="Debug">
        <option name="DEBUG_PORT" value="" />
        <option name="TRANSPORT" value="0" />
        <option name="LOCAL" value="true" />
      </RunnerSettings>
      <RunnerSettings RunnerId="Run" />
      <ConfigurationWrapper RunnerId="Debug" />
      <ConfigurationWrapper RunnerId="Run" />
      <method />
    </configuration>
    <configuration default="true" type="#org.jetbrains.idea.devkit.run.PluginConfigurationType" factoryName="Plugin">
      <module name="" />
      <option name="VM_PARAMETERS" value="-Xmx512m -Xms256m -XX:MaxPermSize=250m" />
      <option name="PROGRAM_PARAMETERS" />
      <method />
    </configuration>
    <configuration default="true" type="Remote" factoryName="Remote">
      <option name="USE_SOCKET_TRANSPORT" value="true" />
      <option name="SERVER_MODE" value="false" />
      <option name="SHMEM_ADDRESS" value="javadebug" />
      <option name="HOST" value="localhost" />
      <option name="PORT" value="5005" />
      <method />
    </configuration>
    <configuration default="true" type="TestNG" factoryName="TestNG">
      <module name="" />
      <option name="ALTERNATIVE_JRE_PATH_ENABLED" value="false" />
      <option name="ALTERNATIVE_JRE_PATH" />
      <option name="SUITE_NAME" />
      <option name="PACKAGE_NAME" />
      <option name="MAIN_CLASS_NAME" />
      <option name="METHOD_NAME" />
      <option name="GROUP_NAME" />
      <option name="TEST_OBJECT" value="CLASS" />
      <option name="VM_PARAMETERS" value="-ea" />
      <option name="PARAMETERS" />
      <option name="WORKING_DIRECTORY" value="$PROJECT_DIR$" />
      <option name="OUTPUT_DIRECTORY" />
      <option name="ANNOTATION_TYPE" />
      <option name="ENV_VARIABLES" />
      <option name="PASS_PARENT_ENVS" value="true" />
      <option name="TEST_SEARCH_SCOPE">
        <value defaultName="moduleWithDependencies" />
      </option>
      <option name="USE_DEFAULT_REPORTERS" value="false" />
      <option name="PROPERTIES_FILE" />
      <envs />
      <properties />
      <listeners />
      <method />
    </configuration>
    <configuration default="true" type="Applet" factoryName="Applet">
      <module name="" />
      <option name="MAIN_CLASS_NAME" />
      <option name="HTML_FILE_NAME" />
      <option name="HTML_USED" value="false" />
      <option name="WIDTH" value="400" />
      <option name="HEIGHT" value="300" />
      <option name="POLICY_FILE" value="$APPLICATION_HOME_DIR$/bin/appletviewer.policy" />
      <option name="VM_PARAMETERS" />
      <option name="ALTERNATIVE_JRE_PATH_ENABLED" value="false" />
      <option name="ALTERNATIVE_JRE_PATH" />
      <method />
    </configuration>
    <configuration default="true" type="Application" factoryName="Application">
      <option name="MAIN_CLASS_NAME" />
      <option name="VM_PARAMETERS" />
      <option name="PROGRAM_PARAMETERS" />
      <option name="WORKING_DIRECTORY" value="$PROJECT_DIR$" />
      <option name="ALTERNATIVE_JRE_PATH_ENABLED" value="false" />
      <option name="ALTERNATIVE_JRE_PATH" />
      <option name="ENABLE_SWING_INSPECTOR" value="false" />
      <option name="ENV_VARIABLES" />
      <option name="PASS_PARENT_ENVS" value="true" />
      <module name="" />
      <envs />
      <method />
    </configuration>
    <configuration default="true" type="JUnit" factoryName="JUnit">
      <module name="" />
      <option name="ALTERNATIVE_JRE_PATH_ENABLED" value="false" />
      <option name="ALTERNATIVE_JRE_PATH" />
      <option name="PACKAGE_NAME" />
      <option name="MAIN_CLASS_NAME" />
      <option name="METHOD_NAME" />
      <option name="TEST_OBJECT" value="class" />
      <option name="VM_PARAMETERS" value="-ea" />
      <option name="PARAMETERS" />
      <option name="WORKING_DIRECTORY" value="$PROJECT_DIR$" />
      <option name="ENV_VARIABLES" />
      <option name="PASS_PARENT_ENVS" value="true" />
      <option name="TEST_SEARCH_SCOPE">
        <value defaultName="moduleWithDependencies" />
      </option>
      <envs />
      <patterns />
      <method />
    </configuration>
    <list size="1">
      <item index="0" class="java.lang.String" itemvalue="Application.GeigerCounter" />
    </list>
    <recent_temporary>
      <list size="1">
        <item index="0" class="java.lang.String" itemvalue="Application.GeigerCounter" />
      </list>
    </recent_temporary>
    <configuration name="<template>" type="WebApp" default="true" selected="false">
      <Host>localhost</Host>
      <Port>5050</Port>
    </configuration>
  </component>
  <component name="ShelveChangesManager" show_recycled="false" />
  <component name="SvnConfiguration" maxAnnotateRevisions="500" myUseAcceleration="nothing" myAutoUpdateAfterCommit="false" cleanupOnStartRun="false" SSL_PROTOCOLS="sslv3">
    <option name="USER" value="" />
    <option name="PASSWORD" value="" />
    <option name="mySSHConnectionTimeout" value="30000" />
    <option name="mySSHReadTimeout" value="30000" />
    <option name="LAST_MERGED_REVISION" />
    <option name="MERGE_DRY_RUN" value="false" />
    <option name="MERGE_DIFF_USE_ANCESTRY" value="true" />
    <option name="UPDATE_LOCK_ON_DEMAND" value="false" />
    <option name="IGNORE_SPACES_IN_MERGE" value="false" />
    <option name="CHECK_NESTED_FOR_QUICK_MERGE" value="false" />
    <option name="IGNORE_SPACES_IN_ANNOTATE" value="true" />
    <option name="SHOW_MERGE_SOURCES_IN_ANNOTATE" value="true" />
    <option name="FORCE_UPDATE" value="false" />
    <option name="IGNORE_EXTERNALS" value="false" />
    <myIsUseDefaultProxy>false</myIsUseDefaultProxy>
  </component>
  <component name="TaskManager">
    <task active="true" id="Default" summary="Default task">
      <changelist id="fc47e3c0-a8ae-4fcb-b006-1899155244bc" name="Default" comment="" />
      <created>1388883170063</created>
      <updated>1388883170063</updated>
    </task>
    <servers />
  </component>
  <component name="ToolWindowManager">
    <frame x="1744" y="-4" width="1857" height="1085" extended-state="6" />
    <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="JetGradle" active="false" anchor="right" auto_hide="false" internal_type="DOCKED" type="DOCKED" visible="false" weight="0.33" sideWeight="0.5" order="3" side_tool="false" content_ui="tabs" />
      <window_info id="Palette" active="false" anchor="right" auto_hide="false" internal_type="DOCKED" type="DOCKED" visible="false" weight="0.33" sideWeight="0.5" order="3" 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="Debug" active="false" anchor="bottom" auto_hide="false" internal_type="DOCKED" type="DOCKED" visible="false" weight="0.3182773" sideWeight="0.5" order="3" side_tool="false" 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="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="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="Messages" active="true" anchor="bottom" auto_hide="false" internal_type="DOCKED" type="DOCKED" visible="true" weight="0.21558164" 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="Maven Projects" active="false" anchor="right" auto_hide="false" internal_type="DOCKED" type="DOCKED" visible="false" weight="0.33" sideWeight="0.5" order="3" 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="Project" active="false" anchor="left" auto_hide="false" internal_type="DOCKED" type="DOCKED" visible="true" weight="0.2100608" sideWeight="0.78441834" order="0" side_tool="false" content_ui="combo" />
      <window_info id="Run" active="false" anchor="bottom" auto_hide="false" internal_type="DOCKED" type="DOCKED" visible="false" weight="0.22198506" sideWeight="0.5" order="2" 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="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="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="OFFER_MOVE_TO_ANOTHER_CHANGELIST_ON_PARTIAL_COMMIT" value="true" />
    <option name="CHECK_CODE_SMELLS_BEFORE_PROJECT_COMMIT" value="true" />
    <option name="CHECK_NEW_TODO" value="true" />
    <option name="myTodoPanelSettings">
      <value>
        <are-packages-shown value="false" />
        <are-modules-shown value="false" />
        <flatten-packages value="false" />
        <is-autoscroll-to-source value="false" />
      </value>
    </option>
    <option name="PERFORM_UPDATE_IN_BACKGROUND" value="true" />
    <option name="PERFORM_COMMIT_IN_BACKGROUND" value="true" />
    <option name="PERFORM_EDIT_IN_BACKGROUND" value="true" />
    <option name="PERFORM_CHECKOUT_IN_BACKGROUND" value="true" />
    <option name="PERFORM_ADD_REMOVE_IN_BACKGROUND" value="true" />
    <option name="PERFORM_ROLLBACK_IN_BACKGROUND" value="false" />
    <option name="CHECK_LOCALLY_CHANGED_CONFLICTS_IN_BACKGROUND" value="false" />
    <option name="CHANGED_ON_SERVER_INTERVAL" value="60" />
    <option name="SHOW_ONLY_CHANGED_IN_SELECTION_DIFF" value="true" />
    <option name="CHECK_COMMIT_MESSAGE_SPELLING" value="true" />
    <option name="DEFAULT_PATCH_EXTENSION" value="patch" />
    <option name="SHORT_DIFF_HORIZONTALLY" value="true" />
    <option name="SHORT_DIFF_EXTRA_LINES" value="2" />
    <option name="SOFT_WRAPS_IN_SHORT_DIFF" value="true" />
    <option name="INCLUDE_TEXT_INTO_PATCH" value="false" />
    <option name="INCLUDE_TEXT_INTO_SHELF" value="false" />
    <option name="SHOW_FILE_HISTORY_DETAILS" value="true" />
    <option name="SHOW_VCS_ERROR_NOTIFICATIONS" value="true" />
    <option name="SHOW_DIRTY_RECURSIVELY" value="false" />
    <option name="LIMIT_HISTORY" value="true" />
    <option name="MAXIMUM_HISTORY_ROWS" value="1000" />
    <option name="UPDATE_FILTER_SCOPE_NAME" />
    <option name="USE_COMMIT_MESSAGE_MARGIN" value="false" />
    <option name="COMMIT_MESSAGE_MARGIN_SIZE" value="72" />
    <option name="WRAP_WHEN_TYPING_REACHES_RIGHT_MARGIN" value="false" />
    <option name="FORCE_NON_EMPTY_COMMENT" value="false" />
    <option name="CLEAR_INITIAL_COMMIT_MESSAGE" value="false" />
    <option name="LAST_COMMIT_MESSAGE" />
    <option name="MAKE_NEW_CHANGELIST_ACTIVE" value="false" />
    <option name="OPTIMIZE_IMPORTS_BEFORE_PROJECT_COMMIT" value="false" />
    <option name="CHECK_FILES_UP_TO_DATE_BEFORE_COMMIT" value="false" />
    <option name="REFORMAT_BEFORE_PROJECT_COMMIT" value="false" />
    <option name="REFORMAT_BEFORE_FILE_COMMIT" value="false" />
    <option name="FILE_HISTORY_DIALOG_COMMENTS_SPLITTER_PROPORTION" value="0.8" />
    <option name="FILE_HISTORY_DIALOG_SPLITTER_PROPORTION" value="0.5" />
    <option name="ACTIVE_VCS_NAME" />
    <option name="UPDATE_GROUP_BY_PACKAGES" value="false" />
    <option name="UPDATE_GROUP_BY_CHANGELIST" value="false" />
    <option name="UPDATE_FILTER_BY_SCOPE" value="false" />
    <option name="SHOW_FILE_HISTORY_AS_TREE" value="false" />
    <option name="FILE_HISTORY_SPLITTER_PROPORTION" value="0.6" />
  </component>
  <component name="XDebuggerManager">
    <breakpoint-manager />
  </component>
  <component name="antWorkspaceConfiguration">
    <option name="IS_AUTOSCROLL_TO_SOURCE" value="false" />
    <option name="FILTER_TARGETS" value="false" />
  </component>
  <component name="editorHistoryManager">
    <entry file="file://$PROJECT_DIR$/src/com/boztalay/geigercounter/ZapRecorder.java">
      <provider selected="true" editor-type-id="text-editor">
        <state line="18" column="103" selection-start="568" selection-end="583" vertical-scroll-proportion="0.0">
          <folding>
            <element signature="imports" expanded="true" />
            <element signature="e#758#885#0" expanded="true" />
            <element signature="e#874#875#0" expanded="true" />
          </folding>
        </state>
      </provider>
    </entry>
    <entry file="file://$PROJECT_DIR$/src/com/boztalay/geigercounter/GeigerCounter.java">
      <provider selected="true" editor-type-id="text-editor">
        <state line="0" column="0" selection-start="0" selection-end="0" vertical-scroll-proportion="0.0">
          <folding />
        </state>
      </provider>
    </entry>
    <entry file="file://$PROJECT_DIR$/src/com/boztalay/geigercounter/ZapRecorder.java">
      <provider selected="true" editor-type-id="text-editor">
        <state line="29" column="77" selection-start="1027" selection-end="1027" vertical-scroll-proportion="0.0">
          <folding>
            <element signature="imports" expanded="true" />
            <element signature="e#758#885#0" expanded="true" />
            <element signature="e#874#875#0" expanded="true" />
          </folding>
        </state>
      </provider>
    </entry>
    <entry file="jar://$PROJECT_DIR$/libs/firebase-client-jvm-LATEST.jar!/com/firebase/client/utilities/DefaultRunLoop.class">
      <provider selected="true" editor-type-id="text-editor">
        <state line="0" column="0" selection-start="0" selection-end="0" vertical-scroll-proportion="0.0" />
      </provider>
    </entry>
    <entry file="jar://$PROJECT_DIR$/libs/firebase-client-jvm-LATEST.jar!/com/firebase/client/realtime/Connection.class">
      <provider selected="true" editor-type-id="text-editor">
        <state line="52" column="17" selection-start="2797" selection-end="2797" vertical-scroll-proportion="0.0" />
      </provider>
    </entry>
    <entry file="jar://$PROJECT_DIR$/libs/firebase-client-jvm-LATEST.jar!/com/firebase/client/realtime/WebsocketConnection.class">
      <provider selected="true" editor-type-id="text-editor">
        <state line="42" column="17" selection-start="2011" selection-end="2011" vertical-scroll-proportion="0.0" />
      </provider>
    </entry>
    <entry file="file://$PROJECT_DIR$/src/com/boztalay/geigercounter/GeigerCounter.java">
      <provider selected="true" editor-type-id="text-editor">
        <state line="0" column="0" selection-start="0" selection-end="0" vertical-scroll-proportion="0.0">
          <folding />
        </state>
      </provider>
    </entry>
    <entry file="file://$PROJECT_DIR$/src/com/boztalay/geigercounter/ZapRecorder.java">
      <provider selected="true" editor-type-id="text-editor">
        <state line="31" column="13" selection-start="657" selection-end="657" vertical-scroll-proportion="0.0">
          <folding>
            <element signature="imports" expanded="true" />
            <element signature="e#758#885#0" expanded="true" />
            <element signature="e#874#875#0" expanded="true" />
          </folding>
        </state>
      </provider>
    </entry>
    <entry file="file://$PROJECT_DIR$/src/com/boztalay/geigercounter/ZapReader.java">
      <provider selected="true" editor-type-id="text-editor">
        <state line="50" column="46" selection-start="1672" selection-end="1672" vertical-scroll-proportion="0.0">
          <folding />
        </state>
      </provider>
    </entry>
    <entry file="file://$PROJECT_DIR$/src/com/boztalay/geigercounter/GeigerCounter.java">
      <provider selected="true" editor-type-id="text-editor">
        <state line="0" column="0" selection-start="0" selection-end="0" vertical-scroll-proportion="0.0">
          <folding />
        </state>
      </provider>
    </entry>
    <entry file="jar://$PROJECT_DIR$/libs/firebase-client-jvm-LATEST.jar!/com/firebase/client/realtime/Connection.class">
      <provider selected="true" editor-type-id="text-editor">
        <state line="52" column="17" selection-start="2797" selection-end="2797" vertical-scroll-proportion="0.0" />
      </provider>
    </entry>
    <entry file="jar://$PROJECT_DIR$/libs/firebase-client-jvm-LATEST.jar!/com/firebase/client/realtime/WebsocketConnection.class">
      <provider selected="true" editor-type-id="text-editor">
        <state line="42" column="17" selection-start="2011" selection-end="2011" vertical-scroll-proportion="0.0" />
      </provider>
    </entry>
    <entry file="jar://$PROJECT_DIR$/libs/firebase-client-jvm-LATEST.jar!/com/firebase/client/utilities/DefaultRunLoop.class">
      <provider selected="true" editor-type-id="text-editor">
        <state line="0" column="0" selection-start="0" selection-end="0" vertical-scroll-proportion="0.0" />
      </provider>
    </entry>
    <entry file="file://$PROJECT_DIR$/src/com/boztalay/geigercounter/GeigerCounter.java">
      <provider selected="true" editor-type-id="text-editor">
        <state line="13" column="30" selection-start="392" selection-end="392" vertical-scroll-proportion="0.0">
          <folding />
        </state>
      </provider>
    </entry>
    <entry file="file://$PROJECT_DIR$/src/com/boztalay/geigercounter/ZapReader.java">
      <provider selected="true" editor-type-id="text-editor">
        <state line="10" column="51" selection-start="340" selection-end="340" vertical-scroll-proportion="0.0">
          <folding />
        </state>
      </provider>
    </entry>
    <entry file="file://$PROJECT_DIR$/src/com/boztalay/geigercounter/ZapRecorder.java">
      <provider selected="true" editor-type-id="text-editor">
        <state line="49" column="62" selection-start="1896" selection-end="1896" vertical-scroll-proportion="0.44146687">
          <folding>
            <element signature="imports" expanded="true" />
            <element signature="e#758#885#0" expanded="true" />
            <element signature="e#874#875#0" expanded="true" />
          </folding>
        </state>
      </provider>
    </entry>
  </component>
  <component name="masterDetails">
    <states>
      <state key="ArtifactsStructureConfigurable.UI">
        <settings>
          <artifact-editor />
          <last-edited>GeigerCounter:jar</last-edited>
          <splitter-proportions>
            <option name="proportions">
              <list>
                <option value="0.2" />
                <option value="0.5" />
              </list>
            </option>
          </splitter-proportions>
        </settings>
      </state>
      <state key="FacetStructureConfigurable.UI">
        <settings>
          <last-edited>No facets are configured</last-edited>
          <splitter-proportions>
            <option name="proportions">
              <list>
                <option value="0.2" />
              </list>
            </option>
          </splitter-proportions>
        </settings>
      </state>
      <state key="GlobalLibrariesConfigurable.UI">
        <settings>
          <splitter-proportions>
            <option name="proportions">
              <list>
                <option value="0.2" />
              </list>
            </option>
          </splitter-proportions>
        </settings>
      </state>
      <state key="JdkListConfigurable.UI">
        <settings>
          <last-edited>1.7</last-edited>
          <splitter-proportions>
            <option name="proportions">
              <list>
                <option value="0.2" />
              </list>
            </option>
          </splitter-proportions>
        </settings>
      </state>
      <state key="ModuleStructureConfigurable.UI">
        <settings>
          <last-edited>GeigerCounter</last-edited>
          <splitter-proportions>
            <option name="proportions">
              <list>
                <option value="0.2" />
              </list>
            </option>
          </splitter-proportions>
        </settings>
      </state>
      <state key="ProjectJDKs.UI">
        <settings>
          <last-edited>1.6</last-edited>
          <splitter-proportions>
            <option name="proportions">
              <list>
                <option value="0.2" />
              </list>
            </option>
          </splitter-proportions>
        </settings>
      </state>
      <state key="ProjectLibrariesConfigurable.UI">
        <settings>
          <last-edited>jssc</last-edited>
          <splitter-proportions>
            <option name="proportions">
              <list>
                <option value="0.2" />
              </list>
            </option>
          </splitter-proportions>
        </settings>
      </state>
    </states>
  </component>
</project>


text:
<?xml version="1.0"?>
<!DOCTYPE Configure PUBLIC "-//Jetty//Configure//EN" "http://www.eclipse.org/jetty/configure_9_3.dtd">

<!-- =============================================================== -->
<!-- Mixin the Weld / CDI classes to the class loader                -->
<!-- =============================================================== -->

<Configure id="Server" class="org.eclipse.jetty.server.Server">

  <New id="datasource" class="org.eclipse.jetty.plus.jndi.Resource">
    <Arg></Arg>  <!-- reference to Server instance -->
    <Arg>jdbc/ProcessEngine</Arg>
    <Arg>
      <New class="org.h2.jdbcx.JdbcDataSource">
        <Set name="URL">jdbc:h2:mem:process-engine;MVCC=TRUE;TRACE_LEVEL_FILE=0;DB_CLOSE_ON_EXIT=FALSE</Set>
        <Set name="User">sa</Set>
        <Set name="Password">sa</Set>
      </New>
    </Arg>
  </New>

  <Call name="addLifeCycleListener">
    <Arg>
      <New class="org.camunda.bpm.extension.jetty.impl.JettyBpmPlatformBootstrap"/>
    </Arg>
  </Call>

  <New id="processEngineService" class="org.eclipse.jetty.plus.jndi.Resource">
    <Arg></Arg>
    <Arg>global/camunda-bpm-platform/process-engine/ProcessEngineService</Arg>
    <Arg>
      <New class="javax.naming.Reference">
        <Arg>org.camunda.bpm.ProcessEngineService</Arg>
        <Arg>org.camunda.bpm.container.impl.jndi.ProcessEngineServiceObjectFactory</Arg>
        <Arg/>
      </New>
    </Arg>
  </New>

  <New id="processApplicationService" class="org.eclipse.jetty.plus.jndi.Resource">
    <Arg></Arg>
    <Arg>global/camunda-bpm-platform/process-engine/ProcessApplicationService</Arg>
    <Arg>
      <New class="javax.naming.Reference">
        <Arg>org.camunda.bpm.ProcessApplicationService</Arg>
        <Arg>org.camunda.bpm.container.impl.jndi.ProcessApplicationServiceObjectFactory</Arg>
        <Arg/>
      </New>
    </Arg>
  </New>

</Configure>


text:
from __future__ import unicode_literals

from django.db import migrations

def forwards_func(apps, schema_editor):
    Volume = apps.get_model('volumes', 'Volume')

    # Get the blueprint volume from the host def
    for volume in Volume.objects.all():
        for blueprint_volume in volume.host.blueprint_host_definition.volumes.all():
            if blueprint_volume.snapshot == volume.snapshot:
                volume.blueprint_volume = blueprint_volume
                volume.save()

def reverse_func(apps, schema_editor):
    Volume = apps.get_model('volumes', 'Volume')

    # Just put the snapshot back in place
    for volume in Volume.objects.all():
        snapshot = volume.blueprint_volume.snapshot

        if snapshot is None:
            # If the snapshot is null, just delete this volume... it's an invalid configuration
            # going backwards.
            volume.delete()
            continue

        volume.snapshot = snapshot
        volume.hostname = volume.host.hostname
        volume.device = volume.blueprint_volume.device
        volume.mount_point = volume.blueprint_volume.mount_point
        volume.save()

class Migration(migrations.Migration):

    dependencies = [
        ('volumes', '0002_0_8_0_migrations'),
    ]

    operations = [
        # Set the appropriate fields
        migrations.RunPython(forwards_func, reverse_func),
    ]


text:
package data

import (
	"fmt"
	"os"
	"path/filepath"
	"strings"
	"time"
)

// ProjectData is root object collects whole information about this project and
// used for TOC generation as well as HTML version build.
type ProjectData struct {
	Name              string // Project title
	Root              *Node  // Root fot parsed data
	ProjectRootFolder string // path to data folder
}

// FileInfo is a struct created from os.FileInfo interface for serialization.
type FileInfo struct {
	Name    string      `json:"name"`
	Size    int64       `json:"size"`
	Mode    os.FileMode `json:"mode"`
	ModTime time.Time   `json:"mod_time"`
	IsDir   bool        `json:"is_dir"`
}

// Node represents a node in a directory tree.
type Node struct {
	FullPath  string    `json:"path"`
	LocalPath string    `json:"local_path"`
	Info      *FileInfo `json:"info"`
	Children  []*Node   `json:"children"`
	IsDir     bool      `json:"is_dir"`
	Parent    *Node     `json:"-"`
}

// New is basic factory that build ProjectData object
func New() ProjectData {
	project := ProjectData{
		Name:              "Go4Rails",
		ProjectRootFolder: projectRrootDir(),
	}

	return project
}

func projectRrootDir() string {
	pwd, err := os.Getwd()
	if err != nil {
		fmt.Println(err)
		os.Exit(1)
	}
	return pwd
}

// Helper function to create a local FileInfo struct from os.FileInfo interface.
func fileInfoFromInterface(v os.FileInfo) *FileInfo {
	return &FileInfo{v.Name(), v.Size(), v.Mode(), v.ModTime(), v.IsDir()}
}

// NewTree Create directory hierarchy tree.
func newTree(root string) *Node {
	parents := make(map[string]*Node)

	// walker function
	walkFunc := func(path string, info os.FileInfo, err error) error {
		if err != nil {
			return err
		}

		parents[path] = &Node{
			FullPath:  path,
			LocalPath: strings.TrimLeft(path, root),
			Info:      fileInfoFromInterface(info),
			Children:  make([]*Node, 0),
			IsDir:     info.IsDir(),
		}

		return nil
	}

	filepath.Walk(root+"/data", walkFunc)

	var result *Node
	for path, node := range parents {

		parentPath := filepath.Dir(path)
		parent, exists := parents[parentPath]

		// If a parent does not exist, this is the root.
		if !exists {
			result = node
		} else {
			node.Parent = parent
			parent.Children = append(parent.Children, node)
		}

	}

	return result
}

// LoadData will go through data dir and load all examples, parse Ruby & Go files
// Add Sections and Articles into ProjectData object for future use.
func (p *ProjectData) LoadData() {
	p.Root = newTree(p.ProjectRootFolder)
}


text:
// ------------------------------------------------------------------------------
// <auto-generated>
//     This code was generated by a tool.
//
//     Changes to this file may cause incorrect behavior and will be lost if
//     the code is regenerated.
//
//	   Copyright (c) 2017 Citrix ShareFile. All rights reserved.
// </auto-generated>
// ------------------------------------------------------------------------------

package com.citrix.sharefile.api.entities;

import com.citrix.sharefile.api.*;
import com.citrix.sharefile.api.entities.*;
import com.citrix.sharefile.api.models.*;
import com.citrix.sharefile.api.SFApiQuery;
import com.citrix.sharefile.api.interfaces.ISFQuery;

import java.io.InputStream;
import java.util.ArrayList;
import java.net.URI;
import java.util.Date;

import com.google.gson.annotations.SerializedName;
import com.citrix.sharefile.api.enumerations.SFSafeEnum;
import com.citrix.sharefile.api.enumerations.SFSafeEnumFlags;
import com.citrix.sharefile.api.interfaces.ISFApiClient;
import com.citrix.sharefile.api.exceptions.InvalidOrMissingParameterException;

public class SFGroupsEntity extends SFEntitiesBase
{
	public SFGroupsEntity(ISFApiClient client) {
		super(client);
	}

	/**
	* Get Group List
	* Retrieves all Distribution Groups this user has permissions to View in this account
	* @return a list of Groups this user has access to
	*/
	public ISFQuery<SFODataFeed<SFGroup>> get()	{

		SFApiQuery<SFODataFeed<SFGroup>> sfApiQuery = new SFApiQuery<SFODataFeed<SFGroup>>(this.client);
		sfApiQuery.setFrom("Groups");
		sfApiQuery.setHttpMethod("GET");
		return sfApiQuery;
	}

	/**
	* Get Group By ID
	* Retrives a single Group by id
	* @param url
	* @return A single Group object
	*/
	public ISFQuery<SFGroup> get(URI url) throws InvalidOrMissingParameterException 	{
		if (url == null) {
			throw new InvalidOrMissingParameterException("url");
		}

		SFApiQuery<SFGroup> sfApiQuery = new SFApiQuery<SFGroup>(this.client);
		sfApiQuery.setFrom("Groups");
		sfApiQuery.addIds(url);
		sfApiQuery.setHttpMethod("GET");
		return sfApiQuery;
	}

	/**
	* Delete Group
	* Removes a single Group by id
	* @param url
	*/
	public ISFQuery delete(URI url) throws InvalidOrMissingParameterException 	{
		if (url == null) {
			throw new InvalidOrMissingParameterException("url");
		}

		SFApiQuery sfApiQuery = new SFApiQuery(this.client);
		sfApiQuery.setFrom("Groups");
		sfApiQuery.addIds(url);
		sfApiQuery.setHttpMethod("DELETE");
		return sfApiQuery;
	}

	/**
	* Create Group
    * {
    * "Name":"Name",
    * "IsShared":true,
    * "Contacts":[{"Email":"user.one@domain.com"},{"Email":"user.two@domain.com"}]
    * }
	* Creates a new group. The Post body must include the specification of the group.
	* @param group
	* @return the new group instance
	*/
	public ISFQuery<SFGroup> create(SFGroup group) throws InvalidOrMissingParameterException 	{
		if (group == null) {
			throw new InvalidOrMissingParameterException("group");
		}

		SFApiQuery<SFGroup> sfApiQuery = new SFApiQuery<SFGroup>(this.client);
		sfApiQuery.setFrom("Groups");
		sfApiQuery.setBody(group);
		sfApiQuery.setHttpMethod("POST");
		return sfApiQuery;
	}

	/**
	* Update Group
    * {
    * "Name":"Name",
    * "IsShared":true,
    * }
	* Updates an existing group.
	* This operation will ignore the provided clients list. Use the \Contacts navigation link to
	* add/remove elements from a group
	* @param url
	* @param group
	* @return the modified group object
	*/
	public ISFQuery<SFGroup> update(URI url, SFGroup group) throws InvalidOrMissingParameterException 	{
		if (url == null) {
			throw new InvalidOrMissingParameterException("url");
		}
		if (group == null) {
			throw new InvalidOrMissingParameterException("group");
		}

		SFApiQuery<SFGroup> sfApiQuery = new SFApiQuery<SFGroup>(this.client);
		sfApiQuery.setFrom("Groups");
		sfApiQuery.addIds(url);
		sfApiQuery.setBody(group);
		sfApiQuery.setHttpMethod("PATCH");
		return sfApiQuery;
	}

	/**
	* Get Group Contacts
	* Retrieves the Contacts navigation property of a Group
	* @param url
	* @return A feed of Contacts representing the members of the Group
	*/
	public ISFQuery<SFODataFeed<SFContact>> getContacts(URI url) throws InvalidOrMissingParameterException 	{
		if (url == null) {
			throw new InvalidOrMissingParameterException("url");
		}

		SFApiQuery<SFODataFeed<SFContact>> sfApiQuery = new SFApiQuery<SFODataFeed<SFContact>>(this.client);
		sfApiQuery.setFrom("Groups");
		sfApiQuery.setAction("Contacts");
		sfApiQuery.addIds(url);
		sfApiQuery.setHttpMethod("GET");
		return sfApiQuery;
	}

	/**
	* Add Contacts to Group
    * [{"Email":"user.one@domain.com"},{"Id":"abcd"}]
	* Adds a list of contacts to a group
	* The contact list may contain either contact ID (same as User ID) or Email.
	* @param url
	* @param contacts
	* @return The updated list of contacts for this group
	*/
	public ISFQuery<SFODataFeed<SFContact>> createContacts(URI url, ArrayList<SFContact> contacts) throws InvalidOrMissingParameterException 	{
		if (url == null) {
			throw new InvalidOrMissingParameterException("url");
		}
		if (contacts == null) {
			throw new InvalidOrMissingParameterException("contacts");
		}

		SFApiQuery<SFODataFeed<SFContact>> sfApiQuery = new SFApiQuery<SFODataFeed<SFContact>>(this.client);
		sfApiQuery.setFrom("Groups");
		sfApiQuery.setAction("Contacts");
		sfApiQuery.addIds(url);
		sfApiQuery.setBody(contacts);
		sfApiQuery.setHttpMethod("POST");
		return sfApiQuery;
	}

	/**
	* Remove Contacts from Group
    * [{"Email":"user.one@domain.com"},{"Id":"abcd"}]
	* Removes contacts from a group
	* The contact list may contain either contact ID (same as User ID) or Email.
	* This method will ignore missing references in the provided list - i.e., if an email in the contacts
	* list is not present in the group, it will be ignored.
	* The method will not enforce that ID and Email match inside a single Contact instance: Id will be
	* looked up first, then Email.
	* @param url
	* @param contacts
	* @return The updated list of contacts for this group
	*/
	public ISFQuery<SFODataFeed<SFContact>> deleteContacts(URI url, ArrayList<SFContact> contacts) throws InvalidOrMissingParameterException 	{
		if (url == null) {
			throw new InvalidOrMissingParameterException("url");
		}
		if (contacts == null) {
			throw new InvalidOrMissingParameterException("contacts");
		}

		SFApiQuery<SFODataFeed<SFContact>> sfApiQuery = new SFApiQuery<SFODataFeed<SFContact>>(this.client);
		sfApiQuery.setFrom("Groups");
		sfApiQuery.setAction("Contacts");
		sfApiQuery.addIds(url);
		sfApiQuery.setBody(contacts);
		sfApiQuery.setHttpMethod("DELETE");
		return sfApiQuery;
	}

	/**
	* Retrieve Groups associated with a User
	* Returns all groups the user is associated. This is currently limited to the authenticated user.
	* @param url
	* @return Feed of Groups
	*/
	public ISFQuery<SFODataFeed<SFGroup>> getByUser(URI url) throws InvalidOrMissingParameterException 	{
		if (url == null) {
			throw new InvalidOrMissingParameterException("url");
		}

		SFApiQuery<SFODataFeed<SFGroup>> sfApiQuery = new SFApiQuery<SFODataFeed<SFGroup>>(this.client);
		sfApiQuery.setFrom("Users");
		sfApiQuery.setAction("Groups");
		sfApiQuery.addIds(url);
		sfApiQuery.setHttpMethod("GET");
		return sfApiQuery;
	}

}


text:
package com.koch.ambeth.event;

import java.util.List;
import java.util.concurrent.atomic.AtomicBoolean;

import com.koch.ambeth.event.config.EventConfigurationConstants;
import com.koch.ambeth.event.events.EventSessionChanged;
import com.koch.ambeth.event.exceptions.EventPollException;
import com.koch.ambeth.event.model.IEventItem;
import com.koch.ambeth.event.service.IEventService;
import com.koch.ambeth.ioc.IDisposableBean;
import com.koch.ambeth.ioc.IStartingBean;
import com.koch.ambeth.ioc.annotation.Autowired;
import com.koch.ambeth.ioc.config.Property;
import com.koch.ambeth.log.ILogger;
import com.koch.ambeth.log.LogInstance;
import com.koch.ambeth.service.IOfflineListener;
import com.koch.ambeth.util.IClassLoaderProvider;
import com.koch.ambeth.util.collections.specialized.PropertyChangeSupport;

public class EventPoller extends PropertyChangeSupport
		implements IEventPoller, IOfflineListener, IStartingBean, IDisposableBean {
	@LogInstance
	private ILogger log;

	@Autowired
	protected IClassLoaderProvider classLoaderProvider;

	@Autowired
	protected IEventDispatcher eventDispatcher;

	@Autowired
	protected IEventService eventService;

	@Property(name = EventConfigurationConstants.PollingSleepInterval, defaultValue = "100")
	protected long pollSleepInterval;

	@Property(name = EventConfigurationConstants.MaxWaitInterval, defaultValue = "30000")
	protected long maxWaitInterval;

	@Property(name = EventConfigurationConstants.StartPausedActive, defaultValue = "false")
	protected boolean startPaused;

	protected Object writeLock = new Object();

	protected volatile boolean stopRequested = false;

	protected volatile boolean pauseRequested = false;

	protected volatile int iterationId = 1;

	private volatile Thread thread;

	private volatile boolean connected;

	@Override
	public void afterStarted() throws Throwable {
		if (startPaused) {
			pausePolling();
		}
		startPolling();
	}

	@Override
	public void destroy() throws Throwable {
		stopPolling();
	}

	public void stopPolling() {
		synchronized (writeLock) {
			stopRequested = true;
			pauseRequested = false;
			iterationId++;
			writeLock.notifyAll();
			Thread thread = this.thread;
			if (thread != null) {
				thread.interrupt();
			}
		}
	}

	public void startPolling() {
		final int stackIterationId = iterationId;
		thread = new Thread(new Runnable() {
			@Override
			public void run() {
				if (thread == Thread.currentThread()) {
					firePropertyChange(this, P_ACTIVE, false, true);
				}
				try {
					long currentServerSession = 0;
					long currentEventSequence = 0;

					AtomicBoolean errorOccured = new AtomicBoolean();
					loop: while (!stopRequested && stackIterationId == iterationId) {
						try {
							synchronized (writeLock) {
								while (pauseRequested) {
									if (stopRequested) {
										break loop;
									}
									writeLock.wait();
								}
							}
							if (currentServerSession == 0) {
								currentServerSession = eventService.getCurrentServerSession();
								if (thread == Thread.currentThread()) {
									setConnected(true);
								}
							}
							if (currentEventSequence == 0) {
								currentEventSequence = eventService.getCurrentEventSequence();
								setConnected(true);
							}
							currentEventSequence = tryPolling(currentServerSession, currentEventSequence,
									errorOccured);
							if (stopRequested) {
								break;
							}
							if (errorOccured.get()) {
								setConnected(false);
								long sleepTime = Math.max(5000, pollSleepInterval);
								if (log.isDebugEnabled()) {
									log.debug("Error occured. Sleeping for at least " + sleepTime + "ms");
								}
								Thread.sleep(Math.max(5000, pollSleepInterval));
							}
							else if (pollSleepInterval > 0) {
								if (log.isDebugEnabled()) {
									log.debug("Sleeping for at least " + pollSleepInterval + "ms");
								}
								Thread.sleep(pollSleepInterval);
							}
						}
						catch (InterruptedException ignored) {
							Thread.interrupted();
						}
					}
				}
				catch (Throwable e) {
					if (!stopRequested) {
						if (log.isErrorEnabled()) {
							log.error(e);
						}
					}
				}
				finally {
					if (thread == Thread.currentThread()) {
						setConnected(false);
						firePropertyChange(this, P_ACTIVE, true, false);
					}
				}
			}
		});
		thread.setContextClassLoader(classLoaderProvider.getClassLoader());
		thread.setName("Event Polling");
		thread.setDaemon(true);
		thread.start();
	}

	protected long tryPolling(long currentServerSession, long currentEventSequence,
			AtomicBoolean errorOccured) {
		errorOccured.set(true);
		List<IEventItem> events = null;
		try {
			events = eventService.pollEvents(currentServerSession, currentEventSequence, maxWaitInterval);
			errorOccured.set(false);
		}
		catch (Exception e) {
			if (pauseRequested || stopRequested) {
				return -1;
			}
			if (log.isErrorEnabled()) {
				log.error(e);
			}
			Throwable currEx = e;
			while (currEx != null) {
				if (currEx instanceof EventPollException) {
					long newServerSession = eventService.getCurrentServerSession();
					eventDispatcher.dispatchEvent(
							new EventSessionChanged(eventService, currentServerSession, newServerSession));
					break;
				}
				currEx = currEx.getCause();
			}
		}
		if (events == null || events.isEmpty()) {
			return currentEventSequence;
		}
		long timeBeforeDispatch = System.currentTimeMillis();
		eventDispatcher.enableEventQueue();
		try {
			for (int a = 0, size = events.size(); a < size; a++) {
				IEventItem eventObject = events.get(a);
				eventDispatcher.dispatchEvent(eventObject.getEventObject(), eventObject.getDispatchTime(),
						eventObject.getSequenceNumber());
				currentEventSequence = eventObject.getSequenceNumber();
			}
		}
		finally {
			eventDispatcher.flushEventQueue();
		}
		if (log.isInfoEnabled()) {
			long timeAfterDispatch = System.currentTimeMillis();
			log.info("Dispatching" + events.size() + "events took "
					+ (timeAfterDispatch - timeBeforeDispatch) + " ms.");
		}

		return currentEventSequence;
	}

	@Override
	public void pausePolling() {
		synchronized (writeLock) {
			if (pauseRequested) {
				return;
			}
			if (log.isInfoEnabled()) {
				log.info("Polling activated, but paused for concurrency reasons till "
						+ IEventPoller.class.getSimpleName() + ".resumePolling() is called");
			}
			pauseRequested = true;
		}
	}

	@Override
	public void resumePolling() {
		synchronized (writeLock) {
			if (!pauseRequested) {
				return;
			}
			if (log.isInfoEnabled()) {
				log.info("Polling resumed");
			}
			pauseRequested = false;
			writeLock.notifyAll();
		}
	}

	@Override
	public void beginOnline() {
		stopPolling();
	}

	@Override
	public void handleOnline() {
		// Intended blank
	}

	@Override
	public void endOnline() {
		startPolling();
	}

	@Override
	public void beginOffline() {
		stopPolling();
	}

	@Override
	public void handleOffline() {
		// Intended blank
	}

	@Override
	public void endOffline() {
		startPolling();
	}

	@Override
	public boolean isActive() {
		Thread thread = this.thread;
		return thread != null && thread.isAlive();
	}

	@Override
	public boolean isConnected() {
		return connected;
	}

	protected void setConnected(boolean connected) {
		boolean oldConnected = this.connected;
		if (oldConnected == connected) {
			return;
		}
		this.connected = connected;
		firePropertyChange(this, P_CONNECTED, oldConnected, connected);
	}
}


text:
using Arebis.Reflection;
using System;
using System.Collections;
using System.Collections.Generic;
using System.Data.Entity;
using System.Data.Entity.Core;
using System.Data.Entity.Core.Objects;
using System.Data.Entity.Core.Objects.DataClasses;
using System.IO;
using System.Linq;
using System.Linq.Expressions;
using System.Reflection;
using System.Runtime.Serialization.Formatters.Binary;
using System.Text;

namespace Arebis.Data.Entity
{
	/// <summary>
	/// Extension methods on ObjectContext.
	/// </summary>
	public static class ObjectContextExtension
	{
        public static string GetEntitySetNameOf<TEntity>(this ObjectContext context)
            where TEntity : class
        {
            return context.CreateObjectSet<TEntity>().EntitySet.Name;
        }

        public static string GetEntitySetNameOf(this ObjectContext context, object entity)
        {
            var objectStateEntry = context.ObjectStateManager.GetObjectStateEntry(entity);
            return objectStateEntry.EntitySet.Name;
        }

        /// <summary>
        /// Attaches an entire objectgraph to the context.
        /// </summary>
        [Obsolete("Consider using a more advanced mapping framework as http://max.codeplex.com.")]
        public static T AttachObjectGraph<T>(this ObjectContext context, T entity, params Expression<Func<T, object>>[] paths)
            where T : class
		{
			return AttachObjectGraphs(context, new T[] { entity }, paths)[0];
		}

        /// <summary>
        /// Attaches multiple entire objectgraphs to the context.
        /// </summary>
        [Obsolete("Consider using a more advanced mapping framework as http://max.codeplex.com.")]
        public static T[] AttachObjectGraphs<T>(this ObjectContext context, IEnumerable<T> entities, params Expression<Func<T, object>>[] paths)
            where T : class
		{
			T[] unattachedEntities = entities.ToArray();
			T[] attachedEntities = new T[unattachedEntities.Length];
			Type entityType = typeof(T);

			if (unattachedEntities.Length > 0)
			{
				// Workaround to ensure the assembly containing the entity type is loaded:
				// (see: https://forums.microsoft.com/MSDN/ShowPost.aspx?PostID=3405138&SiteID=1)
				try { context.MetadataWorkspace.LoadFromAssembly(entityType.Assembly); }
				catch { }

				#region Automatic preload root entities

				// Create a WHERE clause for preload the root entities:
				StringBuilder where = new StringBuilder("(1=0)");
				List<ObjectParameter> pars = new List<ObjectParameter>();
				int pid = 0;
				foreach (T entity in unattachedEntities)
				{
					// If the entity has an entitykey:
					EntityKey entityKey = ((IEntityWithKey)entity).EntityKey;
					if (entityKey != null)
					{
						where.Append(" OR ((1=1)");
						foreach (EntityKeyMember keymember in entityKey.EntityKeyValues)
						{
							string pname = String.Format("p{0}", pid++);
							where.Append(" AND (it.[");
							where.Append(keymember.Key);
							where.Append("] = @");
							where.Append(pname);
							where.Append(")");
							pars.Add(new ObjectParameter(pname, keymember.Value));
						}
						where.Append(")");
					}
				}

				// If WHERE clause not empty, construct and execute query:
				if (pars.Count > 0)
				{
					// Construct query:
					ObjectQuery<T> query = (ObjectQuery<T>)context.PublicGetProperty(context.GetEntitySetNameOf<T>());
					foreach (var path in paths)
                        query = (ObjectQuery<T>)query.Include(path);
					query = query.Where(where.ToString(), pars.ToArray());

					// Execute query and load entities:
					//Console.WriteLine(query.ToTraceString());
					query.Execute(MergeOption.AppendOnly).ToArray();
				}

				#endregion Automatic preload root entities

				// Attach the root entities:
				for (int i = 0; i < unattachedEntities.Length; i++)
					attachedEntities[i] = (T)context.AddOrAttachInstance(unattachedEntities[i], true);

				// Collect property paths into a tree:
				TreeNode<ExtendedPropertyInfo> root = new TreeNode<ExtendedPropertyInfo>(null);
				foreach (var path in paths)
				{
					List<ExtendedPropertyInfo> members = new List<ExtendedPropertyInfo>();
					EntityFrameworkHelper.CollectRelationalMembers(path, members);
					root.AddPath(members);
				}

				// Navigate over all properties:
				for (int i = 0; i < unattachedEntities.Length; i++)
					NavigatePropertySet(context, root, unattachedEntities[i], attachedEntities[i]);
			}

			// Return the attached root entities:
			return attachedEntities;
		}

        /// <summary>
        /// Adds or attaches the entity to the context. If the entity has an EntityKey,
        /// the entity is attached, otherwise a clone of it is added.
        /// </summary>
        /// <returns>The attached entity.</returns>
        [Obsolete("Consider using a more advanced mapping framework as http://max.codeplex.com.")]
        public static object AddOrAttachInstance(this ObjectContext context, object entity, bool applyPropertyChanges)
		{
			EntityKey entityKey = ((IEntityWithKey)entity).EntityKey;
			if (entityKey == null)
			{
				object attachedEntity = GetShallowEntityClone(entity);
				context.AddObject(context.GetEntitySetNameOf(entity), attachedEntity);
				((IEntityWithKey)entity).EntityKey = ((IEntityWithKey)attachedEntity).EntityKey;
				return attachedEntity;
			}
			else
			{
				object attachedEntity = context.GetObjectByKey(entityKey);
				if (applyPropertyChanges)
					context.ApplyCurrentValues(entityKey.EntitySetName, entity);
				return attachedEntity;
			}
		}

        /// <summary>
        /// Detaches an objectgraph given it's root object.
        /// </summary>
        /// <returns>The detached root object.</returns>
        public static T DetachObjectGraph<T>(this ObjectContext context, T entity)
		{
			using (MemoryStream stream = new MemoryStream())
			{
				//NetDataContractSerializer serializer = new NetDataContractSerializer();
				//serializer.Serialize(stream, entity);
				//stream.Position = 0;
				//return (T)serializer.Deserialize(stream);
				BinaryFormatter formatter = new BinaryFormatter();
				formatter.Serialize(stream, entity);
				stream.Position = 0;
				return (T)formatter.Deserialize(stream);
			}
		}

		#region Entity path marker methods

		/// <summary>
		/// Marker method to indicate this section of the path expression
		/// should not be loaded but only referenced.
		/// </summary>
		public static object ReferenceOnly(this IEntityWithKey entity)
		{
			throw new InvalidOperationException("The ReferenceOnly() method is a marker method in entity property paths and should not be effectively invoked.");
		}

		/// <summary>
		/// Marker method to indicate the instances the method is called on
		/// within path expressions should not be updated.
		/// </summary>
		public static object WithoutUpdate(this IEntityWithKey entity)
		{
			throw new InvalidOperationException("The WithoutUpdate() method is a marker method in entity property paths and should not be effectively invoked.");
		}

		#endregion

		#region Private implementation

		/// <summary>
		/// Navigates a property path on detached instance to translate into attached instance.
		/// </summary>
		private static void NavigatePropertySet(ObjectContext context, TreeNode<ExtendedPropertyInfo> propertynode, object owner, object attachedowner)
		{
			// Try to navigate each of the properties:
			foreach (TreeNode<ExtendedPropertyInfo> childnode in propertynode.Children)
			{
				ExtendedPropertyInfo property = childnode.Item;

				// Retrieve property value:
				object related = property.PropertyInfo.GetValue(owner, null);

				if ((property.ReferenceOnly) && (typeof(IEnumerable).IsAssignableFrom(property.PropertyInfo.PropertyType)))
				{
					// ReferenceOnly marker not valid on collections:
					throw new InvalidOperationException("The ReferenceOnly marker method is not supported on the many side of relations.");
				}
				else if (property.ReferenceOnly)
				{
					// Apply reference update on ReferenceOnly:
					EntityReference reference = (EntityReference)attachedowner.PublicGetProperty(property.PropertyInfo.Name + "Reference");
					reference.EntityKey = ((EntityReference)owner.PublicGetProperty(property.PropertyInfo.Name + "Reference")).EntityKey;
				}
				else if (related is IEnumerable)
				{
					// Load current list in context:
					object attachedlist = property.PropertyInfo.GetValue(attachedowner, null);
					RelatedEnd relatedEnd = (RelatedEnd)attachedlist;
					if (((EntityObject)attachedowner).EntityState != EntityState.Added && !relatedEnd.IsLoaded)
						relatedEnd.Load();

					// Recursively navigate through new members:
					List<object> newlist = new List<object>();
					foreach (var relatedinstance in (IEnumerable)related)
					{
						object attachedinstance = context.AddOrAttachInstance(relatedinstance, !property.NoUpdate);
						newlist.Add(attachedinstance);
						NavigatePropertySet(context, childnode, relatedinstance, attachedinstance);
					}

					// Synchronise lists:
					List<object> removedItems;
					SyncList(attachedlist, newlist, out removedItems);

					// Delete removed items if association is owned:
					if (AssociationEndBehaviorAttribute.GetAttribute(property.PropertyInfo).Owned)
					{
						foreach (var removedItem in removedItems)
							context.DeleteObject(removedItem);
					}

				}
				else if (!typeof(IEnumerable).IsAssignableFrom(property.PropertyInfo.PropertyType))
				{
					// Load reference of currently attached in context:
					RelatedEnd relatedEnd = (RelatedEnd)attachedowner.PublicGetProperty(property.PropertyInfo.Name + "Reference");
					if (((EntityObject)attachedowner).EntityState != EntityState.Added && !relatedEnd.IsLoaded)
						relatedEnd.Load();

					// Recursively navigate through new value (unless it's null):
					object attachedinstance;
					if (related == null)
						attachedinstance = null;
					else
					{
						attachedinstance = context.AddOrAttachInstance(related, !property.NoUpdate);
						NavigatePropertySet(context, childnode, related, attachedinstance);
					}

					// Synchronise value:
					property.PropertyInfo.SetValue(attachedowner, attachedinstance, null);
				}
			}
		}

		/// <summary>
		/// Returns a shallow clone of only the scalar properties.
		/// </summary>
		private static object GetShallowEntityClone(object entity)
		{
			object clone = Activator.CreateInstance(entity.GetType());
			foreach (PropertyInfo prop in entity.GetType().GetProperties())
			{
				if (typeof(RelatedEnd).IsAssignableFrom(prop.PropertyType)) continue;
				//if (typeof(EntityReference).IsAssignableFrom(prop.PropertyType)) continue;
				//if (typeof(IEnumerable).IsAssignableFrom(prop.PropertyType) && (!typeof(String).IsAssignableFrom(prop.PropertyType))) continue;
				if (typeof(IEntityWithKey).IsAssignableFrom(prop.PropertyType)) continue;
				try
				{
					prop.SetValue(clone, prop.GetValue(entity, null), null);
				}
				catch
				{
				}
			}
			return clone;
		}

		/// <summary>
		/// Synchronises a targetlist with a sourcelist by adding or removing items from the targetlist.
		/// The targetlist is untyped and controlled through reflection.
		/// </summary>
		private static void SyncList(object targetlist, List<object> sourcelist, out List<object> removedItems)
		{
			List<object> localsourcelist = new List<object>(sourcelist);
			List<object> toremove = new List<object>();

			// Compare both lists:
			foreach (object item in (IEnumerable)targetlist)
			{
				bool found = false;
				for (int i = 0; i < localsourcelist.Count; i++)
				{
					if (Object.ReferenceEquals(localsourcelist[i], item))
					{
						localsourcelist[i] = null;
						found = true;
					}
				}
				if (!found)
					toremove.Add(item);
			}

			// Add members not in targetlist:
			foreach (object item in localsourcelist)
			{
				if (Object.ReferenceEquals(item, null) == false)
					targetlist.PublicInvokeMethod("Add", item);
			}

			// Remove members not in sourcelist:
			foreach (object item in toremove)
				targetlist.PublicInvokeMethod("Remove", item);

			// Expose removed items:
			removedItems = toremove;
		}

		#endregion
	}
}


text:
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.

package com.microsoft.azure.storage.blob;

import com.microsoft.rest.v2.http.HttpPipeline;
import com.microsoft.rest.v2.http.HttpPipelineLogLevel;
import com.microsoft.rest.v2.http.HttpRequest;
import com.microsoft.rest.v2.http.HttpResponse;
import com.microsoft.rest.v2.policy.RequestPolicy;
import com.microsoft.rest.v2.policy.RequestPolicyFactory;
import com.microsoft.rest.v2.policy.RequestPolicyOptions;
import io.reactivex.Single;
import org.slf4j.LoggerFactory;

import java.io.File;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.UnknownHostException;
import java.util.HashMap;
import java.util.Locale;
import java.util.Map;
import java.util.logging.FileHandler;
import java.util.logging.Level;
import java.util.logging.Logger;

/**
 * This is a factory which creates policies in an {@link HttpPipeline} for logging requests and responses. In most
 * cases, it is sufficient to configure an object of the {@link LoggingOptions} type and set those as a field on a
 * {@link PipelineOptions} structure to configure a default pipeline. The factory and policy must only be used directly
 * when creating a custom pipeline.
 */
public final class LoggingFactory implements RequestPolicyFactory {

    private static final Logger FORCE_LOGGER = Logger.getLogger(LoggingFactory.class.getName());
    private static final org.slf4j.Logger SLF4J_LOGGER = LoggerFactory.getLogger(LoggingFactory.class.getName());
    private static final Map<HttpPipelineLogLevel, Level> JAVA_LOG_LEVEL_MAP = new HashMap<>();
    private static boolean defaultLoggerLoaded;

    static {
        try {
            FORCE_LOGGER.setLevel(Level.WARNING);

            // Create the logs directory if it doesn't exist.
            File logDir = new File(System.getProperty("java.io.tmpdir"), "AzureStorageJavaSDKLogs");
            if (!logDir.exists()) {
                if (!logDir.mkdir()) {
                    throw new Exception("Could not create logs directory");
                }
            }

            /*
            "/" the local pathname separator
            "%t" the system temporary directory
            "%h" the value of the "user.home" system property
            "%g" the generation number to distinguish rotated logs
            "%u" a unique number to resolve conflicts
            "%%" translates to a single percent sign "%"

            10MB files, 5 files

            true- append mode
             */
            FileHandler handler = new FileHandler("%t/AzureStorageJavaSDKLogs/%u%g", 10 * Constants.MB, 5, false);
            handler.setLevel(Level.WARNING);
            FORCE_LOGGER.addHandler(handler);

            JAVA_LOG_LEVEL_MAP.put(HttpPipelineLogLevel.ERROR, Level.SEVERE);
            JAVA_LOG_LEVEL_MAP.put(HttpPipelineLogLevel.WARNING, Level.WARNING);
            JAVA_LOG_LEVEL_MAP.put(HttpPipelineLogLevel.INFO, Level.INFO);
            defaultLoggerLoaded = true;

        /*
        If we can't setup default logging, there's nothing we can do. We shouldn't interfere with the rest of logging.
         */
        } catch (Exception e) {
            defaultLoggerLoaded = false;
            System.err.println("Azure Storage default logging could not be configured due to the following exception: "
                    + e);
        }
    }

    private final LoggingOptions loggingOptions;

    /**
     * Creates a factory which can create LoggingPolicy objects to insert in the pipeline. This will allow for logging
     * requests and responses.
     *
     * @param loggingOptions
     *         The configurations for this factory. Null will indicate use of the default options.
     */
    public LoggingFactory(LoggingOptions loggingOptions) {
        this.loggingOptions = loggingOptions == null ? new LoggingOptions() : loggingOptions;
    }

    @Override
    public RequestPolicy create(RequestPolicy next, RequestPolicyOptions options) {
        return new LoggingPolicy(this, next, options);
    }

    private static final class LoggingPolicy implements RequestPolicy {

        private final LoggingFactory factory;

        private final RequestPolicy nextPolicy;

        private final RequestPolicyOptions options;

        // The following fields are not final because they are updated by the policy.
        private int tryCount;

        private long operationStartTime;

        private long requestStartTime;

        /**
         * Creates a policy which configures the logging behavior within the
         * {@link com.microsoft.rest.v2.http.HttpPipeline}.
         *
         * @param nextPolicy
         *         {@link RequestPolicy}
         * @param options
         *         {@link RequestPolicyOptions}
         * @param factory
         *         {@link LoggingFactory}
         */
        private LoggingPolicy(LoggingFactory factory, RequestPolicy nextPolicy, RequestPolicyOptions options) {
            this.factory = factory;
            this.nextPolicy = nextPolicy;
            this.options = options;
        }

        /**
         * Logs as appropriate.
         *
         * @param request
         *         The request to log.
         *
         * @return A {@link Single} representing the {@link HttpResponse} that will arrive asynchronously.
         */
        @Override
        public Single<HttpResponse> sendAsync(final HttpRequest request) {
            this.tryCount++;
            this.requestStartTime = System.currentTimeMillis();
            if (this.tryCount == 1) {
                this.operationStartTime = requestStartTime;
            }

            if (this.shouldLog(HttpPipelineLogLevel.INFO)) {
                String logMessage = String.format("'%s'==> OUTGOING REQUEST (Try number='%d')%n",
                        sanitizeURL(request.url()), this.tryCount);
                this.log(HttpPipelineLogLevel.INFO, logMessage);
            }

            return nextPolicy.sendAsync(request)
                    .doOnError(throwable -> {
                        if (this.shouldLog(HttpPipelineLogLevel.ERROR)) {
                            String logMessage = String.format(
                                    "Unexpected failure attempting to make request.%nError message:'%s'%n",
                                    throwable.getMessage());
                            this.log(HttpPipelineLogLevel.ERROR, logMessage);
                        }
                    })
                    .doOnSuccess(response -> {
                        long requestEndTime = System.currentTimeMillis();
                        long requestCompletionTime = requestEndTime - requestStartTime;
                        long operationDuration = requestEndTime - operationStartTime;
                        HttpPipelineLogLevel currentLevel = HttpPipelineLogLevel.INFO;

                        String logMessage = Constants.EMPTY_STRING;
                        if (this.shouldLog(HttpPipelineLogLevel.INFO)) {
                            // Assume success and default to informational logging.
                            logMessage = "Successfully Received Response" + System.lineSeparator();
                        }

                        // If the response took too long, we'll upgrade to warning.
                        if (requestCompletionTime
                                >= factory.loggingOptions.minDurationToLogSlowRequestsInMs()) {
                            // Log a warning if the try duration exceeded the specified threshold.
                            if (this.shouldLog(HttpPipelineLogLevel.WARNING)) {
                                currentLevel = HttpPipelineLogLevel.WARNING;
                                logMessage = String.format(Locale.ROOT,
                                        "SLOW OPERATION. Duration > %d ms.%n",
                                        factory.loggingOptions.minDurationToLogSlowRequestsInMs());
                            }
                        }

                        if (((response.statusCode() >= 400 && response.statusCode() <= 499)
                                 && (response.statusCode() != HttpURLConnection.HTTP_NOT_FOUND
                                         && response.statusCode() != HttpURLConnection.HTTP_CONFLICT
                                         && response.statusCode() != HttpURLConnection.HTTP_PRECON_FAILED
                                         && response.statusCode() != 416))
                                        /* 416 is missing from the Enum but it is Range Not Satisfiable */
                                || (response.statusCode() >= 500 && response.statusCode() <= 509)) {
                            String errorString = String.format(Locale.ROOT,
                                    "REQUEST ERROR%nHTTP request failed with status code:'%d'%n",
                                    response.statusCode());
                            if (currentLevel == HttpPipelineLogLevel.WARNING) {
                                logMessage += errorString;
                            } else {
                                logMessage = errorString;
                            }

                            currentLevel = HttpPipelineLogLevel.ERROR;
                        }

                        /*
                        We don't want to format the log message unless we have to. Format once we've determined that
                        either the customer wants this log level or we need to force log it.
                         */
                        if (this.shouldLog(currentLevel)) {
                            String additionalMessageInfo = buildAdditionalMessageInfo(request);
                            String messageInfo = String.format(Locale.ROOT,
                                    "Request try:'%d', request duration:'%d' ms, operation duration:'%d' ms%n%s",
                                    tryCount, requestCompletionTime, operationDuration, additionalMessageInfo);
                            this.log(currentLevel, logMessage + messageInfo);
                        }
                    });
        }

        private String buildAdditionalMessageInfo(final HttpRequest httpRequest) {
            HttpRequest sanitizedRequest = buildSanitizedRequest(httpRequest);
            StringBuilder stringBuilder = new StringBuilder();
            String format = "%s: %s" + System.lineSeparator();
            stringBuilder.append(String.format(format, sanitizedRequest.httpMethod().toString(),
                    sanitizedRequest.url().toString()));
            sanitizedRequest.headers().forEach((header) -> stringBuilder.append(String.format(format, header.name(),
                    header.value())));
            return stringBuilder.toString();
        }

        private HttpRequest buildSanitizedRequest(final HttpRequest initialRequest) {
            // Build new URL and redact SAS signature, if present
            URL url = sanitizeURL(initialRequest.url());

            // Build resultRequest
            HttpRequest resultRequest = new HttpRequest(
                    initialRequest.callerMethod(),
                    initialRequest.httpMethod(),
                    url,
                    initialRequest.headers(),
                    initialRequest.body(),
                    initialRequest.responseDecoder());

            // Redact Authorization header, if present
            if (resultRequest.headers().value(Constants.HeaderConstants.AUTHORIZATION) != null) {
                resultRequest.headers().set(Constants.HeaderConstants.AUTHORIZATION, Constants.REDACTED);
            }

            // Redact Copy Source header SAS signature, if present
            if (resultRequest.headers().value(Constants.HeaderConstants.COPY_SOURCE) != null) {
                try {
                    URL copySourceUrl = sanitizeURL(new URL(resultRequest.headers()
                            .value(Constants.HeaderConstants.COPY_SOURCE)));
                    resultRequest.headers().set(Constants.HeaderConstants.COPY_SOURCE, copySourceUrl.toString());
                } catch (MalformedURLException e) {
                    throw new RuntimeException(e);
                }
            }

            return resultRequest;
        }

        private URL sanitizeURL(URL initialURL) {
            URL resultURL = initialURL;
            try {
                BlobURLParts urlParts = URLParser.parse(initialURL);
                if (urlParts.sasQueryParameters() == null || urlParts.sasQueryParameters().signature() == null) {
                    return resultURL;
                }
                urlParts.withSasQueryParameters(new SASQueryParameters(
                        urlParts.sasQueryParameters().version(),
                        urlParts.sasQueryParameters().services(),
                        urlParts.sasQueryParameters().resourceTypes(),
                        urlParts.sasQueryParameters().protocol(),
                        urlParts.sasQueryParameters().startTime(),
                        urlParts.sasQueryParameters().expiryTime(),
                        urlParts.sasQueryParameters().ipRange(),
                        urlParts.sasQueryParameters().identifier(),
                        urlParts.sasQueryParameters().resource(),
                        urlParts.sasQueryParameters().permissions(),
                        Constants.REDACTED,
                        urlParts.sasQueryParameters().cacheControl(),
                        urlParts.sasQueryParameters().contentDisposition(),
                        urlParts.sasQueryParameters().contentEncoding(),
                        urlParts.sasQueryParameters().contentLanguage(),
                        urlParts.sasQueryParameters().contentType(),
                        urlParts.sasQueryParameters().userDelegationKey()
                ));
                resultURL = urlParts.toURL();

                /*
                We are only making valid changes to what has already been validated as a URL (since we got it from a
                URL object), so there should be no need for either us or the caller to check this error.
                */
            } catch (UnknownHostException | MalformedURLException e) {
                throw new RuntimeException(e);
            }
            return resultURL;
        }

        /*
        We need to support the HttpPipelineLogger as it already exists. We also want to allow users to hook up SLF4J.
        Finally, we need to do our own default logging.
         */
        private void log(HttpPipelineLogLevel level, String message) {
            /*
            We need to explicitly check before we send it to the HttpPipelineLogger as its log function may only
            expect to receive messages for which shouldLog() returns true.
             */
            if (this.options.shouldLog(level)) {
                this.options.log(level, message);
            }

            /*
            The Java logger and slf4j logger should do the correct thing given any log level. FORCE_LOGGER is
            configured to only log warnings and errors.
             */
            if (!this.factory.loggingOptions.disableDefaultLogging() && LoggingFactory.defaultLoggerLoaded) {
                FORCE_LOGGER.log(JAVA_LOG_LEVEL_MAP.get(level), message);
            }
            if (level.equals(HttpPipelineLogLevel.ERROR)) {
                SLF4J_LOGGER.error(message);
            } else if (level.equals(HttpPipelineLogLevel.WARNING)) {
                SLF4J_LOGGER.warn(message);
            } else if (level.equals(HttpPipelineLogLevel.INFO)) {
                SLF4J_LOGGER.info(message);
            }
        }

        /*
        Check the HttpPipelineLogger, SLF4J Logger, and Java Logger
         */
        private boolean shouldLog(HttpPipelineLogLevel level) {
            // Default log Warnings and Errors as long as default logging is enabled.
            if ((level.equals(HttpPipelineLogLevel.WARNING) || level.equals(HttpPipelineLogLevel.ERROR))
                    && !this.factory.loggingOptions.disableDefaultLogging() && LoggingFactory.defaultLoggerLoaded) {
                return true;
            }

            // The user has configured the HttpPipelineLogger to log at this level.
            if (this.options.shouldLog(level)) {
                return true;
            }

            // The SLF4J logger is configured at the given level.
            if ((level.equals(HttpPipelineLogLevel.INFO) && SLF4J_LOGGER.isInfoEnabled())
                    || (level.equals(HttpPipelineLogLevel.WARNING) && SLF4J_LOGGER.isWarnEnabled())
                    || (level.equals(HttpPipelineLogLevel.ERROR) && SLF4J_LOGGER.isErrorEnabled())) {
                return true;
            }

            return false;
        }
    }
}


text:
/*
 * CS3600, Spring 2014
 * Project 2 Starter Code
 * (c) 2013 Alan Mislove
 *
 */

#ifndef __3600DNS_H__
#define __3600DNS_H__

// structure for the header
typedef struct dnsheader_s {
	// GCC lays out structures backwards in each
	// individual byte. the bytes themselves are in order

	// bytes 1-2
	unsigned short id;

	// byte 3
	unsigned short rd:1;
	unsigned short tc:1;
	unsigned short aa:1;
	unsigned short opcode:4;
	unsigned short qr:1;

	// byte 4
	unsigned short rcode:4;
	unsigned short z:3;
	unsigned short ra:1;

	// bytes 5-12
	unsigned short qdcount;
	unsigned short ancount;
	unsigned short nscount;
	unsigned short arcount;
} dnsheader;

// structure for the question
typedef struct dnsquestion_s{
	unsigned char* qname;
	unsigned short qtype;
	unsigned short qclass;
} dnsquestion;

// structure for the answer
typedef struct dnsanswer_s{
	unsigned char* name;
	unsigned short type;
	unsigned short qclass;
	unsigned int ttl;
	unsigned short rdlength;
	unsigned char* rdata;
} dnsanswer;

void packHeaderBuffer(unsigned char* buf, dnsheader header);
unsigned char* unpointerfy(unsigned char* response, int initLocation, int size);
unsigned char* unstringify(unsigned char* str);
unsigned char* pointerFollower(unsigned char* response, int initLocation, int originalLocation);

#endif