text:
#if NET_CORE
using System;
using System.Text;
using System.Text.Encodings.Web;
using Microsoft.AspNetCore.Http;

namespace Com.Mparang.AZLib {
  public class AZCookie {
    private HttpContext context;
    public enum Encrypt {
      PLAIN, BASE64, AES256
    }

    /// 생성자
    public AZCookie(HttpContext p_context) {
      context = p_context;
    }

    ///
    public void Set(string p_key, string p_value, string p_domain, int? p_remain_days, Encrypt? p_encrypt, string p_encrypt_key) {
      string sub_key = null;
      if (p_key.IndexOf(".") > 0) {
        sub_key = p_key.Substring(p_key.IndexOf(".") + 1);
        p_key = p_key.Substring(0, p_key.IndexOf("."));
      }

      Set(p_key, sub_key, p_value, p_domain, p_remain_days, p_encrypt, p_encrypt_key);
    }

    ///
    public void Set(string p_key, string p_sub_key, string p_value, string p_domain, int? p_remain_days, Encrypt? p_encrypt, string p_encrypt_key) {
      //
      string value = "";
      //HttpContext context = System.Web.HttpContext.Current;
      Encrypt encrypt = Encrypt.BASE64;
      int remain_days = 0;

      //
      if (p_encrypt.HasValue) {
        encrypt = p_encrypt.Value;
      }

      //p_key = context.Server.UrlEncode(p_key);
      p_key = Encoding.UTF8.GetString(Encoding.UTF8.GetBytes(p_key));

      if (p_sub_key != null) {
        string cookieValue = Get(p_key, p_encrypt, p_encrypt_key);
        if (cookieValue == null || cookieValue.Trim().Length < 1) cookieValue = "";
        char[] delim_cookieValues = { '&' };
        string[] cookieValues = cookieValue.Split(delim_cookieValues);
        bool existChk = false;
        for (int cnti = 0; cnti < cookieValues.Length; cnti++) {
          if (cookieValues[cnti].IndexOf(p_sub_key + "=") == 0) {
            cookieValues[cnti] = p_sub_key + "=" + p_value;
            existChk = true;
          }
          if (cnti > 0) value += "&";
          value += cookieValues[cnti];
        }
        if (!existChk) {
          if (value.Trim().Length > 0) value += "&";
          value += p_sub_key + "=" + p_value;
        }
      }
      else {
        value = p_value;
      }

      //
      switch (encrypt) {
        case Encrypt.PLAIN:
          break;
        case Encrypt.BASE64:    // BASE64 인코딩된 자료에 대한 반환 처리
          value = Convert.ToBase64String(System.Text.Encoding.UTF8.GetBytes(UrlEncoder.Default.Encode(value)));
          break;
        case Encrypt.AES256:    // AES256 인코딩된 자료에 대한 반환 처리
          //net.imcore.AES256Cipher aes = new net.imcore.AES256Cipher();
          value = new AZEncrypt.AES256().Enc(value, p_encrypt_key);//aes.Encode(value, p_encrypt_key);
          //aes = null;
          break;
      }

      //
      /*HttpCookie cookies = new HttpCookie(p_key);
      cookies.Value = value;*/

      //
      /*if (p_domain != null) {
        cookies.Domain = p_domain;
      }*/

      //
      if (p_remain_days.HasValue) {
        remain_days = p_remain_days.Value;
      }
      //cookies.Expires = DateTime.Today.AddDays(remain_days);
      //context.Response.Cookies.Set(cookies);

      //
      Microsoft.AspNetCore.Http.CookieOptions options = new Microsoft.AspNetCore.Http.CookieOptions();
      options.Expires = DateTime.Today.AddDays(remain_days);
      if (p_domain != null) {
        options.Domain = p_domain;
      }
      context.Response.Cookies.Delete(p_key);
      context.Response.Cookies.Append(p_key, value, options);
    }

    ///
    public void Set<T>(T p_model) {
      Set<T>(null, p_model, null, null, null, null);
    }

    ///
    public void Set<T>(T p_model, string p_domain) {
      Set<T>(null, p_model, p_domain, null, null, null);
    }

    ///
    public void Set<T>(T p_model, string p_domain, Encrypt? p_encrypt, string p_encrypt_key) {
      Set<T>(null, p_model, p_domain, null, p_encrypt, p_encrypt_key);
    }

    ///
    public void Set<T>(string p_key, T p_model, string p_domain, int? p_remain_days, Encrypt? p_encrypt, string p_encrypt_key) {
      string key, value = "";
      Encrypt encrypt = Encrypt.BASE64;
      int remain_days = 0;

      //
      //HttpContext context = System.Web.HttpContext.Current;

      // 쿠키 최상위 이름값이 없으면 모델의 이름으로 지정
      key = p_key != null ? p_key : p_model.GetType().Name;
      key = UrlEncoder.Default.Encode(key);//context.Server.UrlEncode(key);

      // T -> AZData 형식으로 변환
      AZData data = AZString.JSON.Init(AZString.JSON.Convert<T>(p_model)).ToAZData();

      for (int cnti = 0; cnti < data.Size(); cnti++) {
        value += (cnti > 0 ? "&" : "") + data.GetKey(cnti) + "=" + UrlEncoder.Default.Encode(data.GetString(cnti));//context.Server.UrlEncode(data.GetString(cnti));
      }

      //
      if (p_encrypt.HasValue) {
        encrypt = p_encrypt.Value;
      }

      //
      switch (encrypt) {
        case Encrypt.PLAIN:
          break;
        case Encrypt.BASE64:    // BASE64 인코딩된 자료에 대한 반환 처리
          value = Convert.ToBase64String(System.Text.Encoding.UTF8.GetBytes(UrlEncoder.Default.Encode(value)));
          break;
        case Encrypt.AES256:    // AES256 인코딩된 자료에 대한 반환 처리
          //net.imcore.AES256Cipher aes = new net.imcore.AES256Cipher();
          value = new AZEncrypt.AES256().Enc(value, p_encrypt_key);//aes.Encode(value, p_encrypt_key);
          //aes = null;
          break;
      }

      //
      //HttpCookie cookies = new HttpCookie(key);
      //cookies.Value = value;

      //
      /*if (p_domain != null) {
          cookies.Domain = p_domain;
      }*/

      //
      if (p_remain_days.HasValue) {
        remain_days = p_remain_days.Value;
      }

      Microsoft.AspNetCore.Http.CookieOptions options = new Microsoft.AspNetCore.Http.CookieOptions();
      options.Expires = DateTime.Today.AddDays(remain_days);
      if (p_domain != null) {
        options.Domain = p_domain;
      }
      context.Response.Cookies.Delete(p_key);
      context.Response.Cookies.Append(p_key, value, options);
    }

    ///
    public T Get<T>() {
      return Get<T>(null, null, null);
    }

    ///
    public T Get<T>(Encrypt? p_encrypt, string p_encrypt_key) {
      return Get<T>(null, p_encrypt, p_encrypt_key);
    }

    ///
    public T Get<T>(string p_key, Encrypt? p_encrypt, string p_encrypt_key) {
      Type type = typeof(T);
      object model = Activator.CreateInstance(type);

      T rtn_value = default(T);
      string key, value;
      Encrypt encrypt = Encrypt.BASE64;

      //
      //HttpContext context = System.Web.HttpContext.Current;

      // 쿠키 최상위 이름값이 없으면 모델의 이름으로 지정
      key = p_key != null ? p_key : model.GetType().Name;

      if (p_encrypt.HasValue) {
        encrypt = p_encrypt.Value;
      }

      // T -> AZData 형식으로 변환
      AZData data = AZString.JSON.Init(AZString.JSON.Convert<T>((T)model)).ToAZData();
      model = null;

      //
      value = Get(key, encrypt, p_encrypt_key);
      if (value != null) {
        for (int cnti = 0; cnti < data.Size(); cnti++) {
          string sub_value = GetSubValue(data.GetKey(cnti), value);
          if (sub_value != null) {
            data.Set(cnti, sub_value);
          }
        }
        rtn_value = data.Convert<T>();
      }

      return rtn_value;
    }

    ///
    public string Get(string p_key, Encrypt? p_encrypt, string p_encrypt_key) {
      string sub_key = null;
      if (p_key.IndexOf(".") > 0) {
        sub_key = p_key.Substring(p_key.IndexOf(".") + 1);
        p_key = p_key.Substring(0, p_key.IndexOf("."));
      }

      return Get(p_key, sub_key, p_encrypt, p_encrypt_key);
    }

    ///
    public string Get(string p_key, string p_sub_key, Encrypt? p_encrypt, string p_encrypt_key) {
      string rtn_value = null;
      string value = "";
      Encrypt encrypt = Encrypt.BASE64;

      //
      //HttpContext context = System.Web.HttpContext.Current;

      //
      p_key = UrlEncoder.Default.Encode(p_key);

      //
      if (HasKey(p_key)) {
        value = context.Request.Cookies[p_key];//context.Request.Cookies[p_key].Value;
      }

      //
      if (p_encrypt.HasValue) {
        encrypt = p_encrypt.Value;
      }

      switch (encrypt) {
        case Encrypt.PLAIN:
          break;
        case Encrypt.BASE64:    // BASE64 인코딩된 자료에 대한 반환 처리
          try {
            value = Encoding.UTF8.GetString(Convert.FromBase64String(context.Request.Cookies[p_key]));
          }
          catch (Exception) {
            value = "";
          }
          break;
        case Encrypt.AES256:    // AES256 인코딩된 자료에 대한 반환 처리
          try {
            //net.imcore.AES256Cipher aes = new net.imcore.AES256Cipher();
            value = new AZEncrypt.AES256().Dec(value, p_encrypt_key);//aes.Decode(value, p_encrypt_key);
            //aes = null;
          }
          catch (Exception) {
            value = "";
          }
          break;
      }

      //
      if (p_sub_key != null && p_sub_key.Trim().Length > 0) {
        rtn_value = GetSubValue(p_sub_key, value);
      }
      else {
        rtn_value = value;
      }

      return rtn_value;
    }

    ///
    public void Remove(string p_key) {
      context.Response.Cookies.Delete(p_key);
    }

    ///
    public void Clear() {
      //HttpContext context = System.Web.HttpContext.Current;
      foreach (var key in context.Request.Cookies.Keys) {
      //for (int cnti = 0; cnti < context.Request.Cookies.Count; cnti++) {
        context.Response.Cookies.Delete(key);
      }
      //context.Response.Cookies.Clear();
    }

    ///
    public bool HasKey(string p_key) {
      bool rtn_value = false;
      //
      //HttpContext context = System.Web.HttpContext.Current;

      for (int cnti = 0; cnti < context.Request.Cookies.Count; cnti++) {
        if (context.Request.Cookies.ContainsKey(p_key)) {
          rtn_value = true;
          break;
        }
      }
      return rtn_value;
    }

    ///
    private string GetSubValue(string p_sub_key, string p_value) {
      string rtn_value = null;
      //
      //HttpContext context = System.Web.HttpContext.Current;

      bool existChk = false;
      string[] sub_cookies = p_value.Split(new char[] { '&' });
      for (int cnti = 0; cnti < sub_cookies.Length; cnti++) {
        if (sub_cookies[cnti].IndexOf(p_sub_key + "=") == 0) {
          rtn_value = sub_cookies[cnti].Substring(sub_cookies[cnti].IndexOf(p_sub_key + "=") + (p_sub_key + "=").Length);
          existChk = true;
          break;
        }
      }
      if (!existChk) rtn_value = null;

      return rtn_value;
    }
  }
}
#endif


text:
 {{ 'PROFILE' | translate }}

          <form class="form-horizontal">

              {{ 'USERNAME' | translate }}

                {{item.user.username}}

              {{ 'FULL_NAME' | translate }}

                <input ng-show="editEnable.profile" class="form-control" ng-model="item.user.fullName"/>
                {{item.user.fullName}}

              {{ 'EMAIL' | translate }}

                <input ng-show="editEnable.profile" class="form-control" ng-model="item.user.email"/>
                {{item.user.email}}

                {{ 'CURRENT_PASSWORD' | translate }}

                  <input type="password" class="form-control" placeholder="{{ 'CURRENT_PASSWORD' | translate }}" ng-model="item.currentPassword"/>

                {{ 'NEW_PASSWORD' | translate }}

                  <input type="password" class="form-control" placeholder="{{ 'NEW_PASSWORD' | translate }}" ng-model="item.user.password"/>

          </form>

            <button type="button" class="btn btn-default" class="button" ng-hide="editEnable.profile" ng-click="editEnable.profile = true">{{ 'EDIT' | translate }}</button>
            <button type="button" class="btn btn-default" class="button" ng-show="editEnable.profile" ng-click="resetProfile();editEnable.profile = false">{{ 'CANCEL' | translate }}</button>
            <button type="button" class="btn btn-primary" ng-click="save()"  ng-show="editEnable.profile" ng-disabled="saveProgress">

              {{ 'SAVE' | translate }}
            </button>

redpajama_set_name: RedPajamaGithub


text:
namespace gorc {

    class process {
    private:
        maybe<::pid_t> pid;
        maybe<gorc::pipe*> std_input;
        maybe<gorc::pipe*> std_output;
        maybe<gorc::pipe*> std_error;
        maybe<path> working_directory;

        void internal_inside_parent(::pid_t child_pid);
        void internal_inside_child(path const &executable,
                                   std::vector<char *> const &arguments);

    public:
        process(path const &executable,
                argument_list const &args,
                maybe<gorc::pipe*> std_input,
                maybe<gorc::pipe*> std_output,
                maybe<gorc::pipe*> std_error,
                maybe<path> working_directory = nothing);

        ~process();
        int join();
    };

}


text:
class User < ActiveRecord::Base
  # Include default devise modules. Others available are:
  # :confirmable, :lockable, :timeoutable and :omniauthable
  has_many :posts
  has_many :animals
  validates :name, presence: true, uniqueness: true
  devise :database_authenticatable, :registerable,
         :recoverable, :rememberable, :trackable, :validatable

end


text:
<?php

/* EPSINewsBundle:TestTwig:getNews.html.twig */
class __TwigTemplate_ea9e40fda7bd34d4ef4a47ea93d05773c21b10836eaff170d8cd7832e0370072 extends Twig_Template
{
    public function __construct(Twig_Environment $env)
    {
        parent::__construct($env);

        // line 1
        try {
            $this->parent = $this->env->loadTemplate("EPSINewsBundle:Default:index.html.twig");
        } catch (Twig_Error_Loader $e) {
            $e->setTemplateFile($this->getTemplateName());
            $e->setTemplateLine(1);

            throw $e;
        }

        $this->blocks = array(
            'title' => array($this, 'block_title'),
            'content' => array($this, 'block_content'),
        );
    }

    protected function doGetParent(array $context)
    {
        return "EPSINewsBundle:Default:index.html.twig";
    }

    protected function doDisplay(array $context, array $blocks = array())
    {
        $this->parent->display($context, array_merge($this->blocks, $blocks));
    }

    // line 3
    public function block_title($context, array $blocks = array())
    {
        echo "
        Les Actus
    ";
    }

    // line 7
    public function block_content($context, array $blocks = array())
    {
        // line 8
        echo "

Mes super news !

Dernieres news parues :

        ";
        // line 13
        $context['_parent'] = (array) $context;
        $context['_seq'] = twig_ensure_traversable((isset($context["News"]) ? $context["News"] : $this->getContext($context, "News")));
        foreach ($context['_seq'] as $context["_key"] => $context["new"]) {
            // line 14
            echo "

";
            // line 15
            echo twig_escape_filter($this->env, $this->getAttribute($context["new"], "title", array()), "html", null, true);
            echo " - ";
            echo twig_escape_filter($this->env, twig_date_format_filter($this->env, $this->getAttribute($context["new"], "date", array()), "M D y"), "html", null, true);
            echo "

                    ";
            // line 17
            echo twig_escape_filter($this->env, $this->getAttribute($context["new"], "content", array()), "html", null, true);
            echo "

        ";
        }
        $_parent = $context['_parent'];
        unset($context['_seq'], $context['_iterated'], $context['_key'], $context['new'], $context['_parent'], $context['loop']);
        $context = array_intersect_key($context, $_parent) + $_parent;
        // line 21
        echo "

";
    }

    public function getTemplateName()
    {
        return "EPSINewsBundle:TestTwig:getNews.html.twig";
    }

    public function isTraitable()
    {
        return false;
    }

    public function getDebugInfo()
    {
        return array (  79 => 21,  69 => 17,  62 => 15,  59 => 14,  55 => 13,  48 => 8,  45 => 7,  37 => 3,  11 => 1,);
    }
}


text:
<?php

namespace ShopwarePlugin;

use Composer\Composer;
use Composer\IO\IOInterface;
use Composer\Plugin\PluginInterface;

/**
 * Class Plugin
 * @package ShopwarePlugin
 */
class Plugin implements PluginInterface
{
    /**
     * @param Composer $composer
     * @param IOInterface $io
     */
    public function activate(Composer $composer, IOInterface $io)
    {
        $manager = $composer->getRepositoryManager();

        $shopwareRepository = new ShopwareRepository();

        $manager->addRepository($shopwareRepository);
    }
}


text:
NS_ASSUME_NONNULL_BEGIN

typedef UIOffset TransformedValueCType;
static const char * const TransformedValueObjCType = @encode(UIOffset);
static NSString * const TypeDescription = @"Offset";

@implementation NSValueTransformer (MotifUIOffset)

+ (void)load {
    [self
        mtf_registerValueTransformerWithName:MTFOffsetFromNumberTransformerName
        transformedValueObjCType:TransformedValueObjCType
        reverseTransformedValueClass:NSNumber.class
        transformationBlock:^(NSNumber *numberValue, NSError **error) {
            typeof(TransformedValueCType) value = {
                .horizontal = numberValue.floatValue,
                .vertical = numberValue.floatValue,
            };

            return [NSValue value:&value withObjCType:TransformedValueObjCType];
        }];

    [self
        mtf_registerValueTransformerWithName:MTFOffsetFromArrayTransformerName
        transformedValueObjCType:TransformedValueObjCType
        reverseTransformedValueClass:NSArray.class
        transformationBlock:^ NSValue * (NSArray<NSNumber *> *values, NSError **error) {
            if (values.count != 2) {
                return [self
                    mtf_populateTransformationError:error
                    withDescriptionFormat:@"%@ array must have two elements", TypeDescription];
            }

            for (id value in values) {
                if (![value isKindOfClass:NSNumber.class]) {
                    return [self
                        mtf_populateTransformationError:error
                        withDescriptionFormat:@"%@ array elements must be kind of class NSNumber", TypeDescription];
                }
            }

            typeof(TransformedValueCType) value = {
                .horizontal = values[0].floatValue,
                .vertical = values[1].floatValue,
            };

            return [NSValue value:&value withObjCType:TransformedValueObjCType];
        }];

    [self
        mtf_registerValueTransformerWithName:MTFOffsetFromDictionaryTransformerName
        transformedValueObjCType:TransformedValueObjCType
        reverseTransformedValueClass:NSDictionary.class
        transformationBlock:^ NSValue * (NSDictionary<NSString *, NSNumber *> *values, NSError **error) {
            for (id value in [values objectEnumerator]) {
                if (![value isKindOfClass:NSNumber.class]) {
                    return [self
                        mtf_populateTransformationError:error
                        withDescriptionFormat:@"%@ dictionary values must be kind of class NSNumber", TypeDescription];
                }
            }

            NSArray<NSString *> *validKeys = @[ @"horizontal", @"vertical" ];

            // Ensure that the passed properties have valid keys
            NSMutableSet<NSString *> *invalidKeys = [NSMutableSet setWithArray:values.allKeys];
            [invalidKeys minusSet:[NSSet setWithArray:validKeys]];
            if (invalidKeys.count > 0) {
                return [self
                    mtf_populateTransformationError:error
                    withDescriptionFormat:@"%@ invalid dictionary key(s): %@", TypeDescription, invalidKeys];
            }

            typeof(TransformedValueCType) value = {
                .horizontal = values[validKeys[0]].floatValue,
                .vertical = values[validKeys[1]].floatValue,
            };

            return [NSValue value:&value withObjCType:TransformedValueObjCType];
        }];
}

@end

NSString * const MTFOffsetFromNumberTransformerName = @"MTFOffsetFromNumberTransformerName";

NSString * const MTFOffsetFromArrayTransformerName = @"MTFOffsetFromArrayTransformerName";

NSString * const MTFOffsetFromDictionaryTransformerName = @"MTFOffsetFromDictionaryTransformerName";

NS_ASSUME_NONNULL_END


text:
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
  <component name="JavaScriptLibraryMappings">
    <file url="PROJECT" libraries="{Node.js v4.0.0 Core Modules, css-helpers node_modules}" />
    <includedPredefinedLibrary name="Node.js Globals" />
  </component>
</project>


text:
Shortens a link using [YourLS](http://yourls.org)!

## Setup

1. Install this action (LB 6+ required):
  * [Download the repo](https://github.com/hlissner/lb6-actions/archive/master.zip)
  * Unzip the downloaded file
  * Double click Shorten URL (YourLS).lbaction to install it

2. Log in to your YourLS website. For instance, mine is at http://v0.io and
   the admin panel is at https://v0.io/admin

3. Go to the **tools** page (e.g. http://v0.io/admin/tools)

4. Scroll down to "Secure passwordless API call" and take note of your
   **security token** and the **URL to your yourls-api.php script**, e.g.
   http://v0.io/yourls-api.php

5. Run the Shorten URL (YourLS) action. You will get a prompt telling you your
   API details aren't filled in. Click the "Preferences" button and open
   "Preferences.plist" in the finder window that pops up.

6. You should see this window:

   ![](img/01.png)

7. I've put "ABC" and "123" in for signature and url. Replace those with your
   security token and URL to yourls-api.php, respectively.

## Notes

* Hold <kbd>⌘</kbd> while running the action to forcibly bring up the
  Preferences/Report Issue prompt.


text:
#if defined(DDNS_BROADBANDFORUM)
#include "cosa_dynamicdns_apis.h"
#include <utctx/utctx.h>
#include <utapi/utapi.h>
#include <utapi/utapi_util.h>
#include <syscfg/syscfg.h>
#include <sysevent/sysevent.h>
#include "safec_lib_common.h"

      /* MACROS */
#define  SYSCFG_SERVER_ENABLE_KEY         "ddns_server_enable_%lu"
#define  SYSCFG_SERVER_PROTOCOL_KEY       "ddns_server_protocol_%lu"
#define  SYSCFG_SERVER_CHECKINTERVAL_KEY  "ddns_server_checkinterval_%lu"
#define  SYSCFG_SERVER_RETRYINTERVAL_KEY  "ddns_server_retryinterval_%lu"
#define  SYSCFG_SERVER_MAXRETRIES_KEY     "ddns_server_maxretries_%lu"
#define  SYSCFG_SERVER_SERVERPORT_KEY     "ddns_server_serverport_%lu"
#define  SYSCFG_SERVER_SERVERADDRESS_KEY  "ddns_server_serveraddress_%lu"
#define  SYSCFG_SERVER_SERVICENAME_KEY    "ddns_server_servicename_%lu"
#define  DEFAULT_RETRYINTERVAL            660
#define  DEFAULT_MAXRETRIES               10

#define  SYSCFG_HOST_ENABLE_KEY           "ddns_host_enable_%lu"
#define  SYSCFG_HOST_STATUS_KEY           "ddns_host_status_%lu"
#define  SYSCFG_HOST_NAME_KEY             "ddns_host_name_%lu"
#define  HOST_REGISTERED                  1
#define  CLIENT_UPDATED                   3
#define  HOST_DISABLED                    5
#define  MAX_HOST_COUNT                   1

typedef struct {
    char ServiceName[64];
    char Name[64];
    char SupportedProtocols[64];
    char Protocol[16];
    char ServerAddress[64];
} DDNS_SERVICE;

DDNS_SERVICE gDdnsServices[] =
{
/*  structure template
    {
        "ServiceName Parameter"
        "Name parameter" //(to be used by UI display)
        "SupportedProtocols"
        "Protocol" //(default)
        "Server Address"
    },
*/
    {
        "no-ip",
        "No-IP.com",
        "HTTP",
        "HTTP",
        "www.no-ip.com"
    },
    {
        "dyndns",
        "Dyn.com",
        "HTTP",
        "HTTP",
        "www.dyndns.org"
    },
    {
        "duckdns",
        "DuckDNS.org",
        "HTTPS",
        "HTTPS",
        "www.duckdns.org"
    },
    {
        "afraid",
        "FreeDNS.afraid.org",
        "HTTPS",
        "HTTPS",
        "www.freedns.afraid.org"
    },
    {
        "easydns",
        "EasyDNS.com",
        "HTTPS",
        "HTTPS",
        "www.easydns.com"
    },
    {
        "changeip",
        "ChangeIP.com",
        "HTTP",
        "HTTP",
        "www.changeip.com"
    }
};

#ifdef DDNS_SERVICE_BIN
static void RemoveCheckIntervalEntryFromCron(void)
{
    system("sed -i '/#DDNS_CHECK_INTERVAL/d' /var/spool/cron/crontabs/root");
}

static void RemoveRetryIntervalEntryFromCron(void)
{
    system("sed -i '/#DDNS_RETRY_INTERVAL/d' /var/spool/cron/crontabs/root");
}
#endif

/***********************************************************************
 APIs for SYSCFG GET and SET

     *UtGetString
     *UtSetString
     *UtGetUlong
     *UtSetUlong
     *UtGetBool
     *UtSetBool
***********************************************************************/

static int UtGetString(const char *path, char *pVal, ULONG length)
{
    UtopiaContext ctx;

    if (!Utopia_Init(&ctx))
        return ANSC_STATUS_FAILURE;

    Utopia_RawGet(&ctx, NULL, (char *)path, pVal, length);

    Utopia_Free(&ctx, 0);
    return ANSC_STATUS_SUCCESS;
}

static int UtSetString(const char *path, char *val)
{
    UtopiaContext ctx;

    if (!Utopia_Init(&ctx))
       return ANSC_STATUS_FAILURE;

    if (val)
        Utopia_RawSet(&ctx, NULL, (char *)path, val);

    Utopia_Free(&ctx, 1);

    return ANSC_STATUS_SUCCESS;
}

static int UtGetUlong(const char *path, ULONG *pVal)
{
    UtopiaContext ctx;
    char buf[64] = {0};

    if (!Utopia_Init(&ctx))
        return ANSC_STATUS_FAILURE;

    Utopia_RawGet(&ctx, NULL, (char *)path, buf, sizeof(buf));
    if(buf[0] != '\0')
    {
        *pVal = atoi(buf);
    }

    Utopia_Free(&ctx, 0);

    return ANSC_STATUS_SUCCESS;
}

static int UtSetUlong(const char *path, ULONG val)
{
    UtopiaContext ctx;
    char buf[64] = {0};

    if (!Utopia_Init(&ctx))
        return ANSC_STATUS_FAILURE;

    snprintf(buf, sizeof(buf), "%lu", val);
    Utopia_RawSet(&ctx, NULL, (char *)path, buf);

    Utopia_Free(&ctx, 1);

    return ANSC_STATUS_SUCCESS;
}

static int UtGetBool(const char *path, BOOLEAN *pVal)
{
    UtopiaContext ctx;
    char buf[64] = {0};

    if (!Utopia_Init(&ctx))
        return ANSC_STATUS_FAILURE;

    Utopia_RawGet(&ctx, NULL, (char *)path, buf, sizeof(buf));
    if (atoi(buf) == 1)
        *pVal = TRUE;
    else
        *pVal = FALSE;

    Utopia_Free(&ctx, 0);

    return ANSC_STATUS_SUCCESS;
}

static int UtSetBool(const char *path, BOOLEAN val)
{
    UtopiaContext ctx;

    if (!Utopia_Init(&ctx))
       return ANSC_STATUS_FAILURE;

    if (val)
        Utopia_RawSet(&ctx, NULL, (char *)path, "1");
    else
        Utopia_RawSet(&ctx, NULL, (char *)path, "0");

    Utopia_Free(&ctx, 1);

    return ANSC_STATUS_SUCCESS;
}

static int resetDynamicDNSStatus(void)
{
    syscfg_set(NULL, "ddns_client_Status", "1"); /* CLIENT_CONNECTING=1 */
    syscfg_set(NULL, "ddns_host_status_1", "2"); /* HOST_UPDATE_NEEDED=2 */

    return ANSC_STATUS_SUCCESS;
}

/***********************************************************************
 APIs for Object:

    DyanmicDNS.

    *  CosaDmlDynamicDns_GetEnable
    *  CosaDmlDynamicDns_GetsupportedServices
    *  CosaDmlDynamicDns_SetEnable
***********************************************************************/

static int g_NrDynamicDnsClient =  0;

BOOL
CosaDmlDynamicDns_GetEnable()
{
   char buf[8] = {0};

   if (!syscfg_get(NULL, "dynamic_dns_enable", buf, sizeof(buf)))
   {
        //return (strcmp(buf, "1") == 0);
        //Returning true by default as dynamic_dns_enable syscfg dependency has been removed as part of removing the DDNS depenedency from Device.DynamicDNS.X_RDK-COM_Enable DM
        return 1;
   }
   return 0;
}

ULONG
CosaDmlDynamicDns_GetsupportedServices
    (
        char*  supportedServices
    )
{
    char buf[128] = {0};
    errno_t rc = -1;

    if (!syscfg_get( NULL, "ddns_service_providers_list", buf, sizeof(buf)))
    {
        /* destination buffer supportedServices is declared as an array size of 1024 bytes in the calling func. */
        rc = strcpy_s(supportedServices, 1024, buf);
        if(rc != EOK)
        {
            ERR_CHK(rc);
            return -1;
        }
        return 0;
    }
    return -1;
}

ULONG
CosaDmlDynamicDns_SetEnable
    (
        BOOL  bValue
    )
{
   char buf[8] = {0};
   errno_t rc = -1;

       syscfg_get(NULL, "dslite_enable", buf, sizeof(buf));
       if((strcmp(buf, "1") == 0) && bValue == TRUE){
           return -1;
       }
       rc = strcpy_s(buf, sizeof(buf), ((bValue == FALSE) ? "0" : "1"));
       if(rc != EOK)
       {
           ERR_CHK(rc);
           return -1;
       }
       syscfg_set(NULL, "dynamic_dns_enable", buf);
       syscfg_set(NULL, "arddnsclient_1::enable", buf);
       syscfg_set(NULL, "ddns_host_enable_1", buf);
       syscfg_commit();

       if (bValue == TRUE && g_NrDynamicDnsClient != 0) {
#ifdef DDNS_SERVICE_BIN
           CcspTraceInfo(("%s Going to invoke ddns service from CosaDmlDynamicDns_SetEnable() \n", __FUNCTION__));
           v_secure_system("service_ddns restart &");
#else
           CcspTraceInfo(("%s Going to invoke script from CosaDmlDynamicDns_SetEnable() \n", __FUNCTION__));
           v_secure_system("/etc/utopia/service.d/service_dynamic_dns.sh dynamic_dns-restart &");
#endif
       }

#ifdef DDNS_SERVICE_BIN
       if (bValue == FALSE) {
           RemoveCheckIntervalEntryFromCron();
           RemoveRetryIntervalEntryFromCron();
       }
#endif

       return 0;
}

/***********************************************************************
 APIs for Object:

    DyanmicDNS.

    *  CosaDmlDynamicDns_Client_GetNumberOfEntries
    *  CosaDmlDynamicDns_Client_GetEntryByIndex
    *  CosaDmlDynamicDns_Client_SetValues
    *  CosaDmlDynamicDns_Client_AddEntry
    *  CosaDmlDynamicDns_Client_DelEntry
    *  CosaDmlDynamicDns_Client_GetConf
    *  CosaDmlDynamicDns_Client_SetConf
***********************************************************************/

static int
DynamicDns_Client_InsGetIndex
    (
        ULONG ins
    )
{
    int i, ins_num, ret = -1;
    UtopiaContext ctx;

    CosaDmlDynamicDns_Client_GetNumberOfEntries();
    if (!Utopia_Init(&ctx))
        return ANSC_STATUS_FAILURE;

    for (i = 0; i < g_NrDynamicDnsClient; i++)
    {
        Utopia_GetDynamicDnsClientInsNumByIndex(&ctx, i, &ins_num);
        if (ins_num == ins) {
            ret = i;
            break;
        }
    }
    Utopia_Free(&ctx, 0);

    return ret;
}

ULONG
CosaDmlDynamicDns_Client_GetNumberOfEntries(void)
{
    UtopiaContext ctx;

    if(!Utopia_Init(&ctx))
        return ANSC_STATUS_FAILURE;

    Utopia_GetNumberOfDynamicDnsClient(&ctx, &g_NrDynamicDnsClient);
    Utopia_Free(&ctx, 0);
    return g_NrDynamicDnsClient;
}

ANSC_STATUS
CosaDmlDynamicDns_Client_GetEntryByIndex
    (
        ULONG index,
        COSA_DML_DDNS_CLIENT *pEntry
    )
{
    UtopiaContext ctx;
    DynamicDnsClient_t  DDNSclient = {0};

    if (index >= g_NrDynamicDnsClient || !Utopia_Init(&ctx))
    {
        return ANSC_STATUS_FAILURE;
    }

    Utopia_GetDynamicDnsClientByIndex(&ctx, index, &DDNSclient);

    pEntry->InstanceNumber = DDNSclient.InstanceNumber;
    pEntry->Enable = DDNSclient.Enable;
    pEntry->Status = DDNSclient.Status;
    pEntry->LastError = DDNSclient.LastError;
    _ansc_strncpy(pEntry->Alias,    DDNSclient.Alias,    sizeof(pEntry->Alias)-1);
    _ansc_strncpy(pEntry->Username, DDNSclient.Username, sizeof(pEntry->Username)-1);
    _ansc_strncpy(pEntry->Password, DDNSclient.Password, sizeof(pEntry->Password)-1);
    _ansc_strncpy(pEntry->Server,   DDNSclient.Server,   sizeof(pEntry->Server)-1);

    Utopia_Free(&ctx, 0);
    return ANSC_STATUS_SUCCESS;
}

ANSC_STATUS
CosaDmlDynamicDns_Client_SetValues
    (
        ULONG index,
        ULONG ins,
        const char *alias
    )
{
    int rc = -1;
    UtopiaContext ctx;

    if (index >= g_NrDynamicDnsClient || !Utopia_Init(&ctx))
    {
        return ANSC_STATUS_FAILURE;
    }

    rc = Utopia_SetDynamicDnsClientInsAndAliasByIndex(&ctx, index, ins, alias);
    Utopia_Free(&ctx, !rc);

    return (rc != 0) ? ANSC_STATUS_FAILURE : ANSC_STATUS_SUCCESS;
}

ANSC_STATUS
CosaDmlDynamicDns_Client_AddEntry
    (
        COSA_DML_DDNS_CLIENT *pEntry
    )
{
    int rc = -1;
    UtopiaContext ctx;
    DynamicDnsClient_t  DDNSclient = {0};

    if (!Utopia_Init(&ctx))
    {
        return ANSC_STATUS_FAILURE;
    }

    DDNSclient.InstanceNumber = pEntry->InstanceNumber;
    DDNSclient.Enable         = pEntry->Enable;
    _ansc_strncpy(DDNSclient.Alias,    pEntry->Alias,    sizeof(DDNSclient.Alias)-1);
    _ansc_strncpy(DDNSclient.Username, pEntry->Username, sizeof(DDNSclient.Username)-1);
    _ansc_strncpy(DDNSclient.Password, pEntry->Password, sizeof(DDNSclient.Password)-1);
    _ansc_strncpy(DDNSclient.Server,   pEntry->Server,   sizeof(DDNSclient.Server)-1);

    rc = Utopia_AddDynamicDnsClient(&ctx, &DDNSclient);

    Utopia_GetNumberOfDynamicDnsClient(&ctx, &g_NrDynamicDnsClient);
    Utopia_Free(&ctx, !rc);

#if 0
    if (CosaDmlDynamicDns_GetEnable() && pEntry->Enable == TRUE)
    {
        /* reset the DynamicDNS client and host status before restart*/
        resetDynamicDNSStatus();
        CcspTraceInfo(("%s Going to restart dynamic dns service",__FUNCTION__));
#ifdef DDNS_SERVICE_BIN
        if (access("/var/run/updating_ddns_server.txt", F_OK) != 0) {
            v_secure_system("service_ddns restart &");
        }
#else
        v_secure_system("/etc/utopia/service.d/service_dynamic_dns.sh dynamic_dns-restart &");
#endif
    }

#endif

    return (rc != 0) ? ANSC_STATUS_FAILURE : ANSC_STATUS_SUCCESS;
}

ANSC_STATUS
CosaDmlDynamicDns_Client_DelEntry
    (
        ULONG ins
    )
{
    int rc = -1;
    UtopiaContext ctx;

    if (!Utopia_Init(&ctx))
        return ANSC_STATUS_FAILURE;

    rc = Utopia_DelDynamicDnsClient(&ctx, ins);
    Utopia_GetNumberOfDynamicDnsClient(&ctx, &g_NrDynamicDnsClient);
    Utopia_Free(&ctx, !rc);

    return (rc != 0) ? ANSC_STATUS_FAILURE : ANSC_STATUS_SUCCESS;
}

ANSC_STATUS
CosaDmlDynamicDns_Client_GetConf
    (
        ULONG ins,
        COSA_DML_DDNS_CLIENT *pEntry
    )
{
    int index;

    if ((index = DynamicDns_Client_InsGetIndex(ins)) == -1)
    {
        return ANSC_STATUS_FAILURE;
    }

    return CosaDmlDynamicDns_Client_GetEntryByIndex(index, pEntry);
}

/* Clear the ddns_return_status{DnIdx} sysevent variable */
static void reset_ddns_return_status (void)
{
    char server[40];

    if (syscfg_get("arddnsclient_1", "Server", server, sizeof(server)) == 0)
    {
        /*
           Assume server is in the form "Device.DynamicDNS.Server.1"
           and index is a single character.
        */
        size_t len = strlen(server);
        if ((len >= 2) && (server[len - 2] == '.'))
        {
            char buf[32];
            char *index = server + len - 1;
            snprintf(buf, sizeof(buf), "ddns_return_status%s", index);
            commonSyseventSet(buf, "");
        }
    }
}

ANSC_STATUS
CosaDmlDynamicDns_Client_SetConf
    (
        ULONG ins,
        COSA_DML_DDNS_CLIENT *pEntry
    )
{
    int index, rc = -1;
    char client_status[12];
    char enable_path[sizeof(SYSCFG_HOST_ENABLE_KEY) + 1] = {0};
    BOOLEAN enable = FALSE, isUserconfChanged = FALSE;
    UtopiaContext ctx;
    DynamicDnsClient_t  DDNSclient = {0};

    ULONG InsNumber;
    ANSC_HANDLE pHostnameInsContext = NULL;
    PCOSA_CONTEXT_LINK_OBJECT pHostLinkObj = NULL;
    COSA_DML_DDNS_HOST *pHostEntry = NULL;
    bool bReadyUpdate = FALSE;

    if ((index = DynamicDns_Client_InsGetIndex(ins)) == -1 || !Utopia_Init(&ctx))
    {
        return ANSC_STATUS_FAILURE;
    }

    if (index >= g_NrDynamicDnsClient)
    {
        return ANSC_STATUS_FAILURE;
    }

    syscfg_get(NULL, "ddns_client_Status", client_status, sizeof(client_status));

    Utopia_GetDynamicDnsClientByIndex(&ctx, index, &DDNSclient);
    if (CosaDmlDynamicDns_GetEnable() && pEntry->Enable == TRUE &&
       ((strcmp(DDNSclient.Username, pEntry->Username) != 0) ||
       (strcmp(DDNSclient.Password, pEntry->Password) != 0) ||
       (strcmp(DDNSclient.Server, pEntry->Server) != 0)) ||
       (atoi(client_status) != CLIENT_UPDATED))
    {
        CcspTraceInfo(("%s UserConf changed \n",__FUNCTION__));
        isUserconfChanged = TRUE;
    }

    DDNSclient.InstanceNumber = pEntry->InstanceNumber;
    DDNSclient.Enable         = pEntry->Enable;
    _ansc_strncpy(DDNSclient.Alias,    pEntry->Alias,    sizeof(DDNSclient.Alias)-1);
    _ansc_strncpy(DDNSclient.Username, pEntry->Username, sizeof(DDNSclient.Username)-1);
    _ansc_strncpy(DDNSclient.Password, pEntry->Password, sizeof(DDNSclient.Password)-1);
    _ansc_strncpy(DDNSclient.Server,   pEntry->Server,   sizeof(DDNSclient.Server)-1);

    rc = Utopia_SetDynamicDnsClientByIndex(&ctx, index, &DDNSclient);
    Utopia_Free(&ctx, !rc);

    snprintf(enable_path, sizeof(enable_path), SYSCFG_HOST_ENABLE_KEY, ins);
    UtGetBool(enable_path, &enable);
    if (enable != pEntry->Enable)
    {
        UtSetBool(enable_path, pEntry->Enable);
        if (pEntry->Enable == TRUE && CosaDmlDynamicDns_GetEnable()) {
            CcspTraceInfo(("%s UserConf changed - Enable changed from false to true \n",__FUNCTION__));
            isUserconfChanged = TRUE;
        }
    }

    pHostnameInsContext = DDNSHostname_GetEntry(NULL, 0, &InsNumber);
    if (pHostnameInsContext != NULL)
    {
        pHostLinkObj = (PCOSA_CONTEXT_LINK_OBJECT)pHostnameInsContext;
        pHostEntry = (COSA_DML_DDNS_HOST *)pHostLinkObj->hContext;
    }

    if ((pEntry->Enable) && (pEntry->Server[0] != '\0') && (pEntry->Username[0] != '\0') && pHostEntry && (pHostEntry->Enable) && (pHostEntry->Name[0]!='\0'))
    {
        if (strstr(pHostEntry->Name, "duckdns") == NULL)
        {
            /* Check whether password is null or not for services other than duckdns */
            if (pEntry->Password[0] != '\0')
            {
                bReadyUpdate = TRUE;
            }
        }
        else
        {
            /* for duckdns no need to check password */
            bReadyUpdate = TRUE;
        }
    }

    if ((isUserconfChanged == TRUE) && (bReadyUpdate == TRUE))
    {
        /* reset the DynamicDNS client and host status before restart*/
        resetDynamicDNSStatus();
        CcspTraceInfo(("%s Going to restart dynamic dns service",__FUNCTION__));
        reset_ddns_return_status();
#ifdef DDNS_SERVICE_BIN
        if (access("/var/run/updating_ddns_server.txt", F_OK) != 0) {
            v_secure_system("service_ddns restart &");
        }
#else
        v_secure_system("/etc/utopia/service.d/service_dynamic_dns.sh dynamic_dns-restart &");
#endif
    }

    return (rc != 0) ? ANSC_STATUS_FAILURE : ANSC_STATUS_SUCCESS;
}

ULONG
CosaDmlDynamicDns_GetClientStatus()
{
   char buf[8] = {0};
   unsigned long pVal = 6;

   if (!syscfg_get(NULL, "ddns_client_Status", buf, sizeof(buf)))
   {
       if(buf[0] != '\0')
       {
           pVal = atoi(buf);
       }
   }
   return pVal;
}

ULONG
CosaDmlDynamicDns_GetClientLastError()
{
   char buf[8] = {0};
   unsigned long pVal = 1;

   if (!syscfg_get(NULL, "ddns_client_Lasterror", buf, sizeof(buf)))
   {
      if(buf[0] != '\0')
       {
           pVal = atoi(buf);
       }
   }
   return pVal;
}

/***********************************************************************
 APIs for Object:

    DyanmicDNS.Client.{i}.Host.{i}

    *  CosaDmlDynamicDns_Host_GetNumberOfEntries
    *  CosaDmlDynamicDns_Host_GetEntryByIndex
    *  CosaDmlDynamicDns_Host_SetValues
    *  CosaDmlDynamicDns_Host_AddEntry
    *  CosaDmlDynamicDns_Host_DelEntry
    *  CosaDmlDynamicDns_Host_GetConf
    *  CosaDmlDynamicDns_Host_SetConf
***********************************************************************/

static int g_NrDynamicDnsHost =  0;
COSA_DML_DDNS_HOST *g_DDNSHost = NULL;

void CosaInitializeTr181DdnsHost()
{
    int i = 0;
    errno_t rc = -1;
    g_NrDynamicDnsHost = MAX_HOST_COUNT;
    if(!g_DDNSHost && (g_NrDynamicDnsHost > 0))
    {
        g_DDNSHost = (COSA_DML_DDNS_HOST *)AnscAllocateMemory(g_NrDynamicDnsHost * sizeof(COSA_DML_DDNS_HOST));
        if(g_DDNSHost)
        {
            for(i=0; i<g_NrDynamicDnsHost; i++)
            {
                g_DDNSHost[i].Enable = FALSE;
                g_DDNSHost[i].InstanceNumber = i+1;
                rc = sprintf_s(g_DDNSHost[i].Alias, sizeof(g_DDNSHost[i].Alias), "cpe-ddns-host_%d", i+1);
                if(rc < EOK)
                {
                    ERR_CHK(rc);
                }
                g_DDNSHost[i].Status = HOST_DISABLED;
            }
        }
    }
}

static int
DynamicDns_Host_InsGetIndex
    (
        ULONG ins
    )
{
   int i, ret = -1;

    CosaDmlDynamicDns_Host_GetNumberOfEntries();

    for (i = 0; i < g_NrDynamicDnsHost; i++)
    {
        if (g_DDNSHost[i].InstanceNumber == ins) {
            ret = i;
            break;
        }
    }

    return ret;
}

ULONG
CosaDmlDynamicDns_Host_GetNumberOfEntries(void)
{
    return g_NrDynamicDnsHost;
}

ANSC_STATUS
CosaDmlDynamicDns_Host_GetEntryByIndex
    (
        ULONG index,
        COSA_DML_DDNS_HOST *pEntry
    )
{
    char enable_path[sizeof(SYSCFG_HOST_ENABLE_KEY) + 1] = {0};
    char status_path[sizeof(SYSCFG_HOST_STATUS_KEY) + 1] = {0};
    char name_path[sizeof(SYSCFG_HOST_NAME_KEY) + 1] = {0};

    BOOLEAN enable = FALSE;
    char name[256] = {0};
    ULONG status = HOST_DISABLED;

    if (index >= g_NrDynamicDnsHost || (!g_DDNSHost))
    {
        return ANSC_STATUS_FAILURE;
    }

    /* Get from Syscfg db if present or return the default values */
    snprintf(enable_path, sizeof(enable_path), SYSCFG_HOST_ENABLE_KEY, index + 1);
    snprintf(status_path, sizeof(status_path), SYSCFG_HOST_STATUS_KEY, index + 1);
    snprintf(name_path, sizeof(name_path), SYSCFG_HOST_NAME_KEY, index + 1);

    if ((UtGetBool(enable_path, &enable) == ANSC_STATUS_SUCCESS) &&
        (UtGetUlong(status_path, &status) == ANSC_STATUS_SUCCESS) &&
        (UtGetString(name_path, name, (sizeof(name) - 1)) == ANSC_STATUS_SUCCESS))
    {
        g_DDNSHost[index].Enable = enable;
        _ansc_strncpy(g_DDNSHost[index].Name, name, sizeof(g_DDNSHost[index].Name)-1);
        g_DDNSHost[index].Status = status;
    }
    pEntry->InstanceNumber = g_DDNSHost[index].InstanceNumber;
    pEntry->Enable = g_DDNSHost[index].Enable;
    _ansc_strncpy(pEntry->Alias, g_DDNSHost[index].Alias, sizeof(pEntry->Alias)-1);
    _ansc_strncpy(pEntry->Name,  g_DDNSHost[index].Name,  sizeof(pEntry->Name)-1);
    pEntry->Status = g_DDNSHost[index].Status;

    return ANSC_STATUS_SUCCESS;
}

ANSC_STATUS
CosaDmlDynamicDns_Host_SetValues
    (
        ULONG index,
        ULONG ins,
        const char *alias
    )
{

    if (index >= g_NrDynamicDnsHost || !g_DDNSHost)
    {
        return ANSC_STATUS_FAILURE;
    }

    g_DDNSHost[index].InstanceNumber = ins;
    _ansc_strncpy(g_DDNSHost[index].Alias, alias, sizeof(g_DDNSHost[index].Alias)-1);

    return ANSC_STATUS_SUCCESS;
}

ANSC_STATUS
CosaDmlDynamicDns_Host_AddEntry
    (
        COSA_DML_DDNS_HOST *pEntry
    )
{
    CosaDmlDynamicDns_Host_SetValues(0, pEntry->InstanceNumber, pEntry->Alias);

    return ANSC_STATUS_SUCCESS;
}

ANSC_STATUS
CosaDmlDynamicDns_Host_DelEntry
    (
        ULONG ins
    )
{
    return ANSC_STATUS_SUCCESS;
}

ANSC_STATUS
CosaDmlDynamicDns_Host_GetConf
    (
        ULONG ins,
        COSA_DML_DDNS_HOST *pEntry
    )
{
    int index;

    if ((index = DynamicDns_Host_InsGetIndex(ins)) == -1)
    {
        return ANSC_STATUS_FAILURE;
    }

    return CosaDmlDynamicDns_Host_GetEntryByIndex(index, pEntry);
}

ANSC_STATUS
CosaDmlDynamicDns_Host_SetConf
    (
        ULONG ins,
        COSA_DML_DDNS_HOST *pEntry
    )
{
    ULONG index;
    BOOLEAN isHostchanged = FALSE;

    char enable_path[sizeof(SYSCFG_HOST_ENABLE_KEY) + 1] = {0};
    char name_path[sizeof(SYSCFG_HOST_NAME_KEY) + 1] = {0};
    char host_status[2];

    ULONG InsNumber;
    ANSC_HANDLE pClientInsContext = NULL;
    PCOSA_CONTEXT_LINK_OBJECT pClientLinkObj = NULL;
    COSA_DML_DDNS_CLIENT *pClientEntry = NULL;
    BOOL bReadyUpdate = FALSE;

    if ((index = DynamicDns_Host_InsGetIndex(ins)) == -1 || (!g_DDNSHost))
    {
        return ANSC_STATUS_FAILURE;
    }

    snprintf(enable_path, sizeof(enable_path), SYSCFG_HOST_ENABLE_KEY, index + 1);
    snprintf(name_path, sizeof(name_path), SYSCFG_HOST_NAME_KEY, index + 1);

    if (g_DDNSHost[index].Enable != pEntry->Enable)
    {
        isHostchanged = TRUE;
        g_DDNSHost[index].Enable = pEntry->Enable;
        UtSetBool(enable_path, g_DDNSHost[index].Enable);
    }

    if(strcmp(g_DDNSHost[index].Name, pEntry->Name) != 0)
    {
        isHostchanged = TRUE;
        _ansc_strncpy(g_DDNSHost[index].Name, pEntry->Name, sizeof(g_DDNSHost[index].Name)-1);
        UtSetString(name_path, g_DDNSHost[index].Name);
    }

    syscfg_get(NULL, "ddns_host_status_1", host_status, sizeof(host_status));
    if (atoi(host_status) != HOST_REGISTERED)
    {
        isHostchanged = TRUE;
    }

    pClientInsContext = DDNSClient_GetEntry(NULL, 0, &InsNumber);
    if (pClientInsContext)
    {
        pClientLinkObj = (PCOSA_CONTEXT_LINK_OBJECT)pClientInsContext;
        pClientEntry = (COSA_DML_DDNS_CLIENT *)pClientLinkObj->hContext;
    }

    if ((pClientInsContext) && (pClientEntry->Enable) && (pClientEntry->Server[0] != '\0') && (pClientEntry->Username[0] != '\0') && (pEntry->Enable) && (pEntry->Name[0]!='\0'))
    {
        if (strstr(pEntry->Name, "duckdns") == NULL)
        {
            /* Check whether password is null or not for services other than duckdns */
            if (pClientEntry->Password[0] != '\0')
            {
                bReadyUpdate = TRUE;
            }
        }
        else
        {
            /* for duckdns no need to check password */
            bReadyUpdate = TRUE;
        }
    }

    if (bReadyUpdate && CosaDmlDynamicDns_GetEnable() && (g_DDNSHost[index].Enable == TRUE) && (isHostchanged == TRUE) && (g_DDNSHost[index].Name[0] != '\0'))
    {
        /* reset the DynamicDNS client and host status before restart*/
        resetDynamicDNSStatus();
        g_DDNSHost[index].Status = 2; /* HOST_UPDATE_NEEDED=2 */
        CcspTraceInfo(("%s Going to restart dynamic dns service",__FUNCTION__));
        reset_ddns_return_status();
#ifdef DDNS_SERVICE_BIN
        if (access("/var/run/updating_ddns_server.txt", F_OK) != 0) {
            v_secure_system("service_ddns restart &");
        }
#else
        v_secure_system("/etc/utopia/service.d/service_dynamic_dns.sh dynamic_dns-restart &");
#endif
    }
    return ANSC_STATUS_SUCCESS;
}

/* To get the Last successful update of this name to the Dynamic DNS Server. */
ULONG
CosaDmlDynamicDns_GetHostLastUpdate
    (
        char*  lastUpdate
    )
{
    char buf[128] = {0};
    errno_t rc = -1;

    if (!syscfg_get( NULL, "ddns_host_lastupdate_1", buf, sizeof(buf)))
    {
        /* destination buffer lastUpdate is defined as array size of 256 bytes in calling func. */
        rc = strcpy_s(lastUpdate, 256, buf);
        if(rc != EOK)
        {
            ERR_CHK(rc);
            return -1;
        }
        return 0;
    }
    return -1;
}

/***********************************************************************
 APIs for Object:

    DyanmicDNS.Server.{i}

    *  CosaDmlDynamicDns_Server_GetNumberOfEntries
    *  CosaDmlDynamicDns_Server_GetEntryByIndex
    *  CosaDmlDynamicDns_Server_SetValues
    *  CosaDmlDynamicDns_Server_AddEntry
    *  CosaDmlDynamicDns_Server_DelEntry
    *  CosaDmlDynamicDns_Server_GetConf
    *  CosaDmlDynamicDns_Server_SetConf
***********************************************************************/

static int g_NrDynamicDnsServer =  0;
COSA_DML_DDNS_SERVER  *g_DDNSServer = NULL;

void CosaInitializeTr181DdnsServiceProviderList()
{
    char service_list[128] = {0};
    errno_t rc = -1;

    if (!syscfg_get( NULL, "ddns_service_providers_list", service_list, sizeof(service_list)))
    {
        ULONG index = 0;
        char enable_path[sizeof(SYSCFG_SERVER_ENABLE_KEY) + 1] = {0};
        char servicename_path[sizeof(SYSCFG_SERVER_SERVICENAME_KEY) +1] = {0};
        char serveraddress_path[sizeof(SYSCFG_SERVER_SERVERADDRESS_KEY) +1] = {0};
        g_NrDynamicDnsServer = sizeof(gDdnsServices)/sizeof(DDNS_SERVICE);
        g_DDNSServer = (COSA_DML_DDNS_SERVER *)AnscAllocateMemory(g_NrDynamicDnsServer * sizeof(COSA_DML_DDNS_SERVER));
       for(index = 0; index<g_NrDynamicDnsServer; index++)
        {
            g_DDNSServer[index].Enable = FALSE;
            g_DDNSServer[index].InstanceNumber = index+1;
            rc = sprintf_s(g_DDNSServer[index].Alias, sizeof(g_DDNSServer[index].Alias), "cpe-ddns-server_%lu", index+1);
            if(rc < EOK)
            {
                ERR_CHK(rc);
            }
            if (strstr(service_list, gDdnsServices[index].ServiceName))
            {
                g_DDNSServer[index].Enable = TRUE;
                snprintf(enable_path, sizeof(enable_path), SYSCFG_SERVER_ENABLE_KEY, index+1);
                UtSetBool(enable_path, g_DDNSServer[index].Enable);

                snprintf(g_DDNSServer[index].ServiceName, sizeof(g_DDNSServer[index].ServiceName), gDdnsServices[index].ServiceName);
               snprintf(servicename_path, sizeof(servicename_path), SYSCFG_SERVER_SERVICENAME_KEY, index + 1);
                UtSetString(servicename_path, g_DDNSServer[index].ServiceName);

                snprintf(g_DDNSServer[index].Name, sizeof(g_DDNSServer[index].Name), gDdnsServices[index].Name);
                snprintf(g_DDNSServer[index].SupportedProtocols, sizeof(g_DDNSServer[index].SupportedProtocols), gDdnsServices[index].SupportedProtocols);
                snprintf(g_DDNSServer[index].Protocol, sizeof(g_DDNSServer[index].Protocol), gDdnsServices[index].Protocol);

                snprintf(g_DDNSServer[index].ServerAddress, sizeof(g_DDNSServer[index].ServerAddress), gDdnsServices[index].ServerAddress);
                snprintf(serveraddress_path, sizeof(serveraddress_path), SYSCFG_SERVER_SERVERADDRESS_KEY, index + 1);
                UtSetString(serveraddress_path, g_DDNSServer[index].ServerAddress);
            }
        }
    }
}

static int
DynamicDns_Server_InsGetIndex
    (
        ULONG ins
    )
{
    int i, ret = -1;

    CosaDmlDynamicDns_Server_GetNumberOfEntries();

    for (i = 0; i < g_NrDynamicDnsServer; i++)
    {
        if (g_DDNSServer[i].InstanceNumber == ins) {
            ret = i;
            break;
        }
    }

    return ret;
}

ULONG
CosaDmlDynamicDns_Server_GetNumberOfEntries(void)
{
    return g_NrDynamicDnsServer;
}

ANSC_STATUS
CosaDmlDynamicDns_Server_GetEntryByIndex
    (
        ULONG index,
        COSA_DML_DDNS_SERVER *pEntry
    )
{
    char enable_path[sizeof(SYSCFG_SERVER_ENABLE_KEY) + 1] = {0};
    char protocol_path[sizeof(SYSCFG_SERVER_PROTOCOL_KEY) + 1] = {0};
    char checkinterval_path[sizeof(SYSCFG_SERVER_CHECKINTERVAL_KEY) + 1] = {0};
    char retryinterval_path[sizeof(SYSCFG_SERVER_RETRYINTERVAL_KEY) + 1] = {0};
    char maxretries_path[sizeof(SYSCFG_SERVER_MAXRETRIES_KEY) + 1] = {0};
    char serverport_path[sizeof(SYSCFG_SERVER_SERVERPORT_KEY) + 1] = {0};
    char serveraddress_path[sizeof(SYSCFG_SERVER_SERVERADDRESS_KEY) + 1] = {0};

    char protocol[8] = {0}, serveraddress[256] = {0};
    ULONG checkinterval = 0, retryinterval = DEFAULT_RETRYINTERVAL, maxretries = DEFAULT_MAXRETRIES, serverport = 0;
   BOOLEAN enable = FALSE;

    if (index >= g_NrDynamicDnsServer || (!g_DDNSServer))
    {
        return ANSC_STATUS_FAILURE;
    }

    /* Get from Syscfg db if present or return the default values */
    snprintf(enable_path, sizeof(enable_path), SYSCFG_SERVER_ENABLE_KEY, index + 1);
    snprintf(protocol_path, sizeof(protocol_path), SYSCFG_SERVER_PROTOCOL_KEY, index + 1);
    snprintf(checkinterval_path, sizeof(checkinterval_path), SYSCFG_SERVER_CHECKINTERVAL_KEY, index + 1);
    snprintf(retryinterval_path, sizeof(retryinterval_path), SYSCFG_SERVER_RETRYINTERVAL_KEY, index + 1);
    snprintf(maxretries_path, sizeof(maxretries_path), SYSCFG_SERVER_MAXRETRIES_KEY, index + 1);
    snprintf(serverport_path, sizeof(serverport_path), SYSCFG_SERVER_SERVERPORT_KEY, index + 1);
    snprintf(serveraddress_path, sizeof(serveraddress_path), SYSCFG_SERVER_SERVERADDRESS_KEY, index + 1);

    if ((UtGetBool(enable_path, &enable) == ANSC_STATUS_SUCCESS) &&
        (UtGetString(protocol_path, protocol, (sizeof(protocol) - 1)) == ANSC_STATUS_SUCCESS) &&
        (UtGetString(serveraddress_path, serveraddress, (sizeof(serveraddress) - 1)) == ANSC_STATUS_SUCCESS) &&
        (UtGetUlong(checkinterval_path, &checkinterval) == ANSC_STATUS_SUCCESS) &&
        (UtGetUlong(retryinterval_path, &retryinterval) == ANSC_STATUS_SUCCESS) &&
        (UtGetUlong(maxretries_path, &maxretries) == ANSC_STATUS_SUCCESS) &&
        (UtGetUlong(serverport_path, &serverport) == ANSC_STATUS_SUCCESS))
    {
         g_DDNSServer[index].Enable = enable;
         g_DDNSServer[index].CheckInterval = checkinterval;
         g_DDNSServer[index].RetryInterval = retryinterval;
         g_DDNSServer[index].MaxRetries = maxretries;
         g_DDNSServer[index].ServerPort = serverport;
         if (!AnscEqualString(protocol, "", TRUE))
         {
             _ansc_strncpy(g_DDNSServer[index].Protocol, protocol, sizeof(g_DDNSServer[index].Protocol)-1);
        }
         _ansc_strncpy(g_DDNSServer[index].ServerAddress, serveraddress, sizeof(g_DDNSServer[index].ServerAddress)-1);
    }

    /*Copy the values */
    pEntry->InstanceNumber = g_DDNSServer[index].InstanceNumber;
    pEntry->ServerPort = g_DDNSServer[index].ServerPort;
    pEntry->CheckInterval = g_DDNSServer[index].CheckInterval;
    pEntry->RetryInterval = g_DDNSServer[index].RetryInterval;
    pEntry->MaxRetries = g_DDNSServer[index].MaxRetries;
    pEntry->Enable = g_DDNSServer[index].Enable;
    _ansc_strncpy(pEntry->ServerAddress, g_DDNSServer[index].ServerAddress, sizeof(pEntry->ServerAddress)-1);
    _ansc_strncpy(pEntry->Protocol,      g_DDNSServer[index].Protocol,      sizeof(pEntry->Protocol)-1);
    _ansc_strncpy(pEntry->Alias,         g_DDNSServer[index].Alias,         sizeof(pEntry->Alias)-1);
    _ansc_strncpy(pEntry->Name,          g_DDNSServer[index].Name,          sizeof(pEntry->Name)-1);
    _ansc_strncpy(pEntry->ServiceName,   g_DDNSServer[index].ServiceName,   sizeof(pEntry->ServiceName)-1);
    _ansc_strncpy(pEntry->SupportedProtocols, g_DDNSServer[index].SupportedProtocols, sizeof(pEntry->SupportedProtocols)-1);

    return ANSC_STATUS_SUCCESS;
}

ANSC_STATUS
CosaDmlDynamicDns_Server_SetValues
    (
        ULONG index,
        ULONG ins,
        const char *alias
    )
{

    if (index >= g_NrDynamicDnsServer || !g_DDNSServer)
    {
        return ANSC_STATUS_FAILURE;
    }

    g_DDNSServer[index].InstanceNumber = ins;
    _ansc_strncpy(g_DDNSServer[index].Alias, alias, sizeof(g_DDNSServer[index].Alias)-1);

    return ANSC_STATUS_SUCCESS;
}

ANSC_STATUS
CosaDmlDynamicDns_Server_AddEntry
    (
        COSA_DML_DDNS_SERVER *pEntry
    )
{
    return ANSC_STATUS_SUCCESS;
}

ANSC_STATUS
CosaDmlDynamicDns_Server_DelEntry
    (
        ULONG ins
    )
{
    return ANSC_STATUS_SUCCESS;
}

ANSC_STATUS
CosaDmlDynamicDns_Server_GetConf
    (
        ULONG ins,
        COSA_DML_DDNS_SERVER *pEntry
    )
{
    int index;

    if ((index = DynamicDns_Server_InsGetIndex(ins)) == -1)
    {
        return ANSC_STATUS_FAILURE;
    }

    return CosaDmlDynamicDns_Server_GetEntryByIndex(index, pEntry);
}

ANSC_STATUS
CosaDmlDynamicDns_Server_SetConf
    (
        ULONG ins,
        COSA_DML_DDNS_SERVER *pEntry
    )
{
    ULONG index;
    char enable_path[sizeof(SYSCFG_SERVER_ENABLE_KEY) + 1] = {0};
    char protocol_path[sizeof(SYSCFG_SERVER_PROTOCOL_KEY) + 1] = {0};
    char checkinterval_path[sizeof(SYSCFG_SERVER_CHECKINTERVAL_KEY) + 1] = {0};
    char retryinterval_path[sizeof(SYSCFG_SERVER_RETRYINTERVAL_KEY) + 1] = {0};
    char maxretries_path[sizeof(SYSCFG_SERVER_MAXRETRIES_KEY) + 1] = {0};
    char serverport_path[sizeof(SYSCFG_SERVER_SERVERPORT_KEY) + 1] = {0};
    char serveraddress_path[sizeof(SYSCFG_SERVER_SERVERADDRESS_KEY) + 1] = {0};
    char servicename_path[sizeof(SYSCFG_SERVER_SERVICENAME_KEY) +1] = {0};

    if ((index = DynamicDns_Server_InsGetIndex(ins)) == -1 || (!g_DDNSServer))
    {
        return ANSC_STATUS_FAILURE;
    }

#ifndef DDNS_SERVICE_BIN
    if (vsystem("killall -9 ez-ipupdate") != 0)
    {
       fprintf(stderr, "%s: fail to killall ez-ipupdate\n", __FUNCTION__);
    }
#endif

    snprintf(enable_path, sizeof(enable_path), SYSCFG_SERVER_ENABLE_KEY, index + 1);
    snprintf(protocol_path, sizeof(protocol_path), SYSCFG_SERVER_PROTOCOL_KEY, index + 1);
    snprintf(checkinterval_path, sizeof(checkinterval_path), SYSCFG_SERVER_CHECKINTERVAL_KEY, index + 1);
    snprintf(retryinterval_path, sizeof(retryinterval_path), SYSCFG_SERVER_RETRYINTERVAL_KEY, index + 1);
    snprintf(maxretries_path, sizeof(maxretries_path), SYSCFG_SERVER_MAXRETRIES_KEY, index + 1);
    snprintf(serverport_path, sizeof(serverport_path), SYSCFG_SERVER_SERVERPORT_KEY, index + 1);
    snprintf(serveraddress_path, sizeof(serveraddress_path), SYSCFG_SERVER_SERVERADDRESS_KEY, index + 1);
    snprintf(servicename_path, sizeof(servicename_path), SYSCFG_SERVER_SERVICENAME_KEY, index + 1);

    g_DDNSServer[index].ServerPort = pEntry->ServerPort;
    g_DDNSServer[index].CheckInterval = pEntry->CheckInterval;
    g_DDNSServer[index].RetryInterval = pEntry->RetryInterval;
    g_DDNSServer[index].MaxRetries = pEntry->MaxRetries;
    g_DDNSServer[index].InstanceNumber = pEntry->InstanceNumber;
    g_DDNSServer[index].Enable         = pEntry->Enable;
    _ansc_strncpy(g_DDNSServer[index].ServerAddress, pEntry->ServerAddress, sizeof(g_DDNSServer[index].ServerAddress)-1);
    _ansc_strncpy(g_DDNSServer[index].Protocol,      pEntry->Protocol,      sizeof(g_DDNSServer[index].Protocol)-1);
    _ansc_strncpy(g_DDNSServer[index].ServiceName,      pEntry->ServiceName,      sizeof(g_DDNSServer[index].ServiceName)-1);

    /* Set syscfg variable */
    UtSetBool(enable_path, g_DDNSServer[index].Enable);
    UtSetString(protocol_path, g_DDNSServer[index].Protocol);
    UtSetString(serveraddress_path, g_DDNSServer[index].ServerAddress);
    UtSetString(servicename_path, g_DDNSServer[index].ServiceName);
    UtSetUlong(checkinterval_path, g_DDNSServer[index].CheckInterval);
    UtSetUlong(retryinterval_path, g_DDNSServer[index].RetryInterval);
    UtSetUlong(maxretries_path, g_DDNSServer[index].MaxRetries);
    UtSetUlong(serverport_path, g_DDNSServer[index].ServerPort);

#ifdef DDNS_SERVICE_BIN
    if (g_DDNSServer[index].CheckInterval != 0)
    {
        BOOLEAN client_enable = 0;
        UtGetBool("arddnsclient_1::enable", &client_enable);
        if (client_enable)
        {
            char buf[30];
            int server_index = -1;
            UtGetString("arddnsclient_1::Server", buf, sizeof(buf));
            if ((sscanf(buf, "Device.DynamicDNS.Server.%d", &server_index) == 1) &&
                (server_index == (index + 1)))
            {
                int se_fd = -1;
                token_t se_token;
                RemoveCheckIntervalEntryFromCron();
                FILE *cron_fp = fopen("/var/spool/cron/crontabs/root", "a+");
                if (!cron_fp)
                    return ANSC_STATUS_FAILURE;
                fprintf(cron_fp, "* * * * * /usr/bin/service_ddns ddns-check &  #DDNS_CHECK_INTERVAL\n");
                fclose(cron_fp);
                se_fd = sysevent_open("127.0.0.1", SE_SERVER_WELL_KNOWN_PORT, SE_VERSION, "service_ddns", &se_token);
                sysevent_set(se_fd, se_token, "crond-restart", "1", 0);
                sysevent_close(se_fd, se_token);
            }
        }
    }
    else
    {
        /* Delete the DDNS_CHECK_INTERVAL entry from crontab */
        RemoveCheckIntervalEntryFromCron();
    }
#endif

    return ANSC_STATUS_SUCCESS;
}
#endif


text:
"""Feed: Continents

Revision ID: 1c5f54d4aa34
Revises: 312c1d408043
Create Date: 2014-12-10 22:22:23.565032

"""

# revision identifiers, used by Alembic.
revision = '1c5f54d4aa34'
down_revision = '312c1d408043'

from alembic import op
import sqlalchemy as sa
from sqlalchemy.sql import table, column

from csv import reader
from findaconf import app
from findaconf.models import Continent

def upgrade():
    csv_path = app.config['BASEDIR'].child('migrations', 'csv', 'en')
    csv_file = csv_path.child('continents.csv')
    with open(csv_file) as file_handler:
        csv = list(reader(file_handler))
        csv.pop(0)
        data = [{'alpha2': c[0].lower(), 'title': c[1]} for c in csv]

    # Create an ad-hoc table to use for the insert statement.
    continent_table = table('continent',
        column('alpha2', sa.String),
        column('title', sa.String),
    )

    # Insert data.
    op.bulk_insert(continent_table, data)

def downgrade():
    op.execute(Continent.__table__.delete())


text:
import os
import logging
import posixpath

from rest_framework import status
from rest_framework.authentication import SessionAuthentication
from rest_framework.permissions import IsAuthenticated
from rest_framework.response import Response
from rest_framework.views import APIView

from seahub.api2.authentication import TokenAuthentication
from seahub.api2.throttling import UserRateThrottle
from seahub.api2.utils import api_error
from seahub.related_files.models import RelatedFiles
from seahub.tags.models import FileUUIDMap
from seahub.utils import normalize_file_path
from seahub.utils.timeutils import timestamp_to_isoformat_timestr
from seahub.views import check_folder_permission
from seahub.constants import PERMISSION_READ_WRITE

from seaserv import seafile_api

logger = logging.getLogger(__name__)

class RelatedFilesView(APIView):

    authentication_classes = (TokenAuthentication, SessionAuthentication)
    permission_classes = (IsAuthenticated,)
    throttle_classes = (UserRateThrottle,)

    def get_related_file(self, r_repo_id, r_file_path, r_uuid):
        related_file = dict()
        related_file["name"] = r_uuid.filename
        related_file["repo_id"] = r_repo_id
        r_repo = seafile_api.get_repo(r_repo_id)
        if not r_repo:
            related_file["repo_name"] = ""
        related_file["repo_name"] = r_repo.name
        related_file["path"] = r_file_path
        file_obj = seafile_api.get_dirent_by_path(r_repo_id, r_file_path)
        related_file["size"] = file_obj.size
        related_file["last_modified"] = timestamp_to_isoformat_timestr(file_obj.mtime)
        return related_file

    def get(self, request):
        """list all related files of a file.
        """
        # argument check
        repo_id = request.GET.get('repo_id')
        if not repo_id:
            error_msg = 'repo_id invalid.'
            return api_error(status.HTTP_400_BAD_REQUEST, error_msg)

        file_path = request.GET.get('file_path')
        if not file_path:
            error_msg = 'file_path invalid.'
            return api_error(status.HTTP_400_BAD_REQUEST, error_msg)
        file_path = normalize_file_path(file_path)

        # resource check
        repo = seafile_api.get_repo(repo_id)
        if not repo:
            error_msg = 'Library %s not found.' % repo_id
            return api_error(status.HTTP_404_NOT_FOUND, error_msg)

        file_id = seafile_api.get_file_id_by_path(repo_id, file_path)
        if not file_id:
            error_msg = 'File %s not found.' % file_path
            return api_error(status.HTTP_404_NOT_FOUND, error_msg)

        # permission check
        if not check_folder_permission(request, repo_id, '/'):
            error_msg = 'Permission denied.'
            return api_error(status.HTTP_403_FORBIDDEN, error_msg)

        filename = os.path.basename(file_path)
        parent_path = os.path.dirname(file_path)
        uuid = FileUUIDMap.objects.get_or_create_fileuuidmap(repo_id, parent_path, filename, is_dir=False)
        try:
            file_uuid_list = RelatedFiles.objects.get_related_files_uuid(uuid)
        except Exception as e:
            logger.error(e)
            error_msg = 'Internal Server Error'
            return api_error(status.HTTP_500_INTERNAL_SERVER_ERROR, error_msg)

        related_files = list()
        for file_uuid in file_uuid_list:
            if file_uuid.o_uuid == uuid:
                r_path = posixpath.join(file_uuid.r_uuid.parent_path, file_uuid.r_uuid.filename)
                r_repo_id = file_uuid.r_uuid.repo_id
                r_file_id = seafile_api.get_file_id_by_path(r_repo_id, r_path)
                if not r_file_id:
                    continue
                related_file = self.get_related_file(r_repo_id, r_path, file_uuid.r_uuid)
                related_file["related_id"] = file_uuid.pk
                related_files.append(related_file)
            else:
                r_path = posixpath.join(file_uuid.o_uuid.parent_path, file_uuid.o_uuid.filename)
                r_repo_id = file_uuid.o_uuid.repo_id
                r_file_id = seafile_api.get_file_id_by_path(r_repo_id, r_path)
                if not r_file_id:
                    continue
                related_file = self.get_related_file(r_repo_id, r_path, file_uuid.o_uuid)
                related_file["related_id"] = file_uuid.pk
                related_files.append(related_file)

        return Response({"related_files": related_files}, status=status.HTTP_200_OK)

    def post(self, request):
        """add a related file for a file
        """
        # argument check
        o_repo_id = request.data.get('o_repo_id')
        if not o_repo_id:
            error_msg = 'o_repo_id invalid.'
            return api_error(status.HTTP_400_BAD_REQUEST, error_msg)

        r_repo_id = request.data.get('r_repo_id')
        if not r_repo_id:
            error_msg = 'r_repo_id invalid.'
            return api_error(status.HTTP_400_BAD_REQUEST, error_msg)

        o_path = request.data.get('o_path')
        if not o_path:
            error_msg = 'o_file_path invalid.'
            return api_error(status.HTTP_400_BAD_REQUEST, error_msg)
        o_path = normalize_file_path(o_path)

        r_path = request.data.get('r_path')
        if not r_path:
            error_msg = 'r_file_path invalid.'
            return api_error(status.HTTP_400_BAD_REQUEST, error_msg)
        r_path = normalize_file_path(r_path)

        if o_repo_id == r_repo_id and o_path == r_path:
            error_msg = 'Cannot relate itself.'
            return api_error(status.HTTP_400_BAD_REQUEST, error_msg)

        # resource check
        o_repo = seafile_api.get_repo(o_repo_id)
        r_repo = seafile_api.get_repo(r_repo_id)
        if not o_repo:
            error_msg = 'Library %s not found.' % o_repo_id
            return api_error(status.HTTP_404_NOT_FOUND, error_msg)
        if not r_repo:
            error_msg = 'Library %s not found.' % r_repo_id
            return api_error(status.HTTP_404_NOT_FOUND, error_msg)

        o_file_id = seafile_api.get_file_id_by_path(o_repo_id, o_path)
        r_file_id = seafile_api.get_file_id_by_path(r_repo_id, r_path)
        if not o_file_id:
            error_msg = 'File %s not found.' % o_path
            return api_error(status.HTTP_404_NOT_FOUND, error_msg)
        if not r_file_id:
            error_msg = 'File %s not found.' % r_path
            return api_error(status.HTTP_404_NOT_FOUND, error_msg)

        related_file_uuid = RelatedFiles.objects.get_related_file_uuid(o_repo_id, r_repo_id, o_path, r_path)
        if related_file_uuid:
            error_msg = 'related file already exist.'
            return api_error(status.HTTP_400_BAD_REQUEST, error_msg)

        # permission check
        if check_folder_permission(request, o_repo_id, '/') != PERMISSION_READ_WRITE:
            error_msg = 'Permission denied.'
            return api_error(status.HTTP_403_FORBIDDEN, error_msg)

        try:
            related_file_uuid = RelatedFiles.objects.add_related_file_uuid(o_repo_id, r_repo_id, o_path, r_path)
        except Exception as e:
            logger.error(e)
            error_msg = 'Internal Server Error'
            return api_error(status.HTTP_500_INTERNAL_SERVER_ERROR, error_msg)

        related_file = self.get_related_file(r_repo_id, r_path, related_file_uuid.r_uuid)
        related_file["related_id"] = related_file_uuid.pk

        return Response({"related_file": related_file}, status.HTTP_201_CREATED)

class RelatedFileView(APIView):

    authentication_classes = (TokenAuthentication, SessionAuthentication)
    permission_classes = (IsAuthenticated,)
    throttle_classes = (UserRateThrottle,)

    def delete(self, request, related_id):
        """delete a related file from a file
        """
        # argument check
        repo_id = request.data.get('repo_id')
        if not repo_id:
            error_msg = 'repo_id invalid.'
            return api_error(status.HTTP_400_BAD_REQUEST, error_msg)

        file_path = request.data.get('file_path')
        if not file_path:
            error_msg = 'file_path invalid.'
            return api_error(status.HTTP_400_BAD_REQUEST, error_msg)
        file_path = normalize_file_path(file_path)

        # resource check
        related_file_uuid = RelatedFiles.objects.get_related_file_uuid_by_id(related_id)
        if not related_file_uuid:
            error_msg = 'Related %s does not exist.' % related_id
            return api_error(status.HTTP_404_NOT_FOUND, error_msg)

        file_id = seafile_api.get_file_id_by_path(repo_id, file_path)
        if not file_id:
            error_msg = 'File %s not found.' % file_path
            return api_error(status.HTTP_404_NOT_FOUND, error_msg)

        # permission check
        if check_folder_permission(request, repo_id, '/') != PERMISSION_READ_WRITE:
            print(check_folder_permission(request, repo_id, file_path))
            error_msg = 'Permission denied.'
            return api_error(status.HTTP_403_FORBIDDEN, error_msg)

        try:
            RelatedFiles.objects.delete_related_file_uuid(related_id)
        except Exception as e:
            logger.error(e)
            error_msg = 'Internal Server Error'
            return api_error(status.HTTP_500_INTERNAL_SERVER_ERROR, error_msg)

        return Response({"success": "true"}, status=status.HTTP_200_OK)


text:
var Application = (function() {

  'use strict';

  var app = function() {

    var that = this;
    var started = false;

    //
    // public
    //
    var pizzaShop = {

      cart:[],
      setupEvents: function(){

        $("#jumpToOrders").off().bind('click', function(){

              window.location.href = "/";

        });

        $(".deleteBtn").off().bind('click', function(e){
            var _id;
            e.preventDefault();

            _id = $(this).val();

            if(confirm("This will permanently delete this item. \n\n Are you sure?")){
              $.ajax({
                method: "DELETE",
                url: "/api/orders/" + _id,
                data: { dummy: _id}
              })
              .done(function( msg ) {
                  window.location.href = "/orders";
              });

            }

        });

      },
      start: function(){
        this.setupEvents();
      }

    };

    return pizzaShop;

  }();

  app.start();

  return app;
})();


text:
<?php

/**
 * Article form base class.
 *
 * @package    ##PROJECT_NAME##
 * @subpackage form
 * @author     Your name here
 * @version    SVN: $Id: sfPropelFormGeneratedTemplate.php 16976 2009-04-04 12:47:44Z fabien $
 */
class BaseArticleForm extends BaseFormPropel
{
  public function setup()
  {
    $this->setWidgets(array(
      'id'                  => new sfWidgetFormInputHidden(),
      'title'               => new sfWidgetFormInput(),
      'body'                => new sfWidgetFormTextarea(),
      'Online'              => new sfWidgetFormInputCheckbox(),
      'excerpt'             => new sfWidgetFormInput(),
      'category_id'         => new sfWidgetFormPropelChoice(array('model' => 'Category', 'add_empty' => false)),
      'created_at'          => new sfWidgetFormDateTime(),
      'end_date'            => new sfWidgetFormDateTime(),
      'book_id'             => new sfWidgetFormPropelChoice(array('model' => 'Book', 'add_empty' => true)),
      'author_article_list' => new sfWidgetFormPropelChoiceMany(array('model' => 'Author')),
    ));

    $this->setValidators(array(
      'id'                  => new sfValidatorPropelChoice(array('model' => 'Article', 'column' => 'id', 'required' => false)),
      'title'               => new sfValidatorString(array('max_length' => 255)),
      'body'                => new sfValidatorString(array('required' => false)),
      'Online'              => new sfValidatorBoolean(array('required' => false)),
      'excerpt'             => new sfValidatorString(array('required' => false)),
      'category_id'         => new sfValidatorPropelChoice(array('model' => 'Category', 'column' => 'id')),
      'created_at'          => new sfValidatorDateTime(array('required' => false)),
      'end_date'            => new sfValidatorDateTime(array('required' => false)),
      'book_id'             => new sfValidatorPropelChoice(array('model' => 'Book', 'column' => 'id', 'required' => false)),
      'author_article_list' => new sfValidatorPropelChoiceMany(array('model' => 'Author', 'required' => false)),
    ));

    $this->validatorSchema->setPostValidator(
      new sfValidatorPropelUnique(array('model' => 'Article', 'column' => array('title', 'category_id')))
    );

    $this->widgetSchema->setNameFormat('article[%s]');

    $this->errorSchema = new sfValidatorErrorSchema($this->validatorSchema);

    parent::setup();
  }

  public function getModelName()
  {
    return 'Article';
  }

  public function updateDefaultsFromObject()
  {
    parent::updateDefaultsFromObject();

    if (isset($this->widgetSchema['author_article_list']))
    {
      $values = array();
      foreach ($this->object->getAuthorArticles() as $obj)
      {
        $values[] = $obj->getAuthorId();
      }

      $this->setDefault('author_article_list', $values);
    }

  }

  protected function doSave($con = null)
  {
    parent::doSave($con);

    $this->saveAuthorArticleList($con);
  }

  public function saveAuthorArticleList($con = null)
  {
    if (!$this->isValid())
    {
      throw $this->getErrorSchema();
    }

    if (!isset($this->widgetSchema['author_article_list']))
    {
      // somebody has unset this widget
      return;
    }

    if (is_null($con))
    {
      $con = $this->getConnection();
    }

    $c = new Criteria();
    $c->add(AuthorArticlePeer::ARTICLE_ID, $this->object->getPrimaryKey());
    AuthorArticlePeer::doDelete($c, $con);

    $values = $this->getValue('author_article_list');
    if (is_array($values))
    {
      foreach ($values as $value)
      {
        $obj = new AuthorArticle();
        $obj->setArticleId($this->object->getPrimaryKey());
        $obj->setAuthorId($value);
        $obj->save();
      }
    }
  }

}


text:
require 'spec_helper'

describe "UserPages" do

  subject { page }

  describe "index" do
    let(:user) { FactoryGirl.create(:user) }
    before do
      sign_in user
      visit users_path
    end

    it {should have_selector('title', text: 'All users') }
    it { should have_selector('h1', text: 'All users') }

    describe "pagination" do
      before(:all) { 30.times { FactoryGirl.create(:user) } }
      after(:all) { User.delete_all }
      before(:each) do
        sign_in user
        visit users_path
      end
      it { should have_selector('div.pagination')}

      it "should list each user" do
        User.paginate(page: 1).each do |user|
          page.should have_selector('li', text: user.name)
        end
      end
    end

    describe "delete links" do
      it { should_not have_link('delete') }

      describe "as an admin user" do
        let(:admin) { FactoryGirl.create(:admin) }
        before do
          sign_in admin
          visit users_path
        end

        it { should have_link('delete', href: user_path(User.first)) }
        it "should be able to delete another user" do
          expect { click_link('delete')}.to change(User, :count).by(-1)
        end

        it { should_not have_link('delete', href: user_path(admin)) }
        end
      end
    end
  describe "profile page" do

    let(:user) {FactoryGirl.create(:user)}
    let!(:m1) { FactoryGirl.create(:micropost, user: user, content: "Foo") }
    let!(:m2) { FactoryGirl.create(:micropost, user: user, content: "Bar") }

    before { visit user_path(user) }

    it { should have_selector('h1', text: user.name) }
    it { should have_selector('title', text: user.name) }

    describe "microposts" do
      it { should have_content(m1.content) }
      it { should have_content(m2.content) }
      it { should have_content(user.microposts.count) }
    end
  end
  describe "signup page" do
    before { visit signup_path }

    let(:submit) { "Create my account" }

    describe "with invalid information" do
      it "should not create a user" do
        expect { click_button submit}.not_to change(User, :count)
      end
    end

    describe "with valid information" do
      before do
        fill_in "Name",         with: "Example User"
        fill_in "Email",        with: "user@example.com"
        fill_in "Password",     with: "foobar"
        fill_in "Confirmation", with: "foobar"
      end

      it "should create a user" do
        expect { click_button submit }.to change(User, :count).by(1)
      end

      describe "after saving the user" do
        before { click_button "Create my account"}

        let(:user) {User.find_by_email('user@example.com')}

        it { should have_selector('title',text: user.name)}
        it{ should have_selector('div.alert.alert-success', text: 'Welcome')}

      end
    end
  end

  describe "edit" do
    let(:user) { FactoryGirl.create(:user) }
    before do
      sign_in user
      visit edit_user_path(user)
    end

    describe "page" do
      it { should have_selector('h1', text: "Update your profile") }
      it { should have_selector('title', text: "Edit user") }
      it { should have_link('change', href: 'http://gravatar.com/emails')}
    end

    describe "with invalid information" do
      before { click_button "Save changes"}
      it { should have_content('error')}
    end

    describe "with valid information" do
      let(:new_name) { "New Name" }
      let(:new_email) { "new@example.com" }
      before do
        fill_in "Name", with: new_name
        fill_in "Email", with: new_email
        fill_in "Password", with: user.password
        fill_in "Confirmation", with: user.password
        click_button "Save changes"
      end

      it { should have_selector('title',text: new_name)}
      it{ should have_selector('div.alert.alert-success') }
      it {should have_link('Sign out', href: signout_path) }
      specify { user.reload.name.should == new_name }
      specify { user.reload.email.should == new_email }
    end
 end
end


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using SitecoreCognitiveServices.Foundation.MSSDK.Models.Bing.VideoSearch;

namespace SitecoreCognitiveServices.Foundation.MSSDK.Models.Bing.WebSearch {
    public class WebSearchVideos
    {
        public string Id { get; set; }
        public string ReadLink { get; set; }
        public string WebSearchUrl { get; set; }
        public bool IsFamilyFriendly { get; set; }
        public List<VideoSearchResult> Value { get; set; }
        public string Scenario { get; set; }
    }
}


text:
(function(scope){
	function fQueue(capacity) {
		capacity = capacity || 8192;

		var array = new Array(capacity);
		var size = 0;
		var first = 0;
		var last = -1;

		function enqueue(item){
			size ++;
			last ++;

			if (last == capacity)
				last = 0;
			if (size > capacity)
				dequeue();

			array[last] = item;
		}

		function dequeue() {
			if (size == 0)
				return undefined;

			item = array[first];
			first ++;
			size --;

			if (first == capacity)
				first = 0;

			return item;
		}

		this.enqueue = enqueue;
		this.dequeue = dequeue;
		this.size = function() { return size; };
	}

	scope.fQueue = fQueue;
})(window);


text:
/*
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package io.netty.util.internal;

import java.util.AbstractQueue;
import java.util.Iterator;
import java.util.concurrent.atomic.AtomicReference;

/**
 * Forked from JCTools.
 */
abstract class BaseLinkedAtomicQueue<E> extends AbstractQueue<E> {
    private final AtomicReference<LinkedQueueAtomicNode<E>> producerNode;
    private final AtomicReference<LinkedQueueAtomicNode<E>> consumerNode;
    public BaseLinkedAtomicQueue() {
        producerNode = new AtomicReference<LinkedQueueAtomicNode<E>>();
        consumerNode = new AtomicReference<LinkedQueueAtomicNode<E>>();
    }
    protected final LinkedQueueAtomicNode<E> lvProducerNode() {
        return producerNode.get();
    }
    protected final LinkedQueueAtomicNode<E> lpProducerNode() {
        return producerNode.get();
    }
    protected final void spProducerNode(LinkedQueueAtomicNode<E> node) {
        producerNode.lazySet(node);
    }
    protected final LinkedQueueAtomicNode<E> xchgProducerNode(LinkedQueueAtomicNode<E> node) {
        return producerNode.getAndSet(node);
    }
    protected final LinkedQueueAtomicNode<E> lvConsumerNode() {
        return consumerNode.get();
    }

    protected final LinkedQueueAtomicNode<E> lpConsumerNode() {
        return consumerNode.get();
    }
    protected final void spConsumerNode(LinkedQueueAtomicNode<E> node) {
        consumerNode.lazySet(node);
    }
    @Override
    public final Iterator<E> iterator() {
        throw new UnsupportedOperationException();
    }

    /**
     * {@inheritDoc}

     *

     * IMPLEMENTATION NOTES:

     * This is an O(n) operation as we run through all the nodes and count them.

     *
     * @see java.util.Queue#size()
     */
    @Override
    public final int size() {
        LinkedQueueAtomicNode<E> chaserNode = lvConsumerNode();
        final LinkedQueueAtomicNode<E> producerNode = lvProducerNode();
        int size = 0;
        // must chase the nodes all the way to the producer node, but there's no need to chase a moving target.
        while (chaserNode != producerNode && size < Integer.MAX_VALUE) {
            LinkedQueueAtomicNode<E> next;
            while ((next = chaserNode.lvNext()) == null) {
                continue;
            }
            chaserNode = next;
            size++;
        }
        return size;
    }
    /**
     * {@inheritDoc}

     *

     * IMPLEMENTATION NOTES:

     * Queue is empty when producerNode is the same as consumerNode. An alternative implementation would be to observe
     * the producerNode.value is null, which also means an empty queue because only the consumerNode.value is allowed to
     * be null.
     *
     * @see MessagePassingQueue#isEmpty()
     */
    @Override
    public final boolean isEmpty() {
        return lvConsumerNode() == lvProducerNode();
    }
}


text:
"""
Implementation of ranking metrics.
"""
import numpy as np
from numpy import sum

def aucEval(data, gt, gf):
    """
     Area under the Receiver-Operator curve.

     This is a fast implementation that follows the trajectory of the ROC curve and needs only a single pass through the data.
     Start in lower-right corner, for a pos document go up, for neg document go right.

     This implementation assumes that the ranking is complete.
    """
    _gt = np.count_nonzero(data)
    _gf = len(data) - _gt
    allPairs = _gt * _gf

    accum = np.cumsum(data)
    accum = sum(accum[np.logical_not(data)])
    if allPairs == 0 or len(data)==0:
        return 0.5

    return 1. * accum / allPairs

def normalizeAUC(data, gt, gf):
    """
    Rescale aucEval to [-1, +1] to better match the perturbation level
    """
    classicAUC = aucEval(data, gt, gf)
    scaledAUC = (classicAUC - 0.5) * 2
    return scaledAUC

def extendedAucEval(data, gt, gf):
    """
    Hack AUC to gracefully handle the case where not all positive documents are contained in the ranking
    """
    _gt = np.count_nonzero(data)
    _gf = len(data) - _gt
    allPairs = gt * _gf  #virtually add ground truth docs that were not part of the ranking

    accum = np.cumsum(data)
    accum = sum(accum[np.logical_not(data)])
    if allPairs == 0 or len(data)==0:
        return 0.5

    return 1. * accum / allPairs

def normalizeExtendedAUC(data, gt, gf):
    """
    Rescale extendedAucEval to [-1, +1] to better match the perturbation level
    """
    classicAUC = extendedAucEval(data, gt, gf)
    scaledAUC = (classicAUC - 0.5) * 2
    return scaledAUC

def precREval(data, gt, gf):
    """
    Compute R-Precision (Precision at a rank that represents the number of relevant documents).
    """
    if(gt == 0): print 'gt=0 in precREval'
    return 1.0 * sum(data[0:gt])/gt

def mapEval(data, gt, gf):
    """
    Compute Mean average precision following this algorithm:
    - for every rank p that yields a positive document:
    --- compute precision at p
    - take the average of all computed precisions
    """
    relevant = np.count_nonzero(data)
    if relevant == 0:
        # no relevant documents, produce 0.0
        return 0.0
    d = np.array(data, dtype='f8')
    prec = np.cumsum(d) / (np.arange(len(d)) + 1)
    score = 1.0 * np.sum(prec[data]) / gt
    return score

def dcg(data):
    """
    Compute Discounted Cumulative Gain which is computed by
    - for every rank p that yields a positive document:
    --- 1/log(p+2)
    - sum over all values
    """
    d = np.array(data, dtype='f8')
    return sum(d / np.log(np.arange(len(d))+2))

def generate_ideal(gt, gf):
    """
    generate the ideal ranking for nDCG
    """
    ideal = np.zeros(gt+gf)
    ideal[:gt] = True
    return ideal

def ndcgEval(data, gt, gf):
    """
    Normalized Discounted Cumulative Gain:
     DCG / DCG(ideal ranking)
    """
    ideal = generate_ideal(gt, gf)
    dcgScore = dcg(data)
    norm = dcg(ideal[:len(data)])
    if(norm == 0): print('norm=0 in ndcgEval')
    return dcgScore / norm

def ndcgREval(data, gt, gf):
    """
    Compute NDCG@R, where R is the number of relevant documents
    """
    ideal = generate_ideal(gt,gf)
    dcgScore = dcg(data[:(gt)])
    norm = dcg(ideal[:(gt)][:len(data)])
    if(norm == 0): print('norm=0 in ndcgREval')
    return dcgScore / norm


text:
Pattern: Use of `__idiv__` method

Issue: -

## Description

This method does not exist in _Python 3_. Using `__itruediv__` and setting `__idiv__ = __itruediv__` should be preferred.


text:
class acWXHTMLWindow;
class apDebuggedProcessRunSuspendedEvent;
class apStatistics;
class gdStatisticsPanel;
class afProgressBarWrapper;

// Local:
#include <AMDTGpuDebuggingComponents/Include/gdStringConstants.h>
#include <AMDTGpuDebuggingComponents/Include/views/gdStatisticsViewBase.h>

// Infra:
#include <AMDTOSWrappers/Include/osFilePath.h>
#include <AMDTAPIClasses/Include/Events/apMonitoredObjectsTreeEvent.h>
#include <AMDTApplicationComponents/Include/acRawFileHandler.h>
#include <AMDTApplicationComponents/Include/acDataView.h>
#include <AMDTApplicationComponents/Include/acColorSampleBox.h>

// AMDTApplicationFramework:
#include <AMDTApplicationFramework/Include/views/afBaseView.h>

// need to undef Bool after all includes so the moc will compile in Linux
#undef Bool

// Pre-Decleration:
class gdAPICallsHistoryView;

// ----------------------------------------------------------------------------------
// Class Name:           gdStatisticsView: public acFrame
//                       public apIEventsObserver
// General Description:  The Statistics viewer.
// ----------------------------------------------------------------------------------
class GD_API gdStatisticsView : public QTabWidget
{
    Q_OBJECT

    friend class gdStatisticsPanel;

public:
    // Constructors:
    gdStatisticsView(afProgressBarWrapper* pProgressBar, QWidget* pParent, gdStatisticsPanel* pParentStatisticsPanel, bool isAnalyzeModeEnabled = true);

    // Destructor
    ~gdStatisticsView();

    // Update utilities:
    bool updateStatisticsViewers();
    void applyPageOnClick(gdStatisticsViewIndex windowIndex);
    void clearAllViewers();

    // Layout:
    virtual void setFrameLayout(const QSize& viewSize);

    // Public UI events:
    void onUpdateShowDetailedBatchData(bool& isEnabled, bool& isChecked);
    void onDetailedBatchDataButton();
    void onUpdateDetailedBatchDataButton(bool& isEnabled);
    bool displayContext(const apContextID& contextID, bool forceUpdate = false);

    void exportStatistics(int pageIndex);
    int pageItemCount(int pageIndex);

    // Selected page:
    int selectedPageIndex();
    void setSelectedPage(int selectedPageIndex);
    void setSelectedPageFromGlobalIndex(int selectedPageIndex);
    gdStatisticsViewBase* selectedPage();

    void setActiveContext(apContextID activeContext) {_activeContext = activeContext;} ;

    // Edit menu commands
    virtual void onUpdateEdit_Copy(bool& isEnabled);
    virtual void onUpdateEdit_SelectAll(bool& isEnabled);

    virtual void onEdit_Copy();
    virtual void onEdit_SelectAll();

    // Debugged process event handlers:
    virtual void onTreeItemSelection(const apMonitoredObjectsTreeSelectedEvent& eve);
    void onBreakpointHitEvent();

    void setChartWindow(acChartWindow* pChartWindow) {_pChartWindow = pChartWindow;};

    // Get the requested statistics view:
    gdStatisticsViewBase* statisticsPage(gdStatisticsViewIndex windowIndex);

    /// \param[out] selectedText returns the text currently selected
    virtual void GetSelectedText(gtString& selectedText);

protected:

    // Layout creation functions:
    void createStatisticsPages();

    bool createRenderContextWindow();
    void initializeColorVectors();

    // Virtual function:
    // Raise the view and show it as top window:
    virtual void raiseView();

    // Chart help functions:
    void updateViewerChart(gdStatisticsViewIndex windowIndex, gdStatisticsViewBase* pViewer, int sampledDataIndex, bool useColorsBeforeSort, acChartType chartType);
    bool addItemToChart(gdStatisticsViewBase* pViewer, bool isNewData, int& amountOfNonZeroItems, bool useColorsBeforeSort, int itemIndex, int sampledDataIndex, bool isSelected);

    int windowIDToTabViewerID(int cmdId);

    void showPagesAccordingToContextType();

protected slots:

    void onPageChange(int newPageIndex);

    // List click event handlers:
    void onStateChangeStatsClick(QTableWidgetItem* pClickedItem);
    void onDeprecationStatsClick(QTableWidgetItem* pClickedItem);
    void onBatchStatsClick(QTableWidgetItem* pClickedItem);
    void onFunctionStatisticsClick(QTableWidgetItem* pClickedItem);
    void onTotalStatisticsClick(QTableWidgetItem* pClickedItem);
    void onListSelectionChanged();
    void onCallsHistoryClick(const QModelIndex& index);
    bool connectViewToHandlers();
    void onChartItemClicked(int chartItemIndex);

    virtual void onFindClick();
    virtual void onFindNext();
    void onColumnSorted();

protected:

    // Progress bar:
    afProgressBarWrapper* _pProgressBar;

    // Statistics Chart:
    acChartWindow* _pChartWindow;

    // Parent panel:
    gdStatisticsPanel* _pParentStatisticsPanel;

    // Contain the proportion for the top / bottom panels:
    float _bottomPanelProp;

    // Contain the proportion for the left / right bottom panels:
    float _leftPanelProp;

    // Currently active context
    apContextID _activeContext;

    // Previous active context:
    apContextID _previousDisplayedContext;

    // Holds the current statistics information:
    apStatistics* _pStatistics;

    // Remember which panes were shown when hiding the viewer
    bool _isChartShown;

    gdStatisticsViewIndex _lastSelectedNoteBookPane;

    // Contain true iff analyze mode is currently enabled:
    bool _isAnalyzeModeEnabled;

    // Vector of booleans containing true iff the page i is currently displayed:
    bool _shouldDisplayPages[GD_STATISTICS_VIEW_LAST_VIEWER_INDEX + 1];

    // Array of pages captions:
    QString m_pagesCaptions[GD_STATISTICS_VIEW_LAST_VIEWER_INDEX + 1];

    // Statistics viewer pages:
    gdStatisticsViewBase* _pages[GD_STATISTICS_VIEW_LAST_VIEWER_INDEX + 1];

    // Calls history view:
    gdAPICallsHistoryView* _pCallHistoryView;

    // Contain true iff the view is currently shown in VS:
    bool _isShown;

    // Contain true if we should ignore item activation events;
    bool _ignoreListSelectionEvents;

    // Force chart data update:
    bool _forceChartUpdate;

};

#endif  // __GDSTATISTICSVIEW


text:
'use strict';

var grunt = require('grunt');

/*
  ======== A Handy Little Nodeunit Reference ========
  https://github.com/caolan/nodeunit
  Test methods:
    test.expect(numAssertions)
    test.done()
  Test assertions:
    test.ok(value, [message])
    test.equal(actual, expected, [message])
    test.notEqual(actual, expected, [message])
    test.deepEqual(actual, expected, [message])
    test.notDeepEqual(actual, expected, [message])
    test.strictEqual(actual, expected, [message])
    test.notStrictEqual(actual, expected, [message])
    test.throws(block, [error], [message])
    test.doesNotThrow(block, [error], [message])
    test.ifError(value)
*/

exports.osslsigncode = {
  setUp: function(done){
    // setup here if necessary
    done();
  },

  load: function(test){
    test.expect(6);

    var actual = require('../tasks/osslsigncode');
    var expected = 'function';
    test.equal(typeof actual, expected, 'Should export a function');

    test.equal(grunt.file.exists('tmp/cert_output.key'), true, 'tmp/cert_output.key should exist');
    test.equal(grunt.file.exists('tmp/cert_output.spc'), true, 'tmp/cert_output.spc should exist');
    test.equal(grunt.file.exists('tmp/cert_tmp_cert.pem'), true, 'tmp/cert_tmp_cert.pem should exist');
    test.equal(grunt.file.exists('tmp/cert_tmp_key.pem'), true, 'tmp/cert_tmp_key.pem should exist');
    test.equal(grunt.file.exists('bin-out/app.signed.msi'), true, 'bin-out/app.signed.msi should exist');

    test.done();
  }
};


text:
var rimraf
  , path = require("path")

try {
  rimraf = require("../fiber")
} catch (er) {
  console.error("skipping fiber test")
}

if (rimraf) {
  Fiber(function () {
    rimraf(path.join(__dirname, "target")).wait()
  }).run()
}


text:
<?php
/**
 * Autocompleting text field, using script.aculo.us
 *
 * @deprecated 2.4 Use third-party alternatives like http://code.google.com/p/ss-module-formfields/ or http://silverstripe.org/tag-field-module/
 *
 * @package forms
 * @subpackage fields-formattedinput
 */
class AutocompleteTextField extends TextField {

	protected $optionsURL;

	function __construct($name, $title = null, $optionsURL, $value = "", $maxLength = null){
		$this->optionsURL = $optionsURL;

		parent::__construct($name, $title, $value, $maxLength);
	}

	function extraClass() {
		return parent::extraClass() . " autocomplete";
	}

	function Field() {
		// Requirements::javascript(SAPPHIRE_DIR . '/javascript/AutocompleteTextField.js');
		$attributes = array(
			'class' => "{$this->class} text" . ($this->extraClass() ? $this->extraClass() : ''),
			'type' => 'text',
			'id' => $this->id(),
			'name' => $this->name,
			'value' => $this->Value(),
			'tabindex' => $this->getTabIndex(),
			'size' => $this->maxLength ? min( $this->maxLength, 30 ) : 30
		);
		if($this->maxLength) $attributes['maxlength'] = $this->maxLength;

		return $this->createTag('input', $attributes) . "
id() . "_Options\" class=\"autocompleteoptions\">
";
	}

	function FieldHolder() {
		$holder = parent::FieldHolder();

		$id = $this->id();

		$holder .= <<<JS

JS;

		return $holder;
	}
}
?>