text:
(function (window) {
  'use strict';

  /*
   *  Represenets an editor
   *  @constructor
   *  @param {DOMNode} element - The TEXTAREA element to add the Wysiwyg to.
   *  @param {object} userOptions - The default options selected by the user.
   */
  function Wysiwyg (editor, userOptions) {
    // This calls the $ function, with the element as a parameter and
    // returns the jQuery object wrapper for element. It also assigns the
    // jQuery object wrapper to the property $editor on `this`.
    var wrapper = document.createElement('div');
    var toolWrapper = document.createElement('div');
    wrapper.classList.add('seditor-wrapper');
    toolWrapper.classList.add('seditor-toolbar');

    if (editor.clientWidth && editor.clientWidth > 200) {
      wrapper.style.width = editor.clientWidth + 'px';
    }
    var richer = this;

    this.selectedRange = null;
    var tmp = editor.cloneNode();

    editor.replaceWith(wrapper);
    this.editor = editor = tmp;
    editor.classList.add('seditor-content');

    wrapper.appendChild(toolWrapper);
    wrapper.appendChild(editor);

    this.toolWrapper = toolWrapper;

    var defaults = {
      toolbarSelector: '[data-role=editor-toolbar]',
      commandRole: 'edit',
      activeToolbarClass: 'btn-active',
      selectionMarker: 'edit-focus-marker',
      selectionColor: 'darkgrey',
      dragAndDropImages: true,
      keypressTimeout: 200,
      file: {
        error: function (reason, detail) {
          console.log('File upload error', reason, detail);
        }
        // uploader
        // @file File
        // @callback function(url) {}
        // uploader: function(file, callback) {}
      },
      // fileUpload:
      widgetLabels: {
        font: 'Font',
        forecolor: 'Font Color',
        backcolor: 'Background Color',
        fontsize: 'Font Size'
      },
      widgetAlias: {
        font: 'fontName'
      },
      widgetDetails: {
        font: ['Serif', 'Sans', 'Arial', 'Arial Black', 'Courier',
          'Courier New', 'Comic Sans MS', 'Helvetica', 'Impact', 'Lucida Grande', 'Lucida Sans', 'Tahoma', 'Times',
          'Times New Roman', 'Verdana'
        ].map(function (item) {
          return {
            key: item,
            style: 'font-family:' + item,
            text: item
          };
        }),
        fontsize: [{
          key: 7,
          style: 'font-size: xx-large',
          text: 'xx-large'
        },
        {
          key: 6,
          style: 'font-size: x-large',
          text: 'x-large'
        },
        {
          key: 5,
          style: 'font-size: large',
          text: 'large'
        },
        {
          key: 4,
          style: 'font-size: medium',
          text: 'medium'
        },
        {
          key: 3,
          style: 'font-size: small',
          text: 'small'
        },
        {
          key: 2,
          style: 'font-size: x-small',
          text: 'x-small'
        },
        {
          key: 1,
          style: 'font-size: xx-small',
          text: 'xx-small'
        }
        ],
        forecolor: ['#000000', '#0000FF', '#30AD23', '#FF7F00', '#FF0000', '#FFFF00', '#FFFFFF'].map(function (color) {
          return {
            key: color,
            style: 'color:' + color
          };
        }),
        backcolor: ['#000000', '#0000FF', '#30AD23', '#FF7F00', '#FF0000', '#FFFF00', '#FFFFFF'].map(function (color) {
          return {
            key: color,
            style: 'background:' + color
          };
        })
      },
      widgetIcons: {
        font: 'text-height',
        backcolor: 'paint-brush',
        forecolor: 'font',
        insertunorderedlist: 'list-ul',
        insertorderedlist: 'list-ol',
        justifyleft: 'align-left',
        justifycenter: 'align-center',
        justifyright: 'align-right',
        justifyfull: 'align-justify',
        redo: 'repeat',
        fontsize: 'header'
      },
      widgets: [
        'font',
        'fontsize',
        'forecolor',
        'backcolor', [
          'bold',
          'italic',
          'strikethrough',
          'underline'
        ],
        [
          'insertunorderedlist',
          'insertorderedlist',
          'outdent',
          'indent'
        ],

        ['justifyleft',
          'justifycenter',
          'justifyright',
          'justifyfull'
        ],
        'link', ['unlink',
          'image'
        ],

        ['undo',
          'redo'
        ]
      ]
    };

    var options = Object.assign({}, defaults, userOptions);
    var toolbarBtnSelector = 'a[data-' + options.commandRole + '],button[data-' + options.commandRole + '],input[type=button][data-' + options.commandRole + ']';
    // this.bindHotkeys( editor, options, toolbarBtnSelector );

    if (options.dragAndDropImages) {
      this.initFileDrops(editor, options, toolbarBtnSelector);
    }
    this.setupToolbar(toolWrapper, options);

    this.bindToolbar(editor, toolWrapper, options, toolbarBtnSelector);

    editor.setAttribute('contenteditable', true);
    ['mouseup', 'keyup', 'mouseout'].forEach(function (event) {
      editor.addEventListener(event, function () {
        richer.saveSelection();
        richer.updateToolbar(editor, toolbarBtnSelector, options);
      });
    });

    window.addEventListener('touchend', function (e) {
      var isInside = (editor.is(e.target) || editor.has(e.target).length > 0);
      var currentRange = this.getCurrentRange();
      var clear = currentRange && (currentRange.startContainer === currentRange.endContainer && currentRange.startOffset === currentRange.endOffset);

      if (!clear || isInside) {
        richer.saveSelection();
        richer.updateToolbar(editor, toolbarBtnSelector, options);
      }
    });
    document.querySelectorAll('.seditor-btn-group a.seditor-dropdown-toggle').forEach(function (btn) {
      btn.addEventListener('click', function (e) {
        e.stopPropagation();
        document.querySelectorAll('.seditor-btn-group .seditor-dropdown-menu.show').forEach(function (other) {
          if (other !== menu) {
            other.classList.remove('show');
          }
        });
        var menu = this.parentNode.querySelector('.seditor-dropdown-menu');
        if (menu) {
          menu.classList.toggle('show');
        }
      }.bind(btn));
    });
    document.querySelectorAll('.seditor-btn-group .seditor-dropdown-menu').forEach(function (menu) {
      menu.addEventListener('blur', function (e) {
        menu.classList.remove('show');
      });
    });
    document.body.addEventListener('click', function (e) {
      document.querySelectorAll('.seditor-btn-group .seditor-dropdown-menu.show').forEach(function (menu) {
        if (e.path.indexOf(menu) === -1) {
          menu.classList.remove('show');
        }
      });
    });
  }

  Wysiwyg.prototype.readFileIntoDataUrl = function (fileInfo, options) {
    if (options.file.uploader && typeof options.file.uploader === 'function') {
      return new Promise(function (resolve, reject) {
        options.file.uploader(fileInfo, resolve);
      });
    } else {
      return new Promise(function (resolve, reject) {
        /* eslint-disable */
        var fReader = new FileReader()

        fReader.onload = function (e) {
          resolve(e.target.result)
          // loader.resolve( e.target.result );
        }

        fReader.onerror = reject
        fReader.readAsDataURL(fileInfo)
      })
    }
  }

  Wysiwyg.prototype.setupToolbar = function (toolbar, options) {
    var tools = ''
    var that = this
    options.widgets.forEach(function (widget) {
      if (typeof widget === 'string') {
        tools += '
' + that.setupToolBtn(widget, options) + '
'
      } else {
        tools += '
'
        widget.forEach(function (w) {
          tools += that.setupToolBtn(w, options)
        })
        tools += '
'
      }
    })
    toolbar.innerHTML = tools
  }
  Wysiwyg.prototype.setupToolBtn = function (widget, options) {
    if (widget === 'link') {
      this.hasCreateLink = true
      return '' +
        '
' +
        '<input placeholder="URL" type="text" data-' + options.commandRole + '="createLink" />' +
        '<button class="seditor-btn seditor-btn-createlink" type="button">Add</button>' +
        '
'
    } else if (widget === 'image') {
      return ' ' +
        '<input class="imgUpload" type="file" data-role="magic-overlay" data-target="#pictureBtn" data-' +
        options.commandRole + '="insertImage" />'
    }
    if (options.widgetDetails[widget]) {
      var btn = '' +
         '' + (options.widgetLabels[widget] || widget || '') + '' +
         ''
      var li = '
'

      options.widgetDetails[widget].forEach(function (dt) {
        var key, text, style
        key = text = dt
        widget = options.widgetAlias[widget] || widget
        if (typeof dt === 'object') {
          key = dt.key
          text = dt.text || key
          style = dt.style
        }
        li += '
' + text + '
'
      })
      li += '
'
      return btn + li
    } else {
      return ''
    }
  }

  Wysiwyg.prototype.cleanHtml = function (o) {
    var self = this
    if (String(self.editor.dataset['htmlMode']) === 'true') {
      // $( self ).html( $( self ).text( );
      self.editor.innerHTML = self.editor.textContent
      self.editor.setAttribute('contenteditable', true)
      self.editor.dataset['htmlMode'] = false
      // $( self ).data( "htmlMode", false );
    }
    var html = self.editor.innerHTML
    self.editor.innerHTML = ''
    return html
  };

  Wysiwyg.prototype.updateToolbar = function (editor, toolbarBtnSelector, options) {
    if (options.activeToolbarClass) {
      this.toolWrapper.querySelectorAll(toolbarBtnSelector).forEach(function (self) {
        var data = self.dataset
        var commandArr = data[options.commandRole].split(' ')
        var command = commandArr[0]

        // If the command has an argument and its value matches this button. == used for string/number comparison
        if (commandArr.length > 1 && document.queryCommandEnabled(command) && document.queryCommandValue(command) === commandArr[1]) {
          self.classList.add(options.activeToolbarClass)

        // Else if the command has no arguments and it is active
        } else if (commandArr.length === 1 && document.queryCommandEnabled(command) && document.queryCommandState(command)) {
          self.classList.add(options.activeToolbarClass)
        }

        // Else the command is not active
        else {
          self.classList.remove(options.activeToolbarClass)
        }
      })
    }
  }

  Wysiwyg.prototype.execCommand = function (commandWithArgs, valueArg, editor, options, toolbarBtnSelector) {
    if (String(editor.dataset['htmlMode']) === 'true') {
      console.log('html mode, rich editor disabled')
      return
    }
    var commandArr = commandWithArgs.split(' ')
    var command = commandArr.shift()
    var args = commandArr.join(' ') + (valueArg || '')

    var parts = commandWithArgs.split('-')

    if (parts.length === 1) {
      document.execCommand(command, false, args)
    } else if (parts[0] === 'format' && parts.length === 2) {
      document.execCommand('formatBlock', false, parts[1])
    }

    // ( editor ).trigger( "change" );
    this.updateToolbar(editor, toolbarBtnSelector, options)
  }

  Wysiwyg.prototype.getCurrentRange = function () {
    var sel, range
    if (window.getSelection) {
      sel = window.getSelection()
      if (sel.getRangeAt && sel.rangeCount) {
        range = sel.getRangeAt(0)
      }
    } else if (document.selection) {
      range = document.selection.createRange()
    }

    return range
  }

  Wysiwyg.prototype.saveSelection = function () {
    this.selectedRange = this.getCurrentRange()
  }

  Wysiwyg.prototype.restoreSelection = function () {
    var selection
    if (window.getSelection || document.createRange) {
      selection = window.getSelection()
      if (this.selectedRange) {
        try {
          selection.removeAllRanges()
        } catch (ex) {
          document.body.createTextRange().select()
          document.selection.empty()
        }
        selection.addRange(this.selectedRange)
      }
    } else if (document.selection && this.selectedRange) {
      this.selectedRange.select()
    }
  }

  // Adding Toggle HTML Editor.
  Wysiwyg.prototype.toggleHtmlEdit = function () {
    var editor = this.editor
    if (String(editor.dataset['htmlMode']) !== 'true') {
      var oContent = editor.innerHTML
      var editorPre = document.createElement('pre')
      editorPre.appendChild(document.createTextNode(oContent))
      editorPre.setAttribute('contenteditable', true)
      editor.pre = editorPre
      editor.innerHTML = ' '
      editor.appendChild(editorPre)
      editor.setAttribute('contenteditable', false)
      editor.dataset['htmlMode'] = true
      editor.focus()
    } else {
      if (editor.pre) {
        editor.innerHTML = editor.pre.innerText
        editor.pre = null
      } else {
        editor.innerHTML = editor.innerText
      }
      editor.setAttribute('contenteditable', true)
      editor.dataset['htmlMode'] = false
      editor.focus()
    }
  }

  Wysiwyg.prototype.insertFiles = function (files, options, editor, toolbarBtnSelector) {
    var self = this
    editor.focus()
    for (var i = 0, l = files.length; i < l; i++) {
      // files.forEach(function( idx, fileInfo ) {
      (function (idx, fileInfo) {
        if (/^image\//.test(fileInfo.type)) {
          self.readFileIntoDataUrl(fileInfo, options).then(function (dataUrl) {
            self.execCommand('insertimage', dataUrl, editor, options, toolbarBtnSelector)
          }).catch(function (e) {
            options.file.error('file-reader', e)
          })
        } else {
          options.file.error('unsupported-file-type', fileInfo.type)
        }
      })(i, files[i])
    }
  }

  Wysiwyg.prototype.markSelection = function (color, options) {
    this.restoreSelection()
    if (document.queryCommandSupported('hiliteColor')) {
      document.execCommand('hiliteColor', false, color || 'transparent')
    }
    this.saveSelection()
  }

  // Move selection to a particular element
  function selectElementContents (element) {
    if (window.getSelection && document.createRange) {
      var selection = window.getSelection()
      var range = document.createRange()
      range.selectNodeContents(element)
      selection.removeAllRanges()
      selection.addRange(range)
    } else if (document.selection && document.body.createTextRange) {
      var textRange = document.body.createTextRange()
      textRange.moveToElementText(element)
      textRange.select()
    }
  }

  Wysiwyg.prototype.bindToolbar = function (editor, toolbar, options, toolbarBtnSelector) {
    var self = this
    toolbar.querySelectorAll(toolbarBtnSelector).forEach(function (btn) {
      btn.addEventListener('click', function () {
        self.restoreSelection()
        editor.focus()

        if (editor.dataset[options.commandRole] === 'html') {
          self.toggleHtmlEdit()
        } else {
          self.execCommand(this.dataset[(options.commandRole)], null, editor, options, toolbarBtnSelector)
        }

        self.saveSelection()
      }.bind(btn))
    });

    ['webkitspeechchange, change'].forEach(function (event) {
      toolbar.querySelectorAll('input[type=text][data-' + options.commandRole + ']').forEach(function (btn) {
        btn.addEventListener(event, function () {
          var newValue = this.value // Ugly but prevents fake double-calls due to selection restoration
          this.value = '';
          self.restoreSelection()

          var text = window.getSelection()
          if (text.toString().trim() === '' && newValue) {
            // create selection if there is no selection
            self.editor.append('' + newValue + '')
            selectElementContents(self.editor.querySelector('span:last'))
          }

          if (newValue) {
            editor.focus()
            self.execCommand(this.dataset[options.commandRole], newValue, editor, options, toolbarBtnSelector)
          }
          self.saveSelection()
        }.bind(btn))
      })
    })
    toolbar.querySelectorAll('input[type=text][data-' + options.commandRole + ']').forEach(function (btn) {
      btn.addEventListener('blur', function () {
        self.markSelection(false, options)
      })
    })

    toolbar.querySelectorAll('input[type=file][data-' + options.commandRole + ']').forEach(function (btn) {
      btn.addEventListener('change', function () {
        self.restoreSelection()
        if (this.type === 'file' && this.files && this.files.length > 0) {
          self.insertFiles(this.files, options, editor, toolbarBtnSelector)
        }
        self.saveSelection()
        this.value = ''
      })
    })
    if (this.hasCreateLink) {
      toolbar.querySelectorAll('.seditor-btn-createlink').forEach(function (btn) {
        btn.addEventListener('click', function () {
          self.restoreSelection()
          editor.focus()
          var input = this.parentNode.querySelector('input')
          if (input && input.value && input.value.trim()) {
            if (editor.dataset[options.commandRole] === 'html') {
              self.toggleHtmlEdit()
            } else {
              self.execCommand(input.dataset[(options.commandRole)], input.value, editor, options, toolbarBtnSelector)
            }
            this.parentNode.classList.remove('show')
          }
          self.saveSelection()
        })
      })
    }
  }
  // init editor drag/drop file
  Wysiwyg.prototype.initFileDrops = function (editor, options, toolbarBtnSelector) {
    var self = this
    editor.addEventListener('drop', function (e) {
      var dataTransfer = e.dataTransfer
      e.stopPropagation()
      e.preventDefault()

      if (dataTransfer && dataTransfer.files && dataTransfer.files.length > 0) {
        self.insertFiles(dataTransfer.files, options, editor, toolbarBtnSelector)
      }
    });
    ['dragenter', 'dragover'].forEach(function (event) {
      editor.addEventListener(event, function (e) {
        return false
      })
    })
  }

  window.sEditor = function (selector, options) {
    var editors = []
    document.querySelectorAll(selector).forEach(function (el) {
      editors.push(new Wysiwyg(el, options))
    })
    if (editors.length === 1) {
      editors = editors[0]
    }
    return editors
  }
})(window)


text:
(function (Handsontable) {
    "use strict";

    var RichTextEditor = Handsontable.editors.TextEditor.prototype.extend();
    document.hotckeditor1_created=false;
    var hotparent;

    RichTextEditor.prototype.createElements = function () {
        // Call the original createElements method
        Handsontable.editors.TextEditor.prototype.createElements.apply(this, arguments);

        $("body").append("
"+
            "<textarea id='hotckmodal99' class='handsontableInput'></textarea>"+

            "<input type='submit' tabindex='-1' style='position:absolute; top:-1000px'>"+
            "
"
        );

        var dialog1=$( "#divckholder99" ).dialog({
            autoOpen: false,
            height: 400,
            width: 550,
            xmodal: true,
            buttons: {
                "Batal": function(){
                    dialog1.dialog( "close" );
                },
                "Simpan": function() {
                    dialog1.dialog( "close" );
                    hotparent.instance.setDataAtCell(hotparent.row, hotparent.col, CKEDITOR.instances['hotckmodal99'].getData());
                }
            },
            close: function() {
                //dialog1.dialog( "close" );
            }
        });
        CKEDITOR.config.height="100%";
        CKEDITOR.replace( 'hotckmodal99' );
        CKEDITOR.instances['hotckmodal99'].on("instanceReady", function(event){
            document.hotckeditor1_created=true;
        });

    };

    RichTextEditor.prototype.open = function() {
        hotparent=this;
        Handsontable.editors.TextEditor.prototype.open.apply(this, arguments);

        var val=this.instance.getDataAtCell(this.row, this.col)+'';

        if(document.hotckeditor1_created){
            CKEDITOR.instances['hotckmodal99'].setData(val);

            setTimeout(function(){
                CKEDITOR.instances['hotckmodal99'].focus();
                },300);
        }
        else{
            setTimeout(function(){
                CKEDITOR.instances['hotckmodal99'].setData(val);
                setTimeout(function(){
                    CKEDITOR.instances['hotckmodal99'].focus();
                    },300);
                },1000);
        }
        $( "#divckholder99" ).dialog('open');
    };

    RichTextEditor.prototype.finishEditing= function(isCancelled, ctrlDown) {
        // Remember to invoke parent's method
        arguments[0]=true;

        //console.log('revert:'+arguments[0]);
        Handsontable.editors.TextEditor.prototype.finishEditing.apply(this, arguments);

    };

    Handsontable.editors.RichTextEditor = RichTextEditor;
    Handsontable.editors.registerEditor('richTextModal', RichTextEditor);

})(Handsontable);

redpajama_set_name: RedPajamaGithub


text:
package smpl.quote.repository;

import smpl.quote.repository.mock.MockQuoteRepository;
import smpl.quote.repository.service.QuoteService;

public class RepositoryFactory {

	private RepositoryFactory(String storage) {
		init(storage);
	}

	public static QuoteRepository getQuoteRepository() {
		switch (s_factory.storageKind) {
		case RepositoryFactory.MEMORY:
			return s_factory.mockRepos.quoteRepository;
		case RepositoryFactory.MONGODB:
			return s_factory.mongodbRepos.quoteRepository;
		default:
			return null;
		}
	}

	private void init(String storage) {
		this.storageKind = storage;
		this.mockRepos = new Repositories();
		this.mongodbRepos = new Repositories();

		this.mockRepos.quoteRepository = new MockQuoteRepository();
		this.mongodbRepos.quoteRepository = mongoDBQuoteRepository;
	}

	public static synchronized RepositoryFactory getFactory() {
		return s_factory;
	}

	public static void reset(String storage) {
		s_factory = new RepositoryFactory(storage);
	}

	QuoteService mongoDBQuoteRepository;

	private class Repositories {
		QuoteRepository quoteRepository;
	}

	private Repositories mockRepos = new Repositories();
	private Repositories mongodbRepos = new Repositories();

	private String storageKind = RepositoryFactory.MONGODB;
	private static RepositoryFactory s_factory;

	public static final String MEMORY = "memory";
	public static final String MONGODB = "mongodb";
}


text:
package com.progym.activities;

import java.text.ParseException;
import java.util.Date;
import java.util.HashMap;
import java.util.List;

import org.androidannotations.annotations.AfterViews;
import org.androidannotations.annotations.Click;
import org.androidannotations.annotations.EActivity;
import org.apache.commons.lang3.time.DateUtils;

import android.os.Bundle;
import android.os.Parcelable;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentStatePagerAdapter;

import com.progym.R;
import com.progym.R.color;
import com.progym.constants.GlobalConstants;
import com.progym.custom.CaldroidFragmentCustom;
import com.progym.custom.fragments.FoodProgressDailyPieFragment;
import com.progym.custom.fragments.FoodProgressDailyPieFragment_;
import com.progym.custom.fragments.FoodProgressMonthlyLineFragment;
import com.progym.custom.fragments.FoodProgressMonthlyLineFragment_;
import com.progym.custom.fragments.FoodProgressYearlyLineFragment;
import com.progym.custom.fragments.FoodProgressYearlyLineFragment_;
import com.progym.interfaces.IProgressActivity;
import com.progym.model.Meal;
import com.progym.utils.DataBaseUtils;
import com.roomorama.caldroid.CaldroidFragment;

@EActivity ( R.layout.food_progress_activity ) public class ActivityFoodProgress extends ActivityAbstractProgress implements IProgressActivity {

     @Click void twDaily() {

          showProgressBar(ActivityFoodProgress.this);

          Thread t = new Thread(new Runnable() {

               @Override public void run() {

                    FRAGMENT_TYPE = DAILY;
                    List <Meal> meals = DataBaseUtils.getAllPlates();
                    HashMap <Date, Integer> datesToHighligt = new HashMap <Date, Integer>();
                    if ( null != meals && !meals.isEmpty() ) {

                         for ( Meal meal : meals ) {
                              try {
                                   datesToHighligt.put(DateUtils.parseDate(meal.date, DataBaseUtils.DATE_PATTERN_YYYY_MM_DD_HH_MM_SS_MILLIS), com.caldroid.R.color.caldroid_sky_blue);
                              } catch (ParseException e) {
                                   e.printStackTrace();
                              }
                         }
                    }
                    // set up title
                    Bundle bundle = new Bundle();
                    bundle.putString(com.roomorama.caldroid.CaldroidFragment.DIALOG_TITLE, getResources().getString(R.string.select_date));
                    bundle.putBoolean(CaldroidFragment.ENABLE_CLICK_ON_DISABLED_DATES, true);
                    calendar.setArguments(bundle);

                    // highlight dates in calendar with blue color
                    calendar.setBackgroundResourceForDates(datesToHighligt);
                    calendar.show(getSupportFragmentManager(), GlobalConstants.TAG);

                    hideProgressBar(ActivityFoodProgress.this);
               }
          });
          t.start();

     }

     @Click void twMonthly() {
          FRAGMENT_TYPE = MONTHLY;
          updateFragment(FRAGMENT_TYPE);
     }

     @Click void twYearly() {
          FRAGMENT_TYPE = YEARLY;
          updateFragment(FRAGMENT_TYPE);
     }

     @AfterViews void afterViews() {
          viewPager.setAdapter(new ProgressViewPagerAdapter(getSupportFragmentManager()));
          calendar = new CaldroidFragmentCustom();
          calendar.setCaldroidListener(onDateChangeListener);
          twDaily.setBackgroundColor(color.red);
     }

     @Override public void updateFragment(int fragmentType) {
          setProperPadding(fragmentType);
          switch (fragmentType) {
               case DAILY:
                    viewPager.setCurrentItem(DAILY, true);
                    ((ProgressViewPagerAdapter) viewPager.getAdapter()).bargraphDaily.setPieData(SELECTED_DATE, true);
                    break;
               case MONTHLY:
                    viewPager.setCurrentItem(MONTHLY, true);
                    ((ProgressViewPagerAdapter) viewPager.getAdapter()).linegraphMonthly.setLineData3(new Date(), true);
                    break;
               case YEARLY:
                    viewPager.setCurrentItem(YEARLY, true);
                    ((ProgressViewPagerAdapter) viewPager.getAdapter()).linegraphYearly.setYearProgressData(SELECTED_DATE, true);
                    break;
          }
     }

     /**
      * A simple pager adapter
      */
     private class ProgressViewPagerAdapter extends FragmentStatePagerAdapter {

          private static final int               NUM_OF_FRAGMENTS = 3;
          public FoodProgressDailyPieFragment    bargraphDaily    = new FoodProgressDailyPieFragment_();
          public FoodProgressMonthlyLineFragment linegraphMonthly = new FoodProgressMonthlyLineFragment_();
          public FoodProgressYearlyLineFragment  linegraphYearly  = new FoodProgressYearlyLineFragment_();

          public ProgressViewPagerAdapter ( FragmentManager fm ) {
               super(fm);
          }

          @Override public Parcelable saveState() {
               return null;
          }

          @Override public Fragment getItem(int position) {
               Fragment returnFragment = null;
               switch (position) {
                    case DAILY:
                         returnFragment = bargraphDaily;
                         break;

                    case MONTHLY:
                         returnFragment = linegraphMonthly;
                         break;

                    case YEARLY:
                         returnFragment = linegraphYearly;
                         break;

               }
               return returnFragment;
          }

          @Override public int getCount() {
               return NUM_OF_FRAGMENTS;
          }
     }
}


text:
/*globals jQuery, troubleshooting_data */

/** @namespace troubleshooting_data.nonce.icl_restore_notifications */
/** @namespace troubleshooting_data.nonce.icl_remove_notifications */

jQuery(document).ready(function () {

	var remove_notifications_button = jQuery('#icl_remove_notifications');
	var restore_notifications_button = jQuery('#icl_restore_notifications');
	var restore_notifications_all_users = jQuery('#icl_restore_notifications_all_users');
	remove_notifications_button.off('click');
	remove_notifications_button.bind('click', remove_all_notifications);
	restore_notifications_button.off('click');
	restore_notifications_button.bind('click', restore_notifications);

	function remove_all_notifications() {
		if (typeof(event.preventDefault) !== 'undefined') {
			event.preventDefault();
		} else {
			event.returnValue = false;
		}

		jQuery(this).attr('disabled', 'disabled');
		jQuery(this).after(icl_ajxloaderimg);

		var ajax_data = {
			'action': 'icl_remove_notifications',
			'nonce':  troubleshooting_data.nonce.icl_remove_notifications
		};

		jQuery.ajax({
			type:     "POST",
			url:      ajaxurl,
			data:     ajax_data,
			dataType: 'json',
			success:  function (response) {
				remove_notifications_button.removeAttr('disabled');
				alert(troubleshooting_data.strings.done);
				remove_notifications_button.next().fadeOut();
				if(response.reload == 1) {
					location.reload();
				}
			},
			error:    function (jqXHR, status, error) {
				var parsed_response = jqXHR.statusText || status || error;
				alert(parsed_response);
			}
		});

		return false;
	}

	function restore_notifications() {
		if (typeof(event.preventDefault) !== 'undefined') {
			event.preventDefault();
		} else {
			event.returnValue = false;
		}

		jQuery(this).attr('disabled', 'disabled');
		jQuery(this).after(icl_ajxloaderimg);

		var all_users = restore_notifications_all_users.is(':checked') ? 1 : 0;

		var ajax_data = {
			'action': 'icl_restore_notifications',
			'nonce':  troubleshooting_data.nonce.icl_restore_notifications,
			'all_users':  all_users
		};

		jQuery.ajax({
			type:     "POST",
			url:      ajaxurl,
			data:     ajax_data,
			dataType: 'json',
			success:  function (response) {
				restore_notifications_button.removeAttr('disabled');
				alert(troubleshooting_data.strings.done);
				restore_notifications_button.next().fadeOut();
				if(response.reload == 1) {
					location.reload();
				}
			},
			error:    function (jqXHR, status, error) {
				var parsed_response = jqXHR.statusText || status || error;
				alert(parsed_response);
			}
		});

		return false;
	}

	var fix_post_types_and_source_langs_button = jQuery("#icl_fix_post_types");
	var updateTermNamesButton = jQuery("#icl-update-term-names");

	updateTermNamesButton.click(iclUpdateTermNames);

	fix_post_types_and_source_langs_button.click(
		function () {
			jQuery(this).attr('disabled', 'disabled');
			icl_repair_broken_translations();
			jQuery(this).after(icl_ajxloaderimg);

		}
	);

	function icl_repair_broken_translations () {
		jQuery.ajax(
			{
				url: ajaxurl,
				data: {
					action: 'icl_repair_broken_type_and_language_assignments'
				},
				success: function (response) {
					var rows_fixed = response.data;
					fix_post_types_and_source_langs_button.removeAttr('disabled');
					fix_post_types_and_source_langs_button.next().fadeOut();
					var text = '';
					if (rows_fixed > 0) {
						text = troubleshooting_strings.success_1 + rows_fixed + troubleshooting_strings.success_2;
					} else {
						text = troubleshooting_strings.no_problems;
					}
					var type_term_popup_html = '

' + text + '

';
					jQuery(type_term_popup_html).dialog(
						{
							dialogClass: 'wpml-dialog wp-dialog',
							width      : 'auto',
							modal      : true,
							buttons    : {
								Ok: function () {
									jQuery(this).dialog("close");
								}
							}
						}
					);
				}
			});
	}

	function iclUpdateTermNames() {

		var updatedTermNamesTable = jQuery('#icl-updated-term-names-table');

		/* First of all we get all selected rows and the displayed Term names. */

		var selectedTermRows = updatedTermNamesTable.find('input[type="checkbox"]');

		var selectedIDs = {};

		jQuery.each(selectedTermRows, function (index, selectedRow) {
			selectedRow = jQuery(selectedRow);
			if(selectedRow.is(':checked') && selectedRow.val() && selectedRow.attr('name') && jQuery.trim(selectedRow.attr('name')) !== ''){
				selectedIDs[selectedRow.val().toString()] = selectedRow.attr('name');
			}
		});

		var selectedIDsJSON = JSON.stringify(selectedIDs);

		jQuery.ajax(
			{
				url: ajaxurl,
				method: "POST",
				data: {
					action: 'wpml_update_term_names_troubleshoot',
					_icl_nonce: troubleshooting_strings.termNamesNonce,
					terms: selectedIDsJSON
				},
				success: function (response) {

					jQuery.each(response.data, function (index, id) {
						updatedTermNamesTable.find('input[type="checkbox"][value="'+ id +'"]').closest('tr').remove();
					});

					var remainingRows = jQuery('.icl-term-with-suffix-row');

					if (remainingRows.length === 0 ){
						updatedTermNamesTable.hide();
						jQuery('#icl-update-term-names').hide();
						jQuery('#icl-update-term-names-done').show();
					}

					var termSuffixUpdatedHTML = '

' + troubleshooting_strings.suffixesRemoved + '

';
					jQuery(termSuffixUpdatedHTML).dialog(
						{
							dialogClass: 'wpml-dialog wp-dialog',
							width      : 'auto',
							modal      : true,
							buttons    : {
								Ok: function () {
									jQuery(this).dialog("close");
								}
							}

						}
					);
				}
			});
	}

	jQuery('#icl_cache_clear').click(function () {
		var self = jQuery(this);
		self.attr('disabled', 'disabled');
		self.after(icl_ajxloaderimg);
		jQuery.post(location.href + '&debug_action=cache_clear&nonce=' + troubleshooting_strings.cacheClearNonce, function () {
			self.removeAttr('disabled');
			alert( troubleshooting_strings.done );
			self.next().fadeOut();
		});
	});
});


text:
package golinters

import (
	"fmt"
	"strings"
	"sync"

	"github.com/OpenPeeDeeP/depguard"
	"golang.org/x/tools/go/analysis"
	"golang.org/x/tools/go/loader" //nolint:staticcheck // require changes in github.com/OpenPeeDeeP/depguard

	"github.com/golangci/golangci-lint/pkg/config"
	"github.com/golangci/golangci-lint/pkg/golinters/goanalysis"
	"github.com/golangci/golangci-lint/pkg/lint/linter"
	"github.com/golangci/golangci-lint/pkg/result"
)

const depguardLinterName = "depguard"

func NewDepguard() *goanalysis.Linter {
	var mu sync.Mutex
	var resIssues []goanalysis.Issue

	analyzer := &analysis.Analyzer{
		Name: depguardLinterName,
		Doc:  goanalysis.TheOnlyanalyzerDoc,
	}
	return goanalysis.NewLinter(
		depguardLinterName,
		"Go linter that checks if package imports are in a list of acceptable packages",
		[]*analysis.Analyzer{analyzer},
		nil,
	).WithContextSetter(func(lintCtx *linter.Context) {
		dg, err := newDepGuard(&lintCtx.Settings().Depguard)

		analyzer.Run = func(pass *analysis.Pass) (interface{}, error) {
			if err != nil {
				return nil, err
			}

			issues, errRun := dg.run(pass)
			if errRun != nil {
				return nil, errRun
			}

			mu.Lock()
			resIssues = append(resIssues, issues...)
			mu.Unlock()

			return nil, nil
		}
	}).WithIssuesReporter(func(*linter.Context) []goanalysis.Issue {
		return resIssues
	}).WithLoadMode(goanalysis.LoadModeTypesInfo)
}

type depGuard struct {
	loadConfig *loader.Config
	guardians  []*guardian
}

func newDepGuard(settings *config.DepGuardSettings) (*depGuard, error) {
	ps, err := newGuardian(settings)
	if err != nil {
		return nil, err
	}

	d := &depGuard{
		loadConfig: &loader.Config{
			Cwd:   "",  // fallbacked to os.Getcwd
			Build: nil, // fallbacked to build.Default
		},
		guardians: []*guardian{ps},
	}

	for _, additional := range settings.AdditionalGuards {
		add := additional
		ps, err = newGuardian(&add)
		if err != nil {
			return nil, err
		}

		d.guardians = append(d.guardians, ps)
	}

	return d, nil
}

func (d depGuard) run(pass *analysis.Pass) ([]goanalysis.Issue, error) {
	prog := goanalysis.MakeFakeLoaderProgram(pass)

	var resIssues []goanalysis.Issue
	for _, g := range d.guardians {
		issues, errRun := g.run(d.loadConfig, prog, pass)
		if errRun != nil {
			return nil, errRun
		}

		resIssues = append(resIssues, issues...)
	}

	return resIssues, nil
}

type guardian struct {
	*depguard.Depguard
	pkgsWithErrorMessage map[string]string
}

func newGuardian(settings *config.DepGuardSettings) (*guardian, error) {
	dg := &depguard.Depguard{
		Packages:        settings.Packages,
		IncludeGoRoot:   settings.IncludeGoRoot,
		IgnoreFileRules: settings.IgnoreFileRules,
	}

	var err error
	dg.ListType, err = getDepGuardListType(settings.ListType)
	if err != nil {
		return nil, err
	}

	// if the list type was a blacklist the packages with error messages should be included in the blacklist package list
	if dg.ListType == depguard.LTBlacklist {
		noMessagePackages := make(map[string]bool)
		for _, pkg := range dg.Packages {
			noMessagePackages[pkg] = true
		}

		for pkg := range settings.PackagesWithErrorMessage {
			if _, ok := noMessagePackages[pkg]; !ok {
				dg.Packages = append(dg.Packages, pkg)
			}
		}
	}

	return &guardian{
		Depguard:             dg,
		pkgsWithErrorMessage: settings.PackagesWithErrorMessage,
	}, nil
}

func (g guardian) run(loadConfig *loader.Config, prog *loader.Program, pass *analysis.Pass) ([]goanalysis.Issue, error) {
	issues, err := g.Run(loadConfig, prog)
	if err != nil {
		return nil, err
	}

	res := make([]goanalysis.Issue, 0, len(issues))

	for _, issue := range issues {
		res = append(res,
			goanalysis.NewIssue(&result.Issue{
				Pos:        issue.Position,
				Text:       g.createMsg(issue.PackageName),
				FromLinter: depguardLinterName,
			}, pass),
		)
	}

	return res, nil
}

func (g guardian) createMsg(pkgName string) string {
	msgSuffix := "is in the blacklist"
	if g.ListType == depguard.LTWhitelist {
		msgSuffix = "is not in the whitelist"
	}

	var userSuppliedMsgSuffix string
	if g.pkgsWithErrorMessage != nil {
		userSuppliedMsgSuffix = g.pkgsWithErrorMessage[pkgName]
		if userSuppliedMsgSuffix != "" {
			userSuppliedMsgSuffix = ": " + userSuppliedMsgSuffix
		}
	}

	return fmt.Sprintf("%s %s%s", formatCode(pkgName, nil), msgSuffix, userSuppliedMsgSuffix)
}

func getDepGuardListType(listType string) (depguard.ListType, error) {
	if listType == "" {
		return depguard.LTBlacklist, nil
	}

	listT, found := depguard.StringToListType[strings.ToLower(listType)]
	if !found {
		return depguard.LTBlacklist, fmt.Errorf("unsure what list type %s is", listType)
	}

	return listT, nil
}


text:
package com.shmily.tjz.swap.Fragment;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.design.widget.Snackbar;
import android.support.v4.app.Fragment;
import android.support.v4.content.LocalBroadcastManager;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Toast;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.huewu.pla.lib.MultiColumnListView;
import com.huewu.pla.lib.internal.PLA_AdapterView;
import com.shmily.tjz.swap.Db.ShoesSpecial;
import com.shmily.tjz.swap.FriendShoesActivity;
import com.shmily.tjz.swap.Gson.Shoes;
import com.shmily.tjz.swap.Gson.Special;
import com.shmily.tjz.swap.R;
import com.shmily.tjz.swap.Adapter.SpecialAdapter;
import com.shmily.tjz.swap.ShoesActivity;
import com.shmily.tjz.swap.SpecialShowActivity;
import com.shmily.tjz.swap.Utils.GlideImageLoader;
import com.shmily.tjz.swap.Utils.Xutils;
import com.weavey.loading.lib.LoadingLayout;
import com.youth.banner.Banner;
import com.youth.banner.BannerConfig;
import com.youth.banner.Transformer;
import com.youth.banner.listener.OnBannerListener;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import org.xutils.common.Callback;
import org.xutils.http.RequestParams;
import org.xutils.x;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import static android.content.Context.CONNECTIVITY_SERVICE;

/**
 * Created by Shmily_Z on 2017/5/3.
 */

public class SpecialFragment extends Fragment {
    private View rootView;
    private List<ShoesSpecial> shoessearchList = new ArrayList<>();

    private SpecialAdapter adapter;
    List<String> list =new ArrayList<>();
    List<Object> arrayList=new ArrayList<>();
    private Handler handler;
    final int WHAT_NEWS = 1 ;

    private IntentFilter intentFilter;
    private LocalReceiver localReceiver;
    private LocalBroadcastManager localBroadcastManger;
    private LoadingLayout loadingLayout;
    private List<Special> shoesList;
    private List<Shoes> shoesLists =new ArrayList<>();

    private Xutils xutils;

    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        rootView = inflater.inflate(R.layout.special_fragment, container, false);
        localBroadcastManger=LocalBroadcastManager.getInstance(getActivity());
        intentFilter=new IntentFilter();
        intentFilter.addAction("com.shmily.tjz.swap.LOCAL_SPECIAL");
        localReceiver=new LocalReceiver();
        localBroadcastManger.registerReceiver(localReceiver,intentFilter);
        loadingLayout=(LoadingLayout)rootView.findViewById(R.id.special_fragment_load_layout);
        loadingLayout.setLoadingPage(R.layout.define_loading_page);
        xutils=Xutils.getInstance();

        loadnet();
        initroll();
        initview();
        return rootView;
    }
    private void loadnet() {

        ConnectivityManager connectivityManager = (ConnectivityManager) getActivity().getSystemService(CONNECTIVITY_SERVICE);
        //获取系统的连接服务。
        NetworkInfo networkInfo = connectivityManager.getActiveNetworkInfo();
        //获取网络的连接情况。
        if (networkInfo != null && networkInfo.isAvailable()) {
          /*  if (networkInfo.getType()==connectivityManager.TYPE_WIFI){
                Toast.makeText(A.this,"网络已启动啦(WIFI)",Toast.LENGTH_SHORT).show();
            }else if (networkInfo.getType()==connectivityManager.TYPE_MOBILE) {
                Toast.makeText(A.this,"网络已启动啦(3G)",Toast.LENGTH_SHORT).show();

            }*/
            loadingLayout.setStatus(LoadingLayout.Success);//加载成功

        } else {
            loadingLayout.setStatus(LoadingLayout.Loading);
        }

    }

    private void initroll() {
        final Banner banner = (Banner) rootView.findViewById(R.id.banner);

        banner.setOnBannerListener(new OnBannerListener() {
            @Override
            public void OnBannerClick(int position) {
                Special special=shoesList.get(position);
                Intent intent=new Intent(getActivity(), SpecialShowActivity.class);
                intent.putExtra("special_Name",special.getName());
                intent.putExtra("special_Specialcontent",special.getSpecialcontent());
                intent.putExtra("special_Specialname",special.getSpecialname());
                intent.putExtra("special_Url",special.getUrl());
                getActivity().startActivity(intent);
            }
        });

       /* for (int i = 1; i <= 4; i++) {
            StringBuilder url = new StringBuilder();
            url.append("http://www.shmilyz.com/search/").append(i).append(".png");
            String urls = String.valueOf(url);
            ShoesSpecial shoessearch = new ShoesSpecial(urls);
            images.add(shoessearch);
        }*/
        RequestParams params=new RequestParams("http://www.shmilyz.com/ForAndroidHttp/select.action");
        String results= "select * from special";
        params.addBodyParameter("uname",results);

        x.http().post(params, new Callback.CacheCallback<String>() {
            @Override
            public void onSuccess(String result) {

                try {

                    JSONObject jsonobject=new JSONObject(result);
                    JSONArray shoesArray=jsonobject.getJSONArray("result");
                    Gson gson=new Gson();
                    shoesList=gson.fromJson(String.valueOf(shoesArray),new TypeToken<List<Special>>(){}.getType());
                    for(Special special : shoesList)
                    {
                            list.add(special.getName());
                        arrayList.add(special.getUrl());

                    }
                    Message msg = handler.obtainMessage() ;
                    // 设置消息内容(可选)
                    // 设置消息类型
                    msg.what = WHAT_NEWS;
                    // 发送消息
                    handler.sendMessage(msg) ;
                } catch (JSONException e) {
                    e.printStackTrace();
                }

            }

            @Override
            public void onError(Throwable ex, boolean isOnCallback) {

            }

            @Override
            public void onCancelled(CancelledException cex) {

            }

            @Override
            public void onFinished() {

            }

            @Override
            public boolean onCache(String result) {
                return false;
            }
        });

        handler = new Handler() {
            @Override
            public void handleMessage(Message msg) {
                // 负责接收Handler消息,并执行UI更新
                // 判断消息的来源:通过消息的类型 what
                switch (msg.what) {
                    case WHAT_NEWS:
                        //设置banner样式
                        banner.setBannerStyle(BannerConfig.NUM_INDICATOR_TITLE);
                        //设置图片加载器
                        banner.setImageLoader(new GlideImageLoader(getActivity()));
                        //设置图片集合
                        banner.setImages(arrayList);
                        //设置banner动画效果
                        banner.setBannerAnimation(Transformer.ZoomOut);
                        //设置标题集合(当banner样式有显示title时)
                        banner.setBannerTitles(list);
                        //设置自动轮播,默认为true
                        banner.isAutoPlay(true);
                        //设置轮播时间
                        banner.setDelayTime(2880);
                        //设置指示器位置(当banner模式中有指示器时)
                        banner.setIndicatorGravity(BannerConfig.CENTER);

                        //banner设置方法全部调用完毕时最后调用
                        banner.start();

                        break;

                }

            }
        } ;

    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        localBroadcastManger.unregisterReceiver(localReceiver);
    }

    private void initview() {
        for (int i = 1; i <= 24; i++) {
            StringBuilder url = new StringBuilder();
            url.append("http://www.shmilyz.com/search/").append(i).append(".png");
            String urls = String.valueOf(url);
            ShoesSpecial shoessearch = new ShoesSpecial(urls);
            shoessearchList.add(shoessearch);

        }
        MultiColumnListView multicolumn = (MultiColumnListView) rootView.findViewById(R.id.list);
        adapter = new SpecialAdapter(getActivity(), shoessearchList);
        multicolumn.setAdapter(adapter);
        multicolumn.setOnItemClickListener(new PLA_AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(PLA_AdapterView<?> parent, View view, int position, long id) {

                getshoes();

            }
        });
    }

    private void getshoes() {

        Map<String, String> maps=new HashMap<String, String>();
        String url="http://www.shmilyz.com/ForAndroidHttp/select.action";
        String sql="SELECT * FROM shoes WHERE id=1";
        Log.i("collect_result",sql);
        maps.put("uname",sql);
        xutils.post(url, maps, new Xutils.XCallBack() {
            @Override
            public void onResponse(String result) {

                try {
                    JSONObject jsonobject=new JSONObject(result);
                    JSONArray shoesArray=jsonobject.getJSONArray("result");
                    Gson gson=new Gson();
                    shoesLists=gson.fromJson(String.valueOf(shoesArray),new TypeToken<List<Shoes>>(){}.getType());
                    Intent intent =new Intent(getActivity(), FriendShoesActivity.class);
                    intent.putExtra(ShoesActivity.SHOES_ID, String.valueOf(shoesLists.get(0).getId()));
                    intent.putExtra(ShoesActivity.SHOES_IMAGE_URL, shoesLists.get(0).getPicture());
                    getActivity().startActivity(intent);
                } catch (JSONException e) {
                    e.printStackTrace();

                }

            }
        });

    }

    class LocalReceiver extends BroadcastReceiver{
         @Override
         public void onReceive(Context context, Intent intent) {
             loadnet();
             initroll();
             initview();
                    }
     }
}


text:
<?php

namespace SugarLoaf\Service;

class ManagedSingleton extends AbstractManagedService
{
    protected $_instance = false;
    protected $_isFullyInstantiated = false;

    public function isFullyInstantiated()
    {
        return $this->_isFullyInstantiated;
    }

    public function setFullyInstantiated()
    {
        $this->_isFullyInstantiated = true;
    }

    protected function instantiate($parameters)
    {
        if (false === $this->_instance) {
            $reflectionObject = new \ReflectionClass($this->_serviceClassRef);
            $this->_instance = $reflectionObject->newInstanceArgs($parameters);

            return $this->_instance;
        }

        return $this->_instance;
    }
}


text:
package com.microsoft.azure.management.network.v2020_04_01.implementation;

import com.microsoft.azure.arm.resources.models.implementation.GroupableResourceCoreImpl;
import com.microsoft.azure.management.network.v2020_04_01.NatGateway;
import rx.Observable;
import com.microsoft.azure.management.network.v2020_04_01.NatGatewaySku;
import java.util.List;
import com.microsoft.azure.SubResource;
import com.microsoft.azure.management.network.v2020_04_01.ProvisioningState;

class NatGatewayImpl extends GroupableResourceCoreImpl<NatGateway, NatGatewayInner, NatGatewayImpl, NetworkManager> implements NatGateway, NatGateway.Definition, NatGateway.Update {
    NatGatewayImpl(String name, NatGatewayInner inner, NetworkManager manager) {
        super(name, inner, manager);
    }

    @Override
    public Observable<NatGateway> createResourceAsync() {
        NatGatewaysInner client = this.manager().inner().natGateways();
        return client.createOrUpdateAsync(this.resourceGroupName(), this.name(), this.inner())
            .map(innerToFluentMap(this));
    }

    @Override
    public Observable<NatGateway> updateResourceAsync() {
        NatGatewaysInner client = this.manager().inner().natGateways();
        return client.createOrUpdateAsync(this.resourceGroupName(), this.name(), this.inner())
            .map(innerToFluentMap(this));
    }

    @Override
    protected Observable<NatGatewayInner> getInnerAsync() {
        NatGatewaysInner client = this.manager().inner().natGateways();
        return client.getByResourceGroupAsync(this.resourceGroupName(), this.name());
    }

    @Override
    public boolean isInCreateMode() {
        return this.inner().id() == null;
    }

    @Override
    public String etag() {
        return this.inner().etag();
    }

    @Override
    public Integer idleTimeoutInMinutes() {
        return this.inner().idleTimeoutInMinutes();
    }

    @Override
    public ProvisioningState provisioningState() {
        return this.inner().provisioningState();
    }

    @Override
    public List<SubResource> publicIpAddresses() {
        return this.inner().publicIpAddresses();
    }

    @Override
    public List<SubResource> publicIpPrefixes() {
        return this.inner().publicIpPrefixes();
    }

    @Override
    public String resourceGuid() {
        return this.inner().resourceGuid();
    }

    @Override
    public NatGatewaySku sku() {
        return this.inner().sku();
    }

    @Override
    public List<SubResource> subnets() {
        return this.inner().subnets();
    }

    @Override
    public List<String> zones() {
        return this.inner().zones();
    }

    @Override
    public NatGatewayImpl withIdleTimeoutInMinutes(Integer idleTimeoutInMinutes) {
        this.inner().withIdleTimeoutInMinutes(idleTimeoutInMinutes);
        return this;
    }

    @Override
    public NatGatewayImpl withPublicIpAddresses(List<SubResource> publicIpAddresses) {
        this.inner().withPublicIpAddresses(publicIpAddresses);
        return this;
    }

    @Override
    public NatGatewayImpl withPublicIpPrefixes(List<SubResource> publicIpPrefixes) {
        this.inner().withPublicIpPrefixes(publicIpPrefixes);
        return this;
    }

    @Override
    public NatGatewayImpl withSku(NatGatewaySku sku) {
        this.inner().withSku(sku);
        return this;
    }

    @Override
    public NatGatewayImpl withZones(List<String> zones) {
        this.inner().withZones(zones);
        return this;
    }

}


text:
using System;

namespace QuickGraph.Algorithms.AllShortestPath
{
	using QuickGraph.Algorithms.AllShortestPath.Reducers;
	using QuickGraph.Algorithms.AllShortestPath.Testers;

	/// <summary>
	/// Collection of classes that compute the All-Shortest path problem.
	/// </summary>
	/// <remarks>
	/// <para>
	/// An all-shortest path algorithm computes all the shortest path between
	/// all the graph vertices.
	/// </para>
	/// <para>
	/// The <see cref="FloydWarshallAllShortestPathAlgorithm"/> runs in O(V^3).
	/// It can also be used to compute other quantities: transitive hull,
	/// safest path, min-max path, etc.
	/// Those are trigerred by <see cref="IFloydWarshallDistanceReducer"/>
	/// classes.
	/// </para>
	/// </remarks>
	internal class NamespaceDoc
	{
	}
}


text:
layout: post
episodeNumber: 25
title: The Web is Awesome
guest: Jeremy Foster
date: 2014-10-06
audioUrl: https://static.msdevshow.com/episodes/msdevshow_0025.mp3
guestImage: jeremy-foster.jpg
---

### News

 - [Real space battles would be more 'Asteroids' than 'Star Wars'](http://www.engadget.com/2014/09/28/physics-in-space-battles/)
 - [The 4k programmer](http://tonyla.me/blog/2014/09/29/the-4k-programmer/)
 - [4K is for programmers](http://tiamat.tsotech.com/4k-is-for-programmers)
  - [http://www.lg.com/us/commercial/widescreen-monitors/lg-72WX70MF-B](http://www.lg.com/us/commercial/widescreen-monitors/lg-72WX70MF-B)
 - [The NSA Is Funding a Project to Roll All Programming Languages Into One](http://gizmodo.com/the-nsa-is-funding-a-project-to-roll-all-programming-la-1619295603)
  - [Wyvern](http://www.cs.cmu.edu/~aldrich/wyvern/)  on [GitHub](https://github.com/wyvernlang/wyvern)

### Jeremy Foster

 - [https://twitter.com/codefoster](https://twitter.com/codefoster)
 - [http://codefoster.com](http://codefoster.com)
 - [http://codefoster.com/codechat](http://codefoster.com/codechat)

----------

 - [WAT video link](https://www.destroyallsoftware.com/talks/wat)
 - WinJS Shims
  - [https://github.com/MSOpenTech/winstore-jscompat/](https://github.com/MSOpenTech/winstore-jscompat/)
  - [https://github.com/codemonkeychris/angular-winjs](https://github.com/codemonkeychris/angular-winjs)
 - [Web App Template](http://wat.codeplex.com/)
 - [The Semantics of HTML and XAML](http://codefoster.com/semantics/)
 - [Javascript querySelector](http://www.w3schools.com/jsref/met_document_queryselector.asp)

### Azure pick of the week

-   [ExpressRoute](http://azure.microsoft.com/en-us/documentation/services/expressroute/)

### App of the Week

 - [Maestro (Preview)](http://www.windowsphone.com/s?appid=b75be3fa-fbf8-4c1a-bd39-1517c1d6aec0)
  - From [Hidden Pineapple](http://hiddenpineapple.com/) -
[Twitter](http://twitter.com/thehp)


text:
echo "Installing Faucet"

ID="$(grep -Po '(?<=^ID=).*' ${ROOTFS_DIR}/etc/os-release | awk '{print tolower($0)}')"
CODE="$(grep -Po -m 1 '(?<=\()[^\)]+' ${ROOTFS_DIR}/etc/os-release | awk '{print tolower($0)}')"
on_chroot << EOF
apt-get install -y curl apt-transport-https lsb-release tcpdump
echo "deb https://packagecloud.io/faucetsdn/faucet/${ID}/ ${CODE} main" | sudo tee /etc/apt/sources.list.d/faucet.list
curl -L https://packagecloud.io/faucetsdn/faucet/gpgkey | sudo apt-key add -
apt-get update
apt-get install -y --fix-missing faucet-all-in-one
EOF


text:
@interface AddReminderV2Controller ()

@property (nonatomic, strong) PMCalendarController *pmCC;
@end

@implementation AddReminderV2Controller{
 NSArray * sugestionarray;
    NSString * audioPath;
    UIImage* imagenSelected;
    UIBarButtonItem *doneButton;
    UIColor * colorcito;
    NSString* textNote;
    NSDate * datecalendar;
    UIDatePicker *datePicker;

}
@synthesize MyScroll;
@synthesize pmCC;
@synthesize dao;
@synthesize colorband1;
@synthesize colorband2;
@synthesize colorband3;
@synthesize EventNametextField;

@synthesize ImageViewSelected;
@synthesize frameButton;
@synthesize DatePickerContainer;
@synthesize dateSelectedFromCalendar;
@synthesize calendarbutom;
@synthesize selectRepeat;
- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
    }
    return self;
}

- (void)viewDidLoad
{
    [super viewDidLoad];

    CGRect pikerframe = CGRectMake(0, 0, 261, 162);

    datePicker = [[ObjectHolder sharedInstance]datePicker];
    [datePicker setFrame:pikerframe];

//check 24 or 12 and display datepicker corectly
    int * flag =[self retrieve24_12FromUserDefaults];
    NSLocale * locale;
   // NSLog(@"Este es el flag 24 12 %d",flag);
    if((int)flag == 1){
        locale=[[NSLocale alloc]initWithLocaleIdentifier:@"en_GB"];
    }else{
        locale=[[NSLocale alloc]initWithLocaleIdentifier:@"en_US_POSIX"];
    }

    [datePicker setLocale:locale];

    [DatePickerContainer addSubview:datePicker];

    self.navigationItem.hidesBackButton = YES;
    //back buttom
    UIBarButtonItem*back=[[UIBarButtonItem alloc]
                          initWithImage:[UIImage imageNamed:@"home-25.png"] style:UIBarStyleDefault target:self action:@selector(handleBack:)];
    self.navigationItem.leftBarButtonItem=back;
    UIBarButtonItem *recordButton         = [[UIBarButtonItem alloc]
                                           initWithImage:[UIImage imageNamed:@"microphone-24x.png"] style:UIBarStyleDefault target:self action:@selector(recordAction:)];
    UIBarButtonItem *addNote         = [[UIBarButtonItem alloc]
                                             initWithImage:[UIImage imageNamed:@"note-25x.png"] style:UIBarStyleDefault target:self action:@selector(addNoteAction:)];

    UIBarButtonItem *takePictureButton         = [[UIBarButtonItem alloc]
                                                  initWithImage:[UIImage imageNamed:@"camera-24x.png"] style:UIBarStyleDefault target:self action:@selector(takePictureAction:)];

    doneButton          = [[UIBarButtonItem alloc]
                                            initWithImage:[UIImage imageNamed:@"checkmark-25.png"] style:UIBarStyleDefault target:self action:@selector(saveReminderAction:)];

         //initiate DB
    dao = [[DatabaseHelper alloc] init];
    //retrive idcat
    NSInteger * idcat = [self retrieveFromUserDefaults];
        //put colors in band
  colorcito =[self colorFromHexString:[self retrieveColorFromUserDefaults]];

  colorband1.backgroundColor = colorcito;
    colorband2.backgroundColor = colorcito;
    colorband3.backgroundColor = colorcito;
    //put color in buttons hiden buton frame and band
    frameButton.hidden = YES;

    selectRepeat.tintColor=colorcito;

   // selectRepeat.transform = CGAffineTransformMakeRotation(M_PI/2.0);
  //  [self rotateSegmented];
    self.navigationItem.rightBarButtonItems =
    [NSArray arrayWithObjects:doneButton, takePictureButton,recordButton,addNote, nil];

    //fill array of sugestions
    sugestionarray = [dao getHistoryList:idcat];

    // Set a default data source for all instances. Otherwise, you can specify the data source on individual text fields via the autocompleteDataSource property
    [HTAutocompleteTextField setDefaultAutocompleteDataSource:[HTAutocompleteManager sharedManager]];
    self.EventNametextField.delegate = self;

    self.EventNametextField.autocompleteType= HTAutocompleteTypeColor;
    self.EventNametextField.showAutocompleteButton = YES;
    self.EventNametextField.ignoreCase = YES;

    //record voice stuff
    self.voiceHud = [[POVoiceHUD alloc] initWithParentView:self.view];
    self.voiceHud.title = @"Speak Now";
    [self.voiceHud setDelegate:self];
    [self.view addSubview:self.voiceHud];

    //Date fron calendar or original
    if(dateSelectedFromCalendar != nil ){
        datePicker.date = dateSelectedFromCalendar;
    }
       [MyScroll setScrollEnabled:YES];

    // Listen for keyboard appearances and disappearances
    [[NSNotificationCenter defaultCenter] addObserver:self
                                             selector:@selector(keyboardDidShow:)
                                                 name:UIKeyboardDidShowNotification
                                               object:nil];

    [[NSNotificationCenter defaultCenter] addObserver:self
                                             selector:@selector(keyboardDidHide:)
                                                 name:UIKeyboardDidHideNotification
                                               object:nil];

}
- (void)keyboardDidShow: (NSNotification *) notif{
   // NSLog(@"Aparecio teclado");
    self.EventNametextField.autocompleteDisabled=NO;
    self.EventNametextField.showAutocompleteButton=YES;
}

- (void)keyboardDidHide: (NSNotification *) notif{
   //  NSLog(@"Aparecio teclado");
    self.EventNametextField.showAutocompleteButton=NO;
}
-(void)viewDidAppear:(BOOL)animated{

}
-(void)viewDidLayoutSubviews{
[MyScroll setContentSize:CGSizeMake(320, 700)];
}
-(void)handleBack:(id)sender{
   // [[NSNotificationCenter defaultCenter]postNotificationName:@"RefreshCategoriesList" object:nil];
    [self.navigationController popToRootViewControllerAnimated:YES];
}
- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

#pragma mark -

#pragma mark YIPopupTextViewDelegate

- (void)popupTextView:(YIPopupTextView *)textView willDismissWithText:(NSString *)text cancelled:(BOOL)cancelled
{
    NSLog(@"will dismiss: cancelled=%d",cancelled);

}

- (void)popupTextView:(YIPopupTextView *)textView didDismissWithText:(NSString *)text cancelled:(BOOL)cancelled
{
    textNote = text;
    NSLog(@"did dismiss: cancelled=%d",cancelled);
}

-(void)addNoteAction:(id)sender{

    // NOTE: maxCount = 0 to hide count
   // self.navigationController.navigationBarHidden=YES;
    YIPopupTextView* popupTextView = [[YIPopupTextView alloc]  initWithPlaceHolder:@"Reminder Note" maxCount:100 buttonStyle:YIPopupTextViewButtonStyleRightDone doneButtonColor:colorcito];
    popupTextView.delegate = self;
   // popupTextView.caretShiftGestureEnabled = YES;   // default = NO
    popupTextView.keyboardAppearance=UIKeyboardAppearanceDefault;
    popupTextView.text = textNote;

    popupTextView.editable = YES;                  // set editable=NO to show without keyboard

    //[popupTextView showInView:self.view];
    [popupTextView showInViewController:self]; // recommended, especially for iOS7

  }

//new implementation insert in items
-(void)saveReminderAction:(id)sender{
   // NSLog(@"entro save");

    //elementos to store
    NSInteger * idcat = [self retrieveFromUserDefaults];
    NSString * eventName = self.EventNametextField.text;

    NSDate * alarmdate = [datePicker date];

    [[NSCalendar currentCalendar] rangeOfUnit:NSMinuteCalendarUnit
                                    startDate:&alarmdate
                                     interval:NULL
                                      forDate:alarmdate];

    NSString * ImagenPath = [self saveImageGetPath:imagenSelected];

    NSString * note =textNote;
    NSString* recurring = [self returnRecurringSelect];
    //if eventName is Empty show "Reminder"
    if([eventName isEqualToString:@""])
        eventName = @"Reminder";
    if (note == nil ||[note isEqualToString:@""]||[note isEqualToString:@"(null)"])
        note = @"Reminder";

    //insert in reminder if date is good

    if([alarmdate compare:[NSDate date]] == NSOrderedDescending){
    NSInteger *id_item = [dao insert_item:idcat item_Name:eventName alarm:alarmdate note:note repeat:recurring itemclientStatus:0 should_send_item:1];
    if (ImagenPath == nil ||[ImagenPath isEqualToString:@""]||[ImagenPath isEqualToString:@"(null)"]){
        //es null no inserto nada

    }else{
        [dao edit_item_images:idcat id_item:id_item file_Name:ImagenPath];
        [dao UpdateSHOULDSendinFILESbyType:id_item file_type:1 should_send:1 comeFroMSync:NO];
    }

    if (audioPath == nil ||[audioPath isEqualToString:@""]||[audioPath isEqualToString:@"(null)"]){

    }else{
        //insert audio
        [dao edit_item_recordings:idcat id_item:id_item file_Name:audioPath];
        [dao UpdateSHOULDSendinFILESbyType:id_item file_type:2 should_send:1 comeFroMSync:NO];

    }
//insert
    //insert in history
    BOOL resulthistory = [dao insertHistory:idcat history_desc:eventName];

    //NSLog(@"idcat %d eventname %@ ImagePat %@ date %@ Resultado en reminder(idreminder) %d resultado en history %hhd " ,(int)idcat,eventName,ImagenPath,alarmdate,(int)result,resulthistory);

    //shedule notification
    NSString *idtem =[NSString stringWithFormat:@"%d",(int)id_item];
    NSDictionary * data = [NSDictionary dictionaryWithObjectsAndKeys:idtem,@"ID_NOT_PASS" ,recurring,@"RECURRING",alarmdate,@"ORIGINALDATE", nil];

    NSString* UserSelectedSoundReminder = [self retrieveSoundReminderFromUserDefaults];
    //Set notification for firt time to select fire date and repeatin 1 min
    [[LocalNotificationCore sharedInstance]scheduleNotificationOn:alarmdate text:eventName action:@"Show" sound:UserSelectedSoundReminder launchImage:ImagenPath andInfo:data];

    [self performSegueWithIdentifier:@"home" sender:sender];
    //[self.navigationController popToRootViewControllerAnimated:YES];

    }else{
    [[[[iToast makeText:NSLocalizedString(@"Past date, Please select other date!", @"")]setGravity:iToastGravityTop]setDuration:iToastDurationNormal]show];

    }
}

-(NSString*) returnRecurringSelect{
    NSInteger index = [selectRepeat selectedSegmentIndex];

    switch (index) {
        case 0:
            return @"none";
            break;
        case 1:
            return @"day";
            break;
        case 2:
            return @"week";
        case 3:
            return @"month";
            break;
        case 4:
            return @"year";
            break;

        default:
            return @"none";
            break;
    }
}
-(void)recordAction:(id)sender{
   //present option 'Record' and "play" if there one to play

    if (audioPath) {
        UIActionSheet* audioPopup =[[UIActionSheet alloc]initWithTitle:@"Voice note" delegate:self cancelButtonTitle:@"Cancel" destructiveButtonTitle:nil otherButtonTitles:@"Play",@"Record" ,nil];

        audioPopup.tag = 1;
        [audioPopup showInView:[UIApplication sharedApplication].keyWindow];

    }else{
       UIActionSheet* audioPopup =[[UIActionSheet alloc]initWithTitle:@"Voice note" delegate:self cancelButtonTitle:@"Cancel" destructiveButtonTitle:nil otherButtonTitles:@"Record" ,nil];

                audioPopup.tag = 2;
    [audioPopup showInView:[UIApplication sharedApplication].keyWindow];
    }

}
-(void)takePictureAction:(id)sender{
//present option "camera" "Gallery"
       UIActionSheet* photoPopup =[[UIActionSheet alloc]initWithTitle:@"Add photo" delegate:self cancelButtonTitle:@"Cancel" destructiveButtonTitle:nil otherButtonTitles:@"Camera",@"Gallery" ,nil];
    [photoPopup showInView:[UIApplication sharedApplication].keyWindow];
    photoPopup.tag =3;

}
-(void)actionSheet:(UIActionSheet *)actionSheet clickedButtonAtIndex:(NSInteger)buttonIndex{
    UIImagePickerController *picker = [[UIImagePickerController alloc] init];
    NSDate *now = [NSDate dateWithTimeIntervalSinceNow:0];
    NSString *caldate = [now description];
    NSString *pathForAudio = [NSString stringWithFormat:@"%@/Documents/%@.caf", NSHomeDirectory(),caldate];
    if(actionSheet.tag == 3){
    switch (buttonIndex) {
        case (0):
            picker.delegate = self;
            picker.allowsEditing = NO;
            picker.wantsFullScreenLayout = YES;
            picker.sourceType = UIImagePickerControllerSourceTypeCamera;
            //picker.cameraViewTransform = CGAffineTransformScale(picker.cameraViewTransform, CAMERA_TRANSFORM, CAMERA_TRANSFORM);
            [self presentViewController:picker animated:YES completion:NULL];
            break;
        case (1):
            picker.delegate = self;
            picker.allowsEditing = NO;
            picker.wantsFullScreenLayout = YES;
            picker.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;

            [self presentViewController:picker animated:YES completion:NULL];

            break;

        default:
        break;

    }

        //audio sheet
    }else if (actionSheet.tag == 1){

        //there is audio to play
        switch (buttonIndex) {
            case 0:

                [self.voiceHud playSound:audioPath];
                break;
            case 1:
                //record
                //name for audio
                NSLog(@"Entro al record");
                [self.voiceHud startForFilePath:pathForAudio];
                break;

            default:
                break;
        }
    }else if (actionSheet.tag==2){
        //no audio
        switch (buttonIndex) {
            case (0):
                //record
                [self.voiceHud startForFilePath:pathForAudio];

                break;

            default:
                break;
        }

    }
}
-(NSInteger*)retrieve24_12FromUserDefaults
{
    NSUserDefaults *standardUserDefaults = [NSUserDefaults standardUserDefaults];
    NSInteger *val = nil;

    if (standardUserDefaults)
        val = [standardUserDefaults integerForKey:@"24/12"];

    return val;
}

-(NSInteger*)retrieveFromUserDefaults
{
    NSUserDefaults *standardUserDefaults = [NSUserDefaults standardUserDefaults];
    NSInteger *val = nil;

    if (standardUserDefaults)
        val = [standardUserDefaults integerForKey:@"ID_CAT"];

    return val;
}
-(NSString*)retrieveColorFromUserDefaults
{
    NSUserDefaults *standardUserDefaults = [NSUserDefaults standardUserDefaults];
    NSString *val = nil;

    if (standardUserDefaults)
        val = [standardUserDefaults objectForKey:@"COLOR"];

    return val;
}
-(NSString*)retrieveSoundReminderFromUserDefaults
{
    NSUserDefaults *standardUserDefaults = [NSUserDefaults standardUserDefaults];
    NSString *val = nil;

    if (standardUserDefaults)
        val = [standardUserDefaults objectForKey:@"REMINDER_SOUND"];

    return val;
}

// this method gets called by the system automatically when the user taps the keyboard's "Done" button
- (BOOL)textFieldShouldReturn:(HTAutocompleteTextField *)theTextField
{
    //[self.EventNametextField forceRefreshAutocompleteText];

    self.EventNametextField.autocompleteDisabled=YES;
    [self.EventNametextField  resignFirstResponder];

    return YES;
}

- (NSString *)saveImageGetPath: (UIImage*)image
{
    if (image != nil)
    {
        NSString *docDir = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0];

        // create name for picture
        NSDate *now = [NSDate dateWithTimeIntervalSinceNow:0];
        NSString *caldate = [now description];

        NSDateFormatter *datef = [[NSDateFormatter alloc]init];
        datef.dateFormat = @"yyyy-MM-dd--HH:mm:ss";
        NSString* namePhoto = [datef stringFromDate:[NSDate date]];
        NSString *jpegFilePath = [NSString stringWithFormat:@"%@/%@",docDir,caldate];

        NSData *data2 = [NSData dataWithData:UIImageJPEGRepresentation(image, 1.0f)];//1.0f = 100% quality
        [data2 writeToFile:jpegFilePath atomically:YES];
        return jpegFilePath;
    }else
        return nil;
}

//color fron HEX
-(UIColor *)colorFromHexString:(NSString *)hexString {
    if (hexString != nil) {

    unsigned rgbValue = 0;
    NSScanner *scanner = [NSScanner scannerWithString:hexString];
    [scanner setScanLocation:1]; // bypass '#' character
    [scanner scanHexInt:&rgbValue];
        return [UIColor colorWithRed:((rgbValue & 0xFF0000) >> 16)/255.0 green:((rgbValue & 0xFF00) >> 8)/255.0 blue:(rgbValue & 0xFF)/255.0 alpha:1.0];
    }
    return nil;
}
#pragma mark - POVoiceHUD Delegate

- (void)POVoiceHUD:(POVoiceHUD *)voiceHUD voiceRecorded:(NSString *)recordPath length:(float)recordLength {
    audioPath = recordPath;
    [[[[iToast makeText:NSLocalizedString(@"Record saved", @"")]setGravity:iToastGravityBottom]setDuration:iToastDurationNormal]show];

    NSLog(@"Sound recorded with file %@ for %.2f seconds", [recordPath lastPathComponent], recordLength);
}

- (void)voiceRecordCancelledByUser:(POVoiceHUD *)voiceHUD {
    [[[[iToast makeText:NSLocalizedString(@"Record canceled", @"")]setGravity:iToastGravityBottom]setDuration:iToastDurationNormal]show];
    NSLog(@"Voice recording cancelled for HUD: %@", voiceHUD);
}

#pragma mark - Image Picker Controller delegate methods

- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info {

    imagenSelected = info[UIImagePickerControllerOriginalImage];
    self.ImageViewSelected.image = imagenSelected;
    frameButton.hidden = NO;
    doneButton.enabled = YES;
    //colorband3.hidden=NO;
    [picker dismissViewControllerAnimated:NO completion:NULL];

}
- (IBAction)showcalendatButton:(id)sender {

    if ([self.pmCC isCalendarVisible])
    {
        [self.pmCC dismissCalendarAnimated:NO];
    }

    BOOL isPopover = YES;

        self.pmCC = [[PMCalendarController alloc] initWithThemeName:@"default"];

    self.pmCC.delegate = self;
    self.pmCC.mondayFirstDayOfWeek = NO;
    //self.pmCC.showOnlyCurrentMonth = YES; //Only show days in current month

            [self.pmCC presentCalendarFromView:sender
                  permittedArrowDirections:PMCalendarArrowDirectionAny
                                 isPopover:isPopover
                                  animated:YES];

    //le asigno la fecha actual o la seleccionada previamente
    NSDate *temdate;
    if(datecalendar == nil)//firts time in view
        temdate= [NSDate date];
    else
        temdate = [datecalendar dateByAddingTimeInterval:-3600*4];

self.pmCC.period = [PMPeriod oneDayPeriodWithDate:temdate];
    self.pmCC.allowsPeriodSelection = NO;
    self.pmCC.allowsLongPressMonthChange=YES;
   [self calendarController:pmCC didChangePeriod:pmCC.period];

    //[self performSegueWithIdentifier:@"ShowCalendar_segue" sender:sender];
   // CalendarViewController * calend = [[CalendarViewController alloc]init];
   // [self presentViewController:calend animated:NO completion:nil];
}
#pragma mark PMCalendarControllerDelegate methods

- (void)calendarController:(PMCalendarController *)calendarController didChangePeriod:(PMPeriod *)newPeriod
{
   // NSLog(@"Fechaseleccionada %@", newPeriod.startDate.description);
}
-(void)calendarControllerDidDismissCalendar:(PMCalendarController*)calendarController{
NSLog(@"desaparecio");
        NSDate * dateselected = calendarController.period.startDate;

    //cuando se selecciona lo hace con un dia menos no se por que le adiciono un dia y es el actual
    datecalendar = [dateselected dateByAddingDays:1];
   NSDate * hoy = [NSDate date];
    NSLog(@"fecha1 %@ fecha 2 %@", datecalendar.description,[[hoy dateByAddingDays:1] dateWithoutTime].description );

    //si es hoy no cambiar el tiempo..

    if( [datecalendar.dateWithoutTime compare: [[hoy dateByAddingDays:1] dateWithoutTime]]== NSOrderedSame){
        datePicker.date =[NSDate date];
    }else{
    datePicker.date = dateselected;
    }
}

@end


text:
@implementation UIApplication (ESFunction)
- (void)es_hideKeyboard {
    [self sendAction:@selector(resignFirstResponder) to:nil from:nil forEvent:nil];
}
@end


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

namespace ShopifySharp
{
    public abstract class ShopifyService
    {
        /// <summary>
        /// Creates a new instance of <see cref="ShopifyService" />.
        /// </summary>
        /// <param name="myShopifyUrl">The shop's *.myshopify.com URL.</param>
        /// <param name="shopAccessToken">An API access token for the shop.</param>
        protected ShopifyService(string myShopifyUrl, string shopAccessToken)
        {
            _ShopUri = RequestEngine.BuildShopUri(myShopifyUrl);
            _RestClient = RequestEngine.CreateClient(_ShopUri, shopAccessToken);
        }

        #region Private Properties

        protected RestClient _RestClient { get; set; }

        protected Uri _ShopUri { get; set; }

        #endregion
    }
}


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

Editing a Security Role

How to edit the settings and details of a security role using the Security Roles module.

Navigate to Admin >  Security Roles - OR - Go to a Security Roles module.

If the required role is not displayed, at Filter By Role Group select the role from the drop down list.

Click the Edit   button beside the role to be edited.

Edit the settings as required.

                <MadCap:snippetText src="../../../../../../Resources/Snippets/Update.flsnp" />


text:
// Copyright 2016 Jon Skeet. All rights reserved. Use of this source code is governed by the Apache License 2.0, as found in the LICENSE.txt file.
using System;

namespace CSharp7
{
    public class OutDeconstruction
    {
        public static void Main()
        {
            int code = 20;
            string message = "Before";
            // Deconstruct any object with a proper Deconstruct method into existing variables
            // (or properties)
            (code, message) = new Deconstructable { X = 10, Message = "Hi" };
            Console.Write(message); // "Hi"

            // Deconstruct into new var variables
            var (code2, message2, exception) = new Deconstructable();
            var (code3, message3) = new Deconstructable();

            // Deconstruct from existing instance
            var instance = new Deconstructable { X = 10, Message = "Hi" };
            var (code4, message4) = instance;
        }
    }

    public class Deconstructable
    {
        public int X { get; set; }
        public string Message { get; set; }
        public Exception Error { get; set; }

        // Nifty trick: use tuple deconstruction for the body
        // Performance implications?
        public void Deconstruct(out int x, out string message) => (x, message) = (X, Message);

        internal void Deconstruct(out int x, out string message, out Exception e)
        {
            x = X;
            message = Message;
            e = Error;
        }

        internal void CopyTo(Deconstructable other) => (other.X, other.Message, other.Error) = this;
    }
}


text:
package tablecli

import (
	"bytes"
	"os"
	"reflect"
	"regexp"
	"sort"
	"strings"
	"unicode"

	"golang.org/x/crypto/ssh/terminal"
)

var TableConfig = struct {
	BreakOnAny bool
	ForceWrap  bool
}{
	BreakOnAny: false,
	ForceWrap:  false,
}

var ignoredPatterns = []*regexp.Regexp{
	regexp.MustCompile("\033\\[\\d+;\\d+;\\d+m"),
	regexp.MustCompile("\033\\[0m"),
}

type Table struct {
	Headers       Row
	LineSeparator bool
	rows          rowSlice
}

type Row []string

func NewTable() *Table {
	return &Table{}
}

// Sort sorts the rows in the table using the first column as key.
func (t *Table) Sort() {
	sort.Sort(t.rows)
}

func (t *Table) Reverse() {
	sort.Sort(sort.Reverse(t.rows))
}

func (t *Table) SortByColumn(columns ...int) {
	sort.Sort(rowSliceByColumn{rowSlice: t.rows, columns: columns})
}

func (t *Table) addRows(rows rowSlice, sizes []int, buf *bytes.Buffer) {
	for _, row := range rows {
		extraRows := rowSlice{}
		for column, field := range row {
			parts := strings.Split(field, "\n")
			field = parts[0]
			for i := range parts[1:] {
				var newRow Row
				if len(extraRows) > i {
					newRow = extraRows[i]
				} else {
					newRow = Row(make([]string, len(row)))
					extraRows.add(newRow)
				}
				newRow[column] = parts[i+1]
			}
			buf.WriteString("| ")
			buf.WriteString(field)
			buf.Write(bytes.Repeat([]byte(" "), sizes[column]+1-runeLen(field)))
		}
		buf.WriteString("|\n")
		t.addRows(extraRows, sizes, buf)
		ptr1 := reflect.ValueOf(rows).Pointer()
		ptr2 := reflect.ValueOf(t.rows).Pointer()
		if ptr1 == ptr2 && t.LineSeparator {
			t.separator(buf, sizes)
		}
	}
}

func splitJoinEvery(str string, n int) string {
	breakOnAny := TableConfig.BreakOnAny
	breakChars := []rune{' ', '.', ':', '='}
	n -= 1
	str = strings.TrimRightFunc(str, unicode.IsSpace)
	lines := strings.Split(str, "\n")
	var parts [][]rune
	for _, line := range lines {
		line = strings.TrimRightFunc(line, unicode.IsSpace)
		lineRunes := []rune(line)
		strLen := len(lineRunes)
		var start, end int
		for ; start < strLen; start = end {
			end = start + n
			for _, p := range ignoredPatterns {
				pos := p.FindStringIndex(string(lineRunes[start:]))
				if pos != nil && pos[0] < (end-start+1) {
					end += pos[1] - pos[0]
				}
			}
			if end > strLen {
				end = strLen
			}
			oldEnd := end
			skipSpace := false
			breakableChar := false
			if !breakOnAny && end < strLen {
				for ; end > start; end-- {
					for _, chr := range breakChars {
						if chr == lineRunes[end] {
							breakableChar = true
							if chr == ' ' {
								skipSpace = true
							} else if end < oldEnd {
								end++
							}
							break
						}
					}
					if breakableChar {
						break
					}
				}
				if !breakableChar {
					end = oldEnd
				}
			}
			part := make([]rune, end-start)
			copy(part, lineRunes[start:end])
			if breakableChar {
				padding := n - (end - start)
				if padding > 0 {
					part = append(part, []rune(strings.Repeat(" ", padding))...)
				}
				if skipSpace {
					end++
				}
			}
			if end < strLen {
				part = append(part, rune('↵'))
			}
			parts = append(parts, part)
		}
	}
	return redistributeColors(parts)
}

func redistributeColors(parts [][]rune) string {
	var result string
	var lastStartColor, nextResetStr string
	for _, part := range parts {
		nextStartColor := lastStartColor
		partStr := string(part)
		startPos := ignoredPatterns[0].FindStringIndex(partStr)
		resetPos := ignoredPatterns[1].FindStringIndex(partStr)
		if startPos != nil {
			if resetPos == nil || resetPos[0] < startPos[0] {
				nextStartColor = partStr[startPos[0]:startPos[1]]
				nextResetStr = "\033[0m"
			} else {
				nextStartColor = ""
			}
		}
		if resetPos != nil {
			if startPos == nil || resetPos[0] > startPos[0] {
				nextResetStr = ""
				nextStartColor = ""
			}
		}
		partStr = lastStartColor + partStr + nextResetStr
		lastStartColor = nextStartColor
		result += partStr + "\n"
	}
	return strings.TrimRight(result, "\n")
}

func (t *Table) resizeLargestColumn(ttyWidth int) []int {
	sizes := t.columnsSize()
	if ttyWidth == 0 {
		return sizes
	}
	fullSize := 0
	maxIdx, maxVal := -1, -1
	for i, sz := range sizes {
		fullSize += sz
		if sz > maxVal {
			maxVal = sz
			maxIdx = i
		}
	}
	fullSize += len(sizes)*3 + 1
	available := ttyWidth - (fullSize - maxVal)
	if fullSize > ttyWidth && available > 1 {
		for _, row := range t.rows {
			row[maxIdx] = splitJoinEvery(row[maxIdx], available)
		}
	}
	return t.columnsSize()
}

func (t *Table) String() string {
	if t.Headers == nil && len(t.rows) < 1 {
		return ""
	}
	var ttyWidth int
	terminalFd := int(os.Stdout.Fd())
	if TableConfig.ForceWrap {
		terminalFd = int(os.Stdin.Fd())
	}
	if terminal.IsTerminal(terminalFd) {
		ttyWidth, _, _ = terminal.GetSize(terminalFd)
	}
	sizes := t.resizeLargestColumn(ttyWidth)
	buf := bytes.NewBuffer(nil)
	t.separator(buf, sizes)
	if t.Headers != nil {
		for column, header := range t.Headers {
			buf.WriteString("| ")
			buf.WriteString(header)
			buf.Write(bytes.Repeat([]byte(" "), sizes[column]+1-len(header)))
		}
		buf.WriteString("|\n")
		t.separator(buf, sizes)
	}
	t.addRows(t.rows, sizes, buf)
	if !t.LineSeparator {
		t.separator(buf, sizes)
	}
	return buf.String()
}

func (t *Table) Bytes() []byte {
	return []byte(t.String())
}

func (t *Table) AddRow(row Row) {
	t.rows.add(row)
}

func (t *Table) Rows() int {
	return t.rows.Len()
}

func runeLen(s string) int {
	for _, p := range ignoredPatterns {
		s = p.ReplaceAllString(s, "")
	}
	return len([]rune(s))
}

func (t *Table) columnsSize() []int {
	var columns int
	if t.Headers != nil {
		columns = len(t.Headers)
	} else {
		columns = len(t.rows[0])
	}
	sizes := make([]int, columns)
	for _, row := range t.rows {
		for i := 0; i < columns; i++ {
			rowParts := strings.Split(row[i], "\n")
			for _, part := range rowParts {
				partLen := runeLen(part)
				if partLen > sizes[i] {
					sizes[i] = partLen
				}
			}
		}
	}
	if t.Headers != nil {
		for i, header := range t.Headers {
			headerLen := runeLen(header)
			if headerLen > sizes[i] {
				sizes[i] = headerLen
			}
		}
	}
	return sizes
}

func (t *Table) separator(buf *bytes.Buffer, sizes []int) {
	for _, sz := range sizes {
		buf.WriteString("+")
		buf.Write(bytes.Repeat([]byte("-"), sz+2))
	}
	buf.WriteString("+\n")
}

type rowSlice []Row

type rowSliceByColumn struct {
	rowSlice
	columns []int
}

func (l rowSliceByColumn) Len() int {
	return len(l.rowSlice)
}

func (l rowSliceByColumn) Less(i, j int) bool {
	for _, c := range l.columns {
		v1, v2 := strings.ToLower(l.rowSlice[i][c]), strings.ToLower(l.rowSlice[j][c])
		if v1 == v2 {
			continue
		}
		return v1 < v2
	}
	return false
}

func (l rowSliceByColumn) Swap(i, j int) {
	l.rowSlice[i], l.rowSlice[j] = l.rowSlice[j], l.rowSlice[i]
}

func (l *rowSlice) add(r Row) {
	*l = append(*l, r)
}

func (l rowSlice) Len() int {
	return len(l)
}

func (l rowSlice) Less(i, j int) bool {
	return strings.ToLower(l[i][0]) < strings.ToLower(l[j][0])
}

func (l rowSlice) Swap(i, j int) {
	l[i], l[j] = l[j], l[i]
}


text:
import fedmsg
from collection import defaultdict
import json

# Dispatcher
class Dispatcher(object):

    def __init__(self):
        self._observers = defaultdict(list)

    def run(self):
        for name, endpoint, topic, msg in fedmsg.tail_messages():
            for observer in self._observers.get(topic, []):
                observer(name, endpoint, topic, msg)

    def attach_observer(self, topic, observer):
        if observer not in self._observers.get(topic, []):
            self._observers[topic].append(observer)

dispatcher = Dispatcher()

# Base Widget
class BaseWidget(object):
    LISTENER = ""

    def _observe(self, name, endpoint, topic, msg):
        self.update(name, endpoint, topic, msg)

    def update(self, name, endpoint, topic, msg):
        """
        Invoked from the observer to save data.
        """
        data = self.clean(name, endpoint, topic, msg)
        self.save(data)
        self.post_save(name, endpoint, topic, msg, data)

    def get(self, id=None, params={}):
        """
        Called from a generic view to handle widget endpoints.

        Returns a JSON.
        """
        raise NotImplementedError

    def clean(self, name, endpoint, topic, msg):
        """
        Clean raw data and generate data to be saved.
        """
        return msg

    def save(self, data):
        """
        Save data to datastore.
        """
        raise NotImplementedError

    def post_save(self, name, endpoint, topic, msg, data):
        """Run post save hooks."""
        return

# Test Widget
class TestWidget(BaseWidget):
    LISTENER = "testing"

    def get(self, *args, **kwargs):
        return json.dumps({})

    def save(self, data):
        # Code to save data to db
        pass

test_widget = TestWidget()

def initialize_widgets():
    # This code will crawl through widgets dir and initialize
    # all the widgets
    widgets = [test_widget] # get_all_widgets()
    for widget in widgets:
        dispatcher.attach_observer(widget.LISTENER, widget._observe)

initialize_widgets()
dispatcher.run()


text:
'use strict';

const fs = require('fs');
const path = require('path');
const babylon = require('babylon');

/**
 * Extract code comments from the given `string`.
 *
 * ```js
 * var extract = require('babel-extract-comments');
 * console.log(extract('// this is a code comment'));
 * // [{ type: 'CommentBlock',
 * //  value: '!\n * babel-extract-comments <https://github.com/jonschlinkert/babel-extract-comments>\n *\n *
 * // Copyright (c) 2014-2018, Jon Schlinkert.\n * Released under the MIT License.\n ',
 * //   start: 0,
 * //   end: 173,
 * //   loc: SourceLocation { start: [Position], end: [Position] } }]
 * ```
 * @param  {String} `string` String of javascript
 * @return {Array} Array of code comment objects.
 * @api public
 */

function extract(str, options) {
  const res = babylon.parse(str, options);
  return res.comments;
}

/**
 * Extract code comments from a JavaScript file.
 *
 * ```js
 * console.log(extract.file('some-file.js'), { cwd: 'some/path' });
 * // [ { type: 'Line',
 * //     value: ' this is a line comment',
 * //     range: [ 0, 25 ],
 * //     loc: { start: { line: 1, column: 0 }, end: { line: 1, column: 25 } } } ]
 * ```
 * @param  {String} `file` Filepath to the file to parse.
 * @param  {Object} `options` Options to pass to [esprima][].
 * @return {Array} Array of code comment objects.
 * @api public
 */

extract.file = function(file, options) {
  const opts = Object.assign({ cwd: process.cwd() }, options);
  const str = fs.readFileSync(path.resolve(opts.cwd, file), 'utf8');
  return extract(str, options);
};

/**
 * Expose `extract`
 */

module.exports = extract;


text:
using TruRating.Dto.TruService.V220;
using TruRating.TruModule.Device;

namespace TruRating.TruModule.Messages
{
    public class TruServiceMessageFactory : ITruServiceMessageFactory
    {
        internal static ITruServiceMessageFactory CreateDefault()
        {
            return new TruServiceMessageFactory();
        }
        public Request AssemblyRequestQuery(RequestParams requestParams, IDevice device, IReceiptManager receiptManager,
            bool force)
        {
            var result = new Request
            {
                PartnerId = requestParams.PartnerId,
                MerchantId = requestParams.MerchantId,
                TerminalId = requestParams.TerminalId,
                SessionId = requestParams.SessionId,
                Item = new RequestQuery
                {
                    Device = new RequestDevice
                    {
                        Name = device.GetName(),
                        Firmware = device.GetFirmware(),
                        Screen = device.GetScreenCapabilities(),
                        SkipInstruction = device.GetSkipInstruction(),
                        SkipInstructionSpecified = true,
                        Receipt = receiptManager.GetReceiptCapabilities(),
                    },
                    Language = device.GetLanguages(),
                    Server = device.GetServer(),
                    ForceSpecified = true,
                    Force = force
                }
            };
            return result;
        }

        public Request AssembleRequestRating(RequestParams requestParams, RequestRating rating)
        {
            var result = new Request
            {
                PartnerId = requestParams.PartnerId,
                MerchantId = requestParams.MerchantId,
                TerminalId = requestParams.TerminalId,
                SessionId = requestParams.SessionId,
                Item = rating
            };
            return result;
        }

        public Request AssembleRequestQuestion(RequestParams requestParams,
            IDevice device, IReceiptManager receiptManager,
            Trigger trigger)
        {
            var result = new Request
            {
                PartnerId = requestParams.PartnerId,
                MerchantId = requestParams.MerchantId,
                TerminalId = requestParams.TerminalId,
                SessionId = requestParams.SessionId,
                Item = new RequestQuestion
                {
                    Trigger = trigger,
                    Device = new RequestDevice
                    {
                        Name = device.GetName(),
                        Firmware = device.GetFirmware(),
                        Screen = device.GetScreenCapabilities(),
                        SkipInstruction = device.GetSkipInstruction(),
                        SkipInstructionSpecified  = true,
                        Receipt = receiptManager.GetReceiptCapabilities(),
                    },
                    Language = device.GetLanguages(),
                    Server = device.GetServer()
                }
            };
            return result;
        }

        public Request AssembleRequestTransaction(RequestParams requestParams, RequestTransaction requestTransaction)
        {
            var result = new Request
            {
                PartnerId = requestParams.PartnerId,
                MerchantId = requestParams.MerchantId,
                TerminalId = requestParams.TerminalId,
                SessionId = requestParams.SessionId,
                Item = requestTransaction
            };
            return result;
        }

        public Request AssembleRequestPosEvent(PosParams posParams, RequestPosEvent requestPosEvent)
        {
            var result = new Request
            {
                PartnerId = posParams.PartnerId,
                MerchantId = posParams.MerchantId,
                TerminalId = posParams.TerminalId,
                SessionId = posParams.SessionId,
                Item = requestPosEvent
            };
            return result;
        }

        public Request AssembleRequestPosEventList(RequestParams requestParams, RequestPosEventList requestPosEventList)
        {
            var result = new Request
            {
                PartnerId = requestParams.PartnerId,
                MerchantId = requestParams.MerchantId,
                TerminalId = requestParams.TerminalId,
                SessionId = requestParams.SessionId,
                Item = requestPosEventList
            };
            return result;
        }

        public Request AssembleRequestLookup(RequestParams requestParams, IDevice device, IReceiptManager receiptManager, LookupName lookupName)
        {
            var result = new Request
            {
                PartnerId = requestParams.PartnerId,
                MerchantId = requestParams.MerchantId,
                TerminalId = requestParams.TerminalId,
                SessionId = requestParams.SessionId,
                Item = new RequestLookup
                {
                    Name = lookupName,
                    Device = new RequestDevice
                    {
                        Name = device.GetName(),
                        Firmware = device.GetFirmware(),
                        Screen = device.GetScreenCapabilities(),
                        SkipInstruction = device.GetSkipInstruction(),
                        SkipInstructionSpecified = true,
                        Receipt = receiptManager.GetReceiptCapabilities(),
                    },
                    Language = device.GetLanguages(),
                    Server = device.GetServer()
                }
            };
            return result;
        }

        public Request AssembleRequestActivate(RequestParams requestParams, IDevice device, IReceiptManager receiptManager, int sectorNode, string timeZone, PaymentInstant paymentInstant, string emailAddress,
            string password, string address, string mobileNumber, string merchantName, string businessName)
        {
            var result = new Request
            {
                PartnerId = requestParams.PartnerId,
                MerchantId = requestParams.MerchantId,
                TerminalId = requestParams.TerminalId,
                SessionId = requestParams.SessionId,
                Item = new RequestActivate
                {
                    Device = new RequestDevice
                    {
                        Name = device.GetName(),
                        Firmware = device.GetFirmware(),
                        Screen = device.GetScreenCapabilities(),
                        SkipInstruction = device.GetSkipInstruction(),
                        SkipInstructionSpecified = true,
                        Receipt = receiptManager.GetReceiptCapabilities(),
                    },
                    Language = device.GetLanguages(),
                    Server = device.GetServer(),
                    Item = new RequestRegistrationForm
                    {
                        BusinessAddress = address,
                        BusinessName = businessName,
                        MerchantEmailAddress = emailAddress,
                        MerchantMobileNumber = mobileNumber,
                        MerchantName = merchantName,
                        MerchantPassword = password,
                        PaymentInstant = paymentInstant,
                        SectorNode = sectorNode,
                        TimeZone = timeZone
                    }
                }
            };
            return result;
        }

        public Request AssembleRequestActivate(RequestParams requestParams, IDevice device, IReceiptManager receiptManager,string registrationCode)
        {
            var result = new Request
            {
                PartnerId = requestParams.PartnerId,
                MerchantId = requestParams.MerchantId,
                TerminalId = requestParams.TerminalId,
                SessionId = requestParams.SessionId,
                Item = new RequestActivate
                {
                    Device = new RequestDevice
                    {
                        Name = device.GetName(),
                        Firmware = device.GetFirmware(),
                        Screen = device.GetScreenCapabilities(),
                        SkipInstruction = device.GetSkipInstruction(),
                        SkipInstructionSpecified = true,
                        Receipt = receiptManager.GetReceiptCapabilities(),
                    },
                    Language = device.GetLanguages(),
                    Server = device.GetServer(),
                    Item = registrationCode
                }
            };
            return result;
        }

    }
}