text:
#include "includes.h"

extern int DEBUGLEVEL;
extern pstring global_myname;

extern uint16 samba_nb_type; /* Samba's NetBIOS name type. */

/*******************************************************************
 Utility function to add a name to the unicast subnet, or add in
 our IP address if it already exists.
******************************************************************/

void insert_permanent_name_into_unicast( struct subnet_record *subrec,
                                                struct nmb_name *nmbname, uint16 nb_type )
{
  struct name_record *namerec;

  if((namerec = find_name_on_subnet(unicast_subnet, nmbname, FIND_SELF_NAME)) == NULL)
  {
    /* The name needs to be created on the unicast subnet. */
    (void)add_name_to_subnet( unicast_subnet, nmbname->name,
                              nmbname->name_type, nb_type,
                              PERMANENT_TTL, PERMANENT_NAME, 1, &subrec->myip);
  }
  else
  {
    /* The name already exists on the unicast subnet. Add our local
       IP for the given broadcast subnet to the name. */
    add_ip_to_name_record( namerec, subrec->myip);
  }
}

/*******************************************************************
 Utility function to remove a name from the unicast subnet.
******************************************************************/

static void remove_permanent_name_from_unicast( struct subnet_record *subrec,
                                                struct nmb_name *nmbname )
{
  struct name_record *namerec;

  if((namerec = find_name_on_subnet(unicast_subnet, nmbname, FIND_SELF_NAME)) != NULL)
  {
    /* Remove this broadcast subnet IP address from the name. */
    remove_ip_from_name_record( namerec, subrec->myip);
    if(namerec->data.num_ips == 0)
      remove_name_from_namelist( unicast_subnet, namerec);
  }
}

/*******************************************************************
 Utility function always called to set our workgroup and server
 state back to potential browser, or none.
******************************************************************/

static void reset_workgroup_state( struct subnet_record *subrec, char *workgroup_name,
                                   BOOL force_new_election )
{
  struct work_record *work;
  struct server_record *servrec;
  struct nmb_name nmbname;

  if((work = find_workgroup_on_subnet( subrec, workgroup_name)) == NULL)
  {
    DEBUG(0,("reset_workgroup_state: Error - cannot find workgroup %s on \
subnet %s.\n", workgroup_name, subrec->subnet_name ));
    return;
  }

  if((servrec = find_server_in_workgroup( work, global_myname)) == NULL)
  {
    DEBUG(0,("reset_workgroup_state: Error - cannot find server %s \
in workgroup %s on subnet %s\n",
       global_myname, work->work_group, subrec->subnet_name));
    work->mst_state = lp_local_master() ? MST_POTENTIAL : MST_NONE;
    return;
  }

  /* Update our server status - remove any master flag and replace
   it with the potential browser flag. */
  servrec->serv.type &= ~SV_TYPE_MASTER_BROWSER;
  servrec->serv.type |= (lp_local_master() ? SV_TYPE_POTENTIAL_BROWSER : 0);

  /* Tell the namelist writer to write out a change. */
  subrec->work_changed = True;

  /* Reset our election flags. */
  work->ElectionCriterion &= ~0x4;

  work->mst_state = lp_local_master() ? MST_POTENTIAL : MST_NONE;

  /* Forget who the local master browser was for
     this workgroup. */

  set_workgroup_local_master_browser_name( work, "");

  /*
   * Ensure the IP address of this subnet is not registered as one
   * of the IP addresses of the WORKGROUP<1d> name on the unicast
   * subnet. This undoes what we did below when we became a local
   * master browser.
   */

  make_nmb_name(&nmbname, work->work_group, 0x1d);

  remove_permanent_name_from_unicast( subrec, &nmbname);

  if(force_new_election)
    work->needelection = True;
}

/*******************************************************************
  Unbecome the local master browser name release success function.
******************************************************************/

static void unbecome_local_master_success(struct subnet_record *subrec,
                             struct userdata_struct *userdata,
                             struct nmb_name *released_name,
                             struct in_addr released_ip)
{
  BOOL force_new_election = False;

  memcpy((char *)&force_new_election, userdata->data, sizeof(BOOL));

  DEBUG(3,("unbecome_local_master_success: released name %s.\n",
             nmb_namestr(released_name)));

  /* Now reset the workgroup and server state. */
  reset_workgroup_state( subrec, released_name->name, force_new_election );

  if( DEBUGLVL( 0 ) )
  {
    dbgtext( "*****\n\n" );
    dbgtext( "Samba name server %s ", global_myname );
    dbgtext( "has stopped being a local master browser " );
    dbgtext( "for workgroup %s ", released_name->name );
    dbgtext( "on subnet %s\n\n*****\n", subrec->subnet_name );
  }

}

/*******************************************************************
  Unbecome the local master browser name release fail function.
******************************************************************/

static void unbecome_local_master_fail(struct subnet_record *subrec, struct response_record *rrec,
                       struct nmb_name *fail_name)
{
  struct name_record *namerec;
  struct userdata_struct *userdata = rrec->userdata;
  BOOL force_new_election = False;

  memcpy((char *)&force_new_election, userdata->data, sizeof(BOOL));

  DEBUG(0,("unbecome_local_master_fail: failed to release name %s. \
Removing from namelist anyway.\n", nmb_namestr(fail_name)));

  /* Do it anyway. */
  namerec = find_name_on_subnet(subrec, fail_name, FIND_SELF_NAME);
  if(namerec)
    remove_name_from_namelist(subrec, namerec);

  /* Now reset the workgroup and server state. */
  reset_workgroup_state( subrec, fail_name->name, force_new_election );

  if( DEBUGLVL( 0 ) )
  {
    dbgtext( "*****\n\n" );
    dbgtext( "Samba name server %s ", global_myname );
    dbgtext( "has stopped being a local master browser " );
    dbgtext( "for workgroup %s ", fail_name->name );
    dbgtext( "on subnet %s\n\n*****\n", subrec->subnet_name );
  }
}

/*******************************************************************
 Utility function to remove the WORKGROUP<1d> name.
******************************************************************/

static void release_1d_name( struct subnet_record *subrec, char *workgroup_name,
                             BOOL force_new_election)
{
  struct nmb_name nmbname;
  struct name_record *namerec;

  make_nmb_name(&nmbname, workgroup_name, 0x1d);
  if((namerec = find_name_on_subnet( subrec, &nmbname, FIND_SELF_NAME))!=NULL)
  {
    struct userdata_struct *userdata;
    int size = sizeof(struct userdata_struct) + sizeof(BOOL);

    if((userdata = (struct userdata_struct *)malloc(size)) == NULL)
    {
      DEBUG(0,("release_1d_name: malloc fail.\n"));
      return;
    }

    userdata->copy_fn = NULL;
    userdata->free_fn = NULL;
    userdata->userdata_len = sizeof(BOOL);
    memcpy((char *)userdata->data, &force_new_election, sizeof(BOOL));

    release_name(subrec, namerec,
                 unbecome_local_master_success,
                 unbecome_local_master_fail,
                 userdata);

    zero_free(userdata, size);
  }
}

/*******************************************************************
 Unbecome the local master browser MSBROWSE name release success function.
******************************************************************/

static void release_msbrowse_name_success(struct subnet_record *subrec,
                      struct userdata_struct *userdata,
                      struct nmb_name *released_name,
                      struct in_addr released_ip)
{
  DEBUG(4,("release_msbrowse_name_success: Released name %s on subnet %s\n.",
           nmb_namestr(released_name), subrec->subnet_name ));

  /* Remove the permanent MSBROWSE name added into the unicast subnet. */
  remove_permanent_name_from_unicast( subrec, released_name);
}

/*******************************************************************
 Unbecome the local master browser MSBROWSE name release fail function.
******************************************************************/

static void release_msbrowse_name_fail( struct subnet_record *subrec,
                       struct response_record *rrec,
                       struct nmb_name *fail_name)
{
  struct name_record *namerec;

  DEBUG(4,("release_msbrowse_name_fail: Failed to release name %s on subnet %s\n.",
           nmb_namestr(fail_name), subrec->subnet_name ));

  /* Release the name anyway. */
  namerec = find_name_on_subnet(subrec, fail_name, FIND_SELF_NAME);
  if(namerec)
    remove_name_from_namelist(subrec, namerec);

  /* Remove the permanent MSBROWSE name added into the unicast subnet. */
  remove_permanent_name_from_unicast( subrec, fail_name);
}

/*******************************************************************
  Unbecome the local master browser. If force_new_election is true, restart
  the election process after we've unbecome the local master.
******************************************************************/

void unbecome_local_master_browser(struct subnet_record *subrec, struct work_record *work,
                                   BOOL force_new_election)
{
  struct name_record *namerec;
  struct nmb_name nmbname;

  /* Sanity check. */

  DEBUG(2,("unbecome_local_master_browser: unbecoming local master for workgroup %s \
on subnet %s\n",work->work_group, subrec->subnet_name));

  if(find_server_in_workgroup( work, global_myname) == NULL)
  {
    DEBUG(0,("unbecome_local_master_browser: Error - cannot find server %s \
in workgroup %s on subnet %s\n",
       global_myname, work->work_group, subrec->subnet_name));
    work->mst_state = lp_local_master() ? MST_POTENTIAL : MST_NONE;
    return;
  }

  /* Set the state to unbecoming. */
  work->mst_state = MST_UNBECOMING_MASTER;

  /*
   * Release the WORKGROUP<1d> name asap to allow another machine to
   * claim it.
   */

  release_1d_name( subrec, work->work_group, force_new_election);

  /* Deregister any browser names we may have. */
  make_nmb_name(&nmbname, MSBROWSE, 0x1);
  if((namerec = find_name_on_subnet( subrec, &nmbname, FIND_SELF_NAME))!=NULL)
  {
    release_name(subrec, namerec,
                 release_msbrowse_name_success,
                 release_msbrowse_name_fail,
                 NULL);
  }

  /*
   * Ensure we have sent and processed these release packets
   * before returning - we don't want to process any election
   * packets before dealing with the 1d release.
   */

  retransmit_or_expire_response_records(time(NULL));
}

