text:
const path = require('path');
const knex = require('knex')({
  client: 'postgresql',
  connection: {
    database: 'hackdin'
  }
});

const db = require('bookshelf')(knex);

db.knex.schema.hasTable('projects').then(exists => {
  if (!exists) {
    db.knex.schema.createTable('projects', project => {
      project.increments('id').primary();
      project.string('title').unique();
      project.string('description');
      project.string('image');
      project.string('projectUrl');
      project.string('deployedUrl');
      project.integer('school_id').unsigned().references('id').inTable('schools');
      // project.integer('visits');
      project.timestamps();
    }).then(table => {
      console.log('Created Table', table);
    });
  }
});

db.knex.schema.hasTable('engineers').then(exists => {
  if (!exists) {
    db.knex.schema.createTable('engineers', engineer => {
      engineer.increments('id').primary();
      engineer.string('gitHandle').unique();
      engineer.string('name');
      engineer.string('email');
      engineer.text('bio');
      engineer.string('githubUrl');
      engineer.string('linkedinUrl');
      engineer.string('image');
      engineer.integer('school_id').unsigned().references('id').inTable('schools');
      // engineer.integer('visits');
      engineer.timestamps();
    }).then(table => {
      console.log('Created Table', table);
    });
  }
});

db.knex.schema.hasTable('schools').then(exists => {
  if (!exists) {
    db.knex.schema.createTable('schools', school => {
      school.increments('id').primary();
      school.string('schoolName').unique();
      school.string('url');
      // school.timestamps();
    }).then(table => {
      console.log('Created Table', table);
    });
  }
});

db.knex.schema.hasTable('technologies').then(exists => {
  if (!exists) {
    db.knex.schema.createTable('technologies', technology => {
      technology.increments('id').primary();
      technology.string('techName').unique();
    }).then(table => {
      console.log('Created Table', table);
    });
  }
});

// Join table
db.knex.schema.hasTable('projects_engineers').then(exists => {
  if (!exists) {
    db.knex.schema.createTable('projects_engineers', projEng => {
      projEng.increments('id').primary();
      projEng.integer('project_id').unsigned().references('id').inTable('projects');
      projEng.integer('engineer_id').unsigned().references('id').inTable('engineers');
    }).then(table => {
      console.log('Created Table', table);
    });
  }
});

db.knex.schema.hasTable('projects_technologies').then(exists => {
  if (!exists) {
    db.knex.schema.createTable('projects_technologies', projTech => {
      projTech.increments('id').primary();
      projTech.integer('project_id').unsigned().references('id').inTable('projects');
      projTech.integer('technology_id').unsigned().references('id').inTable('technologies');
    }).then(table => {
      console.log('Created Table', table);
    });
  }
});

module.exports = db;


text:
layout: blip
name: "AWS Simple Notification Service (SNS)"
status: "Assess"
first_added: "July 2016"
site: https://aws.amazon.com/sns
yammerid: 15628703
---
PubSub in AWS. Can also be used for sending text and email messaging (though we currently use SendGrid for that)

redpajama_set_name: RedPajamaGithub


text:
package com.kbeanie.multipicker.sample;

import android.net.Uri;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.util.Log;
import android.widget.ImageView;

import com.bumptech.glide.Glide;
import com.kbeanie.multipicker.api.entity.ChosenImage;

import java.io.File;

/**
 * Created by kbibek on 3/3/16.
 */
public class ImagePreviewActivity extends AbActivity {
    private ImageView ivImageGlide;
    private String uri;
    private String mimeType;

    private ChosenImage image;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_image_preview);

        uri = getIntent().getExtras().getString("uri");
        mimeType = getIntent().getExtras().getString("mimetype");
        image = getIntent().getExtras().getParcelable("chosen");

        ivImageGlide = (ImageView) findViewById(R.id.ivImageGlide);

        ivImageGlide.postDelayed(new Runnable() {
            @Override
            public void run() {
                displayImage();
            }
        }, 500);
    }

    private void displayImage() {
        int width = ivImageGlide.getWidth();
        int height = ivImageGlide.getHeight();
        Log.d(getClass().getSimpleName(), "displayImage: " + width + " x " + height);

        Glide.with(this)
                .load(Uri.fromFile(new File(uri)))
                .placeholder(R.drawable.ic_image)
                .into(ivImageGlide);
    }
}


text:
// Copyright (c) 2016 Vadim Macagon
// MIT License, see LICENSE file for full terms.

import * as mobx from 'mobx';
import * as ipc from '../common/ipc/source-dir-registry';
import { PROJECT_IPC_KEY } from '../common/ipc/keys';
import { RendererIPCDispatcher, IRendererDispatcherNode } from './ipc-dispatcher';

/**
 * Provides access to the list of all currently open source directories.
 *
 * The list of source directories is actually managed by [[Project]] in the main process,
 * so to modify the list from a renderer process execute an [[OpenSourceDirCommand]].
 */
export class RendererSourceDirRegistry {
  /** Observable list of currently open source directories. */
  @mobx.observable
  dirPaths: string[] = [];

  private _id: number;
  private _ipcDispatcher: RendererIPCDispatcher;
  private _dispatcherNode: IRendererDispatcherNode;

  constructor(ipcDispatcher: RendererIPCDispatcher) {
    this._ipcDispatcher = ipcDispatcher;

    this._onSync = this._onSync.bind(this);
    this._onUpdate = this._onUpdate.bind(this);

    this._dispatcherNode = this._ipcDispatcher.createNode();
    this._dispatcherNode.onMessage(PROJECT_IPC_KEY, ipc.IPC_SYNC, this._onSync);
    this._dispatcherNode.onMessage(PROJECT_IPC_KEY, ipc.IPC_UPDATE, this._onUpdate);
  }

  dispose(): void {
    if (this._dispatcherNode) {
      this._dispatcherNode.dispose();
      this._dispatcherNode = null;
    }
    this._ipcDispatcher = null;
  }

  private _onSync(msg: ipc.ISyncMessage): void {
    // Assigning a new array to an observable property seems to create a new observable array
    // rather than replacing the contents of the old observable array, which means that a React
    // component that observes this array will not re-render, which is somewhat unexpected
    // behavior. To ensure components are always re-rendered use replace() instead of assignment.
    if (mobx.isObservableArray(this.dirPaths)) {
      this.dirPaths.replace(msg.dirPaths);
    }
  }

  private _onUpdate(msg: ipc.IUpdateMessage): void {
    switch (msg.kind) {
      case 'add':
        this.dirPaths.push(...msg.dirPaths);
        break;
      default:
        throw new Error('Malformed message.');
    }
  }
}


text:
import declare from 'dojo/_base/declare';
import _WidgetBase from 'dijit/_WidgetBase';
import _TemplatedMixin from 'dijit/_TemplatedMixin';
import template from './templates/StyleChooser.html'; // Rollup string plugin
import teamColors from './resources/teams';
import baseStyleFile from './resources/baseStyle';
import strings from 'dojo/i18n!./nls/strings';
import domConstruct from 'dojo/dom-construct';
import on from 'dojo/on';
import AgolUtils from './agol';
import clone from '../../node_modules/lodash-es/cloneDeep';
import CartoQuick from '../../node_modules/carto-quick/src/index';

export default declare([_WidgetBase, _TemplatedMixin], {

  baseClass: 'style-chooser',
  nls: strings,
  templateString: template,

  // set panel header title
  _setTitleAttr: {
    node: 'titleNode',
    type: 'innerHTML'
  },

  postCreate() {
    this.inherited(arguments);
    this.populateSelect(this.styleSelect, teamColors);
    on(this.styleSelect, 'change', (evt) => {
      // if we are on the first (blank) item, disable. otherwise enable
      if (evt.target.value == -1) { // eslint-disable-line
        this.addToArcgisAccount.disabled = true;
      } else {
        this.addToArcgisAccount.disabled = false;
        this.currentPermutations = this.getAllPermutations(teamColors[evt.target.value].colors.hex);
        this.currentPermutationIndex = 0;
        this.tileLayer.loadStyle(
          CartoQuick.getStyle(
            this.currentPermutations[this.currentPermutationIndex],
            clone(baseStyleFile)
          )
        );
      }
    });

    on(this.randomizeColorsButton, 'click', () => {
      this.currentPermutationIndex = this.currentPermutationIndex + 1;
      if (this.currentPermutationIndex === this.currentPermutations.length) {
        this.currentPermutationIndex = 0;
      }
      this.tileLayer.loadStyle(
        CartoQuick.getStyle(
          this.currentPermutations[this.currentPermutationIndex],
          clone(baseStyleFile)
        )
      );
    });

    on(this.addToArcgisAccount, 'click', () => {
      const teamName = this.styleSelect.options[parseInt(this.styleSelect.value, 10) + 1].innerHTML;
      if (!this.agolUtils) {
        this.agolUtils = new AgolUtils('FyzA1FOhv2AroUpG');
      }
      this.agolUtils.saveTileBasemap(CartoQuick.getStyle(
        this.currentPermutations[this.currentPermutationIndex],
        clone(baseStyleFile)
      ), teamName);
    });
  },

  populateSelect(select, teamColorsArray) {
    // set an initial version for now,
    // until we can get the layer loaded event.
    const opt = domConstruct.create('option', {
      innerHTML: `⇩ ${this.nls.ChangeMe} ⇩`,
      value: -1
    });
    this.styleSelect.add(opt);
    teamColorsArray.forEach((team, index) => {
      this.styleSelect.add(domConstruct.create('option', {
        innerHTML: team.name,
        value: index
      }));
    });
  },

  getAllPermutations(input) {
    this.permArr = [];
    this.usedChars = [];
    const returnPermutation = this.permute(input);
    return returnPermutation;
  },
  // http://stackoverflow.com/questions/9960908/permutations-in-javascript
  permute(input) {
    for (let i = 0; i < input.length; i++) {
      const ch = input.splice(i, 1)[0];
      this.usedChars.push(ch);
      if (input.length === 0) {
        this.permArr.push(this.usedChars.slice());
      }
      this.permute(input);
      input.splice(i, 0, ch);
      this.usedChars.pop();
    }
    return this.permArr;
  }
});


text:
from dbt.adapters.sql.connections import SQLConnectionManager  # noqa
from dbt.adapters.sql.impl import SQLAdapter  # noqa


text:
from setuptools import setup
from setuptools.extension import Extension
from Cython.Distutils import build_ext
import sys
import re

get_output = None

try:
    import commands
    get_output = commands.getoutput
except ImportError:
    import subprocess
    def _get_output(*args, **kwargs):
        res = subprocess.check_output(*args, shell=True, **kwargs)
        decoded = res.decode('utf-8')
        return decoded.strip()

    get_output = _get_output

ext_module_misc = Extension(
    'gssapi.base.misc',
    extra_link_args = get_output('krb5-config --libs gssapi').split(),
    extra_compile_args = get_output('krb5-config --cflags gssapi').split(),
    sources = [
        'gssapi/base/misc.pyx',
#        'gssapi/base/cython_converters.pyx'
    ]
)

ext_module_creds = Extension(
    'gssapi.base.creds',
    extra_link_args = get_output('krb5-config --libs gssapi').split(),
    extra_compile_args = get_output('krb5-config --cflags gssapi').split(),
    sources = [
        'gssapi/base/creds.pyx',
#        'gssapi/base/cython_converters.pyx'
    ]
)

ext_module_s4u = Extension(
    'gssapi.base.s4u',
    extra_link_args = get_output('krb5-config --libs gssapi').split(),
    extra_compile_args = get_output('krb5-config --cflags gssapi').split(),
    sources = [
        'gssapi/base/s4u.pyx',
    ]
)

ext_module_names = Extension(
    'gssapi.base.names',
    extra_link_args = get_output('krb5-config --libs gssapi').split(),
    extra_compile_args = get_output('krb5-config --cflags gssapi').split(),
    sources = [
        'gssapi/base/names.pyx',
#        'gssapi/base/cython_converters.pyx'
    ]
)

ext_module_sec_contexts = Extension(
    'gssapi.base.sec_contexts',
    extra_link_args = get_output('krb5-config --libs gssapi').split(),
    extra_compile_args = get_output('krb5-config --cflags gssapi').split(),
    sources = [
        'gssapi/base/sec_contexts.pyx',
#        'gssapi/base/cython_converters.pyx'
    ]
)

ext_module_types = Extension(
    'gssapi.base.types',
    extra_link_args = get_output('krb5-config --libs gssapi').split(),
    extra_compile_args = get_output('krb5-config --cflags gssapi').split(),
    sources = [
        'gssapi/base/types.pyx',
#        'gssapi/base/cython_converters.pyx'
    ]
)

ext_module_message = Extension(
    'gssapi.base.message',
    extra_link_args = get_output('krb5-config --libs gssapi').split(),
    extra_compile_args = get_output('krb5-config --cflags gssapi').split(),
    sources = [
        'gssapi/base/message.pyx',
#        'gssapi/base/cython_converters.pyx'
    ]
)

ext_module_cython_converters = Extension(
    'gssapi.base.cython_converters',
    extra_link_args = get_output('krb5-config --libs gssapi').split(),
    extra_compile_args = get_output('krb5-config --cflags gssapi').split(),
    sources = [
        'gssapi/base/cython_converters.pyx',
#        'gssapi/base/cython_converters.pyx'
    ]
)

long_desc = re.sub('\.\. role:: \w+\(code\)\s*\n\s*.+', '',
                   re.sub(r':(python|bash|code):', '',
                          re.sub(r'\.\. code-block:: \w+', '::',
                                 open('README.txt').read())))

setup(
    name='PyGSSAPI',
    version='1.0.0',
    author='Solly Ross',
    author_email='sross@redhat.com',
    packages=['gssapi', 'gssapi.base', 'gssapi.tests'],
    description='Python GSSAPI Wrapper',
    long_description=long_desc,
    license='LICENSE.txt',
    url="https://github.com/directxman12/python-gssapi",
    classifiers=[
        'Development Status :: 4 - Beta',
        'Programming Language :: Python',
        'Programming Language :: Python :: 2.6',
        'Programming Language :: Python :: 2.7',
        'Programming Language :: Python :: 3',
        'Intended Audience :: Developers',
        'License :: OSI Approved :: BSD License',
        'Programming Language :: Python :: Implementation :: CPython',
        'Topic :: Security',
        'Topic :: Software Development :: Libraries :: Python Modules'
    ],
    cmdclass = {'build_ext': build_ext},
    ext_modules = [
        ext_module_misc,
        ext_module_creds,
        ext_module_names,
        ext_module_sec_contexts,
        ext_module_types,
        ext_module_message,
        ext_module_cython_converters,
        ext_module_s4u,
    ],
    install_requires=[
        'flufl.enum >= 4.0'
    ],
    tests_require=[
        'tox'
    ]
)


text:
//
//  HCPHelper.m
//  HotCodePush
//
//  Created by M on 16/8/26.
//
//

#import "HCPHelper.h"

#import "HCPFileDownloader.h"
#import "HCPFilesStructure.h"
#import "HCPUpdateLoader.h"
#import "HCPInternalPreferences+UserDefaults.h"
#import "NSJSONSerialization+HCPExtension.h"
#import "HCPConfig.h"
#import "NSBundle+HCPExtension.h"
#import "HCPApplicationConfigStorage.h"
#import "HCPAssetsFolderHelper.h"
#import "NSError+HCPExtension.h"
#import "HCPCleanupHelper.h"

@interface HCPHelper()

@property(strong,nonatomic) NSURL *webUrl;
@property(strong,nonatomic) HCPFilesStructure *filesStructure;
@property(strong,nonatomic) HCPApplicationConfig *appConfig;
@property(strong,nonatomic) HCPInternalPreferences *hcpInternalPrefs;
@property(strong,nonatomic) HCPConfig *hcpConfig;

@end

@implementation HCPHelper

-(NSURL *)pathToWww
{
    if ([self isWWwFolderNeedsToBeInstalled])
    {
        return [NSURL URLWithString:[NSBundle pathToWwwFolder]];
    }
    else
    {
        return _filesStructure.wwwFolder;
    }
}

-(HCPHelper *)initWithWebUrl:(NSURL *)webUrl
{
    self = [super init];
    if (self)
    {
        self.webUrl = webUrl;
        [self doLocalInit];

        // 清理空间
        if (_hcpInternalPrefs.currentReleaseVersionName.length > 0) {
            [HCPCleanupHelper removeUnusedReleasesExcept:@[_hcpInternalPrefs.currentReleaseVersionName,
                                                           _hcpInternalPrefs.previousReleaseVersionName,
                                                           _hcpInternalPrefs.readyForInstallationReleaseVersionName]];
        }

        [self loadApplicationConfig];
    }

    return self;
}

-(BOOL)loadFromExternalStorageFolder
{
    if ([self isWWwFolderNeedsToBeInstalled])
    {
        [self installWwwFolder];
        return NO;
    }
    return YES;
}

-(void)fetchUpdate:(FetchUpdateBlock)block
{
    [[HCPUpdateLoader sharedInstance] fetchUpdateWithConfigUrl:_hcpConfig.configUrl
                                                currentWebVersion:_hcpInternalPrefs.currentReleaseVersionName
                                             currentNativeVersion:_hcpConfig.nativeInterfaceVersion
                                                            fetchUpdateBlock:^(BOOL needUpdate, NSError *error) {
                                                                block(needUpdate, error);
                                                                if (error)
                                                                {
                                                                    [self onUpdateDownloadErrorEvent:error];
                                                                }
                                                            }];
}

-(void)downloadUpdate:(DownloadUpdateBlock)block
{
    [[HCPUpdateLoader sharedInstance] downloadUpdateWithDownloadUpdateBlock:^(BOOL success, NSInteger totalFiles, NSInteger fileDownloaded, NSError *error, HCPApplicationConfig *newAppConfig) {
        if (success && !error)
        {
            [self onUpdateIsReadyForInstallation:newAppConfig];
        }
        block(success, totalFiles, fileDownloaded, error);
    }];
}

/**
 *  Install update.
 *
 *  @param callbackID callbackId id of the caller on JavaScript side; it will be used to send back the result of the installation process
 *
 *  @return YES if installation has started; NO otherwise
 */
-(void)installUpdate:(InstallUpdateBlock)block
{
    NSString *newVersion = _hcpInternalPrefs.readyForInstallationReleaseVersionName;
    NSString *currentVersion = _hcpInternalPrefs.currentReleaseVersionName;

    [[HCPUpdateLoader sharedInstance] installVersion:newVersion currentVersion:currentVersion completionBlock:^(BOOL success, NSError *error, HCPApplicationConfig *newAppConfig) {
        if (error)
        {
            //            if (error.code == kHCPNothingToInstallErrorCode)
            //            {
            //                NSNotification *notification = [HCPEvents notificationWithName:kHCPNothingToInstallEvent
            //                                                             applicationConfig:nil
            //                                                                        taskId:nil
            //                                                                         error:error];
            //                [self onNothingToInstallEvent:notification];
            //            }
        }
        block(success, error);
        [self onUpdateInstalledEvent:newAppConfig];
    }];
}

#pragma mark Lifecycle

//- (void)onAppTerminate {
//    [self unsubscribeFromEvents];
//}

- (void)onResume:(NSNotification *)notification {
//    if (!_pluginXmlConfig.isUpdatesAutoInstallationAllowed ||
//        _hcpInternalPrefs.readyForInstallationReleaseVersionName.length == 0) {
//        return;
//    }
//
//    // load app config from update folder and check, if we are allowed to install it
//    HCPFilesStructure *fs = [[HCPFilesStructure alloc] initWithReleaseVersion:_hcpInternalPrefs.readyForInstallationReleaseVersionName];
//    id<HCPConfigFileStorage> configStorage = [[HCPApplicationConfigStorage alloc] initWithFileStructure:fs];
//    HCPApplicationConfig *configFromNewRelease = [configStorage loadFromFolder:fs.downloadFolder];
//
//    if (configFromNewRelease.contentConfig.updateTime == HCPUpdateOnResume ||
//        configFromNewRelease.contentConfig.updateTime == HCPUpdateNow) {
//        [self _installUpdate:nil];
//    }
}

#pragma mark Private API

- (void)installWwwFolder
{
    if (_hcpInternalPrefs.isWwwFolderInstalled)
    {
        _hcpInternalPrefs.wwwFolderInstalled = NO;
        [_hcpInternalPrefs saveToUserDefaults];
    }

    if (_filesStructure.wwwFolder)
    {
        [HCPAssetsFolderHelper installWwwFolderToExternalStorageFolder:_filesStructure.wwwFolder completionBlock:^(BOOL success, NSError *error)
        {
            [self onAssetsInstalledOnExternalStorageEvent];
        }];
    }
}

/**
 *  Load application config from file system
 */
- (void)loadApplicationConfig {
    id<HCPConfigFileStorage> configStorage = [[HCPApplicationConfigStorage alloc] initWithFileStructure:_filesStructure];
    _appConfig = [configStorage loadFromFolder:_filesStructure.wwwFolder];
}

/**
 *  Check if www folder already exists on the external storage.
 *
 *  @return YES - www folder doesn't exist, we need to install it; NO - folder already installed
 */
- (BOOL)isWWwFolderNeedsToBeInstalled {
    NSFileManager *fileManager = [NSFileManager defaultManager];
    BOOL isApplicationUpdated = [NSBundle applicationBuildVersion] != _hcpInternalPrefs.appBuildVersion;
    BOOL isWWwFolderExists = [fileManager fileExistsAtPath:_filesStructure.wwwFolder.path];
    BOOL isWWwFolderInstalled = _hcpInternalPrefs.isWwwFolderInstalled;

    return isApplicationUpdated || !isWWwFolderExists || !isWWwFolderInstalled;
}

/**
 *  Perform initialization of the plugin variables.
 */
- (void)doLocalInit
{
    // 初始化config
    _hcpConfig = [[HCPConfig alloc] init];
    _hcpConfig.webUrl = self.webUrl;

    // 加载internal preferences
    _hcpInternalPrefs = [HCPInternalPreferences loadFromUserDefaults];
    if (_hcpInternalPrefs == nil || _hcpInternalPrefs.currentReleaseVersionName.length == 0)
    {
        _hcpInternalPrefs = [HCPInternalPreferences defaultConfig];
        if (_hcpInternalPrefs.currentReleaseVersionName.length >0)
        {
            [_hcpInternalPrefs saveToUserDefaults];
        }
        else
        {
            NSLog(@"无法读取配置文件");
            return;
        }
    }
    NSLog(@"Currently running release version %@", _hcpInternalPrefs.currentReleaseVersionName);
    // init file structure for www files
    _filesStructure = [[HCPFilesStructure alloc] initWithReleaseVersion:_hcpInternalPrefs.currentReleaseVersionName];
}

/**
 *  If needed - add path to www folder on the external storage to the provided path.
 *
 *  @param pagePath path to which we want add www folder
 *
 *  @return resulting path
 */
- (NSURL *)appendWwwFolderPathToPath:(NSString *)pagePath {
    if ([pagePath hasPrefix:_filesStructure.wwwFolder.absoluteString]) {
        return [NSURL URLWithString:pagePath];
    }

    return [_filesStructure.wwwFolder URLByAppendingPathComponent:pagePath];
}

#pragma mark Events

///**
// *  监听事件
// */
//- (void)subscribeToEvents
//{
//    [self subscribeToLifecycleEvents];
//    [self subscribeToInternalEvents];
//}
//
///**
// *  监听生命周期事件
// */
//- (void)subscribeToLifecycleEvents
//{
//    [[NSNotificationCenter defaultCenter] addObserver:self
//                                             selector:@selector(onResume:)
//                                                 name:UIApplicationWillEnterForegroundNotification
//                                               object:nil];
//
//}

/**
 *  监听内部事件
 */
//- (void)subscribeToInternalEvents
//{
//    NSNotificationCenter *notificationCenter = [NSNotificationCenter defaultCenter];
//
//    // 拷贝bundle事件
//    [notificationCenter addObserver:self
//                           selector:@selector(onBeforeAssetsInstalledOnExternalStorageEvent:)
//                               name:kHCPBeforeBundleAssetsInstalledOnExternalStorageEvent
//                             object:nil];
//    [notificationCenter addObserver:self
//                           selector:@selector(onAssetsInstalledOnExternalStorageEvent:)
//                               name:kHCPBundleAssetsInstalledOnExternalStorageEvent
//                             object:nil];
//    [notificationCenter addObserver:self
//                           selector:@selector(onAssetsInstallationErrorEvent:)
//                               name:kHCPBundleAssetsInstallationErrorEvent
//                             object:nil];
//
//    // 下载事件
//    [notificationCenter addObserver:self
//                           selector:@selector(onUpdateDownloadErrorEvent:)
//                               name:kHCPUpdateDownloadErrorEvent
//                             object:nil];
//    [notificationCenter addObserver:self
//                           selector:@selector(onNothingToUpdateEvent:)
//                               name:kHCPNothingToUpdateEvent
//                             object:nil];
//    [notificationCenter addObserver:self
//                           selector:@selector(onUpdateIsReadyForInstallation:)
//                               name:kHCPUpdateIsReadyForInstallationEvent
//                             object:nil];
//
//    // 安装更新事件
//    [notificationCenter addObserver:self
//                           selector:@selector(onUpdateInstallationErrorEvent:)
//                               name:kHCPUpdateInstallationErrorEvent
//                             object:nil];
//    [notificationCenter addObserver:self
//                           selector:@selector(onBeforeInstallEvent:)
//                               name:kHCPBeforeInstallEvent
//                             object:nil];
//    [notificationCenter addObserver:self
//                           selector:@selector(onUpdateInstalledEvent:)
//                               name:kHCPUpdateIsInstalledEvent
//                             object:nil];
//    [notificationCenter addObserver:self
//                           selector:@selector(onNothingToInstallEvent:)
//                               name:kHCPNothingToInstallEvent
//                             object:nil];
//}

/**
 *  移除监听
 */
//- (void)unsubscribeFromEvents {
//    [[NSNotificationCenter defaultCenter] removeObserver:self];
//}

#pragma mark Bundle installation events

- (void)onBeforeAssetsInstalledOnExternalStorageEvent:(NSNotification *)notification
{

}

- (void)onAssetsInstalledOnExternalStorageEvent
{
    _hcpInternalPrefs.appBuildVersion = [NSBundle applicationBuildVersion];
    _hcpInternalPrefs.wwwFolderInstalled = YES;
    [_hcpInternalPrefs saveToUserDefaults];

//    // 检查更新
//    [self loadApplicationConfig];
//
//    if (![HCPUpdateLoader sharedInstance].isDownloadInProgress &&
//        ![HCPUpdateInstaller sharedInstance].isInstallationInProgress)
//    {
//        [self fetchUpdate:^(BOOL needUpdate, NSError *error) {
//            if (error == nil)
//            {
//                [self downloadUpdate:^(BOOL success, NSInteger totalFiles, NSInteger fileDownloaded, NSError *error) {
//                    //安装
//                }];
//            }
//        }];
//    }
}

- (void)onAssetsInstallationErrorEvent:(NSNotification *)notification
{

}

#pragma mark Update download events

- (void)onUpdateDownloadErrorEvent:(NSError *)error
{
    NSLog(@"Error during update: %@", [error underlyingErrorLocalizedDesription]);

    // probably never happens, but just for safety
    [self rollbackIfCorrupted:error];
}

- (void)onNothingToUpdateEvent:(NSNotification *)notification
{
    NSLog(@"Nothing to update");
}

- (void)onUpdateIsReadyForInstallation:(HCPApplicationConfig *)newAppConfig
{
    // new application config from server
//    HCPApplicationConfig *newConfig = notification.userInfo[kHCPEventUserInfoApplicationConfigKey];

    NSLog(@"Update is ready for installation: %@", newAppConfig.contentConfig.releaseVersion);

    // store, that we are ready for installation
    _hcpInternalPrefs.readyForInstallationReleaseVersionName = newAppConfig.contentConfig.releaseVersion;
    [_hcpInternalPrefs saveToUserDefaults];

//    // if it is allowed - launch the installation
//    if (![HCPUpdateLoader sharedInstance].isDownloadInProgress && ![HCPUpdateInstaller sharedInstance].isInstallationInProgress)
//    {
//        [self installUpdate:^(BOOL success, NSError *error) {
//
//        }];
//    }
}

#pragma mark Update installation events

- (void)onNothingToInstallEvent:(NSNotification *)notification
{

}

- (void)onBeforeInstallEvent:(NSNotification *)notification
{

}

- (void)onUpdateInstallationErrorEvent:(NSNotification *)notification
{
    _hcpInternalPrefs.readyForInstallationReleaseVersionName = @"";
    [_hcpInternalPrefs saveToUserDefaults];

    // probably never happens, but just for safety
//    NSError *error = notification.userInfo[kHCPEventUserInfoErrorKey];
//    [self rollbackIfCorrupted:error];
}

- (void)onUpdateInstalledEvent:(HCPApplicationConfig *)newAppConfig
{
    _appConfig = newAppConfig;

    _hcpInternalPrefs.readyForInstallationReleaseVersionName = @"";
    _hcpInternalPrefs.previousReleaseVersionName = _hcpInternalPrefs.currentReleaseVersionName;
    _hcpInternalPrefs.currentReleaseVersionName = _appConfig.contentConfig.releaseVersion;
    [_hcpInternalPrefs saveToUserDefaults];

    _filesStructure = [[HCPFilesStructure alloc] initWithReleaseVersion:_hcpInternalPrefs.currentReleaseVersionName];
}

#pragma mark Rollback process

- (void)rollbackToPreviousRelease {
    _hcpInternalPrefs.readyForInstallationReleaseVersionName = @"";
    _hcpInternalPrefs.currentReleaseVersionName = _hcpInternalPrefs.previousReleaseVersionName;
    _hcpInternalPrefs.previousReleaseVersionName = @"";
    [_hcpInternalPrefs saveToUserDefaults];

    _filesStructure = [[HCPFilesStructure alloc] initWithReleaseVersion:_hcpInternalPrefs.currentReleaseVersionName];

    if (_appConfig) {
        [self loadApplicationConfig];
    }
}

- (void)rollbackIfCorrupted:(NSError *)error {
    if (error.code != kHCPLocalVersionOfApplicationConfigNotFoundErrorCode && error.code != kHCPLocalVersionOfManifestNotFoundErrorCode) {
        return;
    }

    if (_hcpInternalPrefs.previousReleaseVersionName.length > 0) {
        NSLog(@"WWW folder is corrupted, rolling back to previous version.");
        [self rollbackToPreviousRelease];
    } else {
        NSLog(@"WWW folder is corrupted, reinstalling it from bundle.");
        [self installWwwFolder];
    }
}

@end


text:
#pragma once

#include <sqlpp17/core/char_sequence.h>
#include <sqlpp17/core/join.h>
#include <sqlpp17/core/member.h>
#include <sqlpp17/core/table_alias.h>
#include <sqlpp17/core/table_columns.h>
#include <sqlpp17/core/to_sql_name.h>
#include <sqlpp17/core/type_traits.h>

namespace sqlpp
{
  template <typename TableSpec>
  class table_t : public join_functions<table_t<TableSpec>>,
                  public table_columns<TableSpec, typename TableSpec::_columns>
  {
  public:
    template <typename NamedTypeOrTag>
    [[nodiscard]] constexpr auto as([[maybe_unused]] const NamedTypeOrTag&) const
    {
      if constexpr (std::is_base_of_v<::sqlpp::name_tag_base, NamedTypeOrTag>)
      {
        return table_alias_t<table_t, table_spec<NamedTypeOrTag, type_hash<table_t>()>, TableSpec>{{}};
      }
      else if constexpr (not std::is_same_v<name_tag_of_t<NamedTypeOrTag>, none_t>)
      {
        return table_alias_t<table_t, table_spec<name_tag_of_t<NamedTypeOrTag>, type_hash<table_t>()>, TableSpec>{{}};
      }
      else
      {
        static_assert(wrong<NamedTypeOrTag>,
                      "as() is expecting a named expression (e.g. column, table), or a name tag");
      }
    }
  };

  template <typename TableSpec>
  struct name_tag_of<table_t<TableSpec>>
  {
    using type = typename TableSpec::_sqlpp_name_tag;
  };

  template <typename TableSpec>
  struct table_spec_of<table_t<TableSpec>>
  {
    using type = TableSpec;
  };

  template <typename Context, typename TableSpec>
  [[nodiscard]] auto to_sql_string(Context& context, const table_t<TableSpec>& t)
  {
    return to_sql_name(context, t);
  }

  template <typename TableSpec>
  [[nodiscard]] constexpr auto provided_tables_of([[maybe_unused]] type_t<table_t<TableSpec>>)
  {
    return type_vector<TableSpec>();
  }

  template <typename TableSpec>
  constexpr auto is_table_v<table_t<TableSpec>> = true;

  template <typename TableSpec>
  constexpr auto table_names_of_v<table_t<TableSpec>> = type_set<char_sequence_of_t<table_t<TableSpec>>>();

  template <typename TableSpec>
  [[nodiscard]] constexpr auto column_tuple_of(const table_t<TableSpec>& t)
  {
    return column_tuple_of(table_columns<TableSpec, typename TableSpec::_columns>{});
  }

  template <typename TableSpec>
  [[nodiscard]] constexpr auto all_of(const table_t<TableSpec>& t)
  {
    return column_tuple_of(t);
  }

  template <typename TableSpec>
  constexpr auto columns_of_v<table_t<TableSpec>> =
      columns_of_v<table_columns<TableSpec, typename TableSpec::_columns>>;

  template <typename TableSpec>
  constexpr auto can_be_null_columns_of_v<table_t<TableSpec>> =
      can_be_null_columns_of_v<table_columns<TableSpec, typename TableSpec::_columns>>;

}  // namespace sqlpp


text:
module RuboCop
  # This class handles collecting the options for regenerating a TODO file.
  # @api private
  class ConfigRegeneration
    AUTO_GENERATED_FILE = RuboCop::CLI::Command::AutoGenerateConfig::AUTO_GENERATED_FILE
    COMMAND_REGEX = /(?<=`rubocop )(.*?)(?=`)/.freeze
    DEFAULT_OPTIONS = { auto_gen_config: true }.freeze

    # Get options from the comment in the TODO file, and parse them as options
    def options
      # If there's no existing TODO file, generate one
      return DEFAULT_OPTIONS unless todo_exists?

      match = generation_command.match(COMMAND_REGEX)
      return DEFAULT_OPTIONS unless match

      options = match[1].split
      Options.new.parse(options).first
    end

    private

    def todo_exists?
      File.exist?(AUTO_GENERATED_FILE) && !File.empty?(AUTO_GENERATED_FILE)
    end

    def generation_command
      File.foreach(AUTO_GENERATED_FILE).take(2).last
    end
  end
end


text:
using System;
using Microsoft.Build.Framework;

namespace Qoollo.Concierge.Attributes
{
    /// <summary>
    /// Attribute for parameter description in UserCommand
    /// </summary>
    [AttributeUsage(AttributeTargets.Property, AllowMultiple = false, Inherited = true)]
    public class ParameterAttribute : Attribute
    {
        public ParameterAttribute()
        {
            LongKey = string.Empty;
            IsRequired = false;
            DefaultValue = null;
            Description = string.Empty;
        }

        [Required]
        public char ShortKey { get; set; }

        public string LongKey { get; set; }
        public bool IsRequired { get; set; }
        public object DefaultValue { get; set; }
        public string Description { get; set; }
    }
}


text:
// Copyright Dirk Lemstra https://github.com/dlemstra/Magick.NET.
// Licensed under the Apache License, Version 2.0.

using ImageMagick;
using Xunit;

namespace Magick.NET.Tests
{
    public partial class MagickImageTests
    {
        public class TheFormatInfoProperty
        {
            [Fact]
            public void ShouldReturnTheFormatInformationOfTheImage()
            {
                using (var image = new MagickImage(Files.SnakewarePNG))
                {
                    var info = image.FormatInfo;

                    Assert.NotNull(info);
                    Assert.Equal(MagickFormat.Png, info.Format);
                    Assert.Equal("image/png", info.MimeType);
                }
            }
        }
    }
}


text:
package com.symbolplay.tria.game.rise.generators;

import com.badlogic.gdx.assets.AssetManager;
import com.badlogic.gdx.math.MathUtils;
import com.badlogic.gdx.utils.Array;
import com.symbolplay.tria.game.platforms.Platform;
import com.symbolplay.tria.game.platforms.features.JumpBoostPlatformFeature;

public final class RiseGeneratorStandard {

    public static final float REACH_JUMP_BOOST_SMALL = 22.0f;
    public static final float REACH_JUMP_BOOST_MEDIUM = 32.0f;
    public static final float REACH_JUMP_BOOST_LARGE = 45.0f;

    private final CoinGenerator coinGenerator;
    private final AssetManager assetManager;

    public RiseGeneratorStandard(AssetManager assetManager) {
        this.assetManager = assetManager;
        coinGenerator = new CoinGenerator(assetManager);
    }

    public void generateInitial(RiseGeneratorData rgd) {
        generate(rgd, 1.0f, 0.0f, 0.0f, 30.0f, 1.0f, 1.0f, 0.5f, 1.0f, false, false, false);
        generate(rgd, 1.0f, 0.0f, 0.0f, 40.0f, 1.0f, 1.0f, 0.5f, 1.0f, true, false, true);
    }

    public void generateLow(RiseGeneratorData rgd) {
        float absoluteHeight = rgd.getAbsoluteHeightFloat();
        float height = getGenerationHeight(absoluteHeight);
        generateLow(rgd, height, true);
    }

    public void generateLow(RiseGeneratorData rgd, float height, boolean hasJumpBoost) {
        float absoluteHeight = rgd.getAbsoluteHeightFloat();
        float minStepY = RiseGeneratorUtils.getStandardMinStepY(absoluteHeight);
        float maxStepY = RiseGeneratorUtils.getStandardMaxStepY(absoluteHeight);

        generateLow(rgd, height, minStepY, maxStepY, hasJumpBoost);
    }

    public void generateLow(RiseGeneratorData rgd, float height, float minStepY, float maxStepY, boolean hasJumpBoost) {
        float absoluteHeight = rgd.getAbsoluteHeightFloat();
        float minMovingSpeed = RiseGeneratorUtils.getStandardMinMovingSpeed(absoluteHeight);
        float maxMovingSpeed = RiseGeneratorUtils.getStandardMaxMovingSpeed(absoluteHeight);

        generateLow(rgd, height, minStepY, maxStepY, minMovingSpeed, maxMovingSpeed, hasJumpBoost);
    }

    public void generateLow(
            RiseGeneratorData rgd,
            float height,
            float minStepY,
            float maxStepY,
            float minMovingSpeed,
            float maxMovingSpeed,
            boolean isGenerateJumpBoost) {

        int randomValue = MathUtils.random(4);

        if (randomValue == 0) {
            generate(rgd, 1.0f, 0.0f, 0.2f, height, minStepY, maxStepY, minMovingSpeed, maxMovingSpeed, isGenerateJumpBoost, true, true);
        } else if (randomValue == 1 || randomValue == 2) {
            generate(rgd, 1.0f, 0.2f, 1.0f, height, minStepY, maxStepY, minMovingSpeed, maxMovingSpeed, isGenerateJumpBoost, true, true);
        } else if (randomValue == 3) {
            generate(rgd, 0.3f, 1.0f, 0.2f, height, minStepY, maxStepY, minMovingSpeed, maxMovingSpeed, isGenerateJumpBoost, true, true);
        } else {
            generate(rgd, 0.3f, 0.1f, 1.0f, height, minStepY, maxStepY, minMovingSpeed, maxMovingSpeed, isGenerateJumpBoost, true, true);
        }
    }

    public void generateHigh(RiseGeneratorData rgd) {
        float absoluteHeight = rgd.getAbsoluteHeightFloat();
        float height = getGenerationHeight(absoluteHeight);
        generateHigh(rgd, height, true);
    }

    public void generateHigh(RiseGeneratorData rgd, float height, boolean hasJumpBoost) {
        float absoluteHeight = rgd.getAbsoluteHeightFloat();
        float minStepY = RiseGeneratorUtils.getStandardMinStepY(absoluteHeight);
        float maxStepY = RiseGeneratorUtils.getStandardMaxStepY(absoluteHeight);

        generateHigh(rgd, height, minStepY, maxStepY, hasJumpBoost);
    }

    public void generateHigh(RiseGeneratorData rgd, float height, float minStepY, float maxStepY, boolean hasJumpBoost) {
        float absoluteHeight = rgd.getAbsoluteHeightFloat();
        float minMovingSpeed = RiseGeneratorUtils.getStandardMinMovingSpeed(absoluteHeight);
        float maxMovingSpeed = RiseGeneratorUtils.getStandardMaxMovingSpeed(absoluteHeight);

        generateHigh(rgd, height, minStepY, maxStepY, minMovingSpeed, maxMovingSpeed, hasJumpBoost);
    }

    public void generateHigh(
            RiseGeneratorData rgd,
            float height,
            float minStepY,
            float maxStepY,
            float minMovingSpeed,
            float maxMovingSpeed,
            boolean isGenerateJumpBoost) {

        float absoluteHeight = rgd.getAbsoluteHeightFloat();

        float movingSectionWeight = RiseGeneratorUtils.getStandardMovingSectionWeight(absoluteHeight);
        float repositionSectionWeight = RiseGeneratorUtils.getStandardRepositionSectionWeight(absoluteHeight);
        float mixedSectionWeight = RiseGeneratorUtils.getStandardMixedSectionWeight(absoluteHeight);
        float totalSectionsWeight = movingSectionWeight + repositionSectionWeight + mixedSectionWeight;

        float randomValue = MathUtils.random(totalSectionsWeight);

        if (randomValue <= movingSectionWeight) {
            float movingWeight = getMovingSectionMovingWeight(absoluteHeight);
            float repositionWeight = getMovingSectionRepositionWeight(absoluteHeight);
            generate(rgd, 0.1f, movingWeight, repositionWeight, height, minStepY, maxStepY, minMovingSpeed, maxMovingSpeed, isGenerateJumpBoost, true, true);
        } else if (randomValue <= movingSectionWeight + repositionSectionWeight) {
            generate(rgd, 0.1f, 0.2f, 1.0f, height, minStepY, maxStepY, minMovingSpeed, maxMovingSpeed, isGenerateJumpBoost, true, true);
        } else {
            generate(rgd, 0.1f, 1.0f, 1.0f, height, minStepY, maxStepY, minMovingSpeed, maxMovingSpeed, isGenerateJumpBoost, true, true);
        }
    }

    public void generateRestingPlace(RiseGeneratorData rgd) {
        float height = MathUtils.random(2.0f, 6.0f);
        generate(rgd, 1.0f, 0.0f, 0.0f, height, 2.0f, 4.0f, 0.5f, 1.0f, false, false, true);
    }

    public void generateLowJumpBoostBufferZone(RiseGeneratorData rgd) {
        if (rgd.lastJumpBoostReachAbsoluteHeight > rgd.absoluteHeight) {
            float height = (float) (rgd.lastJumpBoostReachAbsoluteHeight - rgd.absoluteHeight);
            generateLow(rgd, height, false);
        }
    }

    public void generateHighJumpBoostBufferZone(RiseGeneratorData rgd) {
        if (rgd.lastJumpBoostReachAbsoluteHeight > rgd.absoluteHeight) {
            float height = (float) (rgd.lastJumpBoostReachAbsoluteHeight - rgd.absoluteHeight);
            generateHigh(rgd, height, false);
        }
    }

    public void generateTest(RiseGeneratorData rgd) {
        Array<Platform> platforms = rgd.platforms;

//        {
//            float x = 0.0f;
//            float y = 0.0f;
//
//            Array<PlatformFeatureBaseData> featuresData = new Array<PlatformFeatureBaseData>(true, 1);
//            PlatformFeatureBaseData jumpBoostData = new JumpBoostPlatformFeatureData(0.0f, JumpBoostPlatformFeatureData.SIZE_SMALL);
//            featuresData.add(jumpBoostData);
//
//            PlatformData platformData = new PlatformData(rgd.nextPlatformId, rgd.nextGroupId, x, y, featuresData);
//            Platform platform = new Platform(platformData, relativeHeight, assetManager);
//            platforms.add(platform);
//
//            rgd.nextPlatformId++;
//            rgd.nextGroupId++;
//
//            rgd.changeGeneratedHeight(12.0f);
//        }
//
//        {
//            float x = 2.0f;
//            float y = 0.0f;
//
//            Array<PlatformFeatureBaseData> featuresData = new Array<PlatformFeatureBaseData>(true, 1);
//            PlatformFeatureBaseData jumpBoostData = new JumpBoostPlatformFeatureData(0.0f, JumpBoostPlatformFeatureData.SIZE_MEDIUM);
//            featuresData.add(jumpBoostData);
//
//            PlatformData platformData = new PlatformData(rgd.nextPlatformId, rgd.nextGroupId, x, y, featuresData);
//            Platform platform = new Platform(platformData, relativeHeight, assetManager);
//            platforms.add(platform);
//
//            rgd.nextPlatformId++;
//            rgd.nextGroupId++;
//
//            rgd.changeGeneratedHeight(12.0f);
//        }
//
//        {
//            float x = 4.0f;
//            float y = 0.0f;
//
//            Array<PlatformFeatureBaseData> featuresData = new Array<PlatformFeatureBaseData>(true, 1);
//            PlatformFeatureBaseData jumpBoostData = new JumpBoostPlatformFeatureData(0.0f, JumpBoostPlatformFeatureData.SIZE_LARGE);
//            featuresData.add(jumpBoostData);
//
//            PlatformData platformData = new PlatformData(rgd.nextPlatformId, rgd.nextGroupId, x, y, featuresData);
//            Platform platform = new Platform(platformData, relativeHeight, assetManager);
//            platforms.add(platform);
//
//            rgd.nextPlatformId++;
//            rgd.nextGroupId++;
//
//            rgd.changeGeneratedHeight(12.0f);
//        }

        {
            float x = 0.0f;
            float y = 0.0f;

            Platform platform = new Platform(rgd.nextPlatformId, rgd.nextGroupId, x, y + rgd.relativeHeight, assetManager);
            platforms.add(platform);

            ItemGenerator.addAntiGravityItem(rgd, platform, assetManager);

            rgd.nextPlatformId++;
            rgd.nextGroupId++;

            rgd.changeGeneratedHeight(5.0f);
        }

        {
            float x = 0.0f;
            float y = 0.0f;

            Platform platform = new Platform(rgd.nextPlatformId, rgd.nextGroupId, x, y + rgd.relativeHeight, assetManager);
            platforms.add(platform);

            ItemGenerator.addRocketItem(rgd, platform, assetManager);

            rgd.nextPlatformId++;
            rgd.nextGroupId++;

            rgd.changeGeneratedHeight(5.0f);
        }

        {
            float x = 0.0f;
            float y = 0.0f;

            Platform platform = new Platform(rgd.nextPlatformId, rgd.nextGroupId, x, y + rgd.relativeHeight, assetManager);
            platforms.add(platform);

            ItemGenerator.addLifeItem(rgd, platform, assetManager);

            rgd.nextPlatformId++;
            rgd.nextGroupId++;

            rgd.changeGeneratedHeight(5.0f);
        }
    }

    private void generate(
            RiseGeneratorData rgd,
            float normalWeight,
            float movingWeight,
            float repositionWeight,
            float height,
            float minStepY,
            float maxStepY,
            float minMovingSpeed,
            float maxMovingSpeed,
            boolean isGenerateJumpBoost,
            boolean isGenerateItems,
            boolean isGenerateCoins) {

        Array<Platform> platforms = rgd.platforms;
        float relativeHeight = rgd.relativeHeight;
        float absoluteHeight = rgd.getAbsoluteHeightFloat();

        float x;
        float y = 0.0f;

        float minRepositionAmount = RiseGeneratorUtils.getStandardMinRepositionAmount(absoluteHeight);
        float maxRepositionAmount = RiseGeneratorUtils.getStandardMaxRepositionAmount(absoluteHeight);

        float jumpBoostTotalChance = 0.075f;

        int itemTypeToGenerate = ItemGenerator.getItemTypeToGenerate(rgd);
        float itemGenerationHeight = 0.0f;
        boolean isItemGenerated = false;
        if (itemTypeToGenerate != ItemGenerator.ITEM_TYPE_TO_GENERATE_NONE) {
            itemGenerationHeight = MathUtils.random(height * 0.8f);
        }

        coinGenerator.setAbsoluteHeight(absoluteHeight);

        while (y < height) {

            int platformType = RiseGeneratorUtils.getStandardRandomPlatformType(normalWeight, movingWeight, repositionWeight);
            if (platformType == RiseGeneratorUtils.STANDARD_MOVEMENT_TYPE_NORMAL) {
                x = RiseGeneratorUtils.getRandomPlatformX();
                rgd.lastNormalPlatformAbsoluteHeight = rgd.absoluteHeight + y;
            } else {
                x = 0.0f;
            }

            Platform platform = new Platform(rgd.nextPlatformId, rgd.nextGroupId, x, y + relativeHeight, assetManager);

            if (platformType == RiseGeneratorUtils.STANDARD_MOVEMENT_TYPE_MOVING) {
                RiseGeneratorUtils.setHorizontalPlatformMovement(platform, minMovingSpeed, maxMovingSpeed);
            } else if (platformType == RiseGeneratorUtils.STANDARD_MOVEMENT_TYPE_REPOSITION) {
                RiseGeneratorUtils.setRepositionPlatformMovement(platform, minRepositionAmount, maxRepositionAmount);
            }

            boolean isJumpBoostThisStep = false;
            if (isGenerateJumpBoost && MathUtils.random() < jumpBoostTotalChance) {
                setJumpBoostPlatformFeature(platform, rgd, rgd.absoluteHeight + y);
                isJumpBoostThisStep = true;
            }

            boolean isItemThisStep = false;
            if (isGenerateItems && itemTypeToGenerate != ItemGenerator.ITEM_TYPE_TO_GENERATE_NONE && y >= itemGenerationHeight && !isJumpBoostThisStep && !isItemGenerated) {
                if (itemTypeToGenerate == ItemGenerator.ITEM_TYPE_TO_GENERATE_LIFE) {
                    ItemGenerator.addLifeItem(rgd, platform, assetManager);
                } else if (itemTypeToGenerate == ItemGenerator.ITEM_TYPE_TO_GENERATE_ANTI_GRAVITY) {
                    ItemGenerator.addAntiGravityItem(rgd, platform, assetManager);
                } else if (itemTypeToGenerate == ItemGenerator.ITEM_TYPE_TO_GENERATE_ROCKET) {
                    ItemGenerator.addRocketItem(rgd, platform, assetManager);
                }

                isItemGenerated = true;
                isItemThisStep = true;
            }

            boolean isCoinThisStep = false;
            if (isGenerateCoins && !isJumpBoostThisStep && !isItemThisStep) {
                coinGenerator.generate(0.3f, rgd, platform);
                isCoinThisStep = true;
            }

            platforms.add(platform);

            rgd.nextPlatformId++;
            rgd.nextGroupId++;

            float yStep;
            if (isJumpBoostThisStep) {
                yStep = 4.0f;
            } else if (isItemThisStep) {
                yStep = MathUtils.random(minStepY, maxStepY);
                yStep = Math.max(yStep, 2.5f);
            } else if (isCoinThisStep) {
                yStep = MathUtils.random(minStepY, maxStepY);
                yStep = Math.max(yStep, 1.5f);
            } else {
                yStep = MathUtils.random(minStepY, maxStepY);
            }

            y += yStep;
        }

        rgd.changeGeneratedHeight(y);
    }

    private static void setJumpBoostPlatformFeature(Platform platform, RiseGeneratorData rgd, double currentAbsoluteHeight) {

        float jumpBoostSmallWeight = 1.0f;
        float jumpBoostMediumWeight = 1.0f;
        float jumpBoostLargeWeight = 0.2f;
        float jumpBoostTotalWeight = jumpBoostSmallWeight + jumpBoostMediumWeight + jumpBoostLargeWeight;

        float randomValue = MathUtils.random(jumpBoostTotalWeight);

        int size;
        float jumpReach;
        if (randomValue < jumpBoostSmallWeight) {
            size = JumpBoostPlatformFeature.SIZE_SMALL;
            jumpReach = REACH_JUMP_BOOST_SMALL;
        } else if (randomValue < jumpBoostSmallWeight + jumpBoostMediumWeight) {
            size = JumpBoostPlatformFeature.SIZE_MEDIUM;
            jumpReach = REACH_JUMP_BOOST_MEDIUM;
        } else {
            size = JumpBoostPlatformFeature.SIZE_LARGE;
            jumpReach = REACH_JUMP_BOOST_LARGE;
        }

        double currentJumpBoostReachAbsoluteHeight = currentAbsoluteHeight + jumpReach;
        if (currentJumpBoostReachAbsoluteHeight > rgd.lastJumpBoostReachAbsoluteHeight) {
            rgd.lastJumpBoostReachAbsoluteHeight = currentJumpBoostReachAbsoluteHeight;
        }

        platform.setJumpBoostFeature(MathUtils.random(), size);
    }

    private static float getGenerationHeight(float absoluteHeight) {
        float min;
        if (absoluteHeight <= 4000.0f) {
            min = 10.0f + absoluteHeight * 0.01f;
        } else {
            min = 50.0f;
        }

        float max;
        if (absoluteHeight <= 4000.0f) {
            max = 30.0f + absoluteHeight * 0.01f;
        } else {
            max = 70.0f;
        }

        return MathUtils.random(min, max);
    }

    // used on high, to increase movement weight on moving rise sections on greater heights to increase difficulty
    private static float getMovingSectionMovingWeight(float absoluteHeight) {
        if (absoluteHeight <= 1000.0f) {
            return 1.0f;
        } else if (absoluteHeight <= 2000.0f) {
            return 1.0f + (absoluteHeight - 1000.0f) * 0.002f;
        } else {
            return 3.0f;
        }
    }

    // used on high, to increase movement weight on moving rise sections on greater heights to increase difficulty
    private static float getMovingSectionRepositionWeight(float absoluteHeight) {
        if (absoluteHeight <= 1000.0f) {
            return 0.2f;
        } else if (absoluteHeight <= 2000.0f) {
            return 0.2f - (absoluteHeight - 1000.0f) * 0.0001f;
        } else {
            return 0.1f;
        }
    }
}


text:
package de.tototec.sbuild.addons

/**
 * Addons for unit testing with JUnit.
 */
package object junit {

}


text:
id: 5ea9997bbec2e9bc47e94db4
title: Developing a Port Scanner
challengeType: 11
videoId: z_qkqZS7KZ4
bilibiliIds:
  aid: 208077317
  bvid: BV1Uh411p7HS
  cid: 409036706
dashedName: developing-a-port-scanner
---

# --question--

## --text--

What is the main difference between the `.connect()` and `.connect_ex()` methods?

## --answers--

There is no difference between the two methods.

---

If there is an error or if no host is found, `.connect()` returns an error code while `.connect_ex()` raises an exception.

---

If there is an error or if no host is found, `.connect()` raises an exception while `.connect_ex()` returns an error code.

## --video-solution--

3


text:
#ifndef __GUICOMMANDS_H_
#define __GUICOMMANDS_H_

#include <shogun/lib/config.h>
#include <shogun/lib/common.h>

//names of octave/python/matlab/R interface commands
#define N_SEND_COMMAND						"send_command"
#define N_CRC								"crc"
#define N_TRANSLATE_STRING					"translate_string"
#define N_GET_HMM							"get_hmm"
#define N_GET_VITERBI_PATH					"get_viterbi_path"
#define N_GET_NUM_SVMS						"get_num_svms"
#define N_GET_SVM							"get_svm"
#define N_GET_CLASSIFIER					"get_classifier"
#define N_GET_CLUSTERING					"get_clustering"
#define N_GET_SVM_OBJECTIVE					"get_svm_objective"
#define N_COMPUTE_SVM_PRIMAL_OBJECTIVE		"compute_svm_primal_objective"
#define N_COMPUTE_SVM_DUAL_OBJECTIVE		"compute_svm_dual_objective"
#define N_COMPUTE_MKL_PRIMAL_OBJECTIVE		"compute_mkl_primal_objective"
#define N_COMPUTE_MKL_DUAL_OBJECTIVE		"compute_mkl_dual_objective"
#define N_COMPUTE_RELATIVE_MKL_DUALITY_GAP	"compute_relative_mkl_duality_gap"
#define N_COMPUTE_ABSOLUTE_MKL_DUALITY_GAP	"compute_absolute_mkl_duality_gap"
#define N_GET_KERNEL_INIT					"get_kernel_init"
#define N_GET_KERNEL_MATRIX					"get_kernel_matrix"
#define N_GET_DISTANCE_MATRIX				"get_distance_matrix"
#define N_HMM_LIKELIHOOD					"hmm_likelihood"
#define N_GET_KERNEL_OPTIMIZATION			"get_kernel_optimization"
#define N_COMPUTE_BY_SUBKERNELS				"compute_by_subkernels"
#define N_SET_SUBKERNEL_WEIGHTS				"set_subkernel_weights"
#define N_SET_SUBKERNEL_WEIGHTS_COMBINED	"set_subkernel_weights_combined"
#define N_GET_DOTFEATURE_WEIGHTS_COMBINED	"get_dotfeature_weights_combined"
#define N_SET_DOTFEATURE_WEIGHTS_COMBINED	"set_dotfeature_weights_combined"
#define N_SET_LAST_SUBKERNEL_WEIGHTS		"set_last_subkernel_weights"
#define N_SET_WD_POS_WEIGHTS				"set_WD_position_weights"
#define N_GET_SUBKERNEL_WEIGHTS				"get_subkernel_weights"
#define N_GET_LAST_SUBKERNEL_WEIGHTS		"get_last_subkernel_weights"
#define N_GET_WD_POS_WEIGHTS				"get_WD_position_weights"
#define N_COMPUTE_POIM_WD					"compute_poim_wd"
#define N_GET_WD_SCORING					"get_WD_scoring"
#define N_GET_WD_CONSENSUS					"get_WD_consensus"
#define N_GET_SPEC_SCORING					"get_SPEC_scoring"
#define N_GET_SPEC_CONSENSUS				"get_SPEC_consensus"
#define N_GET_FEATURES						"get_features"
#define N_GET_LABELS						"get_labels"
#define N_GET_VERSION						"get_version"
#define N_GET_PREPROC_INIT					"get_preproc_init"
#define N_GET_HMM_DEFS						"get_hmm_defs"
#define N_SET_HMM							"set_hmm"
#define N_MODEL_PROB_NO_B_TRANS				"model_prob_no_b_trans"
#define N_BEST_PATH_NO_B_TRANS				"best_path_no_b_trans"
#define N_SIGNALS_SET_MODEL				"signals_set_model"
#define N_SIGNALS_SET_POSITIONS			"signals_set_positions"
#define N_SIGNALS_SET_LABELS				"signals_set_labels"
#define N_SIGNALS_SET_SPLIT				"signals_set_split"
#define N_SIGNALS_SET_TRAIN_MASK			"signals_set_train_mask"
#define N_SIGNALS_ADD_FEATURE				"signals_add_feature"
#define N_SIGNALS_ADD_KERNEL				"signals_add_kernel"
#define N_SIGNALS_RUN					"signals_run"
#define N_BEST_PATH_TRANS_DERIV				"best_path_trans_deriv"
#define N_BEST_PATH_TRANS					"best_path_trans"
#define N_SET_PLIF_STRUCT					"set_plif_struct"
#define N_GET_PLIF_STRUCT					"get_plif_struct"
#define N_PRECOMPUTE_SUBKERNELS				"precompute_subkernels"
#define N_PRECOMPUTE_CONTENT_SVMS			"precompute_content_svms"
#define N_GET_LIN_FEAT					"get_lin_feat"
#define N_INIT_INTRON_LIST				"init_intron_list"
#define N_SET_LIN_FEAT					"set_lin_feat"
#define N_INIT_DYN_PROG					"init_dyn_prog"
#define N_CLEAN_UP_DYN_PROG					"clean_up_dyn_prog"
#define N_PRECOMPUTE_TILING_FEATURES			"precompute_tiling_features"
#define N_LONG_TRANSITION_SETTINGS			"long_transition_settings"
#define N_SET_MODEL					"set_model"
#define N_SET_FEATURE_MATRIX				"set_feature_matrix"
#define N_SET_FEATURE_MATRIX_SPARSE			"set_feature_matrix_sparse"
#define N_BEST_PATH_2STRUCT					"best_path_2struct"
#define N_BEST_PATH_TRANS_SIMPLE			"best_path_trans_simple"
#define N_BEST_PATH_NO_B					"best_path_no_b"
#define N_SET_SVM							"set_svm"
#define N_SET_LINEAR_CLASSIFIER				"set_linear_classifier"
#define N_SET_CUSTOM_KERNEL					"set_custom_kernel"
#define N_SET_KERNEL_INIT					"set_kernel_init"
#define N_SET_KERNEL_NORMALIZATION			"set_kernel_normalization"
#define N_SET_FEATURES						"set_features"
#define N_ADD_FEATURES						"add_features"
#define N_ADD_MULTIPLE_FEATURES				"add_multiple_features"
#define N_ADD_DOTFEATURES					"add_dotfeatures"
#define N_DEL_LAST_FEATURES					"del_last_features"
#define N_SET_LABELS						"set_labels"
#define N_SET_PREPROC_INIT					"set_preproc_init"
#define N_SET_HMM_DEFS						"set_hmm_defs"
#define N_ONE_CLASS_HMM_CLASSIFY			"one_class_hmm_classify"
#define N_ONE_CLASS_LINEAR_HMM_CLASSIFY		"one_class_linear_hmm_classify"
#define N_HMM_CLASSIFY						"hmm_classify"
#define N_ONE_CLASS_HMM_CLASSIFY_EXAMPLE	"one_class_hmm_classify_example"
#define N_HMM_CLASSIFY_EXAMPLE				"hmm_classify_example"
#define N_CLASSIFY							"classify"
#define N_CLASSIFY_EXAMPLE					"classify_example"
#define N_SVM_CLASSIFY						"svm_classify"
#define N_SVM_CLASSIFY_EXAMPLE				"svm_classify_example"
#define N_GET_PLUGIN_ESTIMATE				"get_plugin_estimate"
#define N_SET_PLUGIN_ESTIMATE				"set_plugin_estimate"
#define N_PLUGIN_ESTIMATE_CLASSIFY			"plugin_estimate_classify"
#define N_PLUGIN_ESTIMATE_CLASSIFY_EXAMPLE	"plugin_estimate_classify_example"

//names of text interface commands
#define N_NEW_HMM						"new_hmm"
#define N_NEW_SVM						"new_svm"
#define N_NEW_CLASSIFIER				"new_classifier"
#define N_NEW_PLUGIN_ESTIMATOR			"new_plugin_estimator"
#define N_NEW_REGRESSION				"new_regression"
#define N_NEW_CLUSTERING				"new_clustering"
#define N_TRAIN_ESTIMATOR				"train_estimator"
#define N_TRAIN_CLASSIFIER				"train_classifier"
#define N_TRAIN_REGRESSION				"train_regression"
#define N_TRAIN_CLUSTERING				"train_clustering"
#define N_SET_PERCEPTRON_PARAMETERS		"set_perceptron_parameters"
#define N_TEST_ESTIMATOR				"test_estimator"
#define N_LOAD_PREPROC					"load_preproc"
#define N_SAVE_PREPROC					"save_preproc"
#define N_LOAD_HMM						"load_hmm"
#define N_SAVE_HMM						"save_hmm"
#define N_LOAD_CLASSIFIER				"load_classifier"
#define N_SAVE_CLASSIFIER				"save_classifier"
#define N_LOAD_LABELS					"load_labels"
#define N_LOAD_FEATURES					"load_features"
#define N_SAVE_FEATURES					"save_features"
#define N_CLEAN_FEATURES				"clean_features"
#define N_RESHAPE						"reshape"
#define N_LOAD_DEFINITIONS				"load_defs"
#define N_SAVE_KERNEL					"save_kernel"
#define N_SET_HMM_AS					"set_hmm_as"
#define N_NORMALIZE						"normalize_hmm"
#define N_RELATIVE_ENTROPY				"relative_entropy"
#define N_ENTROPY						"entropy"
#define N_PERMUTATION_ENTROPY			"permutation_entropy"
#define N_SET_KERNEL					"set_kernel"
#define N_SET_DISTANCE					"set_distance"
#define N_ADD_KERNEL					"add_kernel"
#define N_DEL_LAST_KERNEL				"del_last_kernel"
#define N_CLEAN_KERNEL					"clean_kernel"

#ifdef USE_SVMLIGHT
#define N_RESIZE_KERNEL_CACHE			"resize_kernel_cache"
#endif //USE_SVMLIGHT

#define N_SET_KERNEL_OPTIMIZATION_TYPE	"set_kernel_optimization_type"
#define N_SET_PRIOR_PROBS				"set_prior_probs"
#define N_SET_PRIOR_PROBS_FROM_LABELS	"set_prior_probs_from_labels"
#define N_ATTACH_PREPROC				"attach_preproc"
#define N_ADD_PREPROC					"add_preproc"
#define N_DEL_PREPROC					"del_preproc"
#define N_CLEAN_PREPROC					"clean_preproc"
#define N_INIT_KERNEL					"init_kernel"
#define N_INIT_DISTANCE					"init_distance"
#define N_DELETE_KERNEL_OPTIMIZATION	"delete_kernel_optimization"
#define N_INIT_KERNEL_OPTIMIZATION		"init_kernel_optimization"
#define N_SAVE_PATH						"save_hmm_path"
#define N_SAVE_LIKELIHOOD				"save_hmm_likelihood"
#define N_BEST_PATH						"best_path"
#define N_VITERBI_TRAIN					"vit"
#define N_VITERBI_TRAIN_DEFINED			"vit_def"
#define N_LINEAR_TRAIN					"linear_train"
#define N_CLEAR							"clear"
#define N_CHOP							"chop"
#define N_CONVERGENCE_CRITERIA			"convergence_criteria"
#define N_PSEUDO						"pseudo"
#define N_CONVERT						"convert"
#define N_C								"c"
#define N_LOGLEVEL						"loglevel"
#define N_PROGRESS						"progress"
#define N_PRINT							"print"
#define N_ECHO							"echo"
#define N_SVMQPSIZE						"svm_qpsize"
#define N_SVMBUFSIZE					"svm_bufsize"
#define N_SVMMAXQPSIZE					"svm_max_qpsize"
#define N_THREADS						"threads"
#define N_MKL_PARAMETERS				"mkl_parameters"
#define N_ENT_LAMBDA                    "elasticnet_lambda"
#define N_MKL_BLOCK_NORM                "mkl_block_norm"
#define N_SVM_EPSILON					"svm_epsilon"
#define N_SVM_MAX_TRAIN_TIME			"svm_max_train_time"
#define N_SVR_TUBE_EPSILON				"svr_tube_epsilon"
#define N_SVM_NU						"svm_nu"
#define N_SVM_USE_BIAS					"svm_use_bias"
#define N_MKL_USE_INTERLEAVED_OPTIMIZATION	"mkl_use_interleaved_optimization"
#define N_DO_AUC_MAXIMIZATION			"do_auc_maximization"
#define N_ADD_STATES					"add_states"
#define N_APPEND_HMM					"append_hmm"
#define N_APPEND_MODEL					"append_model"
#define N_BAUM_WELCH_TRAIN				"bw"
#define N_BAUM_WELCH_TRANS_TRAIN		"bw_trans"
#define N_BAUM_WELCH_TRAIN_DEFINED		"bw_def"
#define N_LIKELIHOOD					"likelihood"
#define N_USE_BATCH_COMPUTATION			"use_batch_computation"
#define N_USE_DIAGONAL_SPEEDUP			"use_diagonal_speedup"
#define N_USE_MKL						"use_mkl"
#define N_USE_SHRINKING					"use_shrinking"
#define N_USE_LINADD					"use_linadd"
#define N_OUTPUT_HMM					"output_hmm"
#define N_OUTPUT_HMM_DEFINED			"output_hmm_defined"
#define N_QUIT							"quit"
#define N_EXEC							"exec"
#define N_EXIT							"exit"
#define N_SYNTAX_HIGHLIGHT				"syntax_highlight"
#define N_HELP							"help"
#define N_WHOS							"whos"
#define N_SYSTEM						"!"
#define N_SET_SOLVER					"set_solver"
#define N_SET_CONSTRAINT_GENERATOR		"set_constraint_generator"
#define N_SET_THRESHOLD					"set_threshold"
#define N_INIT_RANDOM					"init_random"
#define N_SVM_TRAIN						"svm_train"
#define N_SVM_TEST						"svm_test"
#define N_ONE_CLASS_HMM_TEST			"one_class_hmm_test"
#define N_HMM_TEST						"hmm_test"
#define N_SET_OUTPUT					"set_output"
#define N_SET_REF_FEAT					"set_ref_features"
#define N_TIC							"tic"
#define N_TOC							"toc"
#define N_KRR_TAU						"krr_tau"
#define N_RUN_PYTHON					"run_python"
#define N_RUN_OCTAVE					"run_octave"
#define N_RUN_R							"run_r"
#define N_PR_LOQO						"pr_loqo"
#define N_SET_CONVERTER						"set_converter"
#define N_APPLY_CONVERTER					"apply_converter"
#define N_EMBED							"embed"
#endif


text:
module Returnly
  VERSION = '0.13.1'

  def platform_version
    defined?(Solidus)
  end
end


text:
<sapp>
	<layout
		type='page'
		background='@drawable/background'
		backgroundScale='cover'
		>

		<linear alignCenter='true'>

			<image
				src='@drawable/lion'
				width='35%sw'
				centerHorizontal='true'/>

			<label
				text='@string/hello_world'
				marginTop='2%sh'
				fontSize='5%sw'
				textColor='white'
				centerHorizontal='true'
				/>

		</linear>

		<button
			style='button_back'
			colorOverlay='white'
			colorOverlayPressed='blue'
			/>

		<drawer gravity='left' dragEdgeSize='6mm'>
			<group width='50%sw' height='fill' background='#a0a0a0'>
				<button text='Close' style='button_normal' width='25%smin' alignCenter='true' cancel='true' />
			</group>
		</drawer>

 	</layout>
</sapp>


text:
package com.entwinemedia.fn.data.json;

public final class JNull implements JValue {
  JNull() {
  }

  @Override public int hashCode() {
    return -2;
  }

  @Override public boolean equals(Object that) {
    return that instanceof JNull;
  }

  @Override public String toString() {
    return "Jsons{null}";
  }
}


text:
package xxxxx.yyyyy.zzzzz.xyz.interfaces.api;

import java.io.File;
import java.io.IOException;
import java.util.regex.Pattern;
import org.apache.maven.model.Model;
import org.apache.maven.model.io.DefaultModelReader;
import org.apache.maven.model.io.ModelReader;

public final class POM {

    private static final String R = "-[0-9]+\\.jar";
    private static final Pattern P = Pattern.compile(R);

    private POM() {
    }

    private static Model getModel() {
        ModelReader modelReader = new DefaultModelReader();
        try {
            return modelReader.read(new File("pom.xml"), null);
        } catch (IOException cause) {
            throw new RuntimeException(cause);
        }
    }

    public static String getArtifactId() {
        Model model = getModel();
        return model.getArtifactId();
    }

    public static String getVersion() {
        Model model = getModel();
        return (model.getVersion() != null) ? model.getVersion() : model.getParent().getVersion();
    }

    public static String resolveVersion(String s, String version) {
        if (P.matcher(s).find()) {
            return s.replaceAll(R, String.format("-%s.jar", version));
        } else {
            return s;
        }
    }
}


text:
    Copyright © {{ consts.year }}
    {{ consts.owner }}.


text:
apt-get -y update
apt-get -yfV dist-upgrade

# Install dependencies.
echo "Installing Git & other dependencies..."
apt-get install -yfV         \
  build-essential            \
  curl                       \
  git-core                   \
  libcurl4-openssl-dev       \
  libreadline-dev            \
  libssl-dev                 \
  libxml2-dev                \
  libxslt1-dev               \
  libyaml-dev                \
  python-software-properties \
  zlib1g-dev                 \
  libffi-dev                 \
  libpq-dev                  \
  imagemagick                \
  libmagickwand-dev          \
  nginx                      \

# get and compile Ruby
echo "Getting & compiling Ruby from source...This will take a LONG TIME. Fear not!"
curl -LSso /tmp/ruby-2.4.1.tar.gz https://cache.ruby-lang.org/pub/ruby/2.4/ruby-2.4.1.tar.gz
tar -zxf /tmp/ruby-2.4.1.tar.gz -C /tmp

cd /tmp/ruby-2.4.1 && \
  ./configure --disable-install-doc && \
  make && \
  sudo make install

# install nodejs
echo "Installing NodeJS"
add-apt-repository -y ppa:chris-lea/node.js
apt-get -y update
apt-get install -y nodejs

# install postgres
echo "Installing PostgreSQL"
set -x
echo "deb http://apt.postgresql.org/pub/repos/apt/ trusty-pgdg main 9.3" \
    | sudo tee -a /etc/apt/sources.list.d/pgdg.list
wget --quiet -O - http://apt.postgresql.org/pub/repos/apt/ACCC4CF8.asc | sudo apt-key add -
sudo apt-get -y update
sudo apt-get -y install postgresql-9.3
sudo apt-get -y install postgresql-contrib-9.3

sudo sed -ibk \
    -re "s/[#]*listen_addresses = '.*'(.*)/listen_addresses = '*'\1/" \
    /etc/postgresql/9.3/main/postgresql.conf
echo "host    all   vagrant   10.0.2.2/32  trust" | sudo tee -a /etc/postgresql/9.3/main/pg_hba.conf
sudo su postgres -c "psql -c \"CREATE ROLE vagrant SUPERUSER LOGIN PASSWORD 'vagrant'\" "
sudo service postgresql restart

echo "gem: --no-ri --no-rdoc" > ~/.gemrc
echo 'installing Bundler'
gem install bundler

# Remove any leftovers
apt-get -y autoremove

sudo service nginx restart

cp /opt/gdi/development/motd.sh /etc/update-motd.d/99-gdi
chmod 755 /etc/update-motd.d/99-gdi


text:
ActionMailer::Base.delivery_method = :smtp
ActionMailer::Base.raise_delivery_errors = false

if RAILS_ENV == "production"
  ActionMailer::Base.default_url_options[:host] = 'proman.cpjobling.org.uk'
  ActionMailer::Base.perform_deliveries = true

  ActionMailer::Base.smtp_settings = {
    :address => "localhost",
    :port => 25,
    :domain => "cpjobling.org.uk"
  }
end

if RAILS_ENV == "development"
  ActionMailer::Base.default_url_options[:host] = 'www.localhost.com'
  ActionMailer::Base.perform_deliveries = false

  ActionMailer::Base.smtp_settings = {
    :enable_starttls_auto => true,
    :address => "smtp.gmail.com",
    :port => 587,
    :domain => 'gmail.com',
    :authentication => :plain,
    :user_name => APP_CONFIG['development_smtp_username'],
    :password =>  APP_CONFIG['developement_smtp_password']
  }

end

if RAILS_ENV == "test"
  ActionMailer::Base.default_url_options[:host] = 'www.example.com'
  ActionMailer::Base.delivery_method = :test
end

if RAILS_ENV == "cucumber"
  ActionMailer::Base.default_url_options[:host] = 'www.example.com'
  ActionMailer::Base.delivery_method = :test
end


text:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical">

    <android.support.design.widget.TabLayout
        android:id="@+id/ac_tab_layout"
        android:layout_width="match_parent"
        android:layout_height="wrap_content" />

    <android.support.v4.view.ViewPager
        android:id="@+id/ac_tab_vp"
        android:layout_width="match_parent"
        android:layout_height="0dp"
        android:layout_weight="1" />

</LinearLayout>


text:
using System;
using System.Collections.Generic;
using Autodesk.Revit.ApplicationServices;
using Autodesk.Revit.Attributes;
using Autodesk.Revit.DB;
using Autodesk.Revit.UI;
using System.IO;
using System.Windows.Media.Imaging;
#endregion

namespace NWCViewExporter
{
    class App : IExternalApplication
    {
        public static string dir = Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().Location);
        static string assyPath = Path.Combine(dir, "NWCViewExporter.dll");
        static string _imgFolder = Path.Combine(dir, "Images");
        public const string Caption = "NWC Exporter";

        public Result OnStartup(UIControlledApplication a)
        {
            try
            {
                AddRibbonPanel(a);
            }
            catch (Exception ex)
            {
                TaskDialog.Show("Ribbon", ex.ToString());
            }
            return Result.Succeeded;
        }

        private void AddRibbonPanel(UIControlledApplication app)
        {
            RibbonPanel panel = app.CreateRibbonPanel("NWC View Exporter");
            PushButtonData pbd_Options = new PushButtonData("Export Options", "Export Options", assyPath, "NWCViewExporter.Options");
            PushButtonData pbd_Sub = new PushButtonData("Subscribe", "Auto NWC ON", assyPath, "NWCViewExporter.SubscribeToEvent");
            pbd_Sub.LargeImage = NewBitmapImage("sub.png");
            pbd_Sub.ToolTip = "Turn ON Automatic NWC file creation after each save.";
            pbd_Sub.LongDescription = "Automatically creates an NWC Navisworks file after each time the project is saved. The selected view in the options dialog is used as the exported view. The NWC file is saved in the directory specified in the options dialog.";
            PushButtonData pbd_Unsub = new PushButtonData("Unsubscribe", "Auto NWC OFF", assyPath, "NWCViewExporter.UnsubscribeFromEvent");
            pbd_Unsub.LargeImage = NewBitmapImage("unsub.png");
            pbd_Unsub.ToolTip = "Turn OFF Automatic NWC file creation.";
            pbd_Unsub.LongDescription = "Turns off the automatic NWC file creator.";

            PushButton pb_Options = panel.AddItem(pbd_Options) as PushButton;
            //pb_Options.LargeImage = NewBitmapImage("options.png");
            pb_Options.LargeImage = GetEmbeddedImage("NWCViewExporter.options.png");
            pb_Options.ToolTip = "Set Options for Automatic NWC Creation";
            pb_Options.LongDescription = "Sets the view to use for Automatic NWC creation on each save as well as the destination folder to save the NWC file.";

            panel.AddSeparator();
            IList<RibbonItem> stacked = panel.AddStackedItems(pbd_Sub, pbd_Unsub);

            //Context help
            ContextualHelp contextHelp = new ContextualHelp(ContextualHelpType.ChmFile, dir + "/Resources/help.htm");

            pb_Options.SetContextualHelp(contextHelp);

            foreach (RibbonItem ri in stacked)
            {
                ri.SetContextualHelp(contextHelp); //set contextHelp for stacked items;
                if (ri.Name == "Subscribe")
                    ri.Enabled = true;
                else
                    ri.Enabled = false;
            }

        }

        static BitmapSource GetEmbeddedImage(string name)
        {
            try
            {
                System.Reflection.Assembly a = System.Reflection.Assembly.GetExecutingAssembly();
                Stream s = a.GetManifestResourceStream(name);
                return BitmapFrame.Create(s);
            }
            catch
            {
                return null;
            }
        }

        BitmapImage NewBitmapImage(string imgName)
        {
            return new BitmapImage(new Uri(Path.Combine(_imgFolder, imgName)));
        }

        public Result OnShutdown(UIControlledApplication a)
        {
            return Result.Succeeded;
        }
    }
}


text:
<feed version="0.3" xmlns="http://purl.org/atom/ns#">
<info type="text/html" mode="base64">
PGRpdj48YSBocmVmPSIvcmVsYXRpdmUvdXJpIj5jbGljayBoZXJlPC9hPjwvZGl2Pg==
</info>
</feed>


text:
<?php

declare(strict_types=1);

namespace Sylius\Bundle\ResourceBundle\DependencyInjection\Compiler;

use Symfony\Component\DependencyInjection\Compiler\CompilerPassInterface;
use Symfony\Component\DependencyInjection\ContainerBuilder;
use Symfony\Component\DependencyInjection\Reference;

/**
 * @author Arkadiusz Krakowiak <arkadiusz.krakowiak@lakion.com>
 */
final class RegisterFormBuilderPass implements CompilerPassInterface
{
    /**
     * {@inheritdoc}
     */
    public function process(ContainerBuilder $container): void
    {
        if (!$container->hasDefinition('sylius.registry.form_builder')) {
            return;
        }

        $registry = $container->findDefinition('sylius.registry.form_builder');

        foreach ($container->findTaggedServiceIds('sylius.default_resource_form.builder') as $id => $attributes) {
            if (!isset($attributes[0]['type'])) {
                throw new \InvalidArgumentException('Tagged grid drivers needs to have `type` attribute.');
            }

            $registry->addMethodCall('register', [$attributes[0]['type'], new Reference($id)]);
        }
    }
}


text:
require 'spec_helper'

describe 'expect_status' do
  it 'should verify correct status code' do
    mock_get('simple_get')
    get '/simple_get'
    expect_status(200)
  end

  it 'should fail when incorrect status code is returned' do
    mock_get('simple_get')
    get '/simple_get'
    expect{expect_status(123)}.to raise_error
  end
end


text:
package database;

import java.sql.SQLException;
import java.util.Date;

import objectFiles.Guest;
import objectFiles.Host;
import objectFiles.Meeting;

public class DatabaseDriver {

	public static void main (String args[]) {
		Database db = new Database("UserInfo", "localhost", 3306);
		try {
			db.getConnection();
			db.addUser("bieren", "root", "a@gmail.com", true);
			System.out.println(db.getUserId("bieren"));
//			db.addUser("byron", "root", "a@gmail.com", true); //testing add host WORKS
//			db.addUser("muyao", "root", "r@gmail.com", false); //testing add host WORKS
//			db.addUser("muyao", "root", "x@gmail.com", true); //should not work
//			db.addUser("gautam2", "root5", "xt2@gmail.com", true); //should work
		} catch (SQLException e) {
			System.out.println("test");
			e.printStackTrace();
		}

		//Host h = db.getHost(2); //testing gethost WORKS
		//System.out.println(h.getEmail() + h.getUsername() + h.getPassword());
//		System.out.println(db.authenticateHost("byron", "root")); //should be 2 WORKS
//		System.out.println(db.authenticateHost("gautam", "mattsucks123")); //should be 2 WORKS
//		System.out.println(db.authenticateHost("byron", "root2")); //should be -1 WORKS
//		System.out.println(db.authenticateHost("gautam2", "root5")); //should be -1 WORKS
//		System.out.println("test2");
//
//		Meeting m = new Meeting(3, 2, 3); //2 x 3 array with 3 users
//		Date d = new Date(); //today's date
//		m.setStartDate(d);
//		m.setStartTime(8);
//		m.setHost(h); //host is byron
//		m.setMeetingName("testmeeting");
//		Guest g = new Guest();
//		g.setUserId(3);
//		Guest g2 = new Guest();
//		g2.setUserId(4);
//		Database meetingDB = new Database("MeetingInfo", "localhost", 3306);
//		try {
//			meetingDB.getConnection();
//		} catch (SQLException e) {
//			// TODO Auto-generated catch block
//			e.printStackTrace();
//		}
//
//		Meeting mtest = meetingDB.getMeeting(6);
//
//		m.setMeetingID(1);
//
//		System.out.println(mtest.getMeetingName());
//
//
//		/*
//		 *		2	0
//		 * 		1	3
//		 * 		0	1
//		 *
//		 */
//
//		Availability av = new Availability();
//
//
//		m.getTimetable()[0][1].getAvailableUsers().add(g);
//		m.getTimetable()[0][1].getAvailableUsers().add(h);
//		m.getTimetable()[0][1].getAvailableUsers().add(g2);
//
//
//
//
//		m.getTimetable()[0][0].getUnavailableUsers().add(g);
//		m.getTimetable()[0][0].getUnavailableUsers().add(h);
//		m.getTimetable()[0][0].getAvailableUsers().add(g2);
//
//		m.getTimetable()[1][0].getAvailableUsers().add(g);
//		m.getTimetable()[1][0].getAvailableUsers().add(h);
//		m.getTimetable()[1][0].getUnavailableUsers().add(g2);
//
//		m.getTimetable()[1][1].getUnavailableUsers().add(g);
//		m.getTimetable()[1][1].getUnavailableUsers().add(h);
//		m.getTimetable()[1][1].getUnavailableUsers().add(g2);
//
//		m.getTimetable()[2][1].getUnavailableUsers().add(g);
//		m.getTimetable()[2][1].getAvailableUsers().add(h);
//		m.getTimetable()[2][1].getAvailableUsers().add(g2);
//
//		m.getTimetable()[2][0].getAvailableUsers().add(g);
//		m.getTimetable()[2][0].getAvailableUsers().add(h);
//		m.getTimetable()[2][0].getAvailableUsers().add(g2);
//
//
//
//		int meetingId = meetingDB.addMeeting(m.getMeetingName(), m.getNumUsers(), m.getNumDays(), m.getNumHoursPerDay(), m.getHost().getUserId(), m.getStartDate(), m.getStartTime());
//
//
//		Database availDB = new Database("AvailabilityInfo", "localhost", 0);
//		try {
//			availDB.getConnection();
//		} catch (SQLException e) {
//
//			e.printStackTrace();
//		}
//
//		String test = "1,1,1,0,1,0";
//		availDB.setAvailFromString(test, meetingId, 2);
//		availDB.setAvailabilities(m.getTimetable(), 26);
//
//		System.out.println(availDB.getMeetingAvailabilities(meetingId));

	}

}


text:
To use the python debugger(PDB) that comes with python, open a script and do
```python
import pdb
```

and at that point where you want the debugger to trigger, insert
```python
pdb.set_trace()
```

The debugger can also be invoked in a single line, as follows.
```python
import pdb; pdb.set_trace()
```

# Check for syntax errors

To check for compile errors,
```bash
python -m py_compile script.py
```

[source](http://stackoverflow.com/questions/4284313/how-can-i-check-the-syntax-of-python-script-without-executing-it)

# Multiline Strings and Multiline statements/expressions
## Multiline Strings
```Python
s = ("this is a very"
     "long string too"
     "for sure ..."
    )
print(s)
```

And this is what you get,
```
this is a verylong string toofor sure
```

It doesn't add any `spaces` or anything. You gotta add it yourself.
[source](http://stackoverflow.com/questions/10660435/pythonic-way-to-create-a-long-multi-line-string)

## Multiline Statements/Expressions
### Implicit
The preferred way is to do it the implicit way. Expressions inside parentheses
can be entered in multiple lines. Python implicitly knows that everything
within the parentheses is part of the same statement/expression
```Python
a = some_func(
    '1' + '2' + '3' + '4')
```

### Explicit
The explicit way is to use the `\` symbol at the point where the line is
continued on the next line
```Python
a = '1' + '2' + \
    '3' + '4'
```

[source](http://stackoverflow.com/questions/4172448/is-it-possible-to-break-a-long-line-to-multiple-lines-in-python)


text:
<?php

namespace Sp\ProvinciaBundle;

use Symfony\Component\HttpKernel\Bundle\Bundle;

class ProvinciaBundle extends Bundle
{
}