text:
package gw.internal.gosu.parser.java.classinfo;

import gw.config.CommonServices;
import gw.internal.gosu.parser.DefaultTypeLoader;
import gw.lang.reflect.IDefaultTypeLoader;
import gw.lang.reflect.ITypeRefFactory;
import gw.lang.reflect.ImplicitPropertyUtil;
import gw.lang.reflect.Modifier;
import gw.lang.reflect.TypeSystem;
import gw.lang.reflect.java.IJavaClassInfo;
import gw.lang.reflect.java.IJavaClassMethod;
import gw.lang.reflect.java.IJavaClassType;
import gw.lang.reflect.java.asm.AsmClass;
import gw.lang.reflect.module.IModule;

public class JavaSourceUtil {

  public static IJavaClassInfo getClassInfo( AsmClass cls, IModule module ) {
    if( isProxy( cls ) ) {
      return getJavaClassInfo( cls, module );
    } else {
      if( !CommonServices.getPlatformHelper().isInIDE() ) {
        // Don't try to load from source unless we have to, this saves a load of time esp. for case
        // where we're loading an inner java class where replacing the '$' below with '.' we bascially
        // put the type system through a load of unnecessary work.
        IJavaClassInfo classInfo = getJavaClassInfo( cls, module );
        if( classInfo != null ) {
          return classInfo;
        }
      }
      return getClassInfo( cls.getName().replace( '$', '.' ), module );
    }
  }

  private static IJavaClassInfo getJavaClassInfo( AsmClass asmClass, IModule module ) {
    for( IModule m : module.getModuleTraversalList() ) {
      TypeSystem.pushModule( m );
      try {
        DefaultTypeLoader defaultTypeLoader = (DefaultTypeLoader)m.getModuleTypeLoader().getDefaultTypeLoader();
        if( defaultTypeLoader != null ) {
          IJavaClassInfo javaClassInfo = defaultTypeLoader.getJavaClassInfo( asmClass, module );
          if( javaClassInfo != null ) {
            return javaClassInfo;
          }
        }
      }
      finally {
        TypeSystem.popModule( m );
      }
    }
    return null;
  }

  public static IJavaClassInfo getClassInfo(Class aClass, IModule gosuModule) {
    DefaultTypeLoader loader = (DefaultTypeLoader) gosuModule.getModuleTypeLoader().getDefaultTypeLoader();
    if (isProxy(aClass)) {
      return loader.getJavaClassInfo( aClass, gosuModule );
    } else if (aClass.isArray()) {
      IJavaClassInfo classInfo = getClassInfo(aClass.getComponentType(), gosuModule);
      IModule module = classInfo.getModule();
      return loader.getJavaClassInfo(aClass, module);
    } else {
      if( !CommonServices.getPlatformHelper().isInIDE() ) {
        // Don't try to load from source unless we have to, this saves a load of time esp. for case
        // where we're loading an inner java class where replacing the '$' below with '.' we bascially
        // put the type system through a load of unnecessary work.
        IJavaClassInfo javaClassInfo = loader.getJavaClassInfo( aClass, gosuModule );
        if (javaClassInfo != null) {
          return javaClassInfo;
        }
      }
      return getClassInfo(aClass.getName().replace('$', '.'), gosuModule);
    }
  }

  private static boolean isProxy(AsmClass aClass) {
    String name = aClass.getName();
    return
        name.endsWith(ITypeRefFactory.USER_PROXY_SUFFIX) ||
        name.endsWith(ITypeRefFactory.SYSTEM_PROXY_SUFFIX);
  }

  private static boolean isProxy(Class aClass) {
    String name = aClass.getName();
    return
        name.endsWith(ITypeRefFactory.USER_PROXY_SUFFIX) ||
        name.endsWith(ITypeRefFactory.SYSTEM_PROXY_SUFFIX);
  }

  public static IJavaClassInfo getClassInfo(String qualifiedName, IModule gosuModule) {
    for (IModule module : gosuModule.getModuleTraversalList()) {
      IDefaultTypeLoader loader = module.getModuleTypeLoader().getDefaultTypeLoader();
      if (loader != null) {
        IJavaClassInfo javaClassInfo = loader.getJavaClassInfo(qualifiedName);
        if (javaClassInfo != null) {
          return javaClassInfo;
        }
      }
    }
    return null;
  }

  public static ImplicitPropertyUtil.ImplicitPropertyInfo getImplicitProperty(IJavaClassMethod method) {
    IJavaClassType returnType = method.getGenericReturnType();
    if (returnType != null) {
      String returnTypeName = returnType.getName();
      int argCount = method.getParameterTypes().length;
      String name = method.getName();
      if (argCount == 0 && !returnTypeName.equals("void")) {
        if (name.startsWith(ImplicitPropertyUtil.GET) && (name.length() > ImplicitPropertyUtil.GET.length())) {
          return new ImplicitPropertyUtil.ImplicitPropertyInfo(false, true, ImplicitPropertyUtil.capitalizeFirstChar(name.substring(3)));
        } else if (name.startsWith(ImplicitPropertyUtil.IS) &&
            (name.length() > ImplicitPropertyUtil.IS.length()) &&
            (returnTypeName.equals("boolean") || returnTypeName.equals("java.lang.Boolean"))) {
          return new ImplicitPropertyUtil.ImplicitPropertyInfo(false, true, ImplicitPropertyUtil.capitalizeFirstChar(name.substring(2)));
        }
      } else if (argCount == 1) {
        if (returnTypeName.equals("void") && name.startsWith(ImplicitPropertyUtil.SET) && (name.length() > ImplicitPropertyUtil.SET.length())) {
          return new ImplicitPropertyUtil.ImplicitPropertyInfo(true, false, ImplicitPropertyUtil.capitalizeFirstChar(name.substring(3)));
        }
      }
    }
    return null;
  }

  public static IJavaClassType resolveInnerClass(IJavaClassInfo rootType, String innerName, IJavaClassInfo whosAskin) {
    for (IJavaClassInfo innerCls : rootType.getDeclaredClasses()) {
      if (innerName.equals(innerCls.getSimpleName()) && isVisible(rootType, innerCls, whosAskin)) {
        return innerCls;
      }
    }
    return null;
  }

  private static boolean isVisible(IJavaClassInfo rootType, IJavaClassInfo innerClass, IJavaClassInfo whosAskin) {
    if ((whosAskin == rootType) || Modifier.isPublic(innerClass.getModifiers()) || (isEnclosed(rootType, whosAskin))) {
      return true;
    }
    if( innerClass.isProtected() && isDescendant(rootType, whosAskin) ) {
      return true;
    }
    if (whosAskin.getNamespace().equals(rootType.getNamespace()) && innerClass.isInternal()) {
      return true;
    }
    return false;
  }

  public static boolean isEnclosed(IJavaClassInfo enclosingClass, IJavaClassInfo nestedClass) {
    IJavaClassInfo enclosingType = nestedClass.getEnclosingClass();
    if (enclosingType == null) {
      return false;
    }
    if (enclosingType == enclosingClass) {
      return true;
    }
    return isEnclosed(enclosingClass, enclosingType);
  }

  public static boolean isDescendant(IJavaClassInfo ancestorClassInfo, IJavaClassInfo descendantClassInfo) {
    IJavaClassInfo superclass = descendantClassInfo.getSuperclass();
    if (superclass != null) {
      if (superclass == ancestorClassInfo) {
        return true;
      }
      if (isDescendant(ancestorClassInfo, superclass)) {
        return true;
      }
    }
    for (IJavaClassInfo iface : descendantClassInfo.getInterfaces()) {
      if (iface == ancestorClassInfo) {
        return true;
      }
      if (isDescendant(ancestorClassInfo, iface)) {
        return true;
      }
    }
    return false;
  }

}


text:
namespace FitFilePreviewer.Decode.Fit.Types
{
   /// <summary>
   /// Implements the profile BpStatus type as an enum
   /// </summary>
   public enum BpStatus : byte
   {
      NoError = 0,
      ErrorIncompleteData = 1,
      ErrorNoMeasurement = 2,
      ErrorDataOutOfRange = 3,
      ErrorIrregularHeartRate = 4,
      Invalid = 0xFF

   }
}

redpajama_set_name: RedPajamaGithub


text:
#pragma once
#include <aws/guardduty/GuardDuty_EXPORTS.h>
#include <aws/core/utils/memory/stl/AWSVector.h>
#include <aws/core/utils/memory/stl/AWSString.h>
#include <utility>

namespace Aws
{
template<typename RESULT_TYPE>
class AmazonWebServiceResult;

namespace Utils
{
namespace Json
{
  class JsonValue;
} // namespace Json
} // namespace Utils
namespace GuardDuty
{
namespace Model
{
  class AWS_GUARDDUTY_API ListFindingsResult
  {
  public:
    ListFindingsResult();
    ListFindingsResult(const Aws::AmazonWebServiceResult<Aws::Utils::Json::JsonValue>& result);
    ListFindingsResult& operator=(const Aws::AmazonWebServiceResult<Aws::Utils::Json::JsonValue>& result);

    inline const Aws::Vector<Aws::String>& GetFindingIds() const{ return m_findingIds; }

    inline void SetFindingIds(const Aws::Vector<Aws::String>& value) { m_findingIds = value; }

    inline void SetFindingIds(Aws::Vector<Aws::String>&& value) { m_findingIds = std::move(value); }

    inline ListFindingsResult& WithFindingIds(const Aws::Vector<Aws::String>& value) { SetFindingIds(value); return *this;}

    inline ListFindingsResult& WithFindingIds(Aws::Vector<Aws::String>&& value) { SetFindingIds(std::move(value)); return *this;}

    inline ListFindingsResult& AddFindingIds(const Aws::String& value) { m_findingIds.push_back(value); return *this; }

    inline ListFindingsResult& AddFindingIds(Aws::String&& value) { m_findingIds.push_back(std::move(value)); return *this; }

    inline ListFindingsResult& AddFindingIds(const char* value) { m_findingIds.push_back(value); return *this; }

    inline const Aws::String& GetNextToken() const{ return m_nextToken; }

    inline void SetNextToken(const Aws::String& value) { m_nextToken = value; }

    inline void SetNextToken(Aws::String&& value) { m_nextToken = std::move(value); }

    inline void SetNextToken(const char* value) { m_nextToken.assign(value); }

    inline ListFindingsResult& WithNextToken(const Aws::String& value) { SetNextToken(value); return *this;}

    inline ListFindingsResult& WithNextToken(Aws::String&& value) { SetNextToken(std::move(value)); return *this;}

    inline ListFindingsResult& WithNextToken(const char* value) { SetNextToken(value); return *this;}

  private:

    Aws::Vector<Aws::String> m_findingIds;

    Aws::String m_nextToken;
  };

} // namespace Model
} // namespace GuardDuty
} // namespace Aws


text:
package org.springframework.security.access.annotation;

import java.util.Collection;

import org.springframework.security.access.AccessDecisionVoter;
import org.springframework.security.access.ConfigAttribute;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.GrantedAuthority;

/**
 * Voter on JSR-250 configuration attributes.
 *
 * @author Ryan Heaton
 * @since 2.0
 */
public class Jsr250Voter implements AccessDecisionVoter<Object> {

	/**
	 * The specified config attribute is supported if its an instance of a
	 * {@link Jsr250SecurityConfig}.
	 * @param configAttribute The config attribute.
	 * @return whether the config attribute is supported.
	 */
	@Override
	public boolean supports(ConfigAttribute configAttribute) {
		return configAttribute instanceof Jsr250SecurityConfig;
	}

	/**
	 * All classes are supported.
	 * @param clazz the class.
	 * @return true
	 */
	@Override
	public boolean supports(Class<?> clazz) {
		return true;
	}

	/**
	 * Votes according to JSR 250.
	 * <p>
	 * If no JSR-250 attributes are found, it will abstain, otherwise it will grant or
	 * deny access based on the attributes that are found.
	 * @param authentication The authentication object.
	 * @param object The access object.
	 * @param definition The configuration definition.
	 * @return The vote.
	 */
	@Override
	public int vote(Authentication authentication, Object object, Collection<ConfigAttribute> definition) {
		boolean jsr250AttributeFound = false;
		for (ConfigAttribute attribute : definition) {
			if (Jsr250SecurityConfig.PERMIT_ALL_ATTRIBUTE.equals(attribute)) {
				return ACCESS_GRANTED;
			}
			if (Jsr250SecurityConfig.DENY_ALL_ATTRIBUTE.equals(attribute)) {
				return ACCESS_DENIED;
			}
			if (supports(attribute)) {
				jsr250AttributeFound = true;
				// Attempt to find a matching granted authority
				for (GrantedAuthority authority : authentication.getAuthorities()) {
					if (attribute.getAttribute().equals(authority.getAuthority())) {
						return ACCESS_GRANTED;
					}
				}
			}
		}
		return jsr250AttributeFound ? ACCESS_DENIED : ACCESS_ABSTAIN;
	}

}


text:
package ch.adivo.bisuite.common;

import java.time.LocalDateTime;

import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.MappedSuperclass;
import javax.persistence.PrePersist;
import javax.persistence.PreUpdate;

import org.springframework.data.annotation.CreatedDate;
import org.springframework.data.annotation.LastModifiedDate;
//import org.springframework.security.core.userdetails.User;

@MappedSuperclass
public class AbstractEntity {
	@Id
	@GeneratedValue(strategy = GenerationType.AUTO)
	private Long id;
	@CreatedDate
	private LocalDateTime created;
	@LastModifiedDate
	private LocalDateTime lastModified;
	// @CreatedBy
	// private User user;

	public LocalDateTime getCreated() {
		return created;
	}

	public Long getId() {
		return id;
	}

	public LocalDateTime getLastModified() {
		return lastModified;
	}

	@PrePersist
	public void prePersist() {
		this.created = LocalDateTime.now();
		this.lastModified = LocalDateTime.now();
	}

	@PreUpdate
	public void preUpdate() {
		this.lastModified = LocalDateTime.now();
	}

}


text:
from rctkdemos.demos import serve_demo, standalone
from rctk.widgets import Panel, Button, StaticText
from rctk.layouts import HBox, VBox

class Demo(object):
    title = "Panel"
    description = "Demonstrates the Panel control"

    def build(self, tk, parent):
        parent.setLayout(HBox())
        p1 = Panel(tk,width=200, height=200)
        p2 = Panel(tk, scrolling=True, width=200, height=200)
        p2.setLayout(VBox())
        p1.append(StaticText(tk, "Non-scrolling panel"))
        p2.append(StaticText(tk, "Scrolling panel"))
        b = Button(tk, "Click me")
        p1.append(b)

        def click(e):
            p2.append(StaticText(tk, "Line added"))
            parent.layout()
            p2.scrollbottom()

        b.click = click

        parent.append(p1)
        parent.append(p2)

Standalone = standalone(Demo)

if __name__ == '__main__':
    serve_demo(Demo)


text:
struct Person {
  char *name;
  int age;
  int height;
  int weight;
};

struct Person *Person_create(char *name, int age, int height, int weight)
{
  struct Person *who = malloc(sizeof(struct Person));
  assert(who != NULL);

  who->name = strdup(name);
  who->age = age;
  who->height = height;
  who->weight = weight;

  return who;
}

void Person_destroy(struct Person *who)
{
  assert(who != NULL);

  free(who->name);
  free(who);

}

void Person_print(struct Person *who)
{
  printf("Name: %s\n", who->name);
  printf("\tAge: %d\n", who->age);
  printf("\tHeight: %d\n", who->height);
  printf("\tWeight: %d\n", who->weight);
}

int main(int argc, char *argv[])
{
  struct Person *salman = Person_create("Salman Hossain", 18, 64, 118);
  struct Person *fahim = Person_create("Fahim Shariar", 18, 64, 118);

  printf("Salman is at memory location %p \n", salman);
  Person_print(salman);

  printf("Fahim is at memory location %p \n", fahim);
  Person_print(fahim);

  salman->age += 20;
  salman->height -= 2;
  salman->weight += 20;
  Person_print(salman);

  fahim->age += 20;
  fahim->weight += 40;
  Person_print(fahim);

  Person_destroy(salman);
  Person_destroy(fahim);

  return 0;

}


text:
import os, sys, logging, errno, ast
from ConfigParser import SafeConfigParser

# Parse config file
parser = SafeConfigParser()
parser.read('config_plots.txt')

###############################################################################
# User modifiable values
#
#
###############################################################################
PROJECT_NAME  = parser.get('PROJECT','project_name')
TAG           = parser.get('PROJECT','TAG')
START_YR      = parser.get('PARAMETERS','START_YR')
END_YR        = parser.get('PARAMETERS','END_YR')
SIMULATIONS   = parser.get('PARAMETERS','SIMULATIONS')
EPIC_OUTPUT   = parser.get('PARAMETERS','EPIC_OUTPUT')
ACM_PARAMS    = ast.literal_eval(parser.get('PARAMETERS','ACM_PARAMS'))
ACY_PARAMS    = ast.literal_eval(parser.get('PARAMETERS','ACY_PARAMS'))
DGN_PARAMS    = ast.literal_eval(parser.get('PARAMETERS','DGN_PARAMS'))
GET_PARAMS    = ast.literal_eval(parser.get('PARAMETERS','GET_PARAMS'))

base_dir      = parser.get('PATHS','base_dir')+os.sep
epic_dir      = base_dir+os.sep+'EPIC'+os.sep+PROJECT_NAME+os.sep
sims_dir      = epic_dir+os.sep+SIMULATIONS+os.sep+EPIC_OUTPUT
plot_dir      = epic_dir+os.sep+SIMULATIONS+os.sep+EPIC_OUTPUT

###############################################################################
#
#
#
###############################################################################
def make_dir_if_missing(d):
    try:
        os.makedirs(d)
    except OSError as exception:
        if exception.errno != errno.EEXIST:
            raise

# Create directories
make_dir_if_missing(epic_dir)
make_dir_if_missing(sims_dir)

# Logging
LOG_FILENAME   = epic_dir+os.sep+'Log_'+TAG+'.txt'
logging.basicConfig(filename = LOG_FILENAME, level=logging.INFO,\
                    format='%(asctime)s    %(levelname)s %(module)s - %(funcName)s: %(message)s',\
                    datefmt="%Y-%m-%d %H:%M:%S") # Logging levels are DEBUG, INFO, WARNING, ERROR, and CRITICAL


text:
<window>
	<defaultcontrol always="true">21</defaultcontrol>
	<coordinates>
		<posx>0</posx>
		<posy>330</posy>
	</coordinates>
	<controls>
		<animation effect="fade" start="0" end="100" time="200">WindowOpen</animation>
		<animation effect="fade" start="100" end="0" time="200">WindowClose</animation>
		<control type="image">
			<description>background</description>
			<posx>0</posx>
			<posy>26</posy>
			<width>1280</width>
			<height>410</height>
			<texture>darkgrey.png</texture>
		</control>
		<control type="label" id="1">
			<description>dialog Heading</description>
			<posx>97</posx>
			<posy>46</posy>
			<width>1062</width>
			<height>37</height>
			font18
			<textcolor>shadow-text</textcolor>
			<shadowcolor>button-text</shadowcolor>
			<align>center</align>
			<aligny>center</aligny>
			<visible>IsEmpty(Control.GetLabel(4))</visible>
		</control>
		<control type="image">
			<posx>74</posx>
			<posy>50</posy>
			<width>1122</width>
			<height>34</height>
			<texture border="16">text-background.png</texture>
		</control>
		<control type="label" id="4">
			<description>Edit Text</description>
			<posx>97</posx>
			<posy>46</posy>
			<width>1062</width>
			<height>37</height>
			font18
			<align>center</align>
			<aligny>center</aligny>
		</control>
		<control type="group">
			<posx>442</posx>
			<posy>120</posy>
			<control type="button" id="11">
				<description>1 button</description>
				<posx>0</posx>
				<posy>0</posy>
				<width>74</width>
				<height>48</height>
				font18
				<align>center</align>
				<aligny>center</aligny>
				<textoffsetx>0</textoffsetx>
				<texturenofocus border="6">key-nofocus.png</texturenofocus>
				<texturefocus border="6">key-focus.png</texturefocus>
				12311
				<onleft>23</onleft>
				<onright>12</onright>
				<onup>20</onup>
				<ondown>14</ondown>
				<textcolor>shadow-text</textcolor>
				<shadowcolor>-</shadowcolor>
			</control>
			<control type="button" id="12">
				<description>2 button</description>
				<posx>88</posx>
				<posy>0</posy>
				<width>74</width>
				<height>48</height>
				font18
				<align>center</align>
				<aligny>center</aligny>
				<textoffsetx>0</textoffsetx>
				<texturenofocus border="6">key-nofocus.png</texturenofocus>
				<texturefocus border="6">key-focus.png</texturefocus>
				12312
				<onleft>11</onleft>
				<onright>13</onright>
				<onup>10</onup>
				<ondown>15</ondown>
				<textcolor>shadow-text</textcolor>
				<shadowcolor>-</shadowcolor>
			</control>
			<control type="button" id="13">
				<description>3 button</description>
				<posx>177</posx>
				<posy>0</posy>
				<width>74</width>
				<height>48</height>
				font18
				<align>center</align>
				<aligny>center</aligny>
				<textoffsetx>0</textoffsetx>
				<texturenofocus border="6">key-nofocus.png</texturenofocus>
				<texturefocus border="6">key-focus.png</texturefocus>
				12313
				<onleft>12</onleft>
				<onright>23</onright>
				<onup>22</onup>
				<ondown>16</ondown>
				<textcolor>shadow-text</textcolor>
				<shadowcolor>-</shadowcolor>
			</control>
			<control type="button" id="23">
				<description>Backspace button</description>
				<posx>265</posx>
				<posy>0</posy>
				<width>74</width>
				<height>110</height>
				font18
				<align>center</align>
				<aligny>center</aligny>
				<textoffsetx>0</textoffsetx>
				<texturenofocus border="6">key-nofocus.png</texturenofocus>
				<texturefocus border="6">key-focus.png</texturefocus>
				<-
				<onleft>13</onleft>
				<onright>11</onright>
				<onup>21</onup>
				<ondown>21</ondown>
				<textcolor>shadow-text</textcolor>
				<shadowcolor>-</shadowcolor>
			</control>
			<control type="button" id="14">
				<description>4 button</description>
				<posx>0</posx>
				<posy>62</posy>
				<width>74</width>
				<height>48</height>
				font18
				<align>center</align>
				<aligny>center</aligny>
				<textoffsetx>0</textoffsetx>
				<texturenofocus border="6">key-nofocus.png</texturenofocus>
				<texturefocus border="6">key-focus.png</texturefocus>
				12314
				<onleft>23</onleft>
				<onright>15</onright>
				<onup>11</onup>
				<ondown>17</ondown>
				<textcolor>shadow-text</textcolor>
				<shadowcolor>-</shadowcolor>
			</control>
			<control type="button" id="15">
				<description>5 button</description>
				<posx>88</posx>
				<posy>62</posy>
				<width>74</width>
				<height>48</height>
				font18
				<align>center</align>
				<aligny>center</aligny>
				<textoffsetx>0</textoffsetx>
				<texturenofocus border="6">key-nofocus.png</texturenofocus>
				<texturefocus border="6">key-focus.png</texturefocus>
				12315
				<onleft>14</onleft>
				<onright>16</onright>
				<onup>12</onup>
				<ondown>18</ondown>
				<textcolor>shadow-text</textcolor>
				<shadowcolor>-</shadowcolor>
			</control>
			<control type="button" id="16">
				<description>6 button</description>
				<posx>177</posx>
				<posy>62</posy>
				<width>74</width>
				<height>48</height>
				font18
				<align>center</align>
				<aligny>center</aligny>
				<textoffsetx>0</textoffsetx>
				<texturenofocus border="6">key-nofocus.png</texturenofocus>
				<texturefocus border="6">key-focus.png</texturefocus>
				12316
				<onleft>15</onleft>
				<onright>23</onright>
				<onup>13</onup>
				<ondown>19</ondown>
				<textcolor>shadow-text</textcolor>
				<shadowcolor>-</shadowcolor>
			</control>
			<control type="button" id="17">
				<description>7 button</description>
				<posx>0</posx>
				<posy>125</posy>
				<width>74</width>
				<height>48</height>
				font18
				<align>center</align>
				<aligny>center</aligny>
				<textoffsetx>0</textoffsetx>
				<texturenofocus border="6">key-nofocus.png</texturenofocus>
				<texturefocus border="6">key-focus.png</texturefocus>
				12317
				<onleft>21</onleft>
				<onright>18</onright>
				<onup>14</onup>
				<ondown>20</ondown>
				<textcolor>shadow-text</textcolor>
				<shadowcolor>-</shadowcolor>
			</control>
			<control type="button" id="18">
				<description>8 button</description>
				<posx>88</posx>
				<posy>125</posy>
				<width>74</width>
				<height>48</height>
				font18
				<align>center</align>
				<aligny>center</aligny>
				<textoffsetx>0</textoffsetx>
				<texturenofocus border="6">key-nofocus.png</texturenofocus>
				<texturefocus border="6">key-focus.png</texturefocus>
				12318
				<onleft>17</onleft>
				<onright>19</onright>
				<onup>15</onup>
				<ondown>10</ondown>
				<textcolor>shadow-text</textcolor>
				<shadowcolor>-</shadowcolor>
			</control>
			<control type="button" id="19">
				<description>9 button</description>
				<posx>177</posx>
				<posy>125</posy>
				<width>74</width>
				<height>48</height>
				font18
				<align>center</align>
				<aligny>center</aligny>
				<textoffsetx>0</textoffsetx>
				<texturenofocus border="6">key-nofocus.png</texturenofocus>
				<texturefocus border="6">key-focus.png</texturefocus>
				12319
				<onleft>18</onleft>
				<onright>21</onright>
				<onup>16</onup>
				<ondown>22</ondown>
				<textcolor>shadow-text</textcolor>
				<shadowcolor>-</shadowcolor>
			</control>
			<control type="button" id="21">
				<description>Done button</description>
				<posx>265</posx>
				<posy>125</posy>
				<width>74</width>
				<height>110</height>
				font13
				<align>center</align>
				<aligny>center</aligny>
				<angle>-90</angle>
				<textoffsetx>0</textoffsetx>
				<texturenofocus border="6">key-nofocus.png</texturenofocus>
				<texturefocus border="6">key-focus.png</texturefocus>
				20177
				<onleft>19</onleft>
				<onright>17</onright>
				<onup>23</onup>
				<ondown>23</ondown>
				<textcolor>shadow-text</textcolor>
				<shadowcolor>-</shadowcolor>
			</control>
			<control type="button" id="20">
				<description>prev button</description>
				<posx>0</posx>
				<posy>187</posy>
				<width>74</width>
				<height>48</height>
				font18
				<<
				<align>center</align>
				<aligny>center</aligny>
				<textoffsetx>0</textoffsetx>
				<texturenofocus border="6">key-nofocus.png</texturenofocus>
				<texturefocus border="6">key-focus.png</texturefocus>
				<onleft>21</onleft>
				<onright>10</onright>
				<onup>17</onup>
				<ondown>11</ondown>
				<textcolor>shadow-text</textcolor>
				<shadowcolor>-</shadowcolor>
			</control>
			<control type="button" id="10">
				<description>0 button</description>
				<posx>88</posx>
				<posy>187</posy>
				<width>74</width>
				<height>48</height>
				font18
				<align>center</align>
				<aligny>center</aligny>
				<textoffsetx>0</textoffsetx>
				<texturenofocus border="6">key-nofocus.png</texturenofocus>
				<texturefocus border="6">key-focus.png</texturefocus>
				12310
				<onleft>20</onleft>
				<onright>22</onright>
				<onup>18</onup>
				<ondown>12</ondown>
				<textcolor>shadow-text</textcolor>
				<shadowcolor>-</shadowcolor>
			</control>
			<control type="button" id="22">
				<description>next button</description>
				<posx>177</posx>
				<posy>187</posy>
				<width>74</width>
				<height>48</height>
				font18
				>>
				<align>center</align>
				<aligny>center</aligny>
				<textoffsetx>0</textoffsetx>
				<texturenofocus border="6">key-nofocus.png</texturenofocus>
				<texturefocus border="6">key-focus.png</texturefocus>
				<onleft>10</onleft>
				<onright>21</onright>
				<onup>19</onup>
				<ondown>13</ondown>
				<textcolor>shadow-text</textcolor>
				<shadowcolor>-</shadowcolor>
			</control>
		</control>
	</controls>
</window>


text:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
  "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />

    <title>34.6. termios — POSIX style tty control — Python 3.3.6 documentation</title>

    <link rel="stylesheet" href="../_static/pydoctheme.css" type="text/css" />
    <link rel="stylesheet" href="../_static/pygments.css" type="text/css" />

    <link rel="search" type="application/opensearchdescription+xml"
          title="Search within Python 3.3.6 documentation"
          href="../_static/opensearch.xml"/>
    <link rel="author" title="About these documents" href="../about.html" />
    <link rel="copyright" title="Copyright" href="../copyright.html" />
    <link rel="top" title="Python 3.3.6 documentation" href="../index.html" />
    <link rel="up" title="34. Unix Specific Services" href="unix.html" />
    <link rel="next" title="34.7. tty — Terminal control functions" href="tty.html" />
    <link rel="prev" title="34.5. crypt — Function to check Unix passwords" href="crypt.html" />
    <link rel="shortcut icon" type="image/png" href="../_static/py.png" />

Navigation

          index

          modules |

          next |

          previous |

Python »

          3.3.6 Documentation »

The Python Standard Library »

34. Unix Specific Services »

34.6. <tt class="xref py py-mod docutils literal">termios</tt> — POSIX style tty control¶

This module provides an interface to the POSIX calls for tty I/O control.  For a
complete description of these calls, see the POSIX or Unix manual pages.  It is
only available for those Unix versions that support POSIX termios style tty
I/O control (and then only if configured at installation time).

All functions in this module take a file descriptor fd as their first
argument.  This can be an integer file descriptor, such as returned by
<tt class="docutils literal">sys.stdin.fileno()</tt>, or a file object, such as <tt class="docutils literal">sys.stdin</tt> itself.

This module also defines all the constants needed to work with the functions
provided here; these have the same name as their counterparts in C.  Please
refer to your system documentation for more information on using these terminal
control interfaces.

The module defines the following functions:

<tt class="descclassname">termios.</tt><tt class="descname">tcgetattr</tt><big>(</big>fd<big>)</big>¶

Return a list containing the tty attributes for file descriptor fd, as
follows: <tt class="docutils literal">[iflag, oflag, cflag, lflag, ispeed, ospeed, cc]</tt> where cc is a
list of the tty special characters (each a string of length 1, except the
items with indices <tt class="xref py py-const docutils literal">VMIN</tt> and <tt class="xref py py-const docutils literal">VTIME</tt>, which are integers when
these fields are defined).  The interpretation of the flags and the speeds as
well as the indexing in the cc array must be done using the symbolic
constants defined in the <tt class="xref py py-mod docutils literal">termios</tt> module.

<tt class="descclassname">termios.</tt><tt class="descname">tcsetattr</tt><big>(</big>fd, when, attributes<big>)</big>¶

Set the tty attributes for file descriptor fd from the attributes, which is
a list like the one returned by <tt class="xref py py-func docutils literal">tcgetattr()</tt>.  The when argument
determines when the attributes are changed: <tt class="xref py py-const docutils literal">TCSANOW</tt> to change
immediately, <tt class="xref py py-const docutils literal">TCSADRAIN</tt> to change after transmitting all queued output,
or <tt class="xref py py-const docutils literal">TCSAFLUSH</tt> to change after transmitting all queued output and
discarding all queued input.

<tt class="descclassname">termios.</tt><tt class="descname">tcsendbreak</tt><big>(</big>fd, duration<big>)</big>¶

Send a break on file descriptor fd.  A zero duration sends a break for 0.25
–0.5 seconds; a nonzero duration has a system dependent meaning.

<tt class="descclassname">termios.</tt><tt class="descname">tcdrain</tt><big>(</big>fd<big>)</big>¶

Wait until all output written to file descriptor fd has been transmitted.

<tt class="descclassname">termios.</tt><tt class="descname">tcflush</tt><big>(</big>fd, queue<big>)</big>¶

Discard queued data on file descriptor fd.  The queue selector specifies
which queue: <tt class="xref py py-const docutils literal">TCIFLUSH</tt> for the input queue, <tt class="xref py py-const docutils literal">TCOFLUSH</tt> for the
output queue, or <tt class="xref py py-const docutils literal">TCIOFLUSH</tt> for both queues.

<tt class="descclassname">termios.</tt><tt class="descname">tcflow</tt><big>(</big>fd, action<big>)</big>¶

Suspend or resume input or output on file descriptor fd.  The action
argument can be <tt class="xref py py-const docutils literal">TCOOFF</tt> to suspend output, <tt class="xref py py-const docutils literal">TCOON</tt> to restart
output, <tt class="xref py py-const docutils literal">TCIOFF</tt> to suspend input, or <tt class="xref py py-const docutils literal">TCION</tt> to restart input.

See also

Module <tt class="xref py py-mod docutils literal">tty</tt>

Convenience functions for common terminal control operations.

34.6.1. Example¶

Here’s a function that prompts for a password with echoing turned off.  Note the
technique using a separate <tt class="xref py py-func docutils literal">tcgetattr()</tt> call and a <tt class="xref std std-keyword docutils literal">try</tt> ...
<tt class="xref std std-keyword docutils literal">finally</tt> statement to ensure that the old tty attributes are restored
exactly no matter what happens:

def getpass(prompt="Password: "):
    import termios, sys
    fd = sys.stdin.fileno()
    old = termios.tcgetattr(fd)
    new = termios.tcgetattr(fd)
    new[3] = new[3] & ~termios.ECHO          # lflags
    try:
        termios.tcsetattr(fd, termios.TCSADRAIN, new)
        passwd = input(prompt)
    finally:
        termios.tcsetattr(fd, termios.TCSADRAIN, old)
    return passwd

Table Of Contents

34.6. <tt class="docutils literal">termios</tt> — POSIX style tty control

34.6.1. Example

Previous topic

34.5. <tt class="docutils literal">crypt</tt> — Function to check Unix passwords

Next topic

34.7. <tt class="docutils literal">tty</tt> — Terminal control functions

This Page

Report a Bug

Show Source

Quick search

    <form class="search" action="../search.html" method="get">
      <input type="text" name="q" />
      <input type="submit" value="Go" />
      <input type="hidden" name="check_keywords" value="yes" />
      <input type="hidden" name="area" value="default" />
    </form>

    Enter search terms or a module, class or function name.

Navigation

          index

          modules |

          next |

          previous |

Python »

          3.3.6 Documentation »

The Python Standard Library »

34. Unix Specific Services »

    © Copyright 1990-2014, Python Software Foundation.

    The Python Software Foundation is a non-profit corporation.
    Please donate.

    Last updated on Oct 12, 2014.
    Found a bug?

    Created using Sphinx 1.2.


text:
class UNIX_ProtocolControllerForUnitFixture :
	public CIMFixtureBase
{
public:
	UNIX_ProtocolControllerForUnitFixture();
	~UNIX_ProtocolControllerForUnitFixture();
	virtual void Run();

};


text:
using namespace std;
using namespace triagens::basics;
using namespace triagens::aql;

// -----------------------------------------------------------------------------
// --SECTION--                                          methods of AggregateNode
// -----------------------------------------------------------------------------

AggregateNode::AggregateNode (ExecutionPlan* plan,
                              triagens::basics::Json const& base,
                              Variable const* expressionVariable,
                              Variable const* outVariable,
                              std::vector<Variable const*> const& keepVariables,
                              std::unordered_map<VariableId, std::string const> const& variableMap,
                              std::vector<std::pair<Variable const*, Variable const*>> const& aggregateVariables,
                              bool count,
                              bool isDistinctCommand)
  : ExecutionNode(plan, base),
    _options(base),
    _aggregateVariables(aggregateVariables),
    _expressionVariable(expressionVariable),
    _outVariable(outVariable),
    _keepVariables(keepVariables),
    _variableMap(variableMap),
    _count(count),
    _isDistinctCommand(isDistinctCommand),
    _specialized(false) {

}

////////////////////////////////////////////////////////////////////////////////
/// @brief toJson, for AggregateNode
////////////////////////////////////////////////////////////////////////////////

void AggregateNode::toJsonHelper (triagens::basics::Json& nodes,
                                  TRI_memory_zone_t* zone,
                                  bool verbose) const {

  triagens::basics::Json json(ExecutionNode::toJsonHelperGeneric(nodes, zone, verbose));  // call base class method

  if (json.isEmpty()) {
    return;
  }

  triagens::basics::Json values(triagens::basics::Json::Array, _aggregateVariables.size());

  for (auto it = _aggregateVariables.begin(); it != _aggregateVariables.end(); ++it) {
    triagens::basics::Json variable(triagens::basics::Json::Object);
    variable("outVariable", (*it).first->toJson())
            ("inVariable", (*it).second->toJson());
    values(variable);
  }
  json("aggregates", values);

  // expression variable might be empty
  if (_expressionVariable != nullptr) {
    json("expressionVariable", _expressionVariable->toJson());
  }

  // output variable might be empty
  if (_outVariable != nullptr) {
    json("outVariable", _outVariable->toJson());
  }

  if (! _keepVariables.empty()) {
    triagens::basics::Json values(triagens::basics::Json::Array, _keepVariables.size());
    for (auto it = _keepVariables.begin(); it != _keepVariables.end(); ++it) {
      triagens::basics::Json variable(triagens::basics::Json::Object);
      variable("variable", (*it)->toJson());
      values(variable);
    }
    json("keepVariables", values);
  }

  json("count", triagens::basics::Json(_count));
  json("isDistinctCommand", triagens::basics::Json(_isDistinctCommand));
  json("specialized", triagens::basics::Json(_specialized));

  _options.toJson(json, zone);

  // And add it:
  nodes(json);
}

////////////////////////////////////////////////////////////////////////////////
/// @brief clone ExecutionNode recursively
////////////////////////////////////////////////////////////////////////////////

ExecutionNode* AggregateNode::clone (ExecutionPlan* plan,
                                     bool withDependencies,
                                     bool withProperties) const {
  auto outVariable = _outVariable;
  auto expressionVariable = _expressionVariable;
  auto aggregateVariables = _aggregateVariables;

  if (withProperties) {
    if (expressionVariable != nullptr) {
      expressionVariable = plan->getAst()->variables()->createVariable(expressionVariable);
    }

    if (outVariable != nullptr) {
      outVariable = plan->getAst()->variables()->createVariable(outVariable);
    }

    // need to re-create all variables
    aggregateVariables.clear();

    for (auto& it : _aggregateVariables) {
      auto out = plan->getAst()->variables()->createVariable(it.first);
      auto in  = plan->getAst()->variables()->createVariable(it.second);
      aggregateVariables.emplace_back(std::make_pair(out, in));
    }
  }

  auto c = new AggregateNode(
    plan,
    _id,
    _options,
    aggregateVariables,
    expressionVariable,
    outVariable,
    _keepVariables,
    _variableMap,
    _count,
    _isDistinctCommand
  );

  // specialize the cloned node
  if (isSpecialized()) {
    c->specialized();
  }

  cloneHelper(c, plan, withDependencies, withProperties);

  return static_cast<ExecutionNode*>(c);
}

////////////////////////////////////////////////////////////////////////////////
/// @brief getVariablesUsedHere
////////////////////////////////////////////////////////////////////////////////

struct UserVarFinder final : public WalkerWorker<ExecutionNode> {
  explicit UserVarFinder (int mindepth)
    : mindepth(mindepth), depth(-1) {
  }

  ~UserVarFinder () {
  }

  std::vector<Variable const*> userVars;
  int mindepth;   // minimal depth to consider
  int depth;

  bool enterSubquery (ExecutionNode*, ExecutionNode*) override final {
    return false;
  }

  void after (ExecutionNode* en) override final {
    if (en->getType() == ExecutionNode::SINGLETON) {
      depth = 0;
    }
    else if (en->getType() == ExecutionNode::ENUMERATE_COLLECTION ||
             en->getType() == ExecutionNode::INDEX ||
             en->getType() == ExecutionNode::ENUMERATE_LIST ||
             en->getType() == ExecutionNode::TRAVERSAL ||
             en->getType() == ExecutionNode::AGGREGATE) {
      depth += 1;
    }
    // Now depth is set correct for this node.
    if (depth >= mindepth) {
      auto const& vars = en->getVariablesSetHere();
      for (auto const& v : vars) {
        if (v->isUserDefined()) {
          userVars.emplace_back(v);
        }
      }
    }
  }
};

////////////////////////////////////////////////////////////////////////////////
/// @brief getVariablesUsedHere, returning a vector
////////////////////////////////////////////////////////////////////////////////

std::vector<Variable const*> AggregateNode::getVariablesUsedHere () const {
  std::unordered_set<Variable const*> v;
  // actual work is done by that method
  getVariablesUsedHere(v);

  // copy result into vector
  std::vector<Variable const*> vv;
  vv.reserve(v.size());
  for (auto const& x : v) {
    vv.emplace_back(x);
  }
  return vv;
}

////////////////////////////////////////////////////////////////////////////////
/// @brief getVariablesUsedHere, modifying the set in-place
////////////////////////////////////////////////////////////////////////////////

void AggregateNode::getVariablesUsedHere (std::unordered_set<Variable const*>& vars) const {
  for (auto const& p : _aggregateVariables) {
    vars.emplace(p.second);
  }

  if (_expressionVariable != nullptr) {
    vars.emplace(_expressionVariable);
  }

  if (_outVariable != nullptr && ! _count) {
    if (_keepVariables.empty()) {
      // Here we have to find all user defined variables in this query
      // amongst our dependencies:
      UserVarFinder finder(1);
      auto myselfAsNonConst = const_cast<AggregateNode*>(this);
      myselfAsNonConst->walk(&finder);
      if (finder.depth == 1) {
        // we are top level, let's run again with mindepth = 0
        finder.userVars.clear();
        finder.mindepth = 0;
        finder.depth = -1;
        finder.reset();
        myselfAsNonConst->walk(&finder);
      }
      for (auto& x : finder.userVars) {
        vars.emplace(x);
      }
    }
    else {
      for (auto& x : _keepVariables) {
        vars.emplace(x);
      }
    }
  }
}

////////////////////////////////////////////////////////////////////////////////
/// @brief estimateCost
////////////////////////////////////////////////////////////////////////////////

double AggregateNode::estimateCost (size_t& nrItems) const {
  double depCost = _dependencies.at(0)->getCost(nrItems);

  // As in the FilterNode case, we are pessimistic here by not reducing the
  // nrItems much, since the worst case for COLLECT is to return as many items
  // as there are input items. In any case, we have to look at all incoming
  // items, and in particular in the COLLECT ... INTO ... case, we have
  // to actually hand on all data anyway, albeit not as separate items.
  // Nevertheless, the optimizer does not do much with AggregateNodes
  // and thus this potential overestimation does not really matter.

  if (_count && _aggregateVariables.empty()) {
    // we are known to only produce a single output row
    nrItems = 1;
  }
  else {
    // we do not know how many rows the COLLECT with produce...
    // the worst case is that there will be as many output rows as input rows
    if (nrItems >= 10) {
      // we assume that the collect will reduce the number of results at least somewhat
      nrItems = static_cast<size_t>(nrItems * 0.80);
    }
  }

  return depCost + nrItems;
}

// Local Variables:
// mode: outline-minor
// outline-regexp: "^\\(/// @brief\\|/// {@inheritDoc}\\|/// @addtogroup\\|// --SECTION--\\|/// @\\}\\)"
// End:


text:
GPad.UndoStack = GPad.Stack.MakeConstructor()
GPad.RedoStack = GPad.Stack.MakeConstructor()


text:
package gedi.util.mutable;

import gedi.util.io.randomaccess.BinaryReader;
import gedi.util.io.randomaccess.BinaryWriter;
import gedi.util.io.randomaccess.FixedSizeBinarySerializable;

import java.io.IOException;

public class MutableByte extends Number implements Comparable<MutableByte>, FixedSizeBinarySerializable, Mutable {
	public byte N;
	public MutableByte() {
	}
	public MutableByte(byte N) {
		this.N = N;
	}
	public MutableByte set(byte N) {
		this.N = N;
		return this;
	}

	@Override
	public String toString() {
		return N+"";
	}
	@Override
	public double doubleValue() {
		return N;
	}
	@Override
	public float floatValue() {
		return N;
	}
	@Override
	public int intValue() {
		return N;
	}
	@Override
	public long longValue() {
		return N;
	}
	@Override
	public int compareTo(MutableByte o) {
		return Byte.compare(N,o.N);
	}
	@Override
	public boolean equals(Object obj) {
		if (!(obj instanceof MutableByte))
			return false;
		MutableByte n = (MutableByte) obj;
		return N==n.N;
	}
	@Override
	public int hashCode() {
		return Byte.hashCode(N);
	}
	@Override
	public void serialize(BinaryWriter out) throws IOException {
		out.put(N);
	}
	@Override
	public void deserialize(BinaryReader in) throws IOException {
		N = in.get();
	}
	@Override
	public int getFixedSize() {
		return Byte.BYTES;
	}
	@Override
	public int size() {
		return 1;
	}
	@SuppressWarnings("unchecked")
	@Override
	public <T> T get(int index) {
		if (index==0) return (T)new Byte(N);
		throw new IndexOutOfBoundsException();
	}
	@SuppressWarnings("unchecked")
	@Override
	public <T> T set(int index, T o) {
		if (index==0) {
			T re = (T)new Byte(N);
			N = (Byte)o;
			return re;
		}
		throw new IndexOutOfBoundsException();
	}
}


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

   static class GSMCallHistoryTest
   {
      const double pricePerMinute = 0.37;

      public static void Test()
      {
         //Creating an instance of the GSM class.
         Battery battery = new Battery(BatteryType.Li_Ion, 50, 20);
         Display display = new Display();
         var gsm = new GSM("2730 Classic", "Nokia", 40, "Pesho", battery, display);

         //Adding few calls.
         gsm.AddCall(DateTime.Now.Date, DateTime.Now, "0888888878", 10.12);
         gsm.AddCall(DateTime.Now.Date, DateTime.Now, "0888888878", 1.00);
         gsm.AddCall(DateTime.Now.Date, DateTime.Now, "0888888878", 5.18);
         gsm.AddCall(DateTime.Now.Date, DateTime.Now, "0888888878", 2.55);
         Console.WriteLine();

         //Displaying the information about the calls.
         gsm.ShowCallHistory();
         Console.WriteLine();

         //Calculating the total price of the calls in the history.
         Console.WriteLine($"{PriceOfCalls(gsm):F2} lv.");
         Console.WriteLine();

         // Removing the longest call from the history and calculate the total price again.
         DeleteLongestCall(gsm);
         Console.WriteLine();

         //Clearing the call history and print it.
         var newPrice = PriceOfCalls(gsm);
         gsm.ClearHistory();
         Console.WriteLine($"{newPrice:F2} lv.");
         Console.WriteLine();
      }

      public static double PriceOfCalls(GSM gsm)
      {
         double result = 0;

         double duration = 0;

         foreach (var item in gsm.CallHistory)
         {
            duration += item.Duration;
         }

         result = duration * pricePerMinute;

         return result;
      }

      public static void DeleteLongestCall(GSM gsm)
      {
         Call longestCall = gsm.CallHistory[0];

         foreach (var item in gsm.CallHistory)
         {
            if (item.Duration > longestCall.Duration)
            {
               longestCall = item;
            }
         }

         gsm.DeleteCall(longestCall);
      }
   }
}


text:
#pragma hdrstop
//---------------------------------------------------------------------------
#pragma argsused
int main(int argc, char* argv[])
{
  char buffer[2048];
  std::string     text_file;
  std::string     output_file;
  char cif[] = "if";
  char cof[] = "of";
  char call[] = "all";
  char cchannel[] = "channel";
  char cheaders[] = "headers";
  fprintf(stdout,"tms32_reader Copyright by Teodor Buchner, Warsaw University of Technology @ 2014\n");

//  if( parse(argc,argv,"ar", NULL) )    use_autoregression = true;
  if( parse(argc,argv,cif, buffer) )
      if(strlen(buffer))         text_file = buffer;
      else
      {        fprintf(stderr,"Input file not defined\n");        return 0;      }
  buffer[0] = 0;
  if( parse(argc,argv,cof, buffer) )//
      if(strlen(buffer))         output_file = buffer;
  buffer[0] = 0;
  TTms32Reader reader(text_file);
  reader.LoadHeaders();
  if( parse(argc,argv,cheaders, NULL) )
  {
    reader.DumpHeaders("DumpTms32Headers.txt");
  }
  reader.LoadSignals();
  if( parse(argc,argv,call, NULL) )
  {
    TMatlabSave::DoSave(reader.getAllSignals(),output_file.c_str());
    //reader.DumpSignals();
  }
  if( parse(argc,argv,cchannel, buffer) )
  {//-channel 0:0:1000
  if(strlen(buffer))
  {               //-win 100:200
    char separator = ':';
    double values[3];   //-channel 0:4950000:5046000     1sec=1600 60 sec = 60*1600 = 96000
    if(3==scan_line_sep(buffer,values,3,separator))
    {
      unsigned int channel = (unsigned int) values[0];
      unsigned int smp_from = (unsigned int) values[1];
      unsigned int smp_to = (unsigned int) values[2];
//  filename = text_resp_file+"rr_by_resp_file.txt";
      if(output_file.empty()) output_file = "dump.txt";
      reader.DumpChannelFromTo(channel,smp_from,smp_to,output_file.c_str());
    }
  }
  }

  return 0;
}


text:
package com.navercorp.pinpoint.web.controller;

import com.navercorp.pinpoint.common.server.cluster.ClusterKey;
import com.navercorp.pinpoint.thrift.dto.TResult;
import com.navercorp.pinpoint.thrift.dto.command.TCommandEcho;
import com.navercorp.pinpoint.thrift.dto.command.TRouteResult;
import com.navercorp.pinpoint.web.cluster.PinpointRouteResponse;
import com.navercorp.pinpoint.web.service.AgentService;
import com.navercorp.pinpoint.web.response.CodeResult;
import org.apache.thrift.TBase;
import org.apache.thrift.TException;
import org.apache.logging.log4j.Logger;
import org.apache.logging.log4j.LogManager;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.server.ResponseStatusException;

import java.util.Objects;

@RestController
@RequestMapping("/command")
public class CommandController {

    // FIX ME: created for a simple ping/pong test for now
    // need a formal set of APIs and proper code

    private final Logger logger = LogManager.getLogger(this.getClass());

    private final AgentService agentService;

    public CommandController(AgentService agentService) {
        this.agentService = Objects.requireNonNull(agentService, "agentService");
    }

    @GetMapping(value = "/echo")
    public CodeResult echo(@RequestParam("applicationName") String applicationName, @RequestParam("agentId") String agentId,
                                          @RequestParam("startTimeStamp") long startTimeStamp, @RequestParam("message") String message) throws TException {

        final ClusterKey clusterKey = agentService.getClusterKey(applicationName, agentId, startTimeStamp);
        if (clusterKey == null) {
            throw new ResponseStatusException(HttpStatus.INTERNAL_SERVER_ERROR, String.format("Can't find suitable PinpointServer(%s/%s/%d).", applicationName, agentId, startTimeStamp));
        }

        TCommandEcho echo = new TCommandEcho();
        echo.setMessage(message);

        try {
            PinpointRouteResponse pinpointRouteResponse = agentService.invoke(clusterKey, echo);
            if (pinpointRouteResponse != null && pinpointRouteResponse.getRouteResult() == TRouteResult.OK) {
                TBase<?, ?> result = pinpointRouteResponse.getResponse();
                if (result == null) {
                    throw new ResponseStatusException(HttpStatus.INTERNAL_SERVER_ERROR, "result null.");
                } else if (result instanceof TCommandEcho) {
                    return CodeResult.ok(((TCommandEcho) result).getMessage());
                } else if (result instanceof TResult) {
                    throw new ResponseStatusException(HttpStatus.INTERNAL_SERVER_ERROR, (((TResult) result).getMessage()));
                } else {
                    throw new ResponseStatusException(HttpStatus.INTERNAL_SERVER_ERROR, result.toString());
                }
            } else {
                throw new ResponseStatusException(HttpStatus.INTERNAL_SERVER_ERROR, "unknown");
            }
        } catch (TException e) {
            throw new ResponseStatusException(HttpStatus.INTERNAL_SERVER_ERROR, e.getMessage());
        }
    }

}


text:
"use strict";

var xtend = require( "xtend" );
var parallel = require( "async" ).parallel;
var path = require( "path" );
var inline = require( "./util" );

module.exports = function( options, callback )
{
    var settings = xtend( {}, inline.defaults, options );

    var replaceUrl = function( callback )
    {
        var args = this;

        if( inline.isBase64Path( args.src ) )
        {
            return callback( null ); // Skip
        }

        inline.getFileReplacement( args.src, settings, function( err, datauriContent )
        {
            if( err )
            {
                return inline.handleReplaceErr( err, args.src, settings.strict, callback );
            }
            if( typeof( args.limit ) === "number" && datauriContent.length > args.limit * 1000 )
            {
                return callback( null ); // Skip
            }

            var css = "url(\"" + datauriContent + "\")";
            var re = new RegExp( "url\\(\\s?[\"']?(" + inline.escapeSpecialChars( args.src ) + ")[\"']?\\s?\\)", "g" );
            result = result.replace( re, () => css );

            return callback( null );
        } );
    };

    var rebase = function( src )
    {
        var css = "url(\"" + path.join( settings.rebaseRelativeTo, src ).replace( /\\/g, "/" ) + "\")";
        var re = new RegExp( "url\\(\\s?[\"']?(" + inline.escapeSpecialChars( src ) + ")[\"']?\\s?\\)", "g" );
        result = result.replace( re, () => css );
    };

    var result = settings.fileContent;
    var tasks = [];
    var found = null;

    var urlRegex = /url\(\s?["']?([^)'"]+)["']?\s?\).*/i;
    var index = 0;

    if( settings.rebaseRelativeTo )
    {
        var matches = {};
        var src;

        while( ( found = urlRegex.exec( result.substring(index) ) ) !== null )
        {
            src = found[ 1 ];
            matches[ src ] = true;
            index = found.index + index + 1;
        }

        for( src in matches )
        {
            if( !inline.isRemotePath( src ) && !inline.isBase64Path( src ) )
            {
                rebase( src );
            }
        }
    }

    var inlineAttributeCommentRegex = new RegExp( "\\/\\*\\s?" + settings.inlineAttribute + "\\s?\\*\\/", "i" );
    var inlineAttributeIgnoreCommentRegex = new RegExp( "\\/\\*\\s?" + settings.inlineAttribute + "-ignore\\s?\\*\\/", "i" );

    index = 0;
    while( ( found = urlRegex.exec( result.substring(index) ) ) !== null )
    {
        if( !inlineAttributeIgnoreCommentRegex.test( found[ 0 ] ) &&
            ( settings.images || inlineAttributeCommentRegex.test( found[ 0 ] ) ) )
        {
            tasks.push( replaceUrl.bind(
            {
                src: found[ 1 ],
                limit: settings.images
            } ) );
        }
        index = found.index + index + 1;
    }

    parallel( tasks, function( err )
    {
        callback( err, result );
    } );
};


text:
<?php

namespace Google\Service\Dataflow;

class DistributionUpdate extends \Google\Model
{
  protected $countType = SplitInt64::class;
  protected $countDataType = '';
  protected $histogramType = Histogram::class;
  protected $histogramDataType = '';
  protected $maxType = SplitInt64::class;
  protected $maxDataType = '';
  protected $minType = SplitInt64::class;
  protected $minDataType = '';
  protected $sumType = SplitInt64::class;
  protected $sumDataType = '';
  public $sumOfSquares;

  /**
   * @param SplitInt64
   */
  public function setCount(SplitInt64 $count)
  {
    $this->count = $count;
  }
  /**
   * @return SplitInt64
   */
  public function getCount()
  {
    return $this->count;
  }
  /**
   * @param Histogram
   */
  public function setHistogram(Histogram $histogram)
  {
    $this->histogram = $histogram;
  }
  /**
   * @return Histogram
   */
  public function getHistogram()
  {
    return $this->histogram;
  }
  /**
   * @param SplitInt64
   */
  public function setMax(SplitInt64 $max)
  {
    $this->max = $max;
  }
  /**
   * @return SplitInt64
   */
  public function getMax()
  {
    return $this->max;
  }
  /**
   * @param SplitInt64
   */
  public function setMin(SplitInt64 $min)
  {
    $this->min = $min;
  }
  /**
   * @return SplitInt64
   */
  public function getMin()
  {
    return $this->min;
  }
  /**
   * @param SplitInt64
   */
  public function setSum(SplitInt64 $sum)
  {
    $this->sum = $sum;
  }
  /**
   * @return SplitInt64
   */
  public function getSum()
  {
    return $this->sum;
  }
  public function setSumOfSquares($sumOfSquares)
  {
    $this->sumOfSquares = $sumOfSquares;
  }
  public function getSumOfSquares()
  {
    return $this->sumOfSquares;
  }
}

// Adding a class alias for backwards compatibility with the previous class name.
class_alias(DistributionUpdate::class, 'Google_Service_Dataflow_DistributionUpdate');


text:
/* $Id: malloc.c,v 1.1.1.1 2006/06/29 06:43:25 cpu Exp $ */

/*
 * Copyright (c) 2000-2002 Opsycon AB  (www.opsycon.se)
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions
 * are met:
 * 1. Redistributions of source code must retain the above copyright
 *    notice, this list of conditions and the following disclaimer.
 * 2. Redistributions in binary form must reproduce the above copyright
 *    notice, this list of conditions and the following disclaimer in the
 *    documentation and/or other materials provided with the distribution.
 * 3. All advertising materials mentioning features or use of this software
 *    must display the following acknowledgement:
 *	This product includes software developed by Opsycon AB.
 * 4. The name of the author may not be used to endorse or promote products
 *    derived from this software without specific prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS
 * OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
 * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
 * ARE DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY
 * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
 * SUCH DAMAGE.
 *
 */

#include <types.h>
#include "libc.h"

typedef double  ALIGN;

int allocsize __P((void *));

union header {
    struct {
	union header   *ptr;
	UINTN        size;
    } s;
    ALIGN           x;
};

typedef union header HEADER;

static HEADER   base;
static HEADER  *allocp;		/* K&R called allocp, freep */

#define NULL   0
#define NALLOC 128

/* The rest of this file is from pages 185-189 of K & R Edition 2 */

static HEADER *morecore __P((UINT32));

void *
malloc(size_t nbytes)
{
	HEADER *p, *q;	/* K&R called q, prevp */
	UINTN nunits;

	nunits = (nbytes + sizeof (HEADER) - 1) / sizeof (HEADER) + 1;
	if ((q = allocp) == NULL) {	/* no free list yet */
		base.s.ptr = allocp = q = &base;
		base.s.size = 0;
	}
	for (p = q->s.ptr;; q = p, p = p->s.ptr) {
		if (p->s.size >= nunits) {	/* big enough */
			if (p->s.size == nunits)	/* exactly */
				q->s.ptr = p->s.ptr;
			else {		/* allocate tail end */
				p->s.size -= nunits;
				p += p->s.size;
				p->s.size = nunits;
			}
			allocp = q;
			return ((char *)(p + 1));
		}
		if (p == allocp)
			if ((p = morecore (nunits)) == NULL) {
				return (NULL);
			}
	}
}

static HEADER  *
morecore(UINT32 nu)
{
	char *cp;
	HEADER *up;
	int rnu;

	rnu = NALLOC * ((nu + NALLOC - 1) / NALLOC);
	cp = sbrk (rnu * sizeof (HEADER));
	if ((int)cp == NULL)
		return (NULL);
	up = (HEADER *) cp;
	up->s.size = rnu;
	free ((char *)(up + 1));
	return (allocp);
}

void
free(void *ap)
{
	HEADER *p, *q;

	p = (HEADER *) ap - 1;
	for (q = allocp; !(p > q && p < q->s.ptr); q = q->s.ptr)
		if (q >= q->s.ptr && (p > q || p < q->s.ptr))
			break;
	if (p + p->s.size == q->s.ptr) {
		p->s.size += q->s.ptr->s.size;
		p->s.ptr = q->s.ptr->s.ptr;
	} else
		p->s.ptr = q->s.ptr;
	if (q + q->s.size == p) {
		q->s.size += p->s.size;
		q->s.ptr = p->s.ptr;
	} else
		q->s.ptr = p;
	allocp = q;
}

int
allocsize(void *ap)
{
	HEADER *p;

	p = (HEADER *) ap - 1;
	return (p->s.size * sizeof (HEADER));
}


text:
<?php

namespace Site\Factory\Action;

use Core\Action\ViewActionResult;
use Core\Service\MotFrontendIdentityProviderInterface;
use Dvsa\Mot\Frontend\PersonModule\View\ContextProvider;
use DvsaClient\MapperFactory;
use DvsaCommon\Csv\MotTestLogCsvGenerator;
use Interop\Container\ContainerInterface;
use Zend\Mvc\Router\Http\RouteMatch;
use Zend\ServiceManager\FactoryInterface;
use Site\Action\MotTestLog\IndexAction as SiteIndexAction;
use Site\Action\MotTestLog\CsvAction as SiteCsvAction;
use Zend\ServiceManager\ServiceLocatorInterface;

class MotTestLogActionFactory implements FactoryInterface
{
    /**
     * @param ServiceLocatorInterface $serviceLocator
     */
    public function createService(ServiceLocatorInterface $serviceLocator)
    {
        return $this($serviceLocator, MotTestLogActionFactory::class);
    }

    public function __invoke(ContainerInterface $container, $requestedName, array $options = null)
    {
        /** @var RouteMatch $routeMatch */
        $routeMatch = $container->get('Application')->getMvcEvent()->getRouteMatch();
        $action = $routeMatch->getParam('action');

        if ($action === 'downloadCsv') {
            return new SiteCsvAction(
                $container->get('Request'),
                $container->get(MapperFactory::class),
                $container->get(ContextProvider::class),
                new MotTestLogCsvGenerator()
            );
        }

        return new SiteIndexAction(
            $container->get(MotFrontendIdentityProviderInterface::class),
            $container->get('Request'),
            $container->get(MapperFactory::class),
            $container->get(ContextProvider::class),
            new ViewActionResult(),
            $container->get('AuthorisationService')
        );
    }
}


text:
DESKTOP = 'desktop'
MOBILE = 'mobile'

ALL_PLATFORMS = frozenset({DESKTOP, MOBILE})

# Use the constants below to mark on which platforms the story has WPR
# recordings. To disable a story (e.g. because it crashes or takes too long),
# use @decorators.Disabled instead.
DESKTOP_ONLY = frozenset({DESKTOP})
MOBILE_ONLY = frozenset({MOBILE})
NO_PLATFORMS = frozenset()


text:
<!DOCTYPE html>

    <title>Forms</title>

    <link href="bootstrap.css" rel="stylesheet" />
    <link href="bootstrap-theme.css" rel="stylesheet" />

        <form name="myForm" novalidate ng-submit="addUser(newUser)">

                    Email:
                    <input name="userEmail" type="email" class="form-control"
                           required ng-model="newUser.email">

                            Please enter a valid email address

                            Please enter a value

                <button type="submit" class="btn btn-primary btn-block"
                        ng-disabled="myForm.$invalid">OK</button>

        </form>


text:
LAB = $(notdir $(PWD))

all: handout handout-tarfile

handout:
	# Rebuild the handout directory that students download
	(rm -rf $(LAB)-handout; mkdir $(LAB)-handout)
	cp -p src/Makefile-handout $(LAB)-handout/Makefile
	cp -p src/README-handout $(LAB)-handout/README
	cp -p src/hello.c-handout $(LAB)-handout/hello.c
	cp -p src/driver.sh $(LAB)-handout

handout-tarfile: handout
	# Build *-handout.tar and autograde.tar
	tar cvf $(LAB)-handout.tar $(LAB)-handout
	cp -p $(LAB)-handout.tar autograde.tar

clean:
	# Clean the entire lab directory tree.  Note that you can run
	# "make clean; make" at any time while the lab is live with no
	# adverse effects.
	rm -f *~ *.tar
	(cd src; make clean)
	(cd test-autograder; make clean)
	rm -rf $(LAB)-handout
	rm -f autograde.tar
#
# CAREFULL!!! This will delete all student records in the logfile and
# in the handin directory. Don't run this once the lab has started.
# Use it to clean the directory when you are starting a new version
# of the lab from scratch, or when you are debugging the lab prior
# to releasing it to the students.
#
cleanallfiles:
	# Reset the lab from scratch.
	make clean
	rm -f log.txt
	rm -rf handin/*


text:
void Ground::update()
{
    if (!inited)
    {
        fill();
        inited = true;
    }
}

void Ground::render(const WorldPainter& worldPainter) const
{
    for (int row = 0; row < Config::World::HEIGHT_CELL; ++row)
        for (int col = 0; col < Config::World::WIDTH_CELL; ++col)
            renderCell(worldPainter, col, row, cells[row][col]);
}

void Ground::fill()
{
    for (int row = 0; row < Config::World::HEIGHT_CELL; ++row)
        for (int col = 0; col < Config::World::WIDTH_CELL; ++col)
            cells[row][col] = 0;

    for (int row = 0; row < Config::World::HEIGHT_CELL; row += BIG_CELL)
        for (int col = 0; col < Config::World::WIDTH_CELL; col += BIG_CELL)
            cells[row][col] = 1;

    for (int row = BIG_CELL; row < Config::World::HEIGHT_CELL - BIG_CELL; row += BIG_CELL)
        for (int col = BIG_CELL; col < Config::World::WIDTH_CELL - BIG_CELL; col += BIG_CELL)
            cells[row][col] = 2;
}

void Ground::renderCell(const WorldPainter& worldPainter, int col, int row, int cell) const
{
    if (cell)
    {
        col = col * Config::World::CELL_SIZE;
        row = row * Config::World::CELL_SIZE;
        worldPainter.drawUnordered(Vec2(col, row), getCellTexture(cell));
    }
}

std::string Ground::getCellTexture(int cell) const
{
    switch (cell)
    {
        case 1:
            return "assets/tiles/grass.png";
        case 2:
            return "assets/tiles/concrete.png";
        default:
            ;
    }
    return std::string();
}


text:
ACCEPTED

#### According to
Index Fungorum

#### Published in
Anal. Soc. cient. argent. 12(3): 102 (1881)

#### Original name
Meliola brasiliensis Speg.

### Remarks
null


text:
// ----- this file has been automatically generated - do not edit
import { DataType, Variant } from "node-opcua-variant"
import { LocalizedText } from "node-opcua-data-model"
import { UInt32, UInt16, UAString } from "node-opcua-basic-types"
import { UAOrderedList, UAOrderedList_Base } from "node-opcua-nodeset-ua/source/ua_ordered_list"
import { EnumPartQuality } from "./enum_part_quality"
import { EnumProcessIrregularity } from "./enum_process_irregularity"
/**
 * |                |                                                  |
 * |----------------|--------------------------------------------------|
 * |namespace       |http://opcfoundation.org/UA/MachineTool/          |
 * |nodeClass       |ObjectType                                        |
 * |typedDefinition |10:ProductionJobListType ns=10;i=30               |
 * |isAbstract      |false                                             |
 */
export type UAProductionJobList_Base = UAOrderedList_Base;
export interface UAProductionJobList extends Omit<UAOrderedList, "$OrderedObject$">, UAProductionJobList_Base {
}


text:
#pragma once

#include <map>
#include "Reprise/Common.h"

namespace OPS
{
namespace Shared
{
	typedef std::map<const Reprise::RepriseBase*, Reprise::RepriseBase*>	RepriseReferenceMap;

	/** Функция позволяет для двух одинаковых деревьев найти
	   соответствующие друг другу объекты в них.
	   \param left, right - одинаковые деревья
	   \param refMap - map: ключи - для которых нужно найти соответсвие,
							значения - соответсвия
	**/
	void mapReferences(const Reprise::RepriseBase& left,
					   Reprise::RepriseBase& right,
					   RepriseReferenceMap& refMap);

	/** Функция делает то же самое, что и mapReferences(), но для
	  одного объекта. Эта просто обертка над mapReferences() - не используйте
	  её если у вас несколько объектов.
	**/
	Reprise::RepriseBase* mapReference(const Reprise::RepriseBase& left,
									   Reprise::RepriseBase& right,
									   const Reprise::RepriseBase& sourceObject);
}
}


text:
import os
import sys
sys.path.insert(0, os.path.abspath('../../pyCGM_Single')) #TODO this will need to be updated when folder changes

# -- Project information -----------------------------------------------------

project = 'pycgm'
copyright = '2020, Mathew Schwartz'
author = 'Mathew Schwartz'

# The full version, including alpha/beta/rc tags
release = '1.0.0'

# TODO Switch to this
# from pycgm import _about
# release = _about.__version__

# -- General configuration ---------------------------------------------------

# Add any Sphinx extension module names here, as strings. They can be
# extensions coming with Sphinx (named 'sphinx.ext.*') or your custom
# ones.
extensions = ['sphinx.ext.autodoc', 'sphinx.ext.imgmath', 'numpydoc',
              'sphinx.ext.intersphinx', 'sphinx.ext.coverage',
              'sphinx.ext.autosummary', 'sphinx.ext.doctest']

# Ignoring automatic scipy imports
nitpick_ignore = [('py:obj', 'buttord'), ('py:obj', 'buttap'), ('py:obj', 'sosfiltfilt'),
                ('py:obj', 'lfilter_zi'), ('py:obj', 'lfilter'), ('py:obj', 'lfiltic'),
                ('py:obj', 'savgol_filter'), ('py:obj', 'sosfilt')]

# Add any paths that contain templates here, relative to this directory.
templates_path = ['_templates']

# List of patterns, relative to source directory, that match files and
# directories to ignore when looking for source files.
# This pattern also affects html_static_path and html_extra_path.
exclude_patterns = []

# -----------------------------------------------------------------------------
# Sphinx autodoc options
# -----------------------------------------------------------------------------

autoclass_content = 'class'
autodoc_member_order = 'groupwise'

# -----------------------------------------------------------------------------
# Autosummary
# -----------------------------------------------------------------------------

autosummary_imported_members = True
autosummary_generate = True
autosummary_generate_overwrite = True
numpydoc_show_class_members = False

# -- Options for HTML output -------------------------------------------------

# The theme to use for HTML and HTML Help pages.  See the documentation for
# a list of builtin themes.
#
html_theme = 'alabaster'

# Add any paths that contain custom static files (such as style sheets) here,
# relative to this directory. They are copied after the builtin static files,
# so a file named "default.css" will overwrite the builtin "default.css".
html_static_path = ['_static']


text:
<?php

use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use REBELinBLUE\Deployer\Command;

class CreateCommandsTable extends Migration
{
    /**
     * Run the migrations.
     */
    public function up()
    {
        Schema::create('commands', function (Blueprint $table) {
            $table->increments('id');
            $table->string('name');
            $table->text('user');
            $table->text('script');
            $table->unsignedInteger('project_id');
            $table->enum('step', [Command::BEFORE_CLONE, Command::AFTER_CLONE,
                                  Command::BEFORE_INSTALL, Command::AFTER_INSTALL,
                                  Command::BEFORE_ACTIVATE, Command::AFTER_ACTIVATE,
                                  Command::BEFORE_PURGE, Command::AFTER_PURGE, ])->default(Command::AFTER_INSTALL);
            $table->unsignedInteger('order')->default('0');
            $table->timestamps();
            $table->softDeletes();
            $table->foreign('project_id')->references('id')->on('projects');
        });
    }

    /**
     * Reverse the migrations.
     */
    public function down()
    {
        Schema::drop('commands');
    }
}


text: export { MagicWandFilled24 as default } from "../../";


text:
package stormlantern.consul.client.dao

import java.util.UUID

import org.parboiled.common.Base64
import spray.json._

import scala.util.control.NonFatal

trait ConsulHttpProtocol extends DefaultJsonProtocol {

  implicit val uuidFormat = new JsonFormat[UUID] {
    override def read(json: JsValue): UUID = json match {
      case JsString(uuid) => try {
        UUID.fromString(uuid)
      } catch {
        case NonFatal(e) => deserializationError("Expected UUID, but got " + uuid)
      }
      case x => deserializationError("Expected UUID as JsString, but got " + x)
    }

    override def write(obj: UUID): JsValue = JsString(obj.toString)
  }

  implicit val binaryDataFormat = new JsonFormat[BinaryData] {
    override def read(json: JsValue): BinaryData = json match {
      case JsString(data) => try {
        BinaryData(Base64.rfc2045().decode(data))
      } catch {
        case NonFatal(e) => deserializationError("Expected base64 encoded binary data, but got " + data)
      }
      case x => deserializationError("Expected base64 encoded binary data as JsString, but got " + x)
    }

    override def write(obj: BinaryData): JsValue = JsString(Base64.rfc2045().encodeToString(obj.data, false))
  }

  implicit val serviceFormat = jsonFormat(
    (node: String, address: String, serviceId: String, serviceName: String, serviceTags: Option[Set[String]], serviceAddress: String, servicePort: Int) =>
      ServiceInstance(node, address, serviceId, serviceName, serviceTags.getOrElse(Set.empty), serviceAddress, servicePort),
    "Node", "Address", "ServiceID", "ServiceName", "ServiceTags", "ServiceAddress", "ServicePort")
  implicit val httpCheckFormat = jsonFormat(HttpHealthCheck, "HTTP", "Interval")
  implicit val scriptCheckFormat = jsonFormat(ScriptHealthCheck, "Script", "Interval")
  implicit val ttlCheckFormat = jsonFormat(TTLHealthCheck, "TTL")
  implicit val checkWriter = lift {
    new JsonWriter[HealthCheck] {
      override def write(obj: HealthCheck): JsValue = obj match {
        case obj: ScriptHealthCheck => obj.toJson
        case obj: HttpHealthCheck => obj.toJson
        case obj: TTLHealthCheck => obj.toJson
      }
    }
  }
  implicit val serviceRegistrationFormat = jsonFormat(ServiceRegistration, "Name", "ID", "Tags", "Address", "Port", "Check")
  implicit val sessionCreationFormat = jsonFormat(SessionCreation, "LockDelay", "Name", "Node", "Checks", "Behavior", "TTL")
  implicit val keyDataFormat = jsonFormat(KeyData, "Key", "CreateIndex", "ModifyIndex", "LockIndex", "Flags", "Value", "Session")
  implicit val sessionInfoFormat = jsonFormat(SessionInfo, "LockDelay", "Checks", "Node", "ID", "CreateIndex", "Name", "Behavior", "TTL")
}


text:
set -e
set -x

# install needed packages
yum update -y
yum install docker git -y

# disable selinux (not playing well with docker/pgsql)
setenforce 0
cat >/etc/selinux/config <<EOF
SELINUX=enforcing
SELINUXTYPE=targeted
EOF

# setup the docker service
service docker start
chkconfig --level 345 docker on

# anonymously clone discourse docker
cd /var/
git clone https://github.com/discourse/discourse_docker.git discourse
cd discourse

# setup instance from provided env variables

cp samples/standalone.yml containers/app.yml -f -y

sed -i s/DISCOURSE_SMTP_ADDRESS:\ smtp.example.com/DISCOURSE_SMTP_ADDRESS:\ "$SMTP_SERVER"/g containers/app.yml
sed -i s/\#DISCOURSE_SMTP_PORT:\ 587/DISCOURSE_SMTP_PORT:\ "$SMTP_PORT"/g containers/app.yml
sed -i s/\#DISCOURSE_SMTP_USER_NAME:\ user@example.com/DISCOURSE_SMTP_USER_NAME:\ "$SMTP_USER"/g containers/app.yml
sed -i s/\#DISCOURSE_SMTP_PASSWORD:\ pa\$\$word/DISCOURSE_SMTP_PASSWORD:\ "$SMTP_PASSWORD"/g containers/app.yml
sed -i s/DISCOURSE_HOSTNAME:\ \'discourse.example.com\'/DISCOURSE_HOSTNAME:\ \'"$DOMAIN_NAME"\'/g containers/app.yml
sed -i s/DISCOURSE_DEVELOPER_EMAILS:\ \'me@example.com\'/DISCOURSE_DEVELOPER_EMAILS:\ \'"$ADMIN_EMAIL"\'/g containers/app.yml
sed -i s/LANG:\ en_US.UTF-8/LANG:\ es_ES.UTF-8/g containers/app.yml

# bootstrap and start

./launcher bootstrap app
./launcher start app

# TODO(mangelajo): create admin user

./launcher ssh app <<EOF
rails c
User.find_by_email('miguelangel@ajo.es')
EOF

# (in rails console)
#> me = User.find_by_username_or_email('myemailaddress@me.com')
#> me.activate #use this in case you haven't configured your mail server and therefore can't receive the activation mail.
#> me.admin = true
#u=User.where(:email => 'usermail@gmail.com').first
#u.password='userpassword'
#u.password_confirmation='userpassword'
#u.save!
#> me.save


text:
#include "modules/audio_coding/neteq/tools/neteq_performance_test.h"

#include "api/audio/audio_frame.h"
#include "api/audio_codecs/builtin_audio_decoder_factory.h"
#include "api/neteq/neteq.h"
#include "modules/audio_coding/codecs/pcm16b/pcm16b.h"
#include "modules/audio_coding/neteq/default_neteq_factory.h"
#include "modules/audio_coding/neteq/tools/audio_loop.h"
#include "modules/audio_coding/neteq/tools/rtp_generator.h"
#include "rtc_base/checks.h"
#include "system_wrappers/include/clock.h"
#include "test/testsupport/file_utils.h"

using webrtc::NetEq;
using webrtc::test::AudioLoop;
using webrtc::test::RtpGenerator;

namespace webrtc {
namespace test {

int64_t NetEqPerformanceTest::Run(int runtime_ms,
                                  int lossrate,
                                  double drift_factor) {
  const std::string kInputFileName =
      webrtc::test::ResourcePath("audio_coding/testfile32kHz", "pcm");
  const int kSampRateHz = 32000;
  const std::string kDecoderName = "pcm16-swb32";
  const int kPayloadType = 95;

  // Initialize NetEq instance.
  NetEq::Config config;
  config.sample_rate_hz = kSampRateHz;
  webrtc::Clock* clock = webrtc::Clock::GetRealTimeClock();
  auto audio_decoder_factory = CreateBuiltinAudioDecoderFactory();
  auto neteq =
      DefaultNetEqFactory().CreateNetEq(config, audio_decoder_factory, clock);
  // Register decoder in |neteq|.
  if (!neteq->RegisterPayloadType(kPayloadType,
                                  SdpAudioFormat("l16", kSampRateHz, 1)))
    return -1;

  // Set up AudioLoop object.
  AudioLoop audio_loop;
  const size_t kMaxLoopLengthSamples = kSampRateHz * 10;  // 10 second loop.
  const size_t kInputBlockSizeSamples = 60 * kSampRateHz / 1000;  // 60 ms.
  if (!audio_loop.Init(kInputFileName, kMaxLoopLengthSamples,
                       kInputBlockSizeSamples))
    return -1;

  int32_t time_now_ms = 0;

  // Get first input packet.
  RTPHeader rtp_header;
  RtpGenerator rtp_gen(kSampRateHz / 1000);
  // Start with positive drift first half of simulation.
  rtp_gen.set_drift_factor(drift_factor);
  bool drift_flipped = false;
  int32_t packet_input_time_ms =
      rtp_gen.GetRtpHeader(kPayloadType, kInputBlockSizeSamples, &rtp_header);
  auto input_samples = audio_loop.GetNextBlock();
  if (input_samples.empty())
    exit(1);
  uint8_t input_payload[kInputBlockSizeSamples * sizeof(int16_t)];
  size_t payload_len = WebRtcPcm16b_Encode(input_samples.data(),
                                           input_samples.size(), input_payload);
  RTC_CHECK_EQ(sizeof(input_payload), payload_len);

  // Main loop.
  int64_t start_time_ms = clock->TimeInMilliseconds();
  AudioFrame out_frame;
  while (time_now_ms < runtime_ms) {
    while (packet_input_time_ms <= time_now_ms) {
      // Drop every N packets, where N = FLAG_lossrate.
      bool lost = false;
      if (lossrate > 0) {
        lost = ((rtp_header.sequenceNumber - 1) % lossrate) == 0;
      }
      if (!lost) {
        // Insert packet.
        int error = neteq->InsertPacket(rtp_header, input_payload);
        if (error != NetEq::kOK)
          return -1;
      }

      // Get next packet.
      packet_input_time_ms = rtp_gen.GetRtpHeader(
          kPayloadType, kInputBlockSizeSamples, &rtp_header);
      input_samples = audio_loop.GetNextBlock();
      if (input_samples.empty())
        return -1;
      payload_len = WebRtcPcm16b_Encode(input_samples.data(),
                                        input_samples.size(), input_payload);
      RTC_DCHECK_EQ(payload_len, kInputBlockSizeSamples * sizeof(int16_t));
    }

    // Get output audio, but don't do anything with it.
    bool muted;
    int error = neteq->GetAudio(&out_frame, &muted);
    RTC_CHECK(!muted);
    if (error != NetEq::kOK)
      return -1;

    RTC_DCHECK_EQ(out_frame.samples_per_channel_, (kSampRateHz * 10) / 1000);

    static const int kOutputBlockSizeMs = 10;
    time_now_ms += kOutputBlockSizeMs;
    if (time_now_ms >= runtime_ms / 2 && !drift_flipped) {
      // Apply negative drift second half of simulation.
      rtp_gen.set_drift_factor(-drift_factor);
      drift_flipped = true;
    }
  }
  int64_t end_time_ms = clock->TimeInMilliseconds();
  return end_time_ms - start_time_ms;
}

}  // namespace test
}  // namespace webrtc


text:
<?xml version="1.0"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
  <modelVersion>4.0.0</modelVersion>
  <groupId>fr.turri</groupId>
  <artifactId>dokujclient</artifactId>
  <packaging>jar</packaging>
  <version>3.9.10-SNAPSHOT</version>
  <name>${project.groupId}:${project.artifactId}</name>
  <description>Library to use the xmlrpc interface of Dokuwiki</description>
  <url>http://turri.fr/dokujclient</url>
  <licenses>
    <license>
      <name>The Apache License, Version 2.0</name>
      <url>http://www.apache.org/licenses/LICENSE-2.0.txt</url>
    </license>
  </licenses>
  <developers>
    <developer>
      <name>Guillaume Turri</name>
      <email>guillaume.turri@gmail.com</email>
    </developer>
  </developers>
  <scm>
    <connection>scm:git:https://github.com/gturri/dokuJClient.git</connection>
    <developerConnection>scm:git:git@github.com:gturri/dokuJClient.git</developerConnection>
    <url>https://github.com/gturri/DokuJClient</url>
    <tag>HEAD</tag>
  </scm>
  <properties>
    <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
    <maven.compiler.source>1.6</maven.compiler.source>
    <maven.compiler.target>1.6</maven.compiler.target>
  </properties>
  <dependencies>
    <dependency>
      <groupId>com.github.tomakehurst</groupId>
      <artifactId>wiremock-jre8</artifactId>
      <version>2.28.0</version>
      <scope>test</scope>
    </dependency>
    <dependency>
      <groupId>com.google.guava</groupId>
      <artifactId>guava</artifactId>
      <version>30.1.1-jre</version>
    </dependency>
    <dependency>
      <groupId>fr.turri</groupId>
      <artifactId>aXMLRPC</artifactId>
      <version>1.12.0</version>
    </dependency>
    <dependency>
      <groupId>junit</groupId>
      <artifactId>junit</artifactId>
      <version>4.13.2</version>
      <scope>test</scope>
    </dependency>
    <dependency>
      <groupId>junit-addons</groupId>
      <artifactId>junit-addons</artifactId>
      <version>1.4</version>
      <scope>test</scope>
    </dependency>
    <dependency>
      <groupId>org.mockito</groupId>
      <artifactId>mockito-all</artifactId>
      <version>1.10.19</version>
      <scope>test</scope>
    </dependency>
    <dependency>
      <groupId>com.martiansoftware</groupId>
      <artifactId>jsap</artifactId>
      <version>2.1</version>
    </dependency>
  </dependencies>
  <reporting>
    <plugins>
      <plugin>
        <groupId>org.apache.maven.plugins</groupId>
        <artifactId>maven-surefire-report-plugin</artifactId>
        <version>3.0.0-M5</version>
      </plugin>
      <plugin>
        <groupId>org.codehaus.mojo</groupId>
        <artifactId>cobertura-maven-plugin</artifactId>
        <version>2.7</version>
      </plugin>
      <plugin>
        <groupId>org.apache.maven.plugins</groupId>
        <artifactId>maven-javadoc-plugin</artifactId>
        <version>3.3.1</version>
        <reportSets>
          <reportSet>
            <reports>
              <report>javadoc</report>
            </reports>
            <configuration>
              <destDir>doc-${project.version}</destDir>
            </configuration>
          </reportSet>
        </reportSets>
      </plugin>
      <plugin>
        <groupId>org.codehaus.mojo</groupId>
        <artifactId>findbugs-maven-plugin</artifactId>
        <version>3.0.5</version>
      </plugin>
      <plugin>
        <groupId>org.apache.maven.plugins</groupId>
        <artifactId>maven-project-info-reports-plugin</artifactId>
        <version>3.1.2</version>
      </plugin>
    </plugins>
  </reporting>
  <build>
    <pluginManagement>
      <plugins>
        <plugin>
          <groupId>org.apache.maven.plugins</groupId>
          <artifactId>maven-release-plugin</artifactId>
          <version>3.0.0-M4</version>
          <configuration>
            <useReleaseProfile>false</useReleaseProfile>
            <releaseProfiles>release</releaseProfiles>
            <goals>deploy</goals>
          </configuration>
        </plugin>
      </plugins>
    </pluginManagement>
    <plugins>
      <plugin>
        <groupId>org.apache.maven.plugins</groupId>
        <artifactId>maven-site-plugin</artifactId>
        <version>3.9.1</version>
      </plugin>
      <plugin>
        <groupId>org.apache.maven.plugins</groupId>
        <artifactId>maven-jar-plugin</artifactId>
        <version>3.2.0</version>
        <configuration>
          <archive>
            <manifest>
              <addClasspath>true</addClasspath>
            </manifest>
          </archive>
        </configuration>
      </plugin>
      <plugin>
        <groupId>org.pitest</groupId>
        <artifactId>pitest-maven</artifactId>
        <version>1.6.6</version>
        <configuration>
          <targetClasses>
            <param>dw*</param>
          </targetClasses>
          <targetTests>
            <param>dw*</param>
          </targetTests>
          <excludedClasses>
            <excludedClass>dw.cli.PasswordReader</excludedClass>
          </excludedClasses>
        </configuration>
      </plugin>
      <plugin>
        <groupId>org.sonatype.plugins</groupId>
        <artifactId>nexus-staging-maven-plugin</artifactId>
        <version>1.6.8</version>
        <extensions>true</extensions>
        <configuration>
          <serverId>ossrh</serverId>
          <nexusUrl>https://oss.sonatype.org/</nexusUrl>
          <autoReleaseAfterClose>true</autoReleaseAfterClose>
        </configuration>
      </plugin>
      <plugin>
        <groupId>org.apache.maven.plugins</groupId>
        <artifactId>maven-javadoc-plugin</artifactId>
        <version>3.3.1</version>
        <executions>
          <execution>
            <id>attach-javadocs</id>
            <goals>
              <goal>jar</goal>
            </goals>
          </execution>
        </executions>
      </plugin>
      <plugin>
        <groupId>org.apache.maven.plugins</groupId>
        <artifactId>maven-assembly-plugin</artifactId>
        <version>3.3.0</version>
        <configuration>
          <descriptors>
            <descriptor>scripts/descriptorRef.xml</descriptor>
          </descriptors>
        </configuration>
        <executions>
          <execution>
            <phase>package</phase>
            <goals>
              <goal>single</goal>
            </goals>
          </execution>
        </executions>
      </plugin>
      <plugin>
        <groupId>org.apache.maven.plugins</groupId>
        <artifactId>maven-dependency-plugin</artifactId>
        <version>3.1.2</version>
        <executions>
          <execution>
            <goals>
              <goal>copy-dependencies</goal>
            </goals>
            <configuration>
              <includeScope>runtime</includeScope>
            </configuration>
          </execution>
        </executions>
        <configuration>
          <outputDirectory>${project.build.directory}</outputDirectory>
        </configuration>
      </plugin>
      <plugin>
        <groupId>org.apache.maven.plugins</groupId>
        <artifactId>maven-antrun-plugin</artifactId>
        <version>3.0.0</version>
        <executions>
            <execution>
                <id>process-test-classes</id>
                <phase>process-test-classes</phase>
                <configuration>
                    <target>
                        <chmod file="target/classes/dokujclient" perm="755" />
                    </target>
                </configuration>
                <goals>
                    <goal>run</goal>
                </goals>
            </execution>
        </executions>
     </plugin>
     <plugin>
       <groupId>com.soebes.maven.plugins</groupId>
       <artifactId>maven-echo-plugin</artifactId>
       <version>0.1</version>
       <executions>
         <execution>
           <phase>process-test-classes</phase>
           <goals>
             <goal>echo</goal>
           </goals>
         </execution>
       </executions>
       <configuration>
         <echos>
           <echo>*** If most tests fail, make sure you've installed the fake wiki. See README for more info ***</echo>
         </echos>
       </configuration>
     </plugin>
     <plugin>
       <groupId>org.apache.maven.plugins</groupId>
       <artifactId>maven-surefire-plugin</artifactId>
       <version>3.0.0-M5</version>
       <executions>
           <execution>
               <id>skip-tests-pre-warning</id>
               <configuration>
                   <skip>true</skip>
               </configuration>
           </execution>
           <execution>
               <id>actual-tests</id>
               <phase>test</phase>
               <goals>
                   <goal>test</goal>
               </goals>
           </execution>
       </executions>
     </plugin>
  </plugins>
    <resources>
      <resource>
        <directory>src/main/resources</directory>
        <filtering>true</filtering>
      </resource>
    </resources>
  </build>
  <profiles>
    <profile>
      <id>release</id>
      <build>
        <plugins>
          <plugin>
            <groupId>org.apache.maven.plugins</groupId>
            <artifactId>maven-source-plugin</artifactId>
            <version>3.2.1</version>
            <executions>
              <execution>
                <id>attach-sources</id>
                <goals>
                  <goal>jar-no-fork</goal>
                </goals>
              </execution>
            </executions>
          </plugin>
          <plugin>
            <groupId>org.apache.maven.plugins</groupId>
            <artifactId>maven-javadoc-plugin</artifactId>
            <version>3.3.1</version>
            <executions>
              <execution>
                <id>attach-javadocs</id>
                <goals>
                  <goal>jar</goal>
                </goals>
              </execution>
            </executions>
          </plugin>
          <plugin>
            <groupId>org.apache.maven.plugins</groupId>
            <artifactId>maven-gpg-plugin</artifactId>
            <version>3.0.1</version>
            <executions>
              <execution>
                <id>sign-artifacts</id>
                <phase>verify</phase>
                <goals>
                  <goal>sign</goal>
                </goals>
              </execution>
            </executions>
          </plugin>
        </plugins>
      </build>
    </profile>
  </profiles>
  <distributionManagement>
    <snapshotRepository>
      <id>ossrh</id>
      <url>https://oss.sonatype.org/content/repositories/snapshots</url>
    </snapshotRepository>
    <repository>
      <id>ossrh</id>
      <url>https://oss.sonatype.org/service/local/staging/deploy/maven2/</url>
    </repository>
  </distributionManagement>
</project>


text:
module VagrantPlugins
  module Parallels
    module Action
      class SetupPackageFiles
        def initialize(app, env)
          @app = app

          env["package.include"] ||= []
          env["package.vagrantfile"] ||= nil
        end

        def call(env)
          files = {}
          env["package.include"].each do |file|
            source = Pathname.new(file)

            # If the source is relative then we add the file as-is to the include
            # directory. Otherwise, we copy only the file into the root of the
            # include directory. Kind of strange, but seems to match what people
            # expect based on history.
            if source.relative?
              dest = source
            else
              dest = source.basename
            end

            # Assign the mapping
            files[file] = dest
          end

          if env["package.vagrantfile"]
            # Vagrantfiles are treated special and mapped to a specific file
            files[env["package.vagrantfile"]] = "_Vagrantfile"
          end

          # Verify the mapping
          files.each do |from, _|
            raise Vagrant::Errors::PackageIncludeMissing,
              :file => from if !File.exist?(from)
          end

          # Save the mapping
          env["package.files"] = files

          @app.call(env)
        end
      end
    end
  end
end


text:
package org.wso2.carbon.apimgt.impl.notifier.events;

import java.util.Map;
import java.util.Objects;

/**
 * An Event Object which can holds the data related to Application which are required
 * for the validation purpose in a gateway.
 */
public class ApplicationEvent extends Event {
    private String uuid;
    private int applicationId;
    private String applicationName;
    private String tokenType;
    private String applicationPolicy;
    private String groupId;
    private Map<String,String> attributes;
    private String subscriber;

    public ApplicationEvent(String eventId, long timestamp, String type, int tenantId, String tenantDomain,
                            int applicationId, String uuid, String applicationName, String tokenType,
            String applicationPolicy, String groupId, Map<String, String> attributes, String subscriber) {
        this.eventId = eventId;
        this.timeStamp = timestamp;
        this.type = type;
        this.tenantId = tenantId;
        this.applicationId = applicationId;
        this.uuid = uuid;
        this.applicationName = applicationName;
        this.tokenType = tokenType;
        this.applicationPolicy = applicationPolicy;
        this.groupId = groupId;
        this.tenantDomain = tenantDomain;
        this.attributes = attributes;
        this.subscriber = subscriber;
    }

    @Override
    public String toString() {
        return "ApplicationEvent{" +
                "applicationId=" + applicationId +
                ", applicationName='" + applicationName + '\'' +
                ", tokenType='" + tokenType + '\'' +
                ", applicationPolicy='" + applicationPolicy + '\'' +
                ", groupId='" + groupId + '\'' +
                ", eventId='" + eventId + '\'' +
                ", timeStamp=" + timeStamp +
                ", type='" + type + '\'' +
                ", tenantId=" + tenantId + '\'' +
                ", tenantDomain=" + tenantDomain +
                ", subscriber=" + subscriber +
                '}';
    }

    @Override
    public boolean equals(Object o) {
        if (this == o) return true;
        if (!(o instanceof ApplicationEvent)) return false;
        ApplicationEvent that = (ApplicationEvent) o;
        return getApplicationId() == that.getApplicationId() &&
                getApplicationName().equals(that.getApplicationName()) &&
                getTokenType().equals(that.getTokenType()) &&
                getGroupId().equals(that.getGroupId()) &&
                getApplicationPolicy().equals(that.getApplicationPolicy());
    }

    @Override
    public int hashCode() {
        return Objects.hash(getApplicationId(), getApplicationName(), getTokenType(), getApplicationPolicy(), getGroupId());
    }

    public int getApplicationId() {
        return applicationId;
    }

    public void setApplicationId(int applicationId) {
        this.applicationId = applicationId;
    }

    public String getApplicationName() {
        return applicationName;
    }

    public void setApplicationName(String applicationName) {
        this.applicationName = applicationName;
    }

    public String getTokenType() {
        return tokenType;
    }

    public void setTokenType(String tokenType) {
        this.tokenType = tokenType;
    }

    public String getApplicationPolicy() {
        return applicationPolicy;
    }

    public void setApplicationPolicy(String applicationPolicy) {
        this.applicationPolicy = applicationPolicy;
    }

    public String getGroupId() {
        return groupId;
    }

    public void setGroupId(String groupId) {
        this.groupId = groupId;
    }

    public Map<String, String> getAttributes() {

        return attributes;
    }

    public void setAttributes(Map<String, String> attributes) {

        this.attributes = attributes;
    }

    public String getUuid() {

        return uuid;
    }

    public void setUuid(String uuid) {

        this.uuid = uuid;
    }

    public String getSubscriber() {
        return subscriber;
    }

    public void setSubscriber(String subscriber) {
        this.subscriber = subscriber;
    }
}


text:
{% if help_text_inline and not error_text_inline %}
    {% include 'uikit/layout/help_text.html' %}
{% endif %}

{% if error_text_inline %}
    {% include 'uikit/layout/field_errors.html' %}
{% else %}
    {% include 'uikit/layout/field_errors_block.html' %}
{% endif %}

{% if not help_text_inline %}
    {% include 'uikit/layout/help_text.html' %}
{% endif %}


text:
using System;
using System.Collections.Generic;
using System.Text;

namespace lpp.EnumHelper
{
    // <summary>
    /// 自定义枚举基础类
    /// </summary>
    public abstract class BaseEnum
    {
        public int Value { get; private set; }
        public string Str { get; private set; }

        protected BaseEnum(int value, string str)
        {
            Value = value;
            Str = str;
        }

        public static Dictionary<int, string> ToDic(List<BaseEnum> baseEnums)
        {
            Dictionary<int, string> dic = new Dictionary<int, string>();
            foreach (BaseEnum baseEnum in baseEnums)
            {
                dic[baseEnum.Value] = baseEnum.Str;
            }

            return dic;
        }

        public static Dictionary<string, int> ToStr2IntDic(List<BaseEnum> baseEnums)
        {
            Dictionary<string, int> dic = new Dictionary<string, int>();
            foreach (BaseEnum baseEnum in baseEnums)
            {
                dic[baseEnum.Str] = baseEnum.Value;
            }

            return dic;
        }
    }
}