/****************************************************************************
  Success in registering the WORKGROUP<1d> name.
  We are now *really* a local master browser.
  ****************************************************************************/

static void become_local_master_stage2(struct subnet_record *subrec,
                                        struct userdata_struct *userdata,
                                        struct nmb_name *registered_name,
                                        uint16 nb_flags,
                                        int ttl, struct in_addr registered_ip)
{
  int i = 0;
  struct server_record *sl;
  struct work_record *work = find_workgroup_on_subnet( subrec, registered_name->name);
  struct server_record *servrec;

  if(!work)
  {
    DEBUG(0,("become_local_master_stage2: Error - cannot find \
workgroup %s on subnet %s\n", registered_name->name, subrec->subnet_name));
    return;
  }

  if((servrec = find_server_in_workgroup( work, global_myname)) == NULL)
  {
    DEBUG(0,("become_local_master_stage2: Error - cannot find server %s \
in workgroup %s on subnet %s\n",
       global_myname, registered_name->name, subrec->subnet_name));
    work->mst_state = lp_local_master() ? MST_POTENTIAL : MST_NONE;
    return;
  }

  DEBUG(3,("become_local_master_stage2: registered as master browser for workgroup %s \
on subnet %s\n", work->work_group, subrec->subnet_name));

  work->mst_state = MST_BROWSER; /* registering WORKGROUP(1d) succeeded */

  /* update our server status */
  servrec->serv.type |= SV_TYPE_MASTER_BROWSER;
  servrec->serv.type &= ~SV_TYPE_POTENTIAL_BROWSER;

  /* Tell the namelist writer to write out a change. */
  subrec->work_changed = True;

  /* Add this name to the workgroup as local master browser. */
  set_workgroup_local_master_browser_name( work, global_myname);

  /* Count the number of servers we have on our list. If it's
     less than 10 (just a heuristic) request the servers
     to announce themselves.
   */
  for( sl = work->serverlist; sl != NULL; sl = sl->next)
    i++;

  if (i < 10)
  {
    /* Ask all servers on our local net to announce to us. */
    broadcast_announce_request(subrec, work);
  }

  /*
   * Now we are a local master on a broadcast subnet, we need to add
   * the WORKGROUP<1d> name to the unicast subnet so that we can answer
   * unicast requests sent to this name. We can create this name directly on
   * the unicast subnet as a WINS server always returns true when registering
   * this name, and discards the registration. We use the number of IP
   * addresses registered to this name as a reference count, as we
   * remove this broadcast subnet IP address from it when we stop becoming a local
   * master browser for this broadcast subnet.
   */

  insert_permanent_name_into_unicast( subrec, registered_name, nb_flags);

  /* Reset the announce master browser timer so that we try and tell a domain
     master browser as soon as possible that we are a local master browser. */
  reset_announce_timer();

  if( DEBUGLVL( 0 ) )
  {
    dbgtext( "*****\n\n" );
    dbgtext( "Samba name server %s ", global_myname );
    dbgtext( "is now a local master browser " );
    dbgtext( "for workgroup %s ", work->work_group );
    dbgtext( "on subnet %s\n\n*****\n", subrec->subnet_name );
  }

}

/****************************************************************************
  Failed to register the WORKGROUP<1d> name.
  ****************************************************************************/
static void become_local_master_fail2(struct subnet_record *subrec,
                                      struct response_record *rrec,
                                      struct nmb_name *fail_name)
{
  struct work_record *work = find_workgroup_on_subnet( subrec, fail_name->name);

  DEBUG(0,("become_local_master_fail2: failed to register name %s on subnet %s. \
Failed to become a local master browser.\n", nmb_namestr(fail_name), subrec->subnet_name));

  if(!work)
  {
    DEBUG(0,("become_local_master_fail2: Error - cannot find \
workgroup %s on subnet %s\n", fail_name->name, subrec->subnet_name));
    return;
  }

  /* Roll back all the way by calling unbecome_local_master_browser(). */
  unbecome_local_master_browser(subrec, work, False);
}

/****************************************************************************
  Success in registering the MSBROWSE name.
  ****************************************************************************/

static void become_local_master_stage1(struct subnet_record *subrec,
                                        struct userdata_struct *userdata,
                                        struct nmb_name *registered_name,
                                        uint16 nb_flags,
                                        int ttl, struct in_addr registered_ip)
{
  char *work_name = userdata->data;
  struct work_record *work = find_workgroup_on_subnet( subrec, work_name);

  if(!work)
  {
    DEBUG(0,("become_local_master_stage1: Error - cannot find \
workgroup %s on subnet %s\n", work_name, subrec->subnet_name));
    return;
  }

  DEBUG(3,("become_local_master_stage1: go to stage 2: register the %s<1d> name.\n",
            work->work_group));

  work->mst_state = MST_MSB; /* Registering MSBROWSE was successful. */

  /*
   * We registered the MSBROWSE name on a broadcast subnet, now need to add
   * the MSBROWSE name to the unicast subnet so that we can answer
   * unicast requests sent to this name. We create this name directly on
   * the unicast subnet.
   */

  insert_permanent_name_into_unicast( subrec, registered_name, nb_flags);

  /* Attempt to register the WORKGROUP<1d> name. */
  register_name(subrec, work->work_group,0x1d,samba_nb_type,
                become_local_master_stage2,
                become_local_master_fail2,
                NULL);
}

/****************************************************************************
  Failed to register the MSBROWSE name.
  ****************************************************************************/

static void become_local_master_fail1(struct subnet_record *subrec,
                                      struct response_record *rrec,
                                      struct nmb_name *fail_name)
{
  char *work_name = rrec->userdata->data;
  struct work_record *work = find_workgroup_on_subnet(subrec, work_name);

  if(!work)
  {
    DEBUG(0,("become_local_master_fail1: Error - cannot find \
workgroup %s on subnet %s\n", work_name, subrec->subnet_name));
    return;
  }

  if(find_server_in_workgroup(work, global_myname) == NULL)
  {
    DEBUG(0,("become_local_master_fail1: Error - cannot find server %s \
in workgroup %s on subnet %s\n",
       global_myname, work->work_group, subrec->subnet_name));
    return;
  }

  reset_workgroup_state( subrec, work->work_group, False );

  DEBUG(0,("become_local_master_fail1: Failed to become a local master browser for \
workgroup %s on subnet %s. Couldn't register name %s.\n",
       work->work_group, subrec->subnet_name, nmb_namestr(fail_name)));
}

/******************************************************************
  Become the local master browser on a subnet.
  This gets called if we win an election on this subnet.

  Stage 1: mst_state was MST_POTENTIAL - go to MST_BACK register ^1^2__MSBROWSE__^2^1.
  Stage 2: mst_state was MST_BACKUP  - go to MST_MSB  and register WORKGROUP<1d>.
  Stage 3: mst_state was MST_MSB  - go to MST_BROWSER.
******************************************************************/

void become_local_master_browser(struct subnet_record *subrec, struct work_record *work)
{
  struct userdata_struct *userdata;
  int size = sizeof(struct userdata_struct) + sizeof(fstring) + 1;

  /* Sanity check. */
  if (!lp_local_master())
  {
    DEBUG(0,("become_local_master_browser: Samba not configured as a local master browser.\n"));
    return;
  }

  if(!AM_POTENTIAL_MASTER_BROWSER(work))
  {
    DEBUG(2,("become_local_master_browser: Awaiting potential browser state. Current state is %d\n",
              work->mst_state ));
    return;
  }

  if(find_server_in_workgroup( work, global_myname) == NULL)
  {
    DEBUG(0,("become_local_master_browser: Error - cannot find server %s \
in workgroup %s on subnet %s\n",
       global_myname, work->work_group, subrec->subnet_name));
    return;
  }

  DEBUG(2,("become_local_master_browser: Starting to become a master browser for workgroup \
%s on subnet %s\n", work->work_group, subrec->subnet_name));

  DEBUG(3,("become_local_master_browser: first stage - attempt to register ^1^2__MSBROWSE__^2^1\n"));
  work->mst_state = MST_BACKUP; /* an election win was successful */

  work->ElectionCriterion |= 0x5;

  /* Tell the namelist writer to write out a change. */
  subrec->work_changed = True;

  /* Setup the userdata_struct. */
  if((userdata = (struct userdata_struct *)malloc(size)) == NULL)
  {
    DEBUG(0,("become_local_master_browser: malloc fail.\n"));
    return;
  }

  userdata->copy_fn = NULL;
  userdata->free_fn = NULL;
  userdata->userdata_len = strlen(work->work_group)+1;
  pstrcpy(userdata->data, work->work_group);

  /* Register the special browser group name. */
  register_name(subrec, MSBROWSE, 0x01, samba_nb_type|NB_GROUP,
                become_local_master_stage1,
                become_local_master_fail1,
                userdata);

  zero_free(userdata, size);
}

/***************************************************************
 Utility function to set the local master browser name. Does
 some sanity checking as old versions of Samba seem to sometimes
 say that the master browser name for a workgroup is the same
 as the workgroup name.
****************************************************************/

void set_workgroup_local_master_browser_name( struct work_record *work, char *newname)
{
  DEBUG(5,("set_workgroup_local_master_browser_name: setting local master name to '%s' \
for workgroup %s.\n", newname, work->work_group ));

#if 0
  /*
   * Apparently some sites use the workgroup name as the local
   * master browser name. Arrrrggghhhhh ! (JRA).
   */
  if(strequal( work->work_group, newname))
  {
    DEBUG(5, ("set_workgroup_local_master_browser_name: Refusing to set \
local_master_browser_name for workgroup %s to workgroup name.\n",
         work->work_group ));
    return;
  }
#endif

  StrnCpy(work->local_master_browser_name, newname,
            sizeof(work->local_master_browser_name)-1);
}


text:
class SigninPermissionsMustBeLowercase < ActiveRecord::Migration
  def up
    SupportedPermission.where(name: "Signin")
                       .update_all(name: "signin")
  end
end

redpajama_set_name: RedPajamaGithub


text:
angular-boilerplate-project
===========================

Version 1.0
--------------

Start up project containing Angular JS Framework and HTML5 Boiler Plate files.
This project has sample partials and angular templates for fast development and deployment.
So no need to search for necessary plugins to get started. Just enable what you need and add / delete as necessary.

Contains the following
------------------------

- Angular JS files v1.2
- jQuery v1.11.1
- Modernizr v2.6.2
- URL Routing
- TweenMax animation library
- .htaccess for clean urls
- Font Awesome
- HTML5 Boiler Plate normalise and css
- Start up sass file
- Partial and template folder setup along with sample files

Future release
---------------
Will integrate Bootstrap and other functionalities to make starting a project easier.
Also will try and reduce the overall file size of the project.


text:
// Modifications copyright (C) 2017, Baidu.com, Inc.
// Copyright 2017 The Apache Software Foundation

// Licensed to the Apache Software Foundation (ASF) under one
// or more contributor license agreements.  See the NOTICE file
// distributed with this work for additional information
// regarding copyright ownership.  The ASF licenses this file
// to you 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 com.baidu.palo.catalog;

import com.google.common.base.Joiner;

import org.apache.kudu.client.PartialRow;
import org.apache.kudu.client.RangePartitionBound;

import java.util.List;

/*
 * describe the partition Info of a kudu table.
 * include hash partition and range partition
 */
public class KuduPartition {

    public enum KuduPartitionType {
        RANGE,
        HASH
    }

    private KuduPartitionType type;
    private List<String> partitionColNames;

    // only for hash partition
    private int bucketsNum;

    // only for range partition
    private List<KuduRange> ranges;

    public static KuduPartition createHashPartition(List<String> partColNames, int bucketsNum) {
        KuduPartition kuduPartitionInfo = new KuduPartition(KuduPartitionType.HASH,
                                                                    partColNames,
                                                                    bucketsNum,
                                                                    null);
        return kuduPartitionInfo;
    }

    public static KuduPartition createRangePartition(List<String> partColNames,
                                                     List<KuduRange> ranges) {
        KuduPartition kuduPartitionInfo = new KuduPartition(KuduPartitionType.RANGE,
                                                            partColNames,
                                                            -1,
                                                            ranges);
        return kuduPartitionInfo;
    }

    private KuduPartition(KuduPartitionType type,
                          List<String> partColNames,
                          int bucketsNum,
                          List<KuduRange> ranges) {
        this.type = type;
        this.partitionColNames = partColNames;
        this.bucketsNum = bucketsNum;
        this.ranges = ranges;
    }

    public static class KuduRange {
        private String partitionName;

        private PartialRow lower;
        private PartialRow upper;

        private RangePartitionBound lowerBound;
        private RangePartitionBound upperBound;

        public KuduRange(String partitionName,
                         PartialRow lower,
                         PartialRow upper,
                         RangePartitionBound lowerBound,
                         RangePartitionBound upperBound) {
            this.partitionName = partitionName;
            this.lower = lower;
            this.upper = upper;
            this.lowerBound = lowerBound;
            this.upperBound = upperBound;
        }

        @Override
        public String toString() {
            StringBuilder sb = new StringBuilder();
            sb.append("PARTITION `").append(partitionName).append("` ");
            if (lowerBound == RangePartitionBound.EXCLUSIVE_BOUND) {
                sb.append("(");
            } else {
                sb.append("[");
            }
            sb.append(lower.toString()).append(" -- ");
            sb.append(upper.toString());
            if (upperBound == RangePartitionBound.EXCLUSIVE_BOUND) {
                sb.append(")");
            } else {
                sb.append("]");
            }

            return sb.toString();
        }
    }

    @Override
    public String toString() {
        StringBuilder sb = new StringBuilder();
        if (type == KuduPartitionType.HASH) {
            sb.append("DISTRIBUTED BY HASH(");
            sb.append(Joiner.on(", ").join(partitionColNames)).append(") ");
            sb.append("BUCKETS ").append(bucketsNum);
        } else {
            sb.append("PARTITION BY RANGE(");
            sb.append(Joiner.on(", ").join(partitionColNames)).append(") (\n");
            sb.append(Joiner.on(",\n").join(ranges)).append("\n)");
        }

        return sb.toString();
    }
}


text: server 'dkdeploy-php.dev', roles: %w[web app backend], primary: true, domain_scheme: 'https'


text:
import React from 'react';
import { getWorkingDays, getHolidaysAfter, getDevHolidaysCountAfter, getRemainingDays } from './working-days-utils';

export default class DeveloperDevDayRow extends React.Component {

  render() {
    const { run, developer, pivotDate } = this.props;

    const workingDays = getWorkingDays(run.version, pivotDate);
    const remaingDays = getRemainingDays(run, developer, workingDays, pivotDate);
    const holidays = getHolidaysAfter(run.holidays, pivotDate);
    const devHolidays = getDevHolidaysCountAfter(run.devHolidays, developer, pivotDate);
    return (

        {`${developer.firstname} ${developer.lastname}`}
        {remaingDays} ({workingDays} - {devHolidays} - {holidays.length})
        {developer.devRatio} %
        {(remaingDays * (developer.devRatio / 100).toFixed(2))}

    );
  }
}

DeveloperDevDayRow.propTypes = {
  run: React.PropTypes.object,
  developer: React.PropTypes.object,
  pivotDate: React.PropTypes.instanceOf(Date),
};


text:
# frozen_string_literal: true

ENV['RAILS_ENV'] ||= 'test'

require 'active_support'
require 'active_support/deprecation'
require 'active_support/core_ext'
require 'file_validators'
require 'rspec'
require 'coveralls'

Coveralls.wear!

locale_path = Dir.glob(File.dirname(__FILE__) + '/locale/*.yml')
I18n.load_path += locale_path unless I18n.load_path.include?(locale_path)
I18n.enforce_available_locales = false

Dir[File.join(File.dirname(__FILE__), 'support/**/*.rb')].each { |f| require f }

RSpec.configure do |config|
  config.include Helpers

  # Suppress stdout in the console
  config.before { allow($stdout).to receive(:write) }
end


text:
package com.kmshack.newsstand;

import java.util.ArrayList;

import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AbsListView;
import android.widget.AbsListView.OnScrollListener;
import android.widget.ArrayAdapter;
import android.widget.ListView;

public class SampleListFragment extends ScrollTabHolderFragment implements OnScrollListener {

	private static final String ARG_POSITION = "position";

	private ListView mListView;
	private ArrayList<String> mListItems;

	private int mPosition;

	public static Fragment newInstance(int position) {
		SampleListFragment f = new SampleListFragment();
		Bundle b = new Bundle();
		b.putInt(ARG_POSITION, position);
		f.setArguments(b);
		return f;
	}

	//Default list view elements -generated dynamically
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		mPosition = getArguments().getInt(ARG_POSITION);

		mListItems = new ArrayList<String>();

		for (int i = 1; i <= 100; i++) {
			mListItems.add(i + ". item - currnet page: " + (mPosition + 1));
		}
	}

	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
		View v = inflater.inflate(R.layout.fragment_list, null);

		mListView = (ListView) v.findViewById(R.id.listView);

		View placeHolderView = inflater.inflate(R.layout.view_header_placeholder, mListView, false);
		mListView.addHeaderView(placeHolderView);

		return v;
	}

	@Override
	public void onActivityCreated(Bundle savedInstanceState) {
		super.onActivityCreated(savedInstanceState);

		mListView.setOnScrollListener(this);
		mListView.setAdapter(new ArrayAdapter<String>(getActivity(), R.layout.list_item, android.R.id.text1, mListItems));
	}

	@Override
	public void adjustScroll(int scrollHeight) {
		if (scrollHeight == 0 && mListView.getFirstVisiblePosition() >= 1) {
			return;
		}

		mListView.setSelectionFromTop(1, scrollHeight);

	}

	@Override
	public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount, int totalItemCount) {
		if (mScrollTabHolder != null)
			mScrollTabHolder.onScroll(view, firstVisibleItem, visibleItemCount, totalItemCount, mPosition);
	}

	@Override
	public void onScrollStateChanged(AbsListView view, int scrollState) {
		// nothing
	}

}


text:
<!doctype html>

        <meta charset="utf-8">
        <meta http-equiv="x-ua-compatible" content="ie=edge">
        <title>NGX Dynamic Dashboard Framework</title>
        <meta name="description" content="">
        <meta name="viewport" content="width=device-width, initial-scale=1">

        <link rel="icon" type="image/x-icon" href="../images/favicon.ico">
	      <link rel="stylesheet" href="../styles/style.css">

            NGX Dynamic Dashboard Framework
            <button type="button" class="btn btn-default btn-menu fa fa-bars" id="btn-menu"></button>

    <input type="text" placeholder="Type to search">

            NGX Dynamic Dashboard Framework

            Getting started

                            Overview

                      README

                            LICENSE

                            Dependencies

                    Modules

                        AboutModule

                                    Components

                                            AboutComponent

                                    Injectables

                                            AboutService

                        AddGadgetModule

                                    Components

                                            AddGadgetComponent

                                    Injectables

                                            AddGadgetService

                        AppModule

                                    Components

                                            AppComponent

                        BoardModule

                                    Components

                                            BoardComponent

                        ConfigurationModule

                                    Components

                                            AIConfigurationTabComponent

                                            BoardsConfigurationTabComponent

                                            ConfigurationComponent

                                            EndPointDetailComponent

                                            EndpointConfigurationTabComponent

                                            OptionsConfigurationTabComponent

                                    Injectables

                                            EndPointService

                                            OptionsService

                        DataListModule

                                    Components

                                            DataListComponent

                        DetailModule

                                    Components

                                            DetailComponent

                        DynamicFormModule

                                    Components

                                            DynamicFormComponent

                                            DynamicFormPropertyComponent

                                    Injectables

                                            PropertyControlService

                        ErrorHandlerModule

                                    Components

                                            ErrorHandlerComponent

                        FacetModule

                                    Components

                                            FacetComponent

                                            FilterListComponent

                                            FilterTagComponent

                                    Injectables

                                            AddGadgetService

                                    Pipes

                                            CapitalizeFirstPipe

                        GadgetModule

                                    Components

                                            BarChartGadgetComponent

                                            BubbleGadgetComponent

                                            CPUGadgetComponent

                                            CPUMGadgetComponent

                                            DiskGadgetComponent

                                            DonutGadgetComponent

                                            DrillDownComponent

                                            EdgeServiceListGadgetComponent

                                            JobAnalysisGadgetComponent

                                            MemoryGadgetComponent

                                            NewsGadgetComponent

                                            PortConnectionGadgetComponent

                                            PropertyListGadgetComponent

                                            ResultViewComponent

                                            ServiceListGadgetComponent

                                            SolutionViewComponent

                                            StatisticGadgetComponent

                                            StorageObjectListComponent

                                            TodoGadgetComponent

                                            TrendGadgetComponent

                                            TrendLineGadgetComponent

                                    Injectables

                                            APITokenService

                                            BarChartService

                                            CPUService

                                            ConnectionService

                                            DiskService

                                            DonutService

                                            EdgeService

                                            StatisticService

                                            StorageService

                                            TodoService

                                            TrendService

                        GadgetSharedModule

                                    Components

                                            GadgetHeaderComponent

                                            GadgetOperationComponent

                                            HelpModalComponent

                                            VisDrillDownComponent

                        GridModule

                                    Components

                                            CellComponent

                                            GridComponent

                                    Injectables

                                            AddGadgetService

                                            BarChartService

                                            BubbleService

                                            CPUService

                                            ConfigurationService

                                            ConnectionService

                                            DonutService

                                            EdgeService

                                            GadgetInstanceService

                                            JobAnalysisService

                                            NewsService

                                            TodoService

                                            TrendLineService

                                            TrendService

                        LayoutModule

                                    Components

                                            BoardLayoutManagerComponent

                        MenuModule

                                    Components

                                            MenuComponent

                                    Injectables

                                            ConfigurationService

                                            EndPointService

                                            GadgetPropertyService

                                            MenuEventService

                                            ObservableWebSocketService

                                            RuntimeService

                        NotificationModule

                                    Components

                                            NotificationComponent

                                            NotificationDetailComponent

                                    Injectables

                                            NotificationService

                        RoutingModule

                        ToastModule

                                    Components

                                            ToastComponent

                                    Injectables

                                            ToastService

                                    Pipes

                                            ReversePipe

                        TypeAheadInputModule

                                    Components

                                            TypeAheadInputComponent

                Classes

                        Bar

                        CPUChartMetric

                        CheckboxProperty

                        DetailResolver

                        DropdownProperty

                        DynamicDropdownProperty

                        EndPoint

                        EndPointModel

                        ErrorHandler

                        ErrorObject

                        Facet

                        FacetTagProcessor

                        GadgetBase

                        GadgetConfigModel

                        GadgetFactory

                        HiddenProperty

                        Message

                        NgADFPage

                        Notification

                        NumberProperty

                        PropertyBase

                        PropertyPage

                        Series

                        SolutionObject

                        Tag

                        TextboxProperty

                        Injectables

                                APITokenService

                                AboutService

                                AddGadgetService

                                BarChartService

                                BubbleService

                                CPUService

                                ConfigurationService

                                ConnectionService

                                DiskService

                                DonutService

                                EdgeService

                                EndPointService

                                GadgetInstanceService

                                GadgetPropertyService

                                JobAnalysisService

                                MenuEventService

                                NewsService

                                NotificationService

                                ObservableWebSocketService

                                OptionsService

                                PropertyControlService

                                RuntimeService

                                StatisticService

                                StorageService

                                ToastService

                                TodoService

                                TrendLineService

                                TrendService

                Interfaces

                        ActionInterface

                        DetailModel

                        GadgetLibraryResponse

                        IEvent

                        IGadget

                Miscellaneous

                      Functions

                      Variables

                Routes

            Documentation coverage

                Documentation generated using

            NGX Dynamic Dashboard Framework

    <input type="text" placeholder="Type to search">

            Getting started

                            Overview

                      README

                            LICENSE

                            Dependencies

                    Modules

                        AboutModule

                                    Components

                                            AboutComponent

                                    Injectables

                                            AboutService

                        AddGadgetModule

                                    Components

                                            AddGadgetComponent

                                    Injectables

                                            AddGadgetService

                        AppModule

                                    Components

                                            AppComponent

                        BoardModule

                                    Components

                                            BoardComponent

                        ConfigurationModule

                                    Components

                                            AIConfigurationTabComponent

                                            BoardsConfigurationTabComponent

                                            ConfigurationComponent

                                            EndPointDetailComponent

                                            EndpointConfigurationTabComponent

                                            OptionsConfigurationTabComponent

                                    Injectables

                                            EndPointService

                                            OptionsService

                        DataListModule

                                    Components

                                            DataListComponent

                        DetailModule

                                    Components

                                            DetailComponent

                        DynamicFormModule

                                    Components

                                            DynamicFormComponent

                                            DynamicFormPropertyComponent

                                    Injectables

                                            PropertyControlService

                        ErrorHandlerModule

                                    Components

                                            ErrorHandlerComponent

                        FacetModule

                                    Components

                                            FacetComponent

                                            FilterListComponent

                                            FilterTagComponent

                                    Injectables

                                            AddGadgetService

                                    Pipes

                                            CapitalizeFirstPipe

                        GadgetModule

                                    Components

                                            BarChartGadgetComponent

                                            BubbleGadgetComponent

                                            CPUGadgetComponent

                                            CPUMGadgetComponent

                                            DiskGadgetComponent

                                            DonutGadgetComponent

                                            DrillDownComponent

                                            EdgeServiceListGadgetComponent

                                            JobAnalysisGadgetComponent

                                            MemoryGadgetComponent

                                            NewsGadgetComponent

                                            PortConnectionGadgetComponent

                                            PropertyListGadgetComponent

                                            ResultViewComponent

                                            ServiceListGadgetComponent

                                            SolutionViewComponent

                                            StatisticGadgetComponent

                                            StorageObjectListComponent

                                            TodoGadgetComponent

                                            TrendGadgetComponent

                                            TrendLineGadgetComponent

                                    Injectables

                                            APITokenService

                                            BarChartService

                                            CPUService

                                            ConnectionService

                                            DiskService

                                            DonutService

                                            EdgeService

                                            StatisticService

                                            StorageService

                                            TodoService

                                            TrendService

                        GadgetSharedModule

                                    Components

                                            GadgetHeaderComponent

                                            GadgetOperationComponent

                                            HelpModalComponent

                                            VisDrillDownComponent

                        GridModule

                                    Components

                                            CellComponent

                                            GridComponent

                                    Injectables

                                            AddGadgetService

                                            BarChartService

                                            BubbleService

                                            CPUService

                                            ConfigurationService

                                            ConnectionService

                                            DonutService

                                            EdgeService

                                            GadgetInstanceService

                                            JobAnalysisService

                                            NewsService

                                            TodoService

                                            TrendLineService

                                            TrendService

                        LayoutModule

                                    Components

                                            BoardLayoutManagerComponent

                        MenuModule

                                    Components

                                            MenuComponent

                                    Injectables

                                            ConfigurationService

                                            EndPointService

                                            GadgetPropertyService

                                            MenuEventService

                                            ObservableWebSocketService

                                            RuntimeService

                        NotificationModule

                                    Components

                                            NotificationComponent

                                            NotificationDetailComponent

                                    Injectables

                                            NotificationService

                        RoutingModule

                        ToastModule

                                    Components

                                            ToastComponent

                                    Injectables

                                            ToastService

                                    Pipes

                                            ReversePipe

                        TypeAheadInputModule

                                    Components

                                            TypeAheadInputComponent

                Classes

                        Bar

                        CPUChartMetric

                        CheckboxProperty

                        DetailResolver

                        DropdownProperty

                        DynamicDropdownProperty

                        EndPoint

                        EndPointModel

                        ErrorHandler

                        ErrorObject

                        Facet

                        FacetTagProcessor

                        GadgetBase

                        GadgetConfigModel

                        GadgetFactory

                        HiddenProperty

                        Message

                        NgADFPage

                        Notification

                        NumberProperty

                        PropertyBase

                        PropertyPage

                        Series

                        SolutionObject

                        Tag

                        TextboxProperty

                        Injectables

                                APITokenService

                                AboutService

                                AddGadgetService

                                BarChartService

                                BubbleService

                                CPUService

                                ConfigurationService

                                ConnectionService

                                DiskService

                                DonutService

                                EdgeService

                                EndPointService

                                GadgetInstanceService

                                GadgetPropertyService

                                JobAnalysisService

                                MenuEventService

                                NewsService

                                NotificationService

                                ObservableWebSocketService

                                OptionsService

                                PropertyControlService

                                RuntimeService

                                StatisticService

                                StorageService

                                ToastService

                                TodoService

                                TrendLineService

                                TrendService

                Interfaces

                        ActionInterface

                        DetailModel

                        GadgetLibraryResponse

                        IEvent

                        IGadget

                Miscellaneous

                      Functions

                      Variables

                Routes

            Documentation coverage

                Documentation generated using

Modules

DataListModule

              <?xml version="1.0" encoding="UTF-8" standalone="no"?>
<!DOCTYPE svg PUBLIC "-//W3C//DTD SVG 1.1//EN"
 "http://www.w3.org/Graphics/SVG/1.1/DTD/svg11.dtd">

<svg width="504pt" height="284pt"
 viewBox="0.00 0.00 504.00 284.00" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink">
<g id="graph0" class="graph" transform="scale(1 1) rotate(0) translate(4 280)">
<title>dependencies</title>
<polygon fill="#ffffff" stroke="transparent" points="-4,4 -4,-280 500,-280 500,4 -4,4"/>
<text text-anchor="start" x="227.0091" y="-42.4" font-family="sans-serif" font-weight="bold" font-size="14.00" fill="#000000">Legend</text>
<polygon fill="#ffffb3" stroke="transparent" points="14,-10 14,-30 34,-30 34,-10 14,-10"/>
<text text-anchor="start" x="37.629" y="-15.4" font-family="sans-serif" font-size="14.00" fill="#000000">  Declarations</text>
<polygon fill="#8dd3c7" stroke="transparent" points="127,-10 127,-30 147,-30 147,-10 127,-10"/>
<text text-anchor="start" x="150.7251" y="-15.4" font-family="sans-serif" font-size="14.00" fill="#000000">  Module</text>
<polygon fill="#80b1d3" stroke="transparent" points="213,-10 213,-30 233,-30 233,-10 213,-10"/>
<text text-anchor="start" x="236.7812" y="-15.4" font-family="sans-serif" font-size="14.00" fill="#000000">  Bootstrap</text>
<polygon fill="#fdb462" stroke="transparent" points="310,-10 310,-30 330,-30 330,-10 310,-10"/>
<text text-anchor="start" x="333.6732" y="-15.4" font-family="sans-serif" font-size="14.00" fill="#000000">  Providers</text>
<polygon fill="#fb8072" stroke="transparent" points="406,-10 406,-30 426,-30 426,-10 406,-10"/>
<text text-anchor="start" x="429.7258" y="-15.4" font-family="sans-serif" font-size="14.00" fill="#000000">  Exports</text>
<g id="clust1" class="cluster">
<title>cluster_DataListModule</title>
<polygon fill="none" stroke="#000000" stroke-dasharray="1,5" points="24,-70 24,-268 472,-268 472,-70 24,-70"/>
</g>
<g id="clust2" class="cluster">
<title>cluster_DataListModule_declarations</title>
<polygon fill="none" stroke="#000000" points="318,-78 318,-130 464,-130 464,-78 318,-78"/>
</g>
<g id="clust4" class="cluster">
<title>cluster_DataListModule_imports</title>
<polygon fill="none" stroke="#000000" points="32,-78 32,-130 310,-130 310,-78 32,-78"/>
</g>
<g id="clust5" class="cluster">
<title>cluster_DataListModule_exports</title>
<polygon fill="none" stroke="#000000" points="182,-208 182,-260 332,-260 332,-208 182,-208"/>
</g>

<g id="node1" class="node">
<title>DataListComponent</title>
<polygon fill="#ffffb3" stroke="#000000" points="455.538,-122 326.462,-122 326.462,-86 455.538,-86 455.538,-122"/>
<text text-anchor="middle" x="391" y="-99.8" font-family="Times,serif" font-size="14.00" fill="#000000">DataListComponent</text>
</g>

<g id="node2" class="node">
<title>DataListModule</title>
<polygon fill="#8dd3c7" stroke="#000000" points="310.7549,-187 307.7549,-191 286.7549,-191 283.7549,-187 203.2451,-187 203.2451,-151 310.7549,-151 310.7549,-187"/>
<text text-anchor="middle" x="257" y="-164.8" font-family="Times,serif" font-size="14.00" fill="#000000">DataListModule</text>
</g>

<g id="edge1" class="edge">
<title>DataListComponent->DataListModule</title>
<path fill="none" stroke="#000000" d="M326.4531,-104C314.8744,-104 306.4054,-104 306.4054,-104 306.4054,-104 306.4054,-140.8939 306.4054,-140.8939"/>
<polygon fill="#000000" stroke="#000000" points="302.9054,-140.8938 306.4054,-150.8939 309.9054,-140.8939 302.9054,-140.8938"/>
</g>

<g id="node5" class="node">
<title>DataListComponent </title>
<polygon fill="#fb8072" stroke="#000000" points="323.5372,-252 190.4628,-252 190.4628,-216 323.5372,-216 323.5372,-252"/>
<text text-anchor="middle" x="257" y="-229.8" font-family="Times,serif" font-size="14.00" fill="#000000">DataListComponent </text>
</g>

<g id="edge4" class="edge">
<title>DataListModule->DataListComponent </title>
<path fill="none" stroke="#000000" stroke-dasharray="5,2" d="M257,-187.1061C257,-187.1061 257,-205.991 257,-205.991"/>
<polygon fill="#000000" stroke="#000000" points="253.5001,-205.9909 257,-215.991 260.5001,-205.991 253.5001,-205.9909"/>
</g>

<g id="node3" class="node">
<title>FacetModule</title>
<polygon fill="#8dd3c7" stroke="#000000" points="301.8669,-122 298.8669,-126 277.8669,-126 274.8669,-122 212.1331,-122 212.1331,-86 301.8669,-86 301.8669,-122"/>
<text text-anchor="middle" x="257" y="-99.8" font-family="Times,serif" font-size="14.00" fill="#000000">FacetModule</text>
</g>

<g id="edge2" class="edge">
<title>FacetModule->DataListModule</title>
<path fill="none" stroke="#000000" d="M257,-122.1061C257,-122.1061 257,-140.991 257,-140.991"/>
<polygon fill="#000000" stroke="#000000" points="253.5001,-140.9909 257,-150.991 260.5001,-140.991 253.5001,-140.9909"/>
</g>

<g id="node4" class="node">
<title>TypeAheadInputModule</title>
<polygon fill="#8dd3c7" stroke="#000000" points="194.4045,-122 191.4045,-126 170.4045,-126 167.4045,-122 39.5955,-122 39.5955,-86 194.4045,-86 194.4045,-122"/>
<text text-anchor="middle" x="117" y="-99.8" font-family="Times,serif" font-size="14.00" fill="#000000">TypeAheadInputModule</text>
</g>

<g id="edge3" class="edge">
<title>TypeAheadInputModule->DataListModule</title>
<path fill="none" stroke="#000000" d="M194.2271,-104C202.2808,-104 207.5947,-104 207.5947,-104 207.5947,-104 207.5947,-140.8939 207.5947,-140.8939"/>
<polygon fill="#000000" stroke="#000000" points="204.0947,-140.8938 207.5947,-150.8939 211.0947,-140.8939 204.0947,-140.8938"/>
</g>
</g>
</svg>

              <button id="zoom-in" class="btn btn-default btn-sm">Zoom in</button>
              <button id="reset" class="btn btn-default btn-sm">Reset</button>
              <button id="zoom-out" class="btn btn-default btn-sm">Zoom out</button>

            Info

            Source

File

            src/app/datalist/data-list.module.ts

Declarations

                                DataListComponent

Imports

                                    FacetModule

                                    TypeAheadInputModule

Exports

                                    DataListComponent

import {CommonModule} from '@angular/common';
import {NgModule} from '@angular/core';
import {FacetModule} from '../facet/facet.module';
import {HttpClientModule} from '@angular/common/http';
import {TypeAheadInputModule} from '../typeahead-input/typeahead-input.module';
import {DataListComponent} from './data-list.component';
import {BrowserAnimationsModule} from '@angular/platform-browser/animations';

@NgModule({
    imports: [
        CommonModule,
        FacetModule,
        TypeAheadInputModule,
        HttpClientModule,
        BrowserAnimationsModule
    ],
    declarations: [
        DataListComponent
    ],
    providers: [],
    exports: [
        DataListComponent
    ]
})
export class DataListModule {
}

 results matching ""

No results matching ""


text:
from bitcoin.main import *
from bitcoin.transaction import *
from bitcoin.bci import *
from bitcoin.deterministic import *
from bitcoin.blocks import *

# Takes privkey, address, value (satoshis), fee (satoshis)
def send(frm, to, value, fee=10000, **kwargs):
    return sendmultitx(frm, to + ":" + str(value), fee, **kwargs)

# Takes privkey, "address1:value1, address2:value2" (satoshis), fee (satoshis)
def sendmultitx(frm, *args, **kwargs):   # def sendmultitx(frm, tovalues, fee=10000, **kwargs)
    tv, fee = args[:-1], int(args[-1])
    network = kwargs.get('network', set_network(tv[0].split(':')[0]))
    outs = []
    outvalue = 0
    for a in tv:
        outs.append(a)
        outvalue += int(a.split(":")[1])

    u = unspent(privtoaddr(frm, (111 if network == 'testnet' else 0)), **kwargs)
    u2 = select(u, int(outvalue)+int(fee))
    argz = u2 + outs + [privtoaddr(frm, (111 if network == 'testnet' else 0)), fee]
    tx = mksend(*argz)
    tx2 = signall(tx, frm)
    return pushtx(tx2, network, **kwargs)

# Takes address, address, value (satoshis), fee(satoshis)
def preparetx(frm, to, value, fee=10000, **kwargs):
    """Composite from fromAddr, toAddr, value & fee"""
    tovalues = to + ":" + str(value)
    return preparemultitx(frm, tovalues, fee, **kwargs)

# Takes address, address:value, address:value ... (satoshis), fee(satoshis)
def preparemultitx(frm, *args, **kwargs):
    tv, fee = args[:-1], int(args[-1])
    network = kwargs.get('network', set_network(tv[0].split(':')[0]))
    outs = []
    outvalue = 0
    for a in tv:
        outs.append(a)
        outvalue += int(a.split(":")[1])

    u = unspent(frm, **kwargs)
    u2 = select(u, int(outvalue)+int(fee))
    argz = u2 + outs + [frm, fee]
    return mksend(*argz)

# BIP32 hierarchical deterministic multisig script
def bip32_hdm_script(*args):
    if len(args) == 3:
        keys, req, path = args
    else:
        i, keys, path = 0, [], []
        while len(args[i]) > 40:
            keys.append(args[i])
            i += 1
        req = int(args[i])
        path = map(int, args[i+1:])
    pubs = sorted(map(lambda x: bip32_descend(x, path), keys))
    return mk_multisig_script(pubs, req)

# BIP32 hierarchical deterministic multisig address
def bip32_hdm_addr(*args):
    return scriptaddr(bip32_hdm_script(*args))

# Setup a coinvault transaction
def setup_coinvault_tx(tx, script):
    txobj = deserialize(tx)
    N = deserialize_script(script)[-2]
    for inp in txobj["ins"]:
        inp["script"] = serialize_script([None] * (N+1) + [script])
    return serialize(txobj)

# Sign a coinvault transaction
def sign_coinvault_tx(tx, priv):
    pub = privtopub(priv)
    txobj = deserialize(tx)
    subscript = deserialize_script(txobj['ins'][0]['script'])
    oscript = deserialize_script(subscript[-1])
    k, pubs = oscript[0], oscript[1:-2]
    for j in range(len(txobj['ins'])):
        scr = deserialize_script(txobj['ins'][j]['script'])
        for i, p in enumerate(pubs):
            if p == pub:
                scr[i+1] = multisign(tx, j, subscript[-1], priv)
        if len(filter(lambda x: x, scr[1:-1])) >= k:
            scr = [None] + filter(lambda x: x, scr[1:-1])[:k] + [scr[-1]]
        txobj['ins'][j]['script'] = serialize_script(scr)
    return serialize(txobj)

# Inspects a transaction
def inspect(tx, **kwargs):
    d = deserialize(tx)
    isum = 0
    ins = {}
    for _in in d['ins']:
        h = _in['outpoint']['hash']
        i = _in['outpoint']['index']
        prevout = deserialize(fetchtx(h, **kwargs))['outs'][i]
        isum += prevout['value']
        a = script_to_address(prevout['script'])
        ins[a] = ins.get(a, 0) + prevout['value']
    outs = []
    osum = 0
    for _out in d['outs']:
        outs.append({'address': script_to_address(_out['script']),
                     'value': _out['value']})
        osum += _out['value']
    return {
        'fee': isum - osum,
        'outs': outs,
        'ins': ins
    }

def merkle_prove(txhash):
    blocknum = str(get_block_height(txhash))
    header = get_block_header_data(blocknum)
    hashes = get_txs_in_block(blocknum)
    i = hashes.index(txhash)
    return mk_merkle_proof(header, hashes, i)

def tx_size(txobj, unit="bytes"):
    """Get Tx size in bytes"""
    if isinstance(txobj, dict):
        return tx_size(serialize(txobj))
    assert unit in ("bytes", "kilobytes")
    if unit=='bytes':
        return len(txobj)
    elif unit=='kilobytes':
        return len(txobj) / 1024.0

def realtime_tx_fee(txobj, priority='medium'):
    """Get realtime Tx Fee (in Satoshis) for txobj"""
    assert priority in ('low', 'medium', 'high')
    if isinstance(txobj, dict):
        return realtime_tx_fee(serialize(txobj), priority)
    tx_size_kbytes = tx_size(txobj, unit='kilobytes')
    tx_fee_api = get_fee_estimate(priority)
    return int(tx_size_kbytes * tx_fee_api)

#def estimate_tx_size(*args):
#    """Estimate Tx size in bytes"""
#    if not isinstance(txobj, dict):
#        txobj = deserialize(txobj)
#    ins   = txobj.get('ins',  [])
#    outs  = txobj.get('outs', [])
#    nins  = len(ins)  if 'ins' else 1
#    nouts = len(outs) if 'outs' else 1
#    return (nouts * 34) + (148 * nins) + 10
#


text:
layout: post
title: vSphere 7.0 and the memory greed
DATE:
subtitle: ''
metadescription: 'Ever encountered "Admission failure in path: nicmgmtd/nicmgmtd"
  ? Well, be aware that vSphere 7 consumes more memory and that might be why.'

---
As I was fooling around with esxcli in my lab I decided to upgrade a 6.7u3 host to 7.0u1. Note that it is a simple vSphere host in workstation to which I allocated a mere 4GB of RAM because I only needed the minimum. I connected the ISO > upgraded > no problem. Then I went on to patch vSphere 7.0 with esxcli and was greeted with :

> Error: Unknown command or namespace software install

Strange. I tried running "_esxcli_" by itself and got the following output. Wait what?

![](/img/vsphere7memorygreed.JPG)

At this point I'm wondering "How on earth did I manage to screw up the most common vSphere upgrade path ever?". I looked into _vmkernel.log_ and found truckloads of these records:

> 2020-11-18T11:35:44.431Z cpu3:68620)UserWorld 'vim-cmd' with cmdline '/bin/vim-cmd -U root -c /etc/vmware/hostd/config.xml hostsvc/autostartmanager/autostart'
>
> 2020-11-18T11:35:44.431Z cpu3:68620)uw.68620 (18832) extraMin/extraFromParent: 256/256, host (0) childEmin/eMinLimit: 1043298/1043298
>
> 2020-11-18T11:35:44.431Z cpu3:68620)User: 3201: vim-cmd: wantCoreDump:vim-cmd signal:6 exitCode:0 coredump:disabled
>
> 2020-11-18T11:35:47.848Z cpu0:68626)Admission failure in path: host:vim:vmvisor:boot:vim-cmd.68626:uw.68626
>
> 2020-11-18T11:35:47.848Z cpu0:68626)UserWorld 'vim-cmd' with cmdline '/bin/vim-cmd -U root -c /etc/vmware/hostd/config.xml hostsvc/autostartmanager/autostart'
>
> 2020-11-18T11:35:47.848Z cpu0:68626)uw.68626 (18877) extraMin/extraFromParent: 50/50, host (0) childEmin/eMinLimit: 1043298/1043298
>
> 2020-11-18T11:35:47.848Z cpu0:68626)Admission failure in path: host:vim:vmvisor:boot:vim-cmd.68626:uw.68626

After a quick googling I found [KB74527](https://kb.vmware.com/s/article/74527) which is not identical but similar "Admission failure in path: nicmgmtd/nicmgmtd". The identified cause relates to a lack of memory:

> This issue occurs because the process nicmgmtd runs out of memory and is not able to fulfill the requests.

Sure enough, when I changed my ESXi VM from 4GB to 8GB everything was back to normal.

**Bottom line**: vSphere 7.0 is hungrier than 6.x in terms of memory... Maybe consider this and run some tests before upgrading your production environment to 7.0 if you don't have much legroom in the resources department.


text:
namespace onnxruntime {
namespace tvm_codegen {

tvm::Tensor Sum(const tvm::Tensor& lhs, const tvm::Tensor& rhs, const std::string& name) {
  return Add(lhs, rhs, name);
}

// helper local macro defines Evaluate of BINARY_OP OpIRCreators
#define VARIADIC_OP(name)                                      \
  Status GENERIC_OP_IR_CREATOR_CLASS(name)::Evaluate(          \
      const tvm::Array<tvm::Tensor>& inputs,                   \
      const Node& node,                                        \
      CodeGenContext&,                                         \
      tvm::Array<tvm::Tensor>& outputs) {                      \
    tvm::Tensor Y = Identity(inputs[0], node.Name() + "0");    \
    for (size_t i = 1; i < inputs.size(); ++i)                 \
      Y = name(Y, inputs[i], node.Name() + std::to_string(i)); \
    outputs.push_back(Y);                                      \
    return Status::OK();                                       \
  }

LIST_VARIADIC_OPS()

#undef VARIADIC_OP

}  // namespace tvm_codegen
}  // namespace onnxruntime


text:
<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto">

    <item
        android:id="@+id/menu_add_edit_recipe_save"
        android:icon="@drawable/ic_save"
        android:title="@string/activity_add_edit_recipe_menu_save"
        app:showAsAction="ifRoom"/>

</menu>


text:
<?php
header("Access-Control-Allow-Origin: *");

$curdir = dirname(__FILE__);
include_once ($curdir."/../api.lib/api.base.php");
include_once ($curdir."/../api.lib/api.game.php");
include_once ($curdir."/../api.lib/api.quest.php");
include_once ($curdir."/../../config/config.php");
include_once ($curdir."/../api.lib/loadtoken.php");

FHQHelpers::checkAuth();

$result = array(
	'result' => 'fail',
	'data' => array(),
);

$message = '';

if (!FHQGame::checkGameDates($message))
	FHQHelpers::showerror(350, $message);

if (!FHQSecurity::isAdmin())
	FHQHelpers::showerror(351, 'Access denied. You are not admin.');

$params = array(
	'quest_uuid' => '',
	'name' => '',
	'short_text' => '',
	'text' => '',
	'score' => '',
	'min_score' => '',
	'subject' => '',
	'idauthor' => '',
	'author' => '',
	'answer' => '',
	'state' => '',
	'description_state' => '',
);

foreach( $params as $key => $val ) {
	if (!FHQHelpers::issetParam($key))
		FHQHelpers::showerror(352, 'Not found parameter "'.$key.'"');
	$params[$key] = FHQHelpers::getParam($key, '');
}

$params['tema'] = base64_encode($params['subject']);
$params['name'] = base64_encode($params['name']);
$params['short_text_copy'] = $params['short_text'];
$params['short_text'] = base64_encode($params['short_text']);
$params['text_copy'] = $params['text'];
$params['text'] = base64_encode($params['text']);
$params['answer_copy'] = $params['answer'];
$params['answer_upper_md5'] = md5(strtoupper($params['answer']));
$params['answer'] = base64_encode($params['answer']);
$params['score'] = intval($params['score']);
$params['min_score'] = intval($params['min_score']);
$params['for_person'] = 0;
$params['id_game'] = FHQGame::id();
$params['idauthor'] = intval($params['idauthor']);
$params['author'] = base64_encode($params['author']);
// $params['state'] = $params['state'];
// $params['description_state'] = $params['description_state'];
// $params['subject'] = $params['subject'];
// $params['quest_uuid'] = $params['quest_uuid'];
$params['gameid'] = FHQGame::id();
$params['userid'] = FHQSecurity::userid();

$conn = FHQHelpers::createConnection($config);
$values_q = array();

foreach ( $params as $k => $v) {
  $values_q[] = '?';
}

$query = 'INSERT INTO quest('.implode(', ', array_keys($params)).', date_change, date_create)
  VALUES('.implode(', ', $values_q).', NOW(), NOW());';

// echo $query;

// $result['params'] = $params;
// $result['query'] = $query;

try {
	$stmt = $conn->prepare($query);
	if($stmt->execute(array_values($params))) {
		$result['data']['quest']['id'] = $conn->lastInsertId();
		$result['result'] = 'ok';
		FHQQuest::updateCountUserSolved($conn, $result['data']['quest']['id']);
	} else {
		$result['error']['pdo'] = $conn->errorInfo();
		$result['error']['code'] = 304;
		$result['error']['message'] = 'Could not insert';
	}
} catch(PDOException $e) {
	FHQHelpers::showerror(747,$e->getMessage());
}

include_once ($curdir."/../api.lib/savetoken.php");
echo json_encode($result);


text:
namespace RenderCore { namespace ColladaConversion
{
    class CompareId
    {
    public:
        bool operator()(const SkeletonRegistry::ImportantNode& lhs, ObjectGuid rhs) const   { return lhs._id < rhs; }
        bool operator()(ObjectGuid lhs, const SkeletonRegistry::ImportantNode& rhs) const   { return lhs < rhs._id; }
        bool operator()(ObjectGuid lhs, ObjectGuid rhs) const                               { return lhs < rhs; }
    };

    bool SkeletonRegistry::IsImportant(ObjectGuid node) const
    {
        if (node == ObjectGuid()) return false;
        auto i = std::lower_bound(_importantNodes.begin(), _importantNodes.end(), node, CompareId());
        return i != _importantNodes.end() && i->_id == node;
    }

    auto SkeletonRegistry::GetOutputMatrixIndex(ObjectGuid node) -> TransformMarker
    {
        if (node == ObjectGuid()) return ~0u;
        auto i = std::lower_bound(_importantNodes.begin(), _importantNodes.end(), node, CompareId());
        if (i != _importantNodes.end() && i->_id == node) {
            if (i->_transformMarker == TransformMarker_UnSet)
                i->_transformMarker = _nextOutputIndex++;
            return i->_transformMarker;
        }

        auto result = _nextOutputIndex++;
        _importantNodes.insert(i, ImportantNode(node, std::string(), result, Identity<Float4x4>(), false));
        return result;
    }

    bool SkeletonRegistry::TryRegisterNode(ObjectGuid node, const char bindingName[])
    {
        if (node == ObjectGuid()) return false;
        // look for other nodes bound to the same name
        for(const auto&i:_importantNodes)
            if (i._bindingName == bindingName)
                return i._id == node;   // duplicate binding name applied to some other node

        auto i = std::lower_bound(_importantNodes.begin(), _importantNodes.end(), node, CompareId());
        if (i != _importantNodes.end() && i->_id == node) {
            if (i->_bindingName.empty()) {
                i->_bindingName = bindingName;
                return true;
            }
            return i->_bindingName == bindingName;    // return true only if it matches the previously registered name
        }

        _importantNodes.insert(i, ImportantNode(node, bindingName, TransformMarker_UnSet, Identity<Float4x4>(), false));
        return true;
    }

    void SkeletonRegistry::AttachInverseBindMatrix(ObjectGuid node, const Float4x4& inverseBind)
    {
        if (node == ObjectGuid()) return;
        auto i = std::lower_bound(_importantNodes.begin(), _importantNodes.end(), node, CompareId());
        if (i != _importantNodes.end() && i->_id == node) {
            i->_inverseBind = inverseBind;
            i->_hasInverseBind = true;
        } else {
            _importantNodes.insert(i, ImportantNode(node, std::string(), TransformMarker_UnSet, inverseBind, true));
        }
    }

    auto    SkeletonRegistry::GetImportantNodes() const -> IteratorRange<const ImportantNode*>
    {
        return MakeIteratorRange(_importantNodes);
    }

    auto SkeletonRegistry::GetNode(ObjectGuid node) const -> ImportantNode
    {
        auto i = std::lower_bound(_importantNodes.begin(), _importantNodes.end(), node, CompareId());
        if (i != _importantNodes.end() && i->_id == node)
            return *i;
        return ImportantNode();
    }

    void    SkeletonRegistry::MarkParameterAnimated(const std::string& paramName)
    {
        auto i = std::lower_bound(_markParameterAnimated.cbegin(), _markParameterAnimated.cend(), paramName);
        if (i != _markParameterAnimated.cend() && (*i) == paramName) return;
        _markParameterAnimated.insert(i, paramName);
    }

    bool    SkeletonRegistry::IsAnimated(const std::string& paramName) const
    {
        auto i = std::lower_bound(_markParameterAnimated.cbegin(), _markParameterAnimated.cend(), paramName);
        return i != _markParameterAnimated.cend() && (*i) == paramName;
    }

    SkeletonRegistry::SkeletonRegistry() : _nextOutputIndex(0) {}
    SkeletonRegistry::~SkeletonRegistry() {}
}}


text:
package com.bot4s.telegram.methods

import com.bot4s.telegram.models.BotCommandScope.BotCommandScope

/**
 *  Use this method to delete the list of the bot's commands for the given scope and user language. After deletion, higher level commands will be shown to affected users. Returns True on success.
 *    @param scope 	        BotCommandScope Optional
 *                          A JSON-serialized object, describing scope of users for which the commands are relevant. Defaults to BotCommandScopeDefault.
 *    @param  languageCode 	String 	Optional
 *                          A two-letter ISO 639-1 language code. If empty, commands will be applied to all users from the given scope, for whose language there are no dedicated commands
 */
case class DeleteMyCommands(
  scope: Option[BotCommandScope] = None,
  languageCode: Option[String] = None
) extends JsonRequest[Boolean]


text:
<?xml version="1.0" encoding="utf-8"?>

<!--
  ~ Copyright (c) Ivanov Pavel (ivanovpv@gmail.com) and Egor Sarnavsky (egoretss@gmail.com) 2012.
  ~   $Author: ivanovpv $
  ~   $Rev: 474 $
  ~   $LastChangedDate: 2014-02-07 $
  -->
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:psm="http://schemas.android.com/apk/res-auto"
    android:id="@+id/cloudyMessageLayout"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:descendantFocusability="blocksDescendants"
    android:orientation="vertical">
    <TextView
        android:id="@+id/separatorText"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:gravity="center_horizontal"
        android:textColor="@android:color/black"
        android:textStyle="bold"
        android:background="@drawable/rounded_separator"
        android:layout_margin="6dp"
        android:text="Today"/>
    <RelativeLayout
        android:id="@+id/sent"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="horizontal"
        android:paddingTop="6dp"
        android:paddingLeft="6dp"
        android:paddingBottom="6dp"
        android:paddingRight="6dp"
        >
        <!--LinearLayout
                android:id="@+id/sentLeftLayout"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:layout_alignParentLeft="true"
                android:orientation="horizontal"
                -->
        <TextView
            android:id="@+id/sentTime"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:paddingBottom="12dip"
            android:paddingRight="24dip"
            android:paddingTop="12dip"
            android:singleLine="true"
            android:textColor="@android:color/white"
            android:textSize="12dip"
            android:layout_centerVertical="true"
            android:layout_alignParentLeft="true"
            android:text="sent time"
            />
        <ImageView
            android:id="@+id/sentStatusIcon"
            android:layout_width="32px"
            android:layout_height="32px"
            android:layout_centerVertical="true"
            android:adjustViewBounds="true"
            android:src="@drawable/exclamation_mark"
            android:ellipsize="none"
            android:layout_toRightOf="@id/sentTime"
            />
        <View
            android:id="@+id/anchor"
            android:layout_width="0dp"
            android:layout_height="0dp"
            android:layout_margin="12dp"
            android:layout_toRightOf="@id/sentStatusIcon"
            />
        <!--/LinearLayout-->
        <LinearLayout
            android:id="@+id/sentMessage"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_alignParentRight="true"
            android:orientation="horizontal"
            android:layout_toRightOf="@id/anchor"
            android:weightSum="3"
            >
            <LinearLayout
                android:orientation="vertical"
                android:id="@+id/sentBody"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:background="@drawable/rounded_sent"
                android:layout_weight="3"
                android:paddingBottom="6dip"
                android:paddingLeft="6dip"
                android:paddingRight="6dip"
                android:paddingTop="6dip"
                >
                <TextView
                    android:id="@+id/sentText"
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:ellipsize="none"
                    android:singleLine="false"
                    android:textSize="16sp"
                    android:textColor="@android:color/black"
                    android:autoLink="all"
                    android:focusable="false"
                    android:background="@drawable/rounded_sent"
                    android:layout_weight="3"
                    android:text="Sent text"
                    />
            </LinearLayout>
            <LinearLayout
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_weight="1"
                >
                <ImageView
                    android:layout_width="12dip"
                    android:layout_height="12dip"
                    android:layout_margin="1dip"
                    android:background="@drawable/ball_sent"
                    android:layout_gravity="top"
                    />
                <ImageView
                    android:layout_width="6dip"
                    android:layout_height="6dip"
                    android:layout_margin="1dip"
                    android:background="@drawable/ball_sent"
                    android:layout_gravity="top"
                    />
            </LinearLayout>
        </LinearLayout>
        <ProgressBar
            android:id="@+id/progressBarPendingStatus"
            style="?android:attr/progressBarStyleSmall"
            android:layout_centerVertical="true"
            android:layout_toLeftOf="@id/sentMessage"
            android:layout_width="wrap_content"
            android:visibility="gone"
            android:layout_height="wrap_content"
            android:layout_toRightOf="@id/sentStatusIcon"
            />
    </RelativeLayout>
</LinearLayout>


text:
<?xml version="1.0" encoding="UTF-8"?>
<!--
  Licensed to the AOS Community (AOS) under one or more
  contributor license agreements.  See the NOTICE file
  distributed with this work for additional information
  regarding copyright ownership.  The AOS licenses this file
  to you 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.
-->
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
  <modelVersion>4.0.0</modelVersion>
  <parent>
    <groupId>aos.t4f</groupId>
    <artifactId>t4f-data-parser</artifactId>
    <version>1.0.0-SNAPSHOT</version>
    <relativePath>..</relativePath>
  </parent>
  <artifactId>t4f-data-parser-mvel</artifactId>
  <name>T4F Data Parser MVEL</name>
  <packaging>jar</packaging>
  <dependencies>
    <dependency>
      <groupId>org.mvel</groupId>
      <artifactId>mvel2</artifactId>
    </dependency>
    <dependency>
      <groupId>junit</groupId>
      <artifactId>junit</artifactId>
    </dependency>
  </dependencies>
  <build>
    <plugins>
      <plugin>
        <groupId>org.apache.maven.plugins</groupId>
        <artifactId>maven-surefire-plugin</artifactId>
        <configuration>
          <forkMode>never</forkMode>
          <excludes>
          <!--
            | Class org.mvel2.optimizers.impl.refl.ReflectiveAccessorOptimizer can not access a
            | member of class org.apache.maven.surefire.report.ConsoleOutputCapture$ForwardingPrintStream
            | with modifiers "public"]
           -->
            <exclude>**/*PrintTest.java</exclude>
            <exclude>**/*ShellTest.java</exclude>
          </excludes>
        </configuration>
      </plugin>
    </plugins>
  </build>
</project>


text:
package com.mtools.core.plugin.annotation;

import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;

/**
 * 临时属性,不需要参与数据库的 增删改查
 * @author zhanggh
 *
 */
@Target({ElementType.METHOD})
@Retention(RetentionPolicy.RUNTIME)
public @interface Temporary {
	String value() default "";
}


text:
package com.puresoltechnologies.ductiledb.xo.test.implementedby;

import com.buschmais.xo.api.proxy.ProxyMethod;
import com.puresoltechnologies.ductiledb.tinkerpop.DuctileEdge;

public class RelationIncrementValueMethod implements ProxyMethod<DuctileEdge> {

    @Override
    public Object invoke(DuctileEdge entity, Object instance, Object[] args) {
	A2B a2b = A2B.class.cast(instance);
	int value = a2b.getValue();
	value++;
	a2b.setValue(value);
	return value;
    }

}


text:
import type { NextPage, GetStaticProps } from 'next';
import { Auth } from '@/components/Auth';
import { Files } from '@/components/files/Files';

const FilesPage: NextPage = () => (
    <Auth>
        <Files />
    </Auth>
);

export const getStaticProps: GetStaticProps = async () => ({ props: { title: 'Files', standalone: false } });

export default FilesPage;


text:
package io.crate.operation.fetch;

import com.google.common.collect.ImmutableList;
import com.google.common.util.concurrent.FutureCallback;
import com.google.common.util.concurrent.Futures;
import com.google.common.util.concurrent.SettableFuture;
import io.crate.core.collections.Bucket;
import io.crate.core.collections.Row;
import io.crate.core.collections.RowN;
import io.crate.testing.CollectingProjector;
import io.crate.test.integration.CrateUnitTest;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.ExpectedException;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;

import static org.hamcrest.Matchers.empty;
import static org.hamcrest.Matchers.is;

public class PositionalBucketMergerTest extends CrateUnitTest {

    @Rule
    public ExpectedException expectedException = ExpectedException.none();

    @Test
    public void testConcurrentSetNextBucket() throws Exception {
        /**
         * Propagate 2 buckets of the same upstream concurrent, every bucket is ordered.
         */
        int numUpstreams = 2;

        CollectingProjector resultProvider = new CollectingProjector();
        final PositionalBucketMerger bucketMerger = new PositionalBucketMerger(resultProvider, numUpstreams, 1);

        final List<List<List<Object[]>>> bucketsPerUpstream = new ArrayList<>(numUpstreams);
        List<List<Object[]>> upstream1 = new ArrayList<>(2);
        upstream1.add(ImmutableList.of(new Object[]{4}, new Object[]{6}, new Object[]{7}));
        upstream1.add(ImmutableList.of(new Object[]{0}, new Object[]{1}, new Object[]{3}));
        bucketsPerUpstream.add(upstream1);

        List<List<Object[]>> upstream2 = new ArrayList<>(2);
        upstream2.add(ImmutableList.of(new Object[]{2}, new Object[]{5}));
        upstream2.add(ImmutableList.of(new Object[]{8}, new Object[]{9}));
        bucketsPerUpstream.add(upstream2);

        final List<Throwable> setNextRowExceptions = new ArrayList<>();
        final CountDownLatch latch = new CountDownLatch(numUpstreams*2);
        final ExecutorService executorService = Executors.newScheduledThreadPool(numUpstreams);
        for (int i = 0; i < bucketsPerUpstream.size(); i++) {
            final int upstreamId = i;

            for (final List<Object[]> bucket : bucketsPerUpstream.get(i)) {
                bucketMerger.registerUpstream(null);
                executorService.execute(new Runnable() {
                    @Override
                    public void run() {
                        List<Row> rows1 = new ArrayList<>();
                        for (Object[] row : bucket) {
                            rows1.add(new PositionalRowDelegate(new RowN(row), (int) row[0]));
                        }
                        try {
                            bucketMerger.setNextBucket(rows1, upstreamId);
                        } catch (Exception e) {
                            setNextRowExceptions.add(e);
                        }
                        bucketMerger.finish();
                        latch.countDown();
                    }
                });
            }
        }
        latch.await();
        executorService.shutdown();
        bucketMerger.finish();

        assertThat(setNextRowExceptions, empty());

        final SettableFuture<Bucket> results = SettableFuture.create();
        Futures.addCallback(resultProvider.result(), new FutureCallback<Bucket>() {
            @Override
            public void onSuccess(Bucket result) {
                results.set(result);
            }

            @Override
            public void onFailure(Throwable t) {
                results.setException(t);
            }
        });

        Bucket result = results.get();
        assertThat(result.size(), is(10));
        Iterator<Row> it = result.iterator();
        for (int i = 0; i < 10; i++) {
            assertThat((int) it.next().get(0), is(i));
        }

        executorService.awaitTermination(1, TimeUnit.SECONDS);
    }

    @Test
    public void testOneUpstreamWillFail() throws Exception {
        int numUpstreams = 2;

        CollectingProjector resultProvider = new CollectingProjector();
        final PositionalBucketMerger bucketMerger = new PositionalBucketMerger(resultProvider, numUpstreams, 1);

        final List<List<List<Object[]>>> bucketsPerUpstream = new ArrayList<>(numUpstreams);
        List<List<Object[]>> upstream1 = new ArrayList<>(2);
        upstream1.add(ImmutableList.of(new Object[]{4}, new Object[]{6}, new Object[]{7}));
        upstream1.add(ImmutableList.of(new Object[]{0}, new Object[]{1}, new Object[]{3}));
        bucketsPerUpstream.add(upstream1);

        List<List<Object[]>> upstream2 = new ArrayList<>(2);
        upstream2.add(ImmutableList.of(new Object[]{2}, new Object[]{5}));
        upstream2.add(ImmutableList.of(new Object[]{8}, new Object[]{9}));
        bucketsPerUpstream.add(upstream2);

        final List<Throwable> setNextRowExceptions = new ArrayList<>();
        final CountDownLatch latch = new CountDownLatch(numUpstreams*2);
        final ExecutorService executorService = Executors.newScheduledThreadPool(numUpstreams);
        // register upstreams
        for (int i = 0; i < bucketsPerUpstream.size()*2; i++) {
            bucketMerger.registerUpstream(null);
        }

        for (int i = 0; i < bucketsPerUpstream.size(); i++) {
            final int upstreamId = i;

            if (upstreamId == numUpstreams-1) {
                // last upstream will fail
                bucketMerger.fail(new Throwable(String.format("[%d] I'm failing", upstreamId)));
                // 2 buckets per node, count down 2 times
                latch.countDown();
                latch.countDown();
                continue;
            }

            for (final List<Object[]> bucket : bucketsPerUpstream.get(i)) {
                executorService.execute(new Runnable() {
                    @Override
                    public void run() {
                        List<Row> rows1 = new ArrayList<>();
                        for (Object[] row : bucket) {
                            rows1.add(new PositionalRowDelegate(new RowN(row), (int) row[0]));
                        }
                        try {
                            bucketMerger.setNextBucket(rows1, upstreamId);
                        } catch (Exception e) {
                            setNextRowExceptions.add(e);
                        }
                        bucketMerger.finish();
                        latch.countDown();
                    }
                });
            }
        }
        latch.await();
        executorService.shutdown();
        bucketMerger.finish();

        assertThat(setNextRowExceptions, empty());

        final SettableFuture<Bucket> results = SettableFuture.create();
        Futures.addCallback(resultProvider.result(), new FutureCallback<Bucket>() {
            @Override
            public void onSuccess(Bucket result) {
                results.set(result);
            }

            @Override
            public void onFailure(Throwable t) {
                results.setException(t);
            }
        });

        expectedException.expect(Throwable.class);
        expectedException.expectMessage(String.format("[%d] I'm failing", numUpstreams-1));
        results.get();

        executorService.awaitTermination(1, TimeUnit.SECONDS);
    }

}


text:
module Axiom
  class Attribute

    # Represents a Float value in a relation tuple
    class Float < Numeric

      # The attribute type
      #
      # @example
      #   type = Axiom::Attribute::Float.type  # => Axiom::Types::Float
      #
      # @return [Class<Types::Float>]
      #
      # @api public
      def self.type
        Types::Float
      end

    end # class Float
  end # class Attribute
end # module Axiom


text:
START_ATF_NAMESPACE
    typedef unsigned __int64 (WINAPIV *COMMDLGPROC)(HWND__ *, unsigned int, unsigned __int64, __int64);
END_ATF_NAMESPACE


text:
Twitter-Mining
==================

A Python Data Mining tool.

Gathers data from Twitter's 100 top celebrities tweets and regular people and saves it to a database

**Steps:**

***run the create_and_insert_users.sql on mysql***

```
$> mysql -u < create_and_insert_users.sql

```

This will create the `twitter_mining` database and the `users` table in MySQL

***Install requiremnts***

Install de requirements listed in requirements.txt

```
$> pip install -r requirements.txt

```

***run the get_users.py***

```
$> python get_users.py

```

Wait for as long as you want. Every 6 hours the get_users.py will do it's work. You can set the sleep time in get_users.py.

***check the results on table users and plot k-means***
```
mysql> SELECT * FROM `users`;

$> python k_means.py
```


text:
using System.Web.Http;
using Umbraco.Core;

namespace SH.Site.EventHandlers
{
    public class WebApiEventHandler : ApplicationEventHandler
    {
        protected override void ApplicationStarted(UmbracoApplicationBase umbracoApplication,
            ApplicationContext applicationContext)
        {
            GlobalConfiguration.Configuration.EnableCors();
        }
    }
}