text:
A simple API to collect timestamps associated for an issue.

## Requirements ##

An XAMP stack.

Optional: flyway
A Jira install, or any project management software
Mozilla firefox/Greasemonkey

## Installation ##

Clone the repository and run

````
composer install
./vendor/bin/flywayMigrate.sh Timesheet
````

To install the application and database. If you dont have flyway installed, use the schema located in `/resources/db/migration/`.

## Usage: API ##

Note that the API uses all `GET` requests, since there may be issues concerning your development server not using HTTPS, any AJAX calls to HTTP from a HTTPS site will be blocked automatically, due to mixed content. Just using `GET` everywhere means can do our requests from the JIRA location to wherever. Optionally, you are free to setup SSL on localhost, but since this may not be the case, we can get going as quick as possible.

`GET` requests that will change whatever is on the server are denoted with `*`.
The endpoints are as follows:
````
'GET', '/user/newuser/[:username]' *
'GET', '/user/[i:id]/newtimestamp/[:task]' *
'GET', '/user/[i:id]/startDay' *
'GET', '/user/[i:id]/finishDay' *
'GET', '/user/[i:id]/currentTask'
'GET', '/user/[i:id]/timestamps/[:date]'
'GET', '/user/[i:id]/timestamps/[:date]/[:date2]'
'GET', '/user/[i:id]/burndown/[:date]'
'GET', '/user/[i:id]/burndown/[:date]/[:date2]'
````

````
'GET', '/user/newuser/[:username]' *
````
You create a new user with your actual name, and populate `[i:id]` with your newly supplied id.

````
'GET', '/user/[i:id]/newtimestamp/[:task]' *
````
Supply the task you are working on, and a new timestamp will be created for that user.
This currently supplies a javascript close in the response to facilitate a Jira install, feel free to remove if not necessary.

````
'GET', '/user/[i:id]/startDay' *
````

Set the first timestamp of the day. This will coincide with your arrival and choice of signalling the day has started.
Currently this is via loading JIRA if you are using the Greasemonkey install.

````
'GET', '/user/[i:id]/finishDay' *
````

Set the last timestamp of the day. If you dont do this, the next timestamp will be the one you set the next day.
It will look like you have been up all night doing something, this usually (hopefully) isnt the case.

````
'GET', '/user/[i:id]/currentTask'
````
This is the current task that is being worked on.

````
'GET', '/user/[i:id]/timestamps/[:date]'
````
This currently will supply you the timestamps for a week. Date is in Mysql format, or string `thisWeek`. Add `[:date2]` with value of `week` or `month` for that months timestamps, or another date for all timestamps between.

````
'GET', '/user/[i:id]/burndown/[:date]'
````
This currently will supply you a burndown of time taken in hours for each task for a week. Date is in mysql format, or string `thisWeek`. Add `[:date2]` with value of `week` or `month` for that months burndown, or another date for burndown between.

Drop the endpoints into your current browser based project management software.

## Usage: Greasemonkey ##

You can opt to git clone to a central server, and distribute the greasemonkey script with the suitable alterations, namely to the `url` variable inside the script. Optionally, the install can be local as well.
After git cloning and installing as above:

````
composer install
./vendor/bin/flywayMigrate.sh Timesheet
````

You need to install the greasemonkey script, which is located at `resources/GreasemonkeyJiraTimesheet.js`. Direct to your jira install, and add the script, choosing `timesheet` for the values required. You will need to update the @include attribute inside the script file itself according to your JIRA install URL.

You will hopefully get the opportunity to add your username after each issue link. Type it in and click the add user button. You will get a new window with a JSON response telling you what your ID is.

Copy the id, and inside the script, edit the `userId` variable to be this id. Upon reloading the Jira page, you will see egg timers. If you click an egg timer, the graphic should switch to signal that this is the current task being worked on.

Try a `'GET', '/user/[i:id]/timestamps/thisWeek'` to ensure data is coming in ok.

You may need to alter the javascript to get it to hook into the page structure.

It may be an idea to set your homepage to your issue tracker. The day will start when the script is loaded for the first time that day.

Click the leaving icon to finish the day.


text:
<?xml version="1.0" encoding="UTF-8"?>
<GeocodeResponse>
 <status>OK</status>
 <result>
  <type>locality</type>
  <type>political</type>
  <formatted_address>9771 Berg im Drautal, Austria</formatted_address>
  <address_component>
   <long_name>Berg im Drautal</long_name>
   <short_name>Berg im Drautal</short_name>
   <type>locality</type>
   <type>political</type>
  </address_component>
  <address_component>
   <long_name>Gemeinde Berg im Drautal</long_name>
   <short_name>Gemeinde Berg im Drautal</short_name>
   <type>administrative_area_level_3</type>
   <type>political</type>
  </address_component>
  <address_component>
   <long_name>Spittal an der Drau District</long_name>
   <short_name>Spittal an der Drau District</short_name>
   <type>administrative_area_level_2</type>
   <type>political</type>
  </address_component>
  <address_component>
   <long_name>Carinthia</long_name>
   <short_name>Carinthia</short_name>
   <type>administrative_area_level_1</type>
   <type>political</type>
  </address_component>
  <address_component>
   <long_name>Austria</long_name>
   <short_name>AT</short_name>
   <type>country</type>
   <type>political</type>
  </address_component>
  <address_component>
   <long_name>9771</long_name>
   <short_name>9771</short_name>
   <type>postal_code</type>
  </address_component>
  <geometry>
   <location>
    <lat>46.7477346</lat>
    <lng>13.1358862</lng>
   </location>
   <location_type>APPROXIMATE</location_type>
   <viewport>
    <southwest>
     <lat>46.7400885</lat>
     <lng>13.1198788</lng>
    </southwest>
    <northeast>
     <lat>46.7553796</lat>
     <lng>13.1518936</lng>
    </northeast>
   </viewport>
  </geometry>
  <place_id>ChIJLxUMj8tUd0cRd922FjvoJWo</place_id>
 </result>
</GeocodeResponse>

redpajama_set_name: RedPajamaGithub


text:
package org.encuestame.social.connect;

import org.encuestame.core.config.EnMePlaceHolderConfigurer;
import org.encuestame.social.api.templates.GoogleBuzzAPITemplate;
import org.encuestame.social.api.operation.GoogleContactsAPIOperations;
import org.encuestame.social.connect.service.ConnectOperations;
import org.encuestame.utils.oauth.AccessGrant;
import org.encuestame.utils.social.SocialProvider;

/**
 * Google SignIn Support.
 * @author Picado, Juan juanATencuestame.org
 * @since Dec 25, 2010 5:57:35 PM
 */
public class GoogleBuzzSignInSocialService extends AbstractSocialSignInConnect<GoogleContactsAPIOperations> {

    /**
     * Constructor.
     * @param accessGrant
     * @param key
     * @throws Exception
     */

    public GoogleBuzzSignInSocialService(final AccessGrant accessToken,
            final ConnectOperations securityOperations) throws Exception {
        super(accessToken, securityOperations);
    }

    /**
     * Google buzz provider.
     */
    @Override
    public SocialProvider getProvider() {
        return SocialProvider.GOOGLE_BUZZ;
    }

    /**
     *
     */
    @Override
    public GoogleBuzzAPITemplate getAPISocialProvider() {
        return new GoogleBuzzAPITemplate(getAccessGrant().getAccessToken(),
                EnMePlaceHolderConfigurer.getProperty("google.api.key"));
    }

}


text: popular cornerstone of application


text:
require 'mongo_store'
require 'dyno/dyno_server'
require 'dyno/dyno_server_check'
require 'passenger/passenger_overview'
require 'passenger/passenger_thread'
require 'dyno_check'


text:
<footer class="Site__footer">
    <div class="Site__footer__content">
    	{% include "footerContent.html" %}
    </div>
</footer>


text:
using System;

namespace ProSecuritiesTrading.MOEX.FIX.Base.Field
{
    public class CashOrderQty
    {
        public const int Tag = 152;
        public static readonly byte[] TagBytes;

        static CashOrderQty()
        {
            TagBytes = new byte[3];
            TagBytes[0] = 49;
            TagBytes[1] = 53;
            TagBytes[2] = 50;
        }
    }
}


text:
["..", "../../lib", "../../lib/vtools"].each do |path|
  dir = File.expand_path(path, __FILE__)
  $:.unshift dir if dir and not $:.include?(dir)
end

require "vtools"
require "rspec"
require "stringio"

# helpers utilities
module Helpers

end

RSpec.configure do |c|
  c.include Helpers
end


text:
if defined?(LivereloadRails)
  LivereloadRails.configure do |config|
    config.logger.level = Logger::DEBUG
  end
end


text:
title: Grav Tools
access:
    admin.login: true
---


text:
import Component from '@ember/component';
import { inject as service } from "@ember/service";
import AlertifyHandler from 'explorviz-frontend/utils/alertify-handler';
import AdditionalData from 'explorviz-frontend/services/additional-data';
import LandscapeRepository from 'explorviz-frontend/services/repos/landscape-repository';
import { action } from '@ember/object';

export default class SQLOpener extends Component {

  // No Ember generated container
  tagName = '';

  @service('additional-data')
  additionalData!: AdditionalData;

  @service('repos/landscape-repository')
  landscapeRepo!: LandscapeRepository;

  @action
  showSql() {
    const latestApplication = this.get('landscapeRepo').get('latestApplication');

    if(latestApplication !== null) {
      if (latestApplication.get('databaseQueries').length === 0){
        AlertifyHandler.showAlertifyMessage("No SQL statements found!");
        return;
      }
      this.get('additionalData').addComponent("visualization/page-setup/sidebar/sql-viewer");
      this.get('additionalData').openAdditionalData();
    }
  }

}


text:
#include <Furrovine++/Platform.Conventions.h>
#include <Furrovine++/Platform.OS.h>

namespace Furrovine {

#ifdef FURROVINEDIRECTX

	const double normalizedevicecoordinatesrange = 1.0;
	const double normalizedevicecoordinatesstart = 0;

#endif // DIRECTX

#ifdef FURROVINEOPENGL

	const double normalizedevicecoordinatesrange = 2.0;
	const double normalizedevicecoordinatesstart = -1.0;

#endif // FURROVINEOPENGL

}


text:
{% load currency_filters %}
{% load i18n %}
{% load purchase_info_tags %}

{% purchase_info_for_product request product as session %}

{% if session.price.exists %}
    {% if session.price.excl_tax == 0 %}

{% trans "Free" %}

    {% elif session.price.is_tax_known %}

{{ session.price.incl_tax|currency:session.price.currency }}

    {% else %}

{{ session.price.excl_tax|currency:session.price.currency }}

    {% endif %}
{% else %}

{% endif %}

    {% if session.availability.is_available_to_buy %}

    {% else %}

    {% endif %}
    {% if verbose %}
        {{ session.availability.message }}
    {% else %}
        {{ session.availability.short_message }}
    {% endif %}


text:
                    Welcome to Demo Corporation

 Bootstrap v3.2.0

Lorem ipsum dolor sit amet, consectetur adipisicing elit. Itaque, optio corporis quae nulla aspernatur in alias at numquam rerum ea excepturi expedita tenetur assumenda voluptatibus eveniet incidunt dicta nostrum quod?

                        Learn More

 Free & Open Source

Lorem ipsum dolor sit amet, consectetur adipisicing elit. Itaque, optio corporis quae nulla aspernatur in alias at numquam rerum ea excepturi expedita tenetur assumenda voluptatibus eveniet incidunt dicta nostrum quod?

                        Learn More

 Easy to Use

Lorem ipsum dolor sit amet, consectetur adipisicing elit. Itaque, optio corporis quae nulla aspernatur in alias at numquam rerum ea excepturi expedita tenetur assumenda voluptatibus eveniet incidunt dicta nostrum quod?

                        Learn More


text:
require 'spec_helper'

describe NetSuite::Configuration do
  let(:config) { NetSuite::Configuration }

  before do
    config.reset!
  end

  describe '#reset!' do
    it 'clears the attributes hash' do
      config.attributes[:blah] = 'something'
      expect(config.attributes).not_to be_empty
      config.reset!
      expect(config.attributes).to be_empty
    end
  end

  describe '#connection' do
    it 'returns a Savon::Client object that allows requests to the service' do
      # reset clears out the password info
      config.email 'me@example.com'
      config.password 'me@example.com'
      config.account 1023

      expect(config.connection).to be_kind_of(Savon::Client)
    end
  end

  describe '#wsdl' do
    context 'when the wsdl has been set' do
      before do
        config.wsdl = 'https://system.sandbox.netsuite.com/wsdl/v2011_2_0/netsuite.wsdl'
      end

      it 'returns a path to the WSDL to use for the API' do
        expect(config.wsdl).to eql('https://system.sandbox.netsuite.com/wsdl/v2011_2_0/netsuite.wsdl')
      end
    end

    context 'when the wsdl has not been set' do
      it 'returns a path to the WSDL to use for the API' do
        expect(config.wsdl).to match(/.*\/netsuite\/wsdl\/2011_2\.wsdl/)
      end
    end

    context 'when the wsdl has not been set, but the API has been set' do
      it 'should correctly return the full HTTP sandbox URL' do
        config.api_version '2013_1'
        config.sandbox false
        expect(config.wsdl).to eql('https://webservices.netsuite.com/wsdl/v2013_1_0/netsuite.wsdl')
      end
    end
  end

  describe '#auth_header' do
    before do
      config.email    = 'user@example.com'
      config.password = 'myPassword'
      config.account  = 1234
    end

    it 'returns a hash representation of the authentication header' do
      expect(config.auth_header).to eql({
        'platformMsgs:passport' => {
          'platformCore:email'    => 'user@example.com',
          'platformCore:password' => 'myPassword',
          'platformCore:account'  => '1234',
          'platformCore:role'     => { :@internalId => '3' },
        }
      })
    end
  end

  describe '#soap_header' do
    before do
      config.email    = 'user@example.com'
      config.password = 'myPassword'
      config.account  = 1234
    end

    it 'adds a new header to the soap header' do
      config.soap_header = {
        'platformMsgs:preferences' => {
          'platformMsgs:ignoreReadOnlyFields' => true,
        }
      }
      expect(config.soap_header).to eql({
        'platformMsgs:preferences' => {
          'platformMsgs:ignoreReadOnlyFields' => true,
        }
      })
    end
  end

  describe '#email' do
    context 'when the email has been set' do
      before do
        config.email = 'test@example.com'
      end

      it 'returns the email' do
        expect(config.email).to eql('test@example.com')
      end
    end

    context 'when the email has not been set' do
      it 'raises a ConfigurationError' do
        expect {
          config.email
        }.to raise_error(NetSuite::ConfigurationError,
          '#email is a required configuration value. Please set it by calling NetSuite::Configuration.email = "me@example.com"')
      end
    end
  end

  describe '#password' do
    context 'when the password has been set' do
      before do
        config.password = 'password'
      end

      it 'returns the password' do
        expect(config.password).to eql('password')
      end
    end

    context 'when the password has not been set' do
      it 'raises a ConfigurationError' do
        expect {
          config.password
        }.to raise_error(NetSuite::ConfigurationError,
          '#password is a required configuration value. Please set it by calling NetSuite::Configuration.password = "my_pass"')
      end
    end
  end

  describe '#account' do
    context 'when the account has been set' do
      before do
        config.account = 4321
      end

      it 'returns the account' do
        expect(config.account).to eql(4321)
      end
    end

    context 'when the account has not been set' do
      it 'raises a ConfigurationError' do
        expect {
          config.account
        }.to raise_error(NetSuite::ConfigurationError,
          '#account is a required configuration value. Please set it by calling NetSuite::Configuration.account = 1234')
      end
    end
  end

  describe '#role' do
    context 'when no role is defined' do
      it 'defaults to "3"' do
        expect(config.role).to eq("3")
      end
    end
  end

  describe '#role=' do
    it 'sets the role according to the input value' do
      config.role = "6"
      expect(config.role).to eq("6")
    end
  end

  describe '#api_version' do
    context 'when no api_version is defined' do
      it 'defaults to 2011_2' do
        expect(config.api_version).to eq('2011_2')
      end
    end
  end

  describe '#api_version=' do
    context 'when api version is defined' do
      it 'sets the api_version of the application' do
        config.api_version = '2012_1'
        expect(config.api_version).to eq('2012_1')
      end
    end
  end

  describe "#credentials" do
    context "when none are defined" do
      skip "should properly create the auth credentials" do

      end
    end

    context "when they are defined" do
      it "should properly replace the default auth credentials" do

      end
    end
  end

end


text:
<?php
/**
 * Created by PhpStorm.
 * User: xiaoqiu
 * Date: 15/6/24
 * Time: 上午9:58
 */
namespace Blog\Plugin;
class MySmarty extends \Smarty{

    public function display($template = NULL, $cache_id = NULL, $compile_id = NULL, $parent = NULL){
        parent::display($template, $cache_id, $compile_id,$parent);
        exit;
    }

}


text:
class Product < ApplicationRecord

  translate :name

end


text:
<readable><title>3286222970_1fa445e38f</title><content>
A little girl runs in the park , looking at somthing out of frame .
A young girl walks quickly outside .
Girl running past a bench .
The girl is running through a park near a wooden park bench .
Young girl in green shirt and sandals runs down the street
</content></readable>


text:
using System;
using EdgeNote.Library.Objects;
using LiteDB;

namespace EdgeNote.UI.Daos
{
    public class LabelDao : AbstractVersionedDao<Label>
    {
        public LabelDao(LiteDatabase _db)
            : base(_db)
        {
        }

        public override string CollectionName
        {
            get
            {
                return "Label";
            }
        }

        public override void BuildIndexes()
        {

        }
    }
}


text:
<?xml version="1.0" encoding="ascii"?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
          "DTD/xhtml1-transitional.dtd">

  <title>pyglet.image.ImageDataRegion</title>
  <link rel="stylesheet" href="epydoc.css" type="text/css" />

      Trees

      Indices

          pyglet . image . ImageDataRegion

        Toggle frames

Class pyglet.image.ImageDataRegion

AbstractImage --+
                |
        ImageData --+
                    |
                   ImageDataRegion

Methods

        __init__(self,
        x,
        y,
        width,
        height,
        image_data)

Initialise image data.

        __getstate__(self)

      sequence of bytes, or str

        get_data(self,
        format,
        pitch)

Get the byte data of the image.

      ImageDataRegion

        get_region(self,
        x,
        y,
        width,
        height)

Retrieve a rectangular region of this image data.

        __repr__(self)
      (Inherited from pyglet.image.AbstractImage)

        blit(self,
        x,
        y,
        z=0,
        width=None,
        height=None)

Draw this image to the active framebuffers.

      (Inherited from pyglet.image.ImageData)

        blit_into(self,
        source,
        x,
        y,
        z)

Draw source on this image.

      (Inherited from pyglet.image.AbstractImage)

        blit_to_texture(self,
        target,
        level,
        x,
        y,
        z,
        internalformat=None)

Draw this image to to the currently bound texture at target.

      (Inherited from pyglet.image.ImageData)

      cls or cls.region_class

        create_texture(self,
        cls,
        rectangle=False,
        force_rectangle=False)

Create a texture containing this image.

      (Inherited from pyglet.image.ImageData)

      ImageData

        get_image_data(self)

Get an ImageData view of this image.

      (Inherited from pyglet.image.ImageData)

      Texture

        get_mipmapped_texture(self)

Return a Texture with mipmaps.

      (Inherited from pyglet.image.ImageData)

      Texture

        get_texture(self,
        rectangle=False,
        force_rectangle=False)

A Texture view of this image.

      (Inherited from pyglet.image.ImageData)

        save(self,
        filename=None,
        file=None,
        encoder=None)

Save this image to a file.

      (Inherited from pyglet.image.AbstractImage)

        set_data(self,
        format,
        pitch,
        data)

Set the byte data of the image.

      (Inherited from pyglet.image.ImageData)

        set_mipmap_image(self,
        level,
        image)

Set a mipmap image for a particular level.

      (Inherited from pyglet.image.ImageData)

Properties

      str

        data

Pixel data, encoded according to format and pitch.

      ImageData

        image_data

An ImageData view of this image.

      (Inherited from pyglet.image.AbstractImage)

      Texture

        mipmapped_texture

A Texture view of this image.

      (Inherited from pyglet.image.AbstractImage)

      Texture

        texture

Get a Texture view of this image.

      (Inherited from pyglet.image.AbstractImage)

Instance Variables

      int

        anchor_x = 0

X coordinate of anchor, relative to left edge of image data

      (Inherited from pyglet.image.AbstractImage)

      int

        anchor_y = 0

Y coordinate of anchor, relative to bottom edge of image data

      (Inherited from pyglet.image.AbstractImage)

      str

        format

The format string to use when reading or writing data.

      (Inherited from pyglet.image.ImageData)

      int

        height

Height of image

      (Inherited from pyglet.image.AbstractImage)

      int

        pitch

Number of bytes per row.

      (Inherited from pyglet.image.ImageData)

      int

        width

Width of image

      (Inherited from pyglet.image.AbstractImage)

Method Details

__init__

    (Constructor)
    __init__(self,
        x,
        y,
        width,
        height,
        image_data)

  Initialise image data.

Overrides:

      ImageData.__init__

__getstate__

    __getstate__(self)

Overrides:

      ImageData.__getstate__

get_data

    get_data(self,
        format,
        pitch)

  Get the byte data of the image.

Returns: sequence of bytes, or str

Overrides:

      ImageData.get_data

Since:
        pyglet 1.1

get_region

    get_region(self,
        x,
        y,
        width,
        height)

  Retrieve a rectangular region of this image data.

Returns: ImageDataRegion

Overrides:

      ImageData.get_region

Property Details

data

  Pixel data, encoded according to format and pitch.

Deprecated:
        Use get_data and set_data.

      Trees

      Indices

          pyglet . image . ImageDataRegion

        Toggle frames

    Generated by Epydoc 3.0beta1 on Thu Dec 31 17:58:19 2009

      http://epydoc.sourceforge.net


text:
import { delay } from 'redux-saga';
import { takeEvery, call, put, select } from 'redux-saga/effects';

import PagesEffects from '../actions/effects/pages-effects';
import PagesModelActions from '../actions/model/pages-model-actions';
import UIPageModel from '../model/ui-page-model';
import * as UIPagesSelectors from '../selectors/ui-pages-selectors';

function* closeTabAnimated({ payload: { pageId, removePageAfterMs } }) {
  const selectedPageId = yield select(UIPagesSelectors.getSelectedPageId);
  const nextSelectedPageId = yield select(UIPagesSelectors.getNextLogicalPageId);

  const tabState = selectedPageId === pageId
    ? UIPageModel.TAB_STATES.FOREGROUND_CLOSED
    : UIPageModel.TAB_STATES.BACKGROUND_CLOSED;

  yield put(PagesModelActions.tabbar.setTabState({
    pageId,
    tabState,
  }));

  if (tabState === UIPageModel.TAB_STATES.FOREGROUND_CLOSED) {
    yield put(PagesModelActions.setSelectedPage({
      pageId: nextSelectedPageId,
    }));
  }

  yield call(delay, removePageAfterMs);
  yield put(PagesModelActions.removePage({
    pageId,
    withoutSelectingNextLogicalPage: true,
  }));
}

function* reorderTabsAnimated({ payload: { oldIndex, newIndex } }) {
  const pageIds = yield select(UIPagesSelectors.getPageIdsInDisplayOrder);
  const reorderedPageId = yield select(UIPagesSelectors.getPageIdAtIndex, oldIndex);

  for (const pageId of pageIds.values()) {
    if (pageId !== reorderedPageId) {
      yield put(PagesModelActions.tabbar.setAllTabAnimationsDisabled({ pageId }));
    }
  }

  yield put(PagesModelActions.tabbar.changeDisplayOrder({ oldIndex, newIndex }));
  yield call(delay, 50);

  for (const pageId of pageIds.values()) {
    if (pageId !== reorderedPageId) {
      yield put(PagesModelActions.tabbar.setAllTabAnimationsEnabled({ pageId }));
    }
  }
}

export default function* () {
  yield [
    takeEvery(PagesEffects.commands.closeTabAnimated, closeTabAnimated),
    takeEvery(PagesEffects.commands.reorderTabsAnimated, reorderTabsAnimated),
  ];
}


text:
exports.type = type;
exports.arch = arch;

var defaultOs = 'Unknown';
var defaultArch = '32';

/**
 * Detects the Operating System of the user's platform by inspecting
 * platform.appVersion
 * @param {{appVersion:string}?} environment optional environment, defaults to global `navigator`
 * @returns {string} 'Windows', 'Mac', 'Linux', or 'Unknown'
 */
function type(environment) {
  /*global navigator*/
  if(arguments.length === 0) {
    environment = navigator;
  }

  if (environment.appVersion.indexOf('Win') !== -1) {
    return 'Windows';
  }

  if (environment.appVersion.indexOf('Mac') !== -1) {
    return 'Mac';
  }

  if (environment.appVersion.indexOf('Linux') !== -1) {
    return 'Linux';
  }

  return defaultOs;
}

/**
 * Detects the X-bit architecture of the user's platform by inspecting
 * platform.userAgent and platform.platform
 * @param {{userAgent:string, platform:string}?} environment optional environment,
 *   defaults to global `navigator`
 * @returns {string} '32' or '64'
 */
function arch(environment) {
  /*global navigator*/
  /*jshint maxcomplexity:6*/
  if(arguments.length === 0) {
    environment = navigator;
  }

  if (/Mac OS X 10\.[0-5]([\.\s]|$)/.test(environment.userAgent)) {
    return '32';
  }

  if (environment.userAgent.indexOf('Mac OS X') !== -1
      || environment.userAgent.indexOf('WOW64') !== -1
      || environment.platform.indexOf('Win64') !== -1
      || environment.platform.indexOf('Linux x86_64') !== -1) {
    return '64';
  }

  return defaultArch;
}


text:
<?php

namespace FieldNation;

interface PaymentDeductionInterface extends DescribableInterface
{
    /**
     * Set the type of payment deduction, generally just "discount".
     * @param string $type
     * @return self
     */
    public function setType($type);

    /**
     * Get the type of payment deduction
     *
     * @return string
     */
    public function getType();

    /**
     * Set the total amount of the discount to be subtracted from the Work Order base total, in dollars.
     * @param string $amount
     * @return self
     */
    public function setAmount($amount);

    /**
     * Get the type of payment deduction
     *
     * @return float
     */
    public function getAmount();
}


text:
from django.db import models

class Lastface(models.Model):
    owner = models.CharField(max_length=60, primary_key=True)
    face = models.CharField(max_length=60)
    created = models.DateTimeField(auto_now=True)

class Favoriteface(models.Model):
    favorited = models.CharField(max_length=60)
    favoriter = models.CharField(max_length=60)
    lastface = models.CharField(max_length=60)
    created = models.DateTimeField(auto_now=True)

    class Meta:
        unique_together = (('favorited', 'favoriter'),)


text:
{#
 Copyright (c) 2015 The Pycroft Authors. See the AUTHORS file.
 This file is part of the Pycroft project and licensed under the terms of
 the Apache License, Version 2.0. See the LICENSE file for details.
#}

Kontenform

    {% if typed_splits is not none%}
Staffelform
{% endif %}

        {{ finance_table_regular.render("report") }}

        {{ finance_table_splitted.render("splitted") }}


text:
import React, { Children, cloneElement } from 'react'
import classnames from 'classnames'
import PropTypes from './utils/proptypes'
import _styles from './styles/_button-group.scss'

export default function ButtonGroup (props) {
  const { children, size, vertical, ...other } = props
  const className = classnames(
    other.className,
    _styles['btn-group'],
    vertical && _styles['btn-group-vertical']
  )

  const btns = Children.toArray(children).map(child => {
    return cloneElement(child, {
      className: classnames(_styles.btn, child.props.className),
      size
    })
  })

  return <div {...other} className={className}>{btns}</div>
}

ButtonGroup.propTypes = {
  children: PropTypes.array_element,
  size: PropTypes.string,
  vertical: PropTypes.bool
}

ButtonGroup.defaultProps = {
  size: 'middle'
}


text:
var Transport = require('winston').Transport
var util = require('util')
var Autowire = require('wantsit').Autowire

var RemoteProcessLogger = function (options) {
  Transport.call(this, options)

  this._parentProcess = Autowire
}
util.inherits(RemoteProcessLogger, Transport)

RemoteProcessLogger.prototype.name = 'remote'

RemoteProcessLogger.prototype.log = function (level, msg, meta, callback) {
  if (this.silent || !msg) {
    return callback(null, true)
  }

  if (msg) {
    this._parentProcess.send('process:log:' + level, {
      date: Date.now(),
      message: msg.toString().trim()
    })

    this.emit('logged')
  }

  callback(null, true)
}

module.exports = RemoteProcessLogger


text:
package org.apache.carbondata.lcm.fileoperations;

import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;

public interface AtomicFileOperations {

  DataInputStream openForRead() throws IOException;

  void close() throws IOException;

  DataOutputStream openForWrite(FileWriteOperation operation) throws IOException;
}


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

    <item
        android:id="@+id/set_as_default"
        android:title="@string/set_chapter_settings_as_default" />

</menu>


text:
def func():
    value = "not-none"

    # Is none
    <caret>if value is None:
        print("None")
        return


text:
wabs
====

A (currently not finished) responsive tabs plugin.


text:
import { Config } from '@jest/types';
declare const defaultOptions: Config.DefaultOptions;
export default defaultOptions;
//# sourceMappingURL=Defaults.d.ts.map


text:
import datetime

from django.contrib.postgres.fields import JSONField
from django.db import models
from django.db.models import F, Max, Q

from .permissions import ProductPermissions
from .utils.json_serializer import CustomJsonEncoder

class SortableModel(models.Model):
    sort_order = models.IntegerField(editable=False, db_index=True, null=True)

    class Meta:
        abstract = True

    def get_ordering_queryset(self):
        raise NotImplementedError("Unknown ordering queryset")

    def get_max_sort_order(self, qs):
        existing_max = qs.aggregate(Max("sort_order"))
        existing_max = existing_max.get("sort_order__max")
        return existing_max

    def save(self, *args, **kwargs):
        if self.pk is None:
            qs = self.get_ordering_queryset()
            existing_max = self.get_max_sort_order(qs)
            self.sort_order = 0 if existing_max is None else existing_max + 1
        super().save(*args, **kwargs)

    def delete(self, *args, **kwargs):
        if self.sort_order is not None:
            qs = self.get_ordering_queryset()
            qs.filter(sort_order__gt=self.sort_order).update(
                sort_order=F("sort_order") - 1
            )
        super().delete(*args, **kwargs)

class PublishedQuerySet(models.QuerySet):
    def published(self):
        today = datetime.date.today()
        return self.filter(
            Q(publication_date__lte=today) | Q(publication_date__isnull=True),
            is_published=True,
        )

    @staticmethod
    def user_has_access_to_all(user):
        return user.is_active and user.has_perm(ProductPermissions.MANAGE_PRODUCTS)

    def visible_to_user(self, user):
        if self.user_has_access_to_all(user):
            return self.all()
        return self.published()

class PublishableModel(models.Model):
    publication_date = models.DateField(blank=True, null=True)
    is_published = models.BooleanField(default=False)

    objects = PublishedQuerySet.as_manager()

    class Meta:
        abstract = True

    @property
    def is_visible(self):
        return self.is_published and (
            self.publication_date is None
            or self.publication_date < datetime.date.today()
        )

class ModelWithMetadata(models.Model):
    private_meta = JSONField(
        blank=True, null=True, default=dict, encoder=CustomJsonEncoder
    )
    meta = JSONField(blank=True, null=True, default=dict, encoder=CustomJsonEncoder)

    class Meta:
        abstract = True

    def get_private_meta(self, namespace: str, client: str) -> dict:
        return self.private_meta.get(namespace, {}).get(client, {})

    def store_private_meta(self, namespace: str, client: str, item: dict):
        if namespace not in self.private_meta:
            self.private_meta[namespace] = {}
        self.private_meta[namespace][str(client)] = item

    def clear_stored_private_meta_for_client(self, namespace: str, client: str):
        self.private_meta.get(namespace, {}).pop(client, None)

    def get_meta(self, namespace: str, client: str) -> dict:
        return self.meta.get(namespace, {}).get(client, {})

    def store_meta(self, namespace: str, client: str, item: dict):
        if namespace not in self.meta:
            self.meta[namespace] = {}
        self.meta[namespace][str(client)] = item

    def clear_stored_meta_for_client(self, namespace: str, client: str):
        self.meta.get(namespace, {}).pop(client, None)


text:
layout: post
published: true
title: Install Hortonworks HDP 3.1.0 on A Cluster of VMWare Virtual Machines
subtitle: Hortonworks Tutorials
date: '2019-03-19'
bigimg: /img/post/Hortonworks.jpg
thumbnail: /img/post/Hortonworks.jpg
categories:
  - Tutorial
tags:
  - Hadoop
  - Big Data
---
This post describes the process to install Hortontworks HDP 3.1.0 on a cluster of three VMWare virtual machines. The process includes four major steps: 1) set up the cluster environemnt; 2) set up a local repository for both Ambari and HDP stacks; 3) Install Ambari server and agent; 4) install, configure and deploy the cluster.

This installation process might work for other versions too. Please check the product versions through Hortonworks support matrix: https://supportmatrix.hortonworks.com/

<!--more-->

# Table of Content

{:.no_toc}

* TOC
{:toc}

# Virtual Nodes Info

Three virtual machines in VMWare with following settings. RedHat Enterprise 7.6 has been installed on each node.

|   Host Name   |   Host IP      | Configuration|
| ------------- | -------------  |------------- |
| hadoop-master | 146.xxx.xxx.75 | 4 x cpu, 16 GB Ram, 100 GB disk |
| hadoop-node-1 | 146.xxx.xxx.76 | 4 x cpu, 16 GB Ram, 100 GB disk |
| hadoop-node-2 | 146.xxx.xxx.77 | 4 x cpu, 16 GB Ram, 100 GB disk |

# 1. Prepare the Cluster Environment

## 1.1. Setting Proxy

If you're behind a proxy, you need to specify your proxy server information, because many repositories, including `yum`, are accessed through the proxy servers. For each host, you can set up proxy server info through adding

```
export https_proxy=https://<your.https-proxy.address>:<port#>
export http_proxy=http://<your.http-proxy.address>:<port#>
```

to the `/root/.bashrc`. Remember to run `source .bashrc` to refresh.

## 1.2. Make sure run level is multi-user text mode

Run following command to check the run level:

```bash
systemctl get-default
```

It is expected to see the response of `multi-user.target`. If not, run the following command to set the run level to multi-user text mode:

```bash
systemctl set-default multi-user.target
```

## 1.3. Check and set hostnames

**Set Hostnames**

For each host in the cluster, confirm that the hostname is set to a Fully Qualified Domain Name ([FQDN](https://en.wikipedia.org/wiki/Fully_qualified_domain_name)) name by running the following command:

```bash
hostname -f
```

This should return a host name that has a format like `fully.qualified.doman.name`
You can use `hostname` command to set the hostname, for example:

```bash
hostname hadoop-master.qualified.doman.name
```

**Edit Network Configuration File**

For each host in the cluster, open the network configuration file through

```bash
vi /etc/sysconfig/network
```

Modify the `HOSTNAME` property to its FQDN:

```
NETWORK=yes
HOSTNAME=fully.qualified.doman.name
```

**Edit Hosts File**

For each host in the cluster, open the hosts file through running `vi /etc/hosts` add a line to each file. For example:

```
146.xxx.xxx.75 hadoop-master.qualified.doman.name hadoop-master
146.xxx.xxx.76 hadoop-node-1.qualified.doman.name hadoop-node-1
146.xxx.xxx.77 hadoop-node-2.qualified.doman.name hadoop-node-2
```

It needs reboot to make these changes effective.

## 1.4. Set up password-less SSH

**For the master host**
- Login to the `hadoop-master` host with `root` user and generate SSH keys using `ssh-keygen -t rsa`. Press enter for all prompts and accept all default values.
- Run the following command `ssh-copy-id localhost`to copy ssh identification for localhost. Enter password when prompted for the password:

- Then run command `ssh hadoop-master` to make sure no password needed.

**For each of other hosts in the cluster:**

- Copy the SSH file from `hadoop-master` to every other hosts in the cluster, through running:

```
scp -pr /root/.ssh root@hadoop-node-1.qualified.doman.name:/root/
```

- Upload the generated `id_rsa.pub` to the `root`'s **.ssh** directory as a file with name **authorized_keys**, through running:

```
cat .ssh/id_rsa.pub | ssh root@hadoop-node-1.qualified.doman.name 'cat >> .ssh/authorized_keys'
```

- Set permissions for **.ssh** directory and **authorized_keys** file:

```
ssh root@hadoop-node-1.qualified.doman.name; chmod 700 .ssh; chmod 640 .ssh/authorized_keys
```

From the `hadoop-master` host, run following commands to make sure inter-node connection using SSH without password:

```
ssh hadoop-node-1
ssh hadoop-node-2
ssh hadoop-master
ssh hadoop-node-2
ssh hadoop-node-1
ssh hadoop-master
```

## 1.5. Enable NTP

Run following commands on each host to install and enable NTP service:

```
yum install -y ntp
systemctl enable ntpd
systemctl start ntpd
```

Run `timedatectl status` and look for following lines to verfiy that NTP is running

```
NTP enabled: yes
NTP synchronized: yes
```

Otherwise, you need to force NTP synchronze through the following steps:

- Stop ntp serivce: `systemctl stop ntpd`
- Add `server your.ntp.server.address` to the `/etc/ntp.conf` 's servers part.
- Force time synchronize: `ntpdate your.ntp.server.address`
- Restart ntp: `systemctl start ntpd`
- Run `systemctl enable ntpdate` to make sure running the `ntpdate` at boot time.

## 1.6. Configure firewall

Run the following commands to disable firewall on each host in the cluster:

```
systemctl disable firewalld
service firewalld stop
```

Run `systemctl status firewalld` to make sure firewall is disabled.

## 1.7. Disable SElinux

For each host in the cluster, change SELINUX value from **enhancing** to **disabled** in `/etc/selinux/config`

# 2. Set up a Local Repository for Ambari and HDP Stack

## 2.1.  Create and start an HTTP sever on the master host:

Install and start Apache Server through the following commands:

```
yum install -y httpd
service httpd restart
chkconfig httpd on
```

Make sure the directory `/var/www/html` has been created on the host.

## 2.2. Set up the local repository

- Download the tarball files for Ambari and HDP stacks through running the following commands:

```
wget http://public-repo-1.hortonworks.com/ambari/centos7/2.x/updates/2.7.3.0/ambari-2.7.3.0-centos7.tar.gz

wget http://public-repo-1.hortonworks.com/HDP/centos7/3.x/updates/3.1.0.0/HDP-3.1.0.0-centos7-rpm.tar.gz

wget http://public-repo-1.hortonworks.com/HDP-UTILS-1.1.0.22/repos/centos7/HDP-UTILS-1.1.0.22-centos7.tar.gz

wget http://public-repo-1.hortonworks.com/HDP-GPL/centos7/3.x/updates/3.1.0.0/HDP-GPL-3.1.0.0-centos7-gpl.tar.gz

```

The URLs can be obtained from [Ambari Repositories](https://docs.hortonworks.com/HDPDocuments/Ambari-2.7.3.0/bk_ambari-installation/content/ambari_repositories.html) and [HDP 3.1.0 Repositories](https://docs.hortonworks.com/HDPDocuments/Ambari-2.7.3.0/bk_ambari-installation/content/hdp_31_repositories.html)

- Untar and copy the files to `/var/www/html/`. For example,
  ```
  tar zxvf ambari-2.7.3.0-centos7.tar.gz -C /var/www/html/
  ```
- Then record the local base URLs which are needed for installing the cluster:

   ```
   Ambari: http://146.xxx.xxx.75/ambari/centos7/2.7.3.0-139/
   HDP: http://146.xxx.xxx.75/HDP/centos7/3.1.0.0-78/
   HDP-GPL: http://146.xxx.xxx.75/HDP-GPL/centos7/3.1.0.0-78/
   HDP-UTILS: http://146.xxx.xxx.75/HDP-UTILS/centos7/1.1.0.22/
   ```

**_Tips_**:

* make sure you can browser in the web browser;
* The path where you can see the `repodata` directory.

# 3. Install Ambari Server and Agent

## 3.1. Download Ambari repository

- Login to the `hadoop-master` host as `root`
- Check the repository URL from [Ambari Repository Links](https://docs.hortonworks.com/HDPDocuments/Ambari-2.7.3.0/bk_ambari-installation/content/ambari_repositories.html)
- Download Ambari repository file to the directory`/etc/yum.repos.d/`, through the following command:

```
wget -nv http://public-repo-1.hortonworks.com/ambari/centos7/2.x/updates/2.7.3.0/ambari.repo -O 		/etc/yum.repos.d/ambari.repo
```

- Edit the `ambari.repo` file and change the `baseurl` and `gpgkey` to the local repository obtained in step 2.2.
- Run `yum repolist` to confirm that the repository has been configured successfully. You should see `ambari-2.7.3.0-xxx` on the list.

See [Download Ambari Repository](https://docs.hortonworks.com/HDPDocuments/Ambari-2.7.3.0/bk_ambari-installation/content/download_the_ambari_repo_lnx7.html) for more information.

## 3.2. Install Ambari server

Install Ambari server on the master node through command:

```
yum install -y ambari-server
```

See [Install Ambari Server](https://docs.hortonworks.com/HDPDocuments/Ambari-2.7.3.0/bk_ambari-installation/content/install-ambari-server-rhel7.html) for more information.

## 3.3. Set up Ambari server

Set
`-Dhttp.proxyHost=<yourProxyHost> -Dhttp.proxyPort=<yourProxyPort> -Dhttps.proxyHost=<yourProxyHost> -Dhttps.proxyPort=<yourProxyPort>`
in the file `/var/lib/ambari-server/ambari-env.sh`

Run following command on the Ambari server host to start the setup process:

```
ambari-server setup
```

See [Set Up Ambari Server](https://docs.hortonworks.com/HDPDocuments/Ambari-2.7.3.0/bk_ambari-installation/content/set_up_the_ambari_server.html) for more information.

# 4. Install, Configure and Deploy the Cluster

## 4.1. Start the Ambari server
You can start the Ambari server through running:

```
ambari-server start
```

After the server starts successfully, you can login to the server with default username/password `admin/admin` at: `http://146.xxx.xxx.75:8080/`

## 4.2. Install HDP through installation wizard

Follow the steps of the Wizard to intall HDP:

- Step 0 - Get Started: give a name to your cluster, for example, `MyHadoop`

- Step 1 - Select Version: select `HDP-3.1`, `Use Local Repository`. Delete all other OS, leave Redhat7 only. Copy the local base URL to the places.

- Step 2 - Install Options settings:

  ![step2.png]({{site.baseurl}}/img/post/Step2.jpg)

- Step 3 - Confirm Hosts: it will automatically do the regiestration with the settings from Step 2.

- Step 4 - Choose Services: choose basic ones, you can add more later.

- Step 5 - Assign Masters: keep default

- Step 6 - Select all for the `Client` option.

# Known Errors

There are the four errors I encountered during the installation process.

**Error 1:** emtpty HDP Url: https://community.hortonworks.com/articles/231020/ambari-273-ambari-writes-empty-baseurl-values-writ.html

**Error 2:** Requires libtirpc-devel: https://community.hortonworks.com/idea/107386/libtirpc-devel-required.html
Run following commands on all hosts:

```
subscription-manager repos --enable=rhel-7-server-optional-rpms
yum install -y libtirpc-devel
```

**Error 3** Hive install failed because of mysql-connector-java.jar due to HTTP error: HTTP Error 404: Not Found
https://community.hortonworks.com/articles/170133/hive-start-failed-because-of-ambari-error-mysql-co.html
Run following commands on Ambari server:

```
yum install -y mysql-connector-java
ls -al /usr/share/java/mysql-connector-java.jar
cd /var/lib/ambari-server/resources/
ln -s /usr/share/java/mysql-connector-java.jar mysql-connector-java.jar

```

**Error 4** Empty Baseurl for Public Repository (No solution, might be proxy issue):
https://community.hortonworks.com/questions/45147/ambari-setup-select-stack-404-error.html
https://community.hortonworks.com/questions/35820/hdp-stack-repositories-not-found.html

**Error 5** Ambari Files View - Service hdfs check failed:
Solved: In order to fix it you should try creating a new "File View" instance by clicking on the "Create Instance" button on the File View. You can choose the default options to create the view instance (if it is not kerberized)
https://community.hortonworks.com/questions/128758/service-hdfs-check-failed-from-ambari.html?page=1&pageSize=10&sort=votes

https://community.hortonworks.com/questions/176438/ambari-files-view-service-hdfs-check-failed.html

https://community.hortonworks.com/questions/88350/service-hdfs-check-failed-1.html

https://community.hortonworks.com/questions/131550/ambari-views-fail-after-kerberos-enabled.html

# References

Official HDP 3.10 installation documentation: <https://docs.hortonworks.com/HDPDocuments/HDP3/HDP-3.1.0/index.html>

Apache Ambari Installation Document:
https://docs.hortonworks.com/HDPDocuments/Ambari-2.7.3.0/bk_ambari-installation/content/ch_Getting_Ready.html

Check Hortonworks Support Matrix to make sure product versions:
<https://supportmatrix.hortonworks.com/>

Using yum with a Proxy server:
https://docs.fedoraproject.org/en-US/Fedora_Core/3/html/Software_Management_Guide/sn-yum-proxy-server.html


text:
module Monorail
  class AuthToken < ActiveRecord::Base
    belongs_to :entity
    before_save :add_token, if: lambda { |at| at.token.blank? }

    scope :not_revoked, -> { where(revoked_at: nil) }

    def revoke!
      unless revoked_at.present?
        self.update_attributes!(revoked_at: Time.zone.now)
      end
    end

    def self.valid_auth?(entity, token)
      AuthToken.not_revoked.exists?(entity_id: entity.id, token: token)
    end

    def replace!
      AuthToken.transaction do
        revoke!
        entity.auth_tokens.create!(name: name)
      end
    end

    private

    def add_token
      self.token = SecureRandom.urlsafe_base64(32)
    end
  end
end


text:
#include "platform/CCPlatformConfig.h"
#if CC_TARGET_PLATFORM == CC_PLATFORM_TIZEN

#include "audio/tizen/AudioEngine-tizen.h"

// for native asset manager
#include <condition_variable>
#include <sys/types.h>
#include <sound_manager.h>
#include "audio/include/AudioEngine.h"
#include "base/CCDirector.h"
#include "base/CCScheduler.h"
#include "platform/CCFileUtils.h"
#include "platform/tizen/CCApplication-tizen.h"

#include <queue>

class AudioEngineThreadPool
{
public:
    AudioEngineThreadPool()
    : _running(true) {
        _threads = std::thread(std::bind(&AudioEngineThreadPool::threadFunc, this));
    }

    ~AudioEngineThreadPool()
    {
        _running = false;
        _sleepCondition.notify_one();
        _threads.join();
    }

    void addTask(const std::function<void()> &task) {
        _tasks.push(task);
        _sleepCondition.notify_one();
    }
private:
    bool _running;
    std::thread _threads;
    std::queue< std::function<void ()> > _tasks;

    void threadFunc(void) {
        while (true) {
            std::function<void ()> task = nullptr;

            if (_tasks.empty())
            {
                if (!_running)
                {
                    break;
                }
                std::unique_lock<std::mutex> lk(_sleepMutex);
                _sleepCondition.wait(lk);
                continue;
            }

            task = _tasks.front();

            task();

            _tasks.pop();
        }
    }

    std::mutex _sleepMutex;
    std::condition_variable _sleepCondition;
};

static AudioEngineThreadPool* _threadPool = nullptr;

using namespace cocos2d;
using namespace cocos2d::experimental;

static void sessionInterruptedCallback(sound_session_interrupted_code_e code, void *user_data)
{
	Application* app = Application::getInstance();
	if(app && app->isPaused())
	{
		return;
	}
	if(code == SOUND_SESSION_INTERRUPTED_COMPLETED)
	{
		AudioEngine::resumeAll();
	}
	else
	{
		AudioEngine::pauseAll();
		if (code == SOUND_SESSION_INTERRUPTED_BY_EARJACK_UNPLUG)
		{
			AudioEngine::resumeAll();
		}
	}
}

AudioPlayer::AudioPlayer()
    : _playerHandle(nullptr)
    , _finishCallback(nullptr)
    , _initCallback(nullptr)
    , _duration(0.0f)
    , _playOver(false)
    , _initSucceed(false)
{
}

static void _stopPlayer(player_h player)
{
    player_state_e state = PLAYER_STATE_NONE;
    player_get_state(player, &state);
    if (state == PLAYER_STATE_PLAYING || state == PLAYER_STATE_PAUSED)
    {
        player_stop(player);
    }
    player_unprepare(player);
}

static void _pausePlayer(player_h player)
{
    player_state_e state;
    player_get_state(player, &state);

    if(state == PLAYER_STATE_PLAYING)
    {
        player_pause(player);
    }
}

static void _resumePlayer(player_h player)
{
    player_state_e state;
    player_get_state(player, &state);

    if(state != PLAYER_STATE_PLAYING)
    {
        player_start(player);
    }
}

AudioPlayer::~AudioPlayer()
{
    _taskMutex.lock();
    _threadPool->addTask(std::bind(_stopPlayer, _playerHandle));
    _threadPool->addTask(std::bind(player_destroy, _playerHandle));
    _taskMutex.unlock();
}

void AudioPlayer::stopPlayer()
{
    _playOver = true;
}

static void completed_callback(void* user_data)
{
    AudioPlayer* player = (AudioPlayer*)user_data;
    player->stopPlayer();
}

void AudioPlayer::init(const std::string& fileFullPath, float volume, bool loop)
{
    do
    {
        player_h player;
        auto playerRet = player_create(&player);
        if(playerRet != PLAYER_ERROR_NONE)
        {
            log("Fail to create player.Error code:%d",playerRet);
            break;
        }

        _playerHandle = player;
        playerRet = player_set_uri(player, fileFullPath.c_str());
        if(playerRet != PLAYER_ERROR_NONE)
        {
            log("Fail to sets the data source for player.Error code:%d",playerRet);
            break;
        }

        player_set_volume(player, volume, volume);
        player_set_completed_cb(player, completed_callback, this);
        if (loop)
        {
            player_set_looping(player, true);
        }
        playerRet = player_prepare(player);
        if(playerRet != PLAYER_ERROR_NONE){
            log("Fail to prepares the media player for playback.Error code:%d",playerRet);
            break;
        }

        playerRet = player_start(player);
        if(playerRet != PLAYER_ERROR_NONE){
            log("Fail to starts playback.Error code:%d",playerRet);
            break;
        }

        _initSucceed = true;
    } while (0);

    if (_initCallback)
    {
        _initCallback();
    }
    _taskMutex.unlock();
}

//====================================================
AudioEngineImpl::AudioEngineImpl()
    : currentAudioID(0)
    , _lazyInitLoop(true)
{

}

AudioEngineImpl::~AudioEngineImpl()
{
    this->stopAll();

    if (_threadPool)
    {
        delete _threadPool;
        _threadPool = nullptr;
    }
    auto scheduler = Director::getInstance()->getScheduler();
    scheduler->unschedule(schedule_selector(AudioEngineImpl::update), this);
}

bool AudioEngineImpl::init()
{
    sound_manager_set_session_type(SOUND_SESSION_TYPE_MEDIA);
    sound_manager_set_media_session_option(SOUND_SESSION_OPTION_MIX_WITH_OTHERS_WHEN_START,
            SOUND_SESSION_OPTION_INTERRUPTIBLE_DURING_PLAY);
    sound_manager_set_media_session_resumption_option(SOUND_SESSION_OPTION_RESUMPTION_BY_SYSTEM_OR_MEDIA_PAUSED);

	sound_manager_set_session_interrupted_cb(sessionInterruptedCallback, this);

	if (!_threadPool)
	{
		_threadPool = new (std::nothrow) AudioEngineThreadPool();
	}

    return true;
}

int AudioEngineImpl::play2d(const std::string &filePath ,bool loop ,float volume)
{
    auto audioId = AudioEngine::INVALID_AUDIO_ID;

    do
    {
        audioId = currentAudioID++;

        auto& player = _audioPlayers[audioId];
        player._audioID = audioId;
        player._initCallback = std::bind(&AudioEngineImpl::initPlayerCallback,this,&player,audioId);

        player._taskMutex.lock();
        _threadPool->addTask(std::bind(&AudioPlayer::init,&player,FileUtils::getInstance()->fullPathForFilename(filePath), volume, loop));

        if (_lazyInitLoop) {
            _lazyInitLoop = false;

            auto scheduler = Director::getInstance()->getScheduler();
            scheduler->schedule(schedule_selector(AudioEngineImpl::update), this, 0.03f, false);
        }
    } while (0);

    return audioId;
}

void AudioEngineImpl::initPlayerCallback(AudioPlayer *player, int audioID)
{
    if (player->_initSucceed)
    {
        AudioEngine::_audioIDInfoMap[audioID].state = AudioEngine::AudioState::PLAYING;
    }
    else
    {
        _threadMutex.lock();
        _toRemoveAudioIDs.push_back(audioID);
        _threadMutex.unlock();
    }
}

void AudioEngineImpl::update(float dt)
{
    if (_threadMutex.try_lock()) {
        int audioID;
        size_t removeAudioCount = _toRemoveAudioIDs.size();
        for (size_t index = 0; index < removeAudioCount; ++index) {
            audioID = _toRemoveAudioIDs[index];
            auto playerIt = _audioPlayers.find(audioID);
            if (playerIt != _audioPlayers.end()) {
                if(playerIt->second._finishCallback) {
                    auto& audioInfo = AudioEngine::_audioIDInfoMap[audioID];
                    playerIt->second._finishCallback(audioID, *audioInfo.filePath);
                }
                _audioPlayers.erase(audioID);
                AudioEngine::remove(audioID);
            }
        }
        _threadMutex.unlock();
    }

    auto itend = _audioPlayers.end();
    for (auto iter = _audioPlayers.begin(); iter != itend; ++iter)
    {
        if(iter->second._playOver)
        {
            if (iter->second._finishCallback)
                iter->second._finishCallback(iter->second._audioID, *AudioEngine::_audioIDInfoMap[iter->second._audioID].filePath);

            AudioEngine::remove(iter->second._audioID);
            _audioPlayers.erase(iter);
            break;
        }
    }

    if(_audioPlayers.empty()){
        _lazyInitLoop = true;

        auto scheduler = Director::getInstance()->getScheduler();
        scheduler->unschedule(schedule_selector(AudioEngineImpl::update), this);
    }
}

void AudioEngineImpl::setVolume(int audioID,float volume)
{
    auto& player = _audioPlayers[audioID];
    player_set_volume(player._playerHandle, volume, volume);
}

void AudioEngineImpl::setLoop(int audioID, bool loop)
{
    auto& player = _audioPlayers[audioID];
    player_set_looping(player._playerHandle, loop);
}

void AudioEngineImpl::pause(int audioID)
{
    auto& player = _audioPlayers[audioID];
    _threadPool->addTask(std::bind(_pausePlayer, player._playerHandle));
}

void AudioEngineImpl::resume(int audioID)
{
    auto& player = _audioPlayers[audioID];
    _threadPool->addTask(std::bind(_resumePlayer, player._playerHandle));
}

void AudioEngineImpl::stop(int audioID)
{
    _audioPlayers.erase(audioID);
}

void AudioEngineImpl::stopAll()
{
     _audioPlayers.clear();
}

float AudioEngineImpl::getDuration(int audioID)
{
    int duration;
    auto& player = _audioPlayers[audioID];
    auto ret = player_get_duration(player._playerHandle, &duration);
    if(ret != PLAYER_ERROR_NONE)
    {
        log("Fail to get duration:%d",ret);
    }
    return duration / 1000.0f;
}

float AudioEngineImpl::getCurrentTime(int audioID)
{
    int currPos;
    auto& player = _audioPlayers[audioID];
    auto ret = player_get_play_position(player._playerHandle, &currPos);
    if(ret != PLAYER_ERROR_NONE)
    {
        CCLOG("Fail to get position:%d",ret);
    }
    return currPos / 1000.0f;
}

bool AudioEngineImpl::setCurrentTime(int audioID, float time)
{
    auto& player = _audioPlayers[audioID];
    int pos = 1000 * time;
    player_set_play_position(player._playerHandle, pos, true, NULL, NULL);

    return true;
}

void AudioEngineImpl::setFinishCallback(int audioID, const std::function<void (int, const std::string &)> &callback)
{
    _audioPlayers[audioID]._finishCallback = callback;
}

void AudioEngineImpl::preload(const std::string& filePath, std::function<void(bool)> callback)
{
    //TODO: implement preload on Tizen platform.
}

#endif


text:
layout: post
title : Can ImageNet features be used for getting pose?
---

I did my internship under _[Prof. Ian D Reid](http://www.robots.ox.ac.uk/~ian/)_ at _University of Adelaide_, I was supposed to work on a ConvNet architecture that can give us the depth and the pose at the same time! So in essence a full-fledged vSLAM system, using a Deep Learning framework. Should be possible, isn't it? Just imagine when you were a kid you were not taught geometry and concepts of optics and vision to move around, you just started moving around, bumping, falling and eventually learning how to walk! Can we train a DeepNet with a similar idea?

So after reading some papers, specifically [_SFM-Net: Learning Structure and Motion from Video_](https://arxiv.org/pdf/1704.07804.pdf) and [_Unsupervised Learning of depth and Ego-Motion from Video_](https://people.eecs.berkeley.edu/~tinghuiz/projects/SfMLearner/cvpr17_sfm_final.pdf) I got some ideas how we could implement this idea.

Well, both the research papers have been published by Google and have similar ideas to estimate the depth and pose.

The basic concept followed in both the research papers is as follows:

- _Two networks one for calculating the depth and other for determining the pose._
- _The estimated pose, and the estimated depth are used to calculate the optic flow, from src image to the target image._
- _This flow is then used to warp one image into another._
- _The better the warp, the better was our estimate of depth and pose._

There are significant differences, in architecture, loss and various other parameters however, the main idea remains the same.

After reading several other papers and even trying some methods that have been proposed,I and [Ravi Garg](https://scholar.google.co.in/citations?user=2dvDXjkAAAAJ&hl=en) had a significant question. **_Can we use features from ImageNet, directly or after fine-tuning, to get the pose?_** Just imagine, you are walking in the streets of a market, you tentatively get an idea of your location by cognitively understanding the complete scene as you move. So can we say that analogous to our understanding of what we are referring to "understanding the complete scene," could be the global features that we get from ImageNet? Worth a shot!

I feel the idea that we are thinking has been proven implicitly by [Learning to See by Moving](https://arxiv.org/abs/1505.01596). In their work they train the network in a supervised manner for pose and say that the features thus obtained can be used for classification. We are just going the other way round.

So we started working on establishing this idea. However, there were several steps involved before we could get this working. First, we needed something in [CAFFE](http://caffe.berkeleyvision.org/) to convert the estimated depth and the estimated pose into optic flow that could help us in warping one image into another. This warp would assist us in creating our unsupervised loss!

So we started making the layers in CAFFE. After struggling a lot with CUDA, we decided to write the layer in python, based on the implementation that has been given by Handa et al. in [GVNN](https://github.com/ankurhanda/gvnn). The GVNN library has been written in Torch, so we created an analogous Python Layer in CAFFE.

We created three layers (look into pygeometry.py):

- **SE3 Generator Layer:** This layer would be used for converting the 6 DoF's that we predict for getting the 4x4 Transformation Matrix
- **Transform 3D Grid:** You need to transform the Target Depth according to the estimated pose.
- **Pin Hole Camera Projection:** You need to project the transformed depth onto the image, or equivalently get the flow and add this flow to your source image to obtain your target image.

The mathematics behind it might seem very complicated. No worries, [Huangying Zhan](https://www.roboticvision.org/rv_person/huangying-zhan/) had prepared a nice documentation regarding the derivation of the formula. The complete documentation can be found here. [Spatial Transformer Network Formulation by Huangying Zhan](https://drive.google.com/file/d/0B3BMdiXdDUoKTzExVVctWHB2NTYzMTNROW85a0Jpa1ZybDNJ/view?usp=sharing)

In most of our articles we would be referring to them as "HuangYing's Layer" :)

So once we have the HuangYing's Layer we repilicated the experiments proposed by Learning to See by Moving, in order to sanity check our layers and setup. Now, we were confident enough that the layers that we are working! Hurrah!

## Network

A schematic view of the network that we used is as shown:

## What's the plan!

So, you see the idea was simple enough:

- _Get the global features for the Src and the Tgt images_
- _Concatenate the two features and pass them through a couple of FC's_
- _Get the 6 DoF's that represent the camera pose to move from Src image to Tgt image_
- _Use the ground truth depth of Tgt image (just for now) and the estimated pose to get the optic flow from Src to Tgt_
- _Use this optic flow to warp our Src image into Tgt image to get a warped Tgt image_
- _Consider the photometric loss between the warped target and the ground truth target image to train._

Key points:

- _We would be creating a mask as the ground truth depth map has too many holes (as in points whose depth values haven't been recorded are marked as zero in the dataset). We don't want to consider those points in our loss calculation._

- _For creating a training set we would be using a particular frame distance or a combination of several frame distances to get the src and the target image. Be careful we need to choose a frame distance that leads to a significan motion!Otherwise the network might learn just to predict zeros :P_

- _We are finetuning the AlexNet which is initialised with the weights of ImageNet clssification features._
- _The NYUDv2 does not give us the ground truth pose. So, we calculated the ground truth pose by running ORB-SLAM on the dataset._

## Tentative Results

So we trained the network and following were the results:

The warp error has gone down significantly. As a matter of fact the average loss, even if we could create a perfect warp using ground truth is of the order of almost 8000, because even if we create a perfect warp there would be points that would go out of the frame and we haven't considered a mask for them. In our training process we have reached a limit of almost 12000 during our training. The training curve seems to have sudden spikes possibly because of use of Adam as an optimiser. When we repeated the experiment with normal SGD (without momentum) there were no spikes, but the training was very slow. So we went on with this model!

The following figure shows a qualitative idea about the pose estimated by looking at the warp that we get from the estimated pose and the groud truth pose. Personally, I feel we can obtain better results if we could clean our data a bit and kind of enforce the loss to to give more weights to the edges!

## Early Fusion Vs Late Fusion

However, we felt we have tried late fusion as an experiment. There is a possibility that we lose too much of information before the concatenation step takes place. So, we wanted to try another experiment that would be based on early fusion of images. In this we would create a 6-channel input concatenating 2 images and then passing them through the AlexNet in order to estimate the pose.

Quantitatively on calculating the [RPE](http://www.rawseeds.org/rs/methods/view/11) for the two methods:

This was expected. However the good news is we did not lose to much even while doing late fusion. The rotational RMSE shows a significant improvement as was expected because a small rotational error leads to a large warp error, however that's not the case with translational error. Intuitively speaking, even when we warp images manually we first consider the roation transform for our ease and then consider the translational transform. Possibly decoupling the fc's and training first for rotation might help. We would consider such experiments some other time :)

Based on the above experiments we were having two choices:

1. We go for depth estimation and pose estimation using two images.
2. We decide to go for pose estimation based on two images and depth estimation based on a single images.

We would be going with the second choice as our aim was development of a MonoSLam system and single view depth estimation. Although, I believe that a potential architecture can be designed using the first idea.

So, this experiment proves that we can estimate the pose using an **unsupervised photometric loss** given we have a reasonable depth map of the target image. So now in order to establish the idea that a single network that can be used for monocular depth estimation we need answer yet another important question. **_Can depth features be used for pose estimation?_**.

For proving this idea I performed a very simple experiment, training a completely supervised network for depth and pose. I took a ResNet 50 1by2, added a bilinear upsampling layer upsamples the last feature map 32 times and trained this network on NYUDv2 datasets to get the deapth map. I knew I can't get good depth maps out of this framework. However, certainly the features that we have in the layers are depth features. After training the network for estimating depth, I froze the depth network, tapped the network from a suitable point, added a couple of FC's and trained the FC's for pose. I was able to train this network reasonbly to get a pose. The success of this experiment proves that depth features can be used for pose estimation as well.

TODO :  create a gist and add the link here so that one can visualise the network that was used!

However to get good results we need to improve our depth features significantly and hence it's architecture.

So we decided to work on depth network that we would be training in a supervised manner for now to get a reasonable depth map. Further we can try working on this network to implement the ideas of Unsupervised Photometric Loss to train it for depth as well as pose.

Cheers,
Harsh Agarwal


text:
package com.daimajia.swipedemo;

import android.animation.ObjectAnimator;
import android.view.View;

/**
 * Created by baha on 8/5/15.
 */
public class LikeBigAnimator extends  BaseViewAnimator {
    @Override
    protected void prepare(View target) {
        getAnimatorAgent().playTogether(
                ObjectAnimator.ofFloat(target, "scaleX", 1, 1.5f, 1.0f),
                ObjectAnimator.ofFloat(target, "scaleY", 1, 1.5f, 1.0f));
    }
}


text:
var $            = require('./$')
  , assertObject = require('./$.assert').obj;
module.exports = function(it){
  assertObject(it);
  return $.getSymbols ? $.getNames(it).concat($.getSymbols(it)) : $.getNames(it);
};


text:
<wicket:panel>

        <form wicket:id="personForm">
            <wicket:child />

                    Vezetéknév *
                    <input class="textinput" wicket:id="lastName"/>

                    Keresztnév *
                    <input class="textinput" wicket:id="firstName"/>

                    Becenév *
                    <input class="textinput" wicket:id="nickName"/>

                    Nem
                    <select class="gender_radios" wicket:id="gender"></select>

                    Születési dátum
                    <input class="textinput" wicket:id="dateOfBirth"/>

                    Cím
                    <input class="textinput" wicket:id="homeAddress"/>

                    Mail
                    <input class="textinput" wicket:id="emailAddress"/>

                    Mobil
                    <input class="textinput" wicket:id="cellPhone"/>

                    Weboldal
                    <input class="textinput" wicket:id="webpage"/>

                    Kollégium
                    <select wicket:id="dormitory"></select>

                    Szobaszám
                    <input class="textinput" wicket:id="room"/>

                    IM

                                <select wicket:id="imProtocol"/>
                                <input style="width: 180px;" class="textinput" wicket:id="imPresenceID"/>
                                <input type="submit" class="btn" wicket:id="imRemove" value="Töröl"/>

                                <input type="submit" class="btn" wicket:id="imAdd" value="Új"/>

                    Fotó
                    Fotó eltávolítása<input style="display: block;" class="textinput" wicket:id="fileInput" type="file"/>

                    Neptun

            <input class="btn" wicket:id="submitButton" type="submit" value="Módosítás"/>
        </form>

</wicket:panel>


text:
import { handleActions } from 'redux-actions'
import standardApi from '../Shared/reducers/standardApi'
import { INITIALIZE_STATE } from '../Shared/actions/initializeState'
import { LOGIN } from './actions'
import { LOGOFF } from '../Logoff/actions'

const initialState = { apiCalls: [], }

export default handleActions({
  [INITIALIZE_STATE]: (state, action) =>
    Object.assign({}, state, {
      username: action.payload.app.login.username,
    }
  ),
  [LOGIN.DATA]: (state, action) =>
    Object.assign({}, state, {
      username: action.payload.username,
    }
  ),
  [LOGOFF.DATA]: (state, action) =>
    Object.assign({}, state, {
      username: undefined,
    }
  ),
  [LOGIN.SENT]: standardApi.sent,
  [LOGIN.FAIL]: standardApi.fail,
  [LOGIN.DONE]: standardApi.done,
}, standardApi.initialState)


text:
* Features
	* Add `--healthcheck` to check the status of all the grabbers (online/offline).

* Fixes
	* Better detection for offline grabbers without crashing the app

* Grabbers
	* Torrentz: Fix parser

## 2.6.6 (2022-01-21)

* Improvements
	* The `--dry-run` option now prevents from persisting any configuration, including pending shows, not just the last execution date.
	* Performance improvements when running with the `-t` flag.

## 2.6.5 (2021-06-10)

* Fixes
	* Bump HTTP read timeout to avoid errors on new grabber.

## 2.6.4 (2021-06-07)

* Grabbers
	* Torrentz: added Torrentz2 grabber.

## 2.6.3 (2021-05-24)

* Fixes
	* Fix download full season feature (`-s/--season`), inadvertently broken in 2.6.2.

## 2.6.2 (2021-05-20)

* Fixes
	* Avoid duplicate downloads when using `-t` and `-o` together.

* Improvements
	* Add `-s` shorthand to the `--season` flag.

## 2.6.1 (2020-09-22)

* Features
	* Add `-q/--queue` to manually add an episode to the pending list.

* Improvements
	* Gracefully exits after option parsing errors.

* Grabbers
	* EZTV: now sorts torrents by number of seeders.
	* ThePirateBay: disable grabber.

## 2.5.5 (2019-04-06)

* Features
	* Allow user to configure include/exclude filters of the results.

* Improvements
	* The `-t/--tomorrow` flag now also performs a normal run if needed.

## 2.5.4 (2019-01-19)

* Features
	* Add `--season` to try and sequentially download all episodes of the given show, for the given season.
	* Add `-t/--tomorrow` to download the shows airing in the current day.

## 2.5.3 (2018-12-14)

* Fixes
	* Fix bug preventing clearing pending shows from working properly.

## 2.5.2 (2018-12-10)

* Fixes
	* Changing the configuration no longer resets the list of pending downloads.

## 2.5.1 (2018-12-03)

* Fixes
	* Fix pending shows handling.

## 2.5.0 (2018-12-02)

* Fixes
	* Fix not detecting successful MyEpisodes login.
	* Fix not detecting non-backwards compatible version changes.
	* Fix names not being sanitised when downloading through `-d/--download`
	* Fix names not being sanitised when downloading through `-f/--file`

* Features
	* Persist list of episodes not found in the configuration.
	* Add `-p/--pending` to show the list of pending downloads.
	* Add `--clear-pending` to empty the list of pending downloads.

* Grabbers
	* KAT: disable grabber.

## 2.4.7 (2018-10-05)

* Grabbers
	* KAT: re-enable grabber, updating rules for new CSS structure.

## 2.4.6 (2018-07-19)

* Grabbers
	* KAT: disable grabber.

## 2.4.5 (2018-05-04)

* Grabbers
	* TorrentAPI: now sorts by seeders.

## 2.4.4 (2018-03-22)

* Grabbers
	* TorrentAPI: fix timeouts.

## 2.4.3 (2018-03-22)

* Fixes
	* Fix new trackers' availability not being checked before attempting to use them.

## 2.4.2 (2018-03-14)

* Fixes
	* Fix bug where the wrong grabber was being removed when offline.

## 2.4.1 (2018-03-12)

* Fixes
	* Fix bug accessing wrong variable when a grabber was offline.

## 2.4.0 (2018-03-04)

* Fixes
	* Fix not reporting "Nothing to download" when it was due to ignored shows.
	* Fix downloading from file not handling newlines well.

* Improvements
	* Reset grabber order after every download.

* Grabbers
	* KAT: fix parsing rules.
	* ThePirateBay: change proxy URL.

## 2.3.0 (2017-09-24)

* Improvements
	* Store configuration file as JSON instead of Marshaling the hash.
	* Use custom User-Agent for all connections.

* Grabbers
	* ThePirateBay: change proxy URL.

## 2.2.2 (2017-08-06)

* Fixes
	* Fix date not being saved in the configuration.

## 2.2.1 (2017-08-03)

* Add LICENSE.md to repo

* Fixes
	* Fix default grabber not being properly selected.

* Improvements
	* Add support for OS X.

* Grabbers
	* TorrentAPI: add temporary workaround for CloudFlare errors.

## 2.2.0 (2017-08-01)

* Add LICENSE information to Gemfile
* Move default path to configuration file to `~/.config/download_tv/config`

* Improvements
	* Improve detection of ignored shows.

## 2.1.1 (2017-07-31)

* Improvements
	* Minor improvements to configuration file handling.

## 2.1.0 (2017-07-21)

* Features
	* Add `-g/--grabber` to select which grabber to use for finding links.
	* Add `--show-grabbers` to list available options.
	* Add `-v` to print gem version.

* Grabbers
	* KAT: added KickAssTorrents grabber.

## 2.0.6 (2017-07-11)

* Improvements
	* Remove colons from the show name for searching.

## 2.0.5 (2017-06-17)

* Features
	* Add `--show-config` to print contents of the configuration file in a readable way.

* Fixes
	* Fix download from file not properly finding the path.

## 2.0.3 (2017-06-07)

* Fixes
	* Fix missing arguments breaking the main entrypoint.
	* Fix ignored shows list not handling multiple comma-separated shows.
	* Minor fixes on configuration file.

## 2.0.0 (2017-06-07)

* Features
	* Add new configuration system.

## 1.0.0 (2017-06-07)

Initial published version.


text:
rem GameBoy Advance Game make file

path=c:\gbadev\tools\devkitadv\bin

gcc -c -O3 -mthumb -mthumb-interwork main.c
gcc -mthumb -mthumb-interwork -o gbagame.elf main.o

objcopy -O binary gbagame.elf gbagame.gba

pause


text:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">

<title>T-Index</title>
<meta name="date" content="2015-04-14">
<link rel="stylesheet" type="text/css" href="../stylesheet.css" title="Style">

JavaScript is disabled on your browser.

Overview

Package

Class

Use

Tree

Deprecated

Index

Help

Prev Letter

Next Letter

Frames

No Frames

All Classes

A B C D E F G H I N O P R S T U V W

T

testCheckConnection() - Method in class com.streakapi.crm.TestStreakAPI

testCreateTargetHost() - Method in class com.streakapi.crm.TestStreakAPI

testGetCurrentUser() - Method in class com.streakapi.crm.TestStreakAPI

TestStreakAPI - Class in com.streakapi.crm

TestStreakAPI() - Constructor for class com.streakapi.crm.TestStreakAPI

Thread - Class in com.streakapi.crm.datatype

Thread() - Constructor for class com.streakapi.crm.datatype.Thread

toString() - Method in class com.streakapi.crm.datatype.AclEntry

toString() - Method in class com.streakapi.crm.datatype.Box

toString() - Method in class com.streakapi.crm.datatype.BoxField

toString() - Method in class com.streakapi.crm.datatype.Comment

toString() - Method in class com.streakapi.crm.datatype.Field

toString() - Method in class com.streakapi.crm.datatype.Fields

toString() - Method in class com.streakapi.crm.datatype.File

toString() - Method in class com.streakapi.crm.datatype.Owner

toString() - Method in class com.streakapi.crm.datatype.Pipeline

toString() - Method in class com.streakapi.crm.datatype.Reminder

toString() - Method in class com.streakapi.crm.datatype.Search

toString() - Method in class com.streakapi.crm.datatype.Snippet

toString() - Method in class com.streakapi.crm.datatype.Stage

toString() - Method in class com.streakapi.crm.datatype.Stages

toString() - Method in class com.streakapi.crm.datatype.Thread

toString() - Method in class com.streakapi.crm.datatype.User

A B C D E F G H I N O P R S T U V W

Overview

Package

Class

Use

Tree

Deprecated

Index

Help

Prev Letter

Next Letter

Frames

No Frames

All Classes


text:
@interface EXHeadlessAppRecord ()

@property (nonatomic, assign) BOOL isBridgeAlreadyLoading;
@property (nonatomic, strong) void(^callback)(BOOL success, NSError * _Nullable error);

@end

@implementation EXHeadlessAppRecord

@synthesize appManager = _appManager;
@synthesize appLoader = _appLoader;

- (nonnull instancetype)initWithManifestUrl:(NSURL *)manifestUrl
                                   callback:(void(^)(BOOL success, NSError * _Nullable error))callback
{
  if (self = [super init]) {
    _callback = callback;
    _isBridgeAlreadyLoading = NO;

    _appManager = [[EXReactAppManager alloc] initWithAppRecord:self initialProps:nil];
    [_appManager setIsHeadless:YES];
    [_appManager setDelegate:self];

    _appLoader = [[EXAppLoader alloc] initWithManifestUrl:manifestUrl];

    [_appLoader setDelegate:self];
    [_appLoader request];
  }
  return self;
}

- (void)rebuildBridge
{
  if (!_isBridgeAlreadyLoading) {
    _isBridgeAlreadyLoading = YES;
    [_appManager rebuildBridge];
  }
}

- (void)maybeExecuteCallbackWithSuccess:(BOOL)success error:(nullable NSError *)error
{
  if (_callback != nil) {
    _callback(success, error);
    _callback = nil;
  }
}

# pragma mark - EXAppRecordInterface

- (void)invalidate
{
  [_appManager invalidate];
  _appLoader = nil;
  _appManager = nil;
}

# pragma mark - EXReactAppManagerUIDelegate

- (void)reactAppManager:(EXReactAppManager *)appManager failedToLoadJavaScriptWithError:(NSError *)error
{
  [self maybeExecuteCallbackWithSuccess:NO error:error];
}

- (void)reactAppManagerIsReadyForLoad:(EXReactAppManager *)appManager
{
  [self maybeExecuteCallbackWithSuccess:YES error:nil];
}

- (void)reactAppManagerDidInvalidate:(EXReactAppManager *)appManager {}
- (void)reactAppManagerFinishedLoadingJavaScript:(EXReactAppManager *)appManager {}
- (void)reactAppManagerStartedLoadingJavaScript:(EXReactAppManager *)appManager {}

# pragma mark - EXAppLoaderDelegate

- (void)appLoader:(EXAppLoader *)appLoader didLoadOptimisticManifest:(NSDictionary *)manifest
{
  dispatch_async(dispatch_get_main_queue(), ^{
    [self rebuildBridge];
  });
}

- (void)appLoader:(EXAppLoader *)appLoader didFinishLoadingManifest:(NSDictionary *)manifest bundle:(NSData *)data
{
  dispatch_async(dispatch_get_main_queue(), ^{
    [self rebuildBridge];
    if (self->_appManager.status == kEXReactAppManagerStatusBridgeLoading) {
      [self->_appManager appLoaderFinished];
    }
  });
}

- (void)appLoader:(EXAppLoader *)appLoader didFailWithError:(NSError *)error
{
  if (_appManager.status == kEXReactAppManagerStatusBridgeLoading) {
    [_appManager appLoaderFailedWithError:error];
  }
  [self maybeExecuteCallbackWithSuccess:NO error:error];
}

- (void)appLoader:(EXAppLoader *)appLoader didLoadBundleWithProgress:(EXLoadingProgress *)progress {}
- (void)appLoader:(EXAppLoader *)appLoader didResolveUpdatedBundleWithManifest:(NSDictionary *)manifest isFromCache:(BOOL)isFromCache error:(NSError *)error {}

@end


text:
package de.bornemisza.ds.users;

import java.util.HashSet;
import java.util.Set;

import javax.ws.rs.ApplicationPath;
import javax.ws.rs.core.Application;

import org.glassfish.jersey.jackson.JacksonFeature;

import de.bornemisza.ds.users.endpoint.Users;

/**
 * Configures a JAX-RS endpoint.
 */
@ApplicationPath("/")
public class JAXRSConfiguration extends Application {

    public JAXRSConfiguration() { }

    @Override
    public Set<Class<?>> getClasses() {
        Set<Class<?>> classes = new HashSet<>();

        classes.add(Users.class);

        classes.add(JacksonFeature.class);

        return classes;
    }

    public static String TOPIC_NEW_USER_ACCOUNT = "NewUserAccount";
    public static String MAP_NEW_USER_ACCOUNT = "NewUserAccount";
    public static String TOPIC_CHANGE_EMAIL_REQUEST = "ChangeEmailRequest";
    public static String MAP_CHANGE_EMAIL_REQUEST = "ChangeEmailRequest";
    public static String MAP_USERID_SUFFIX = "_userId";
    public static String MAP_UUID_SUFFIX = "_uuid";

}


text:
**References:**
- https://en.wikipedia.org/wiki/Autoregressive_integrated_moving_average
- https://www.rdocumentation.org/packages/forecast/versions/8.4/topics/Arima

~~~~
arima(x, order = c(0L, 0L, 0L),
      seasonal = list(order = c(0L, 0L, 0L), period = NA),
      xreg = NULL, include.mean = TRUE,
      transform.pars = TRUE,
      fixed = NULL, init = NULL,
      method = c("CSS-ML", "ML", "CSS"), n.cond,
      SSinit = c("Gardner1980", "Rossignol2011"),
      optim.method = "BFGS",
      optim.control = list(), kappa = 1e6)
~~~~


text:
package me.chanjar.jms.base.sender.disruptor;

import com.lmax.disruptor.EventTranslatorOneArg;
import com.lmax.disruptor.RingBuffer;

import javax.jms.JMSException;

public class PayloadEventProducer {

  private final RingBuffer<PayloadEvent> ringBuffer;

  private static final EventTranslatorOneArg<PayloadEvent, Object> TRANSLATOR =
      (event, sequence, requestDto) -> event.setPayload(requestDto);

  public PayloadEventProducer(RingBuffer<PayloadEvent> ringBuffer) {
    this.ringBuffer = ringBuffer;
  }

  public void onData(Object payload) throws JMSException {

    ringBuffer.publishEvent(TRANSLATOR, payload);

  }

}


text:
import bpy

objs = bpy.context.selected_objects
def delete_uv_groups():
    for obj in objs:
        bpy.context.scene.objects.active = obj
        obj.select = True
        if obj.type == 'MESH':
            uv_textures = obj.data.uv_textures
            for i in range(0, len(uv_textures)):
                uv_textures.remove(uv_textures[0])
            obj.select = False
        else:
            obj.select = False
            continue
delete_uv_groups()


text:
// Python Tools for Visual Studio
// Copyright(c) Microsoft Corporation
// All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the License); you may not use
// this file except in compliance with the License. You may obtain a copy of the
// License at http://www.apache.org/licenses/LICENSE-2.0
//
// THIS CODE IS PROVIDED ON AN  *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS
// OF ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY
// IMPLIED WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE,
// MERCHANTABILITY OR NON-INFRINGEMENT.
//
// See the Apache Version 2.0 License for specific language governing
// permissions and limitations under the License.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.InteropServices;
using Microsoft.PythonTools.Common;
using Microsoft.PythonTools.Infrastructure;
using Microsoft.PythonTools.Interpreter;
using Microsoft.PythonTools.Project;
using Microsoft.VisualStudio;
using Microsoft.VisualStudio.Shell;
using Microsoft.VisualStudio.Shell.Interop;
using Task = System.Threading.Tasks.Task;

namespace Microsoft.PythonTools.Environments {
    /// <summary>
    /// This keeps track of selection and other changes in the IDE and caches
    /// the data to be displayed in the environment status bar switcher,
    /// such as the list of all environments, the current environment,
    /// and the current project.
    /// </summary>
    sealed class EnvironmentSwitcherManager : IVsSelectionEvents, IDisposable {
        private readonly IServiceProvider _serviceProvider;
        private readonly IInterpreterOptionsService _optionsService;
        private readonly IInterpreterRegistryService _registryService;
        private readonly IVsMonitorSelection _monitorSelection;
        private readonly IVsShell _shell;
        private readonly IPythonWorkspaceContextProvider _pythonWorkspaceService;
        private uint _selectionEventsCookie;
        private IVsHierarchy _previousHier;
        private bool _isInitialized;
        private bool _isPythonWorkspace;

        public event EventHandler EnvironmentsChanged;

        public EnvironmentSwitcherManager(IServiceProvider serviceProvider) {
            _serviceProvider = serviceProvider ?? throw new ArgumentNullException(nameof(serviceProvider));
            _optionsService = serviceProvider.GetComponentModel().GetService<IInterpreterOptionsService>();
            _registryService = serviceProvider.GetComponentModel().GetService<IInterpreterRegistryService>();
            _monitorSelection = serviceProvider.GetService(typeof(IVsMonitorSelection)) as IVsMonitorSelection;
            _shell = serviceProvider.GetService(typeof(SVsShell)) as IVsShell;
            _pythonWorkspaceService = serviceProvider.GetComponentModel().GetService<IPythonWorkspaceContextProvider>();
            AllFactories = Enumerable.Empty<IPythonInterpreterFactory>();
        }

        public bool IsClosing { get; set; }

        /// <summary>
        /// Returns whether a Python project, workspace or document is currently
        /// selected / active. Used to control the visibility of the status bar
        /// switcher.
        /// </summary>
        public bool IsInPythonMode => Context != null;

        /// <summary>
        /// Interpreter factory that is currently applicable to the current
        /// project, workspace, or loose document. This may be null even when
        /// <see cref="IsInPythonMode"/> is <c>true</c>, for example when no
        /// environment is found on the machine.
        /// </summary>
        public IPythonInterpreterFactory CurrentFactory { get; private set; }

        /// <summary>
        /// List of factories to present to the user, based on the current
        /// project, workspace or loose document.
        /// </summary>
        /// <remarks>
        /// For a project, this is the list of environments referenced by the
        /// project. For a loose document or workspace, this is the list of all
        /// environments found on the machine.
        /// </remarks>
        public IEnumerable<IPythonInterpreterFactory> AllFactories { get; private set; }

        public IEnvironmentSwitcherContext Context { get; private set; }

        public void Initialize() {
            if (_isInitialized) {
                return;
            }

            _isInitialized = true;

            _optionsService.DefaultInterpreterChanged += OnDefaultInterpreterChanged;
            _registryService.InterpretersChanged += OnInterpretersChanged;
            _pythonWorkspaceService.WorkspaceClosing += OnWorkspaceClosing;
            _pythonWorkspaceService.WorkspaceInitialized += OnWorkspaceInitialized;
            _monitorSelection.AdviseSelectionEvents(this, out _selectionEventsCookie);

            SetInitialContext();
        }

        public void Dispose() {
            if (_isInitialized) {
                _optionsService.DefaultInterpreterChanged -= OnDefaultInterpreterChanged;
                _registryService.InterpretersChanged -= OnInterpretersChanged;
                _pythonWorkspaceService.WorkspaceClosing -= OnWorkspaceClosing;
                _pythonWorkspaceService.WorkspaceInitialized -= OnWorkspaceInitialized;
                _monitorSelection.UnadviseSelectionEvents(_selectionEventsCookie);
            }

            if (Context != null) {
                Context.EnvironmentsChanged -= OnInterpretersChanged;
                Context.Dispose();
            }
        }

        public Task SwitchToFactoryAsync(IPythonInterpreterFactory factory) {
            return Context != null ? Context.ChangeFactoryAsync(factory) : Task.CompletedTask;
        }

        private void OnWorkspaceClosing(object sender, EventArgs e) {
            _isPythonWorkspace = false;
            RefreshFactories();
        }

        private void OnWorkspaceInitialized(object sender, EventArgs e) {
            _isPythonWorkspace = false;
            RefreshFactories();
        }

        private void OnInterpretersChanged(object sender, EventArgs e) {
            RefreshFactories();
        }

        private void OnDefaultInterpreterChanged(object sender, EventArgs e) {
            RefreshFactories();
        }

        private void RefreshFactories() {
            if (IsClosing) {
                return;
            }

            AllFactories = Context?.AllFactories ?? Enumerable.Empty<IPythonInterpreterFactory>();
            CurrentFactory = Context?.CurrentFactory;
            EnvironmentsChanged?.Invoke(this, EventArgs.Empty);

            UIContext.FromUIContextGuid(CommonGuidList.guidPythonToolbarUIContext).IsActive = Context != null;
        }

        private void Reset() {
            ReplaceContext(null);
            RefreshFactories();
        }

        private void SetInitialContext() {
            IntPtr hierPtr = IntPtr.Zero;
            IntPtr containerPtr = IntPtr.Zero;
            try {
                _monitorSelection.GetCurrentSelection(out hierPtr, out uint item, out _, out containerPtr);
                var hier = (hierPtr != IntPtr.Zero ? Marshal.GetObjectForIUnknown(hierPtr) : null) as IVsHierarchy;
                if (hier != null) {
                    HandleSelection(hier, item);
                } else if (ErrorHandler.Succeeded(_monitorSelection.GetCurrentElementValue(VSConstants.DocumentFrame, out object elementVal))) {
                    HandleElementValue(elementVal);
                } else {
                    Reset();
                }
            } finally {
                if (hierPtr != IntPtr.Zero) {
                    Marshal.Release(hierPtr);
                }
                if (containerPtr != IntPtr.Zero) {
                    Marshal.Release(containerPtr);
                }
            }
        }

        private void UpdateContext(PythonProjectNode project, string filePath) {
            var isPythonFile = ModulePath.IsPythonSourceFile(filePath);

            if (project != null) {
                ReplaceContext(new EnvironmentSwitcherProjectContext(project));
            } else if (_pythonWorkspaceService.Workspace != null && (_isPythonWorkspace || isPythonFile)) {
                _isPythonWorkspace = true;
                ReplaceContext(new EnvironmentSwitcherWorkspaceContext(_serviceProvider, _pythonWorkspaceService.Workspace));
            } else if (isPythonFile) {
                ReplaceContext(new EnvironmentSwitcherFileContext(_serviceProvider, filePath));
            } else {
                ReplaceContext(null);
            }

            RefreshFactories();
        }

        private void ReplaceContext(IEnvironmentSwitcherContext newContext) {
            if (Context != null) {
                Context.EnvironmentsChanged -= OnInterpretersChanged;
                Context.Dispose();
            }

            Context = newContext;

            if (Context != null) {
                Context.EnvironmentsChanged += OnInterpretersChanged;
            }
        }

        private void HandleSelection(IVsHierarchy pHierNew, uint itemidNew) {
            try {
                if (pHierNew != null &&
                    (ErrorHandler.Succeeded(pHierNew.GetCanonicalName(itemidNew, out string filePath)) ||
                    _pythonWorkspaceService.Workspace != null)) {
                    // We can get called multiple times for the same project,
                    // only process the first time it changes. It doesn't matter
                    // if it's a different document, since they all use the same
                    // environment(s).
                    if (pHierNew != _previousHier) {
                        var project = pHierNew.GetPythonProject();
                        UpdateContext(project, filePath);
                    }
                } else if (!_isPythonWorkspace) {
                    Reset();
                }

                _previousHier = pHierNew;
            } catch (Exception ex) when (!ex.IsCriticalException()) {
                // Safety catch - selection can be from unknown or untested packages/project types
                Reset();
            }
        }

        private void HandleElementValue(object varValueNew) {
            try {
                var frame = varValueNew as IVsWindowFrame;
                if (frame != null && ErrorHandler.Succeeded(frame.GetProperty((int)__VSFPROPID.VSFPROPID_pszMkDocument, out object filePathObj))) {
                    object hierObj;
                    if (ErrorHandler.Failed(frame.GetProperty((int)__VSFPROPID.VSFPROPID_Hierarchy, out hierObj))) {
                        hierObj = null;
                    }

                    var hier = hierObj as IVsHierarchy;
                    var filePath = filePathObj as string;
                    var project = hier?.GetPythonProject();
                    UpdateContext(project, filePath);
                } else {
                    _previousHier = null;
                    Reset();
                }
            } catch (Exception ex) when (!ex.IsCriticalException()) {
                // Safety catch - selection can be from unknown or untested packages/project types
                Reset();
            }
        }

        int IVsSelectionEvents.OnSelectionChanged(IVsHierarchy pHierOld, uint itemidOld, IVsMultiItemSelect pMISOld, ISelectionContainer pSCOld, IVsHierarchy pHierNew, uint itemidNew, IVsMultiItemSelect pMISNew, ISelectionContainer pSCNew) {
            HandleSelection(pHierNew, itemidNew);

            return VSConstants.S_OK;
        }

        int IVsSelectionEvents.OnElementValueChanged(uint elementid, object varValueOld, object varValueNew) {
            if (VSConstants.DocumentFrame == elementid) {
                HandleElementValue(varValueNew);
            }

            return VSConstants.S_OK;
        }

        int IVsSelectionEvents.OnCmdUIContextChanged(uint dwCmdUICookie, int fActive) {
            return VSConstants.S_OK;
        }
    }
}


text:
import { Statistic } from '../statistics/generate';

/**
 * the main logic for the optimization
 *
 * Example with two selectors 'a-very-long-selector' and 'short-selector':
 *
 * Apperiances:
 *   'short-selector': 10 times
 *   'a-very-long-selector': 2 times
 *
 * Sort them by occorrunce count
 */
// eslint-disable-next-line @typescript-eslint/no-unused-vars, no-unused-vars
const sortSelectors = (selectors: string[], statistic: Statistic): string[] => {
  const { unused, usageCount } = statistic;

  const weightedSelectors = selectors
    .map((selector) => [selector, usageCount[selector] || 0] as const)
    // sort based on weights
    .sort((a, b) => (
      b[1] - a[1]
    ))
    .map(([selector]) => selector);

  // put unsuded to the end
  return [...weightedSelectors, ...unused];
};

export default sortSelectors;


text:
  float: right
}

#crystal-knows-heading {
    display: inline-block
}

img#crystal-logo {
    width: 10%;
    display: inline-block;
    float: left;
    margin: 0 5px 0 0
}