text:
[![Build](https://github.com/MAXakaWIZARD/PoParser/actions/workflows/ci.yml/badge.svg)](https://github.com/MAXakaWIZARD/PoParser/actions)
[![Scrutinizer Code Quality](https://scrutinizer-ci.com/g/MAXakaWIZARD/PoParser/badges/quality-score.png?b=master)](https://scrutinizer-ci.com/g/MAXakaWIZARD/PoParser/?branch=master)
[![Code Climate](https://codeclimate.com/github/MAXakaWIZARD/PoParser/badges/gpa.svg)](https://codeclimate.com/github/MAXakaWIZARD/PoParser)
[![Coverage Status](https://coveralls.io/repos/MAXakaWIZARD/PoParser/badge.svg?branch=master)](https://coveralls.io/r/MAXakaWIZARD/PoParser?branch=master)

[![GitHub tag](https://img.shields.io/github/tag/MAXakaWIZARD/PoParser.svg?label=latest)](https://packagist.org/packages/maxakawizard/po-parser)
[![Packagist](https://img.shields.io/packagist/dt/maxakawizard/po-parser.svg)](https://packagist.org/packages/maxakawizard/po-parser)
[![Packagist](https://img.shields.io/packagist/dm/maxakawizard/po-parser.svg)](https://packagist.org/packages/maxakawizard/po-parser)

[![Minimum PHP Version](http://img.shields.io/badge/php-%3E%3D%207.1-8892BF.svg)](https://php.net/)
[![License](https://img.shields.io/packagist/l/maxakawizard/po-parser.svg)](https://packagist.org/packages/maxakawizard/po-parser)

Gettext *.po files parser for PHP.

This package is compliant with [PSR-4](http://www.php-fig.org/psr/4/) autoloading standard and [PSR-12](http://www.php-fig.org/psr/12/) coding standard.
If you notice compliance oversights, please send a patch via pull request.

## Usage
### Read file content
```php
$parser = new PoParser\Parser();
$parser->read('my-pofile.po');
$entries = $parser->getEntriesAsArrays();
// Now $entries contains every string information in your pofile

echo '<ul>';
foreach ($entries as $entry) {
   echo '<li>'.
   '<b>msgid:</b> '.$entry['msgid'].'<br>'.         // Message ID
   '<b>msgstr:</b> '.$entry['msgstr'].'<br>'.       // Translation
   '<b>reference:</b> '.$entry['reference'].'<br>'. // Reference
   '<b>msgctxt:</b> ' . $entry['msgctxt'].'<br>'.   // Message Context
   '<b>tcomment:</b> ' . $entry['tcomment'].'<br>'. // Translator comment
   '<b>ccomment:</b> ' . $entry['ccomment'].'<br>'. // Code Comment
   '<b>obsolete?:</b> '.(string)$entry['obsolete'].'<br>'. // Is obsolete?
    '<b>fuzzy?:</b> ' .(string)$entry['fuzzy'].     // Is fuzzy?
    '</li>';
}
echo '</ul>';
```

### Modify content
```php
$parser = new PoParser\Parser();
$parser->read('my-pofile.po');
// Entries are stored in array, so you can modify them.

// Use updateEntry method to change messages you want.
$parser->updateEntry('Write your email', 'Escribe tu email');
$parser->write('my-pofile.po');
```

## Todo
* Improve entries edit interface
* Ability to change any entry fields
* Discover what's the meaning of "#@ " line
* Fix multiline `msgstr` processing (for singular and plural entries)
* Implement previous untranslated strings support

## License
This library is released under [MIT](http://www.tldrlegal.com/license/mit-license) license.


text:
/* Script for content page (page in browser)
 * Only communicate with background page */

var imgsrc = $("#ctl00_imgAppBanner").prop("src");
var pagenum = getPage();
var username = getName();

if (imgsrc && imgsrc.indexOf("23.jpg") > 0) {
    /* On the first-step page */
    var links = $("#ctl00_ContentPlaceHolder1_gvEventList").find(".textwrap").find("a");
    if (links.length != 0) {
        console.log("It's on the first-step page");
        getNextReg();
    }
    /* On the second page */
    var btnReg = $("#ctl00_ContentPlaceHolder1_btnRegister");
    if (btnReg.length == 1) {
        console.log("It's on the second-step page");
        secondStep();
    }
    /* On the third page */
    var btnNext = $("#ctl00_ContentPlaceHolder1_btnNext");
    if (btnNext.length == 1) {
        console.log("It's on the third-step page");
        thirdStep();
    }
    /* On the fourth page */
    var btnHome = $("#ctl00_ContentPlaceHolder1_btnHome");
    if (btnHome.length == 1) {
        console.log("It's on the last-step page");
        lastStep();
    }
}

chrome.runtime.onMessage.addListener(function(request, sender, sendRequest) {
    if (request.type == "BeginReg") {      //{type:"BeginReg", index:item}
        var index = request.index;
        console.log("Begin reg process, start with item: " + index);
        firstStep(index);
    }
});

/* Get current page number */
function getPage() {
    var pagenum = $("[style='color:#507CD1;background-color:White;']").find("span").text();
	if (!pagenum) pagenum = 1;
    return pagenum;
}

/* Get user name, to prevent duplicate stats */
function getName() {
	var username = $("#ctl00_lblHelloMsg").text().substr(9);
	return username;
}

/* Inject code into the original page */
function injectCode(code) {
    var actualCode = code;
    var script = document.createElement('script');
    script.textContent = actualCode;
    (document.head || document.documentElement).appendChild(script);
}

function firstStep(index) {
    var page = Math.floor(index / 100);
    if (page != pagenum) {
        console.log("current at page "+pagenum+", redirect to page "+page);
        injectCode("__doPostBack('ctl00$ContentPlaceHolder1$gvEventList','Page$"+page+"')");
    }
    else {
        console.log("Do first step clicking");
        injectCode("__doPostBack('ctl00$ContentPlaceHolder1$gvEventList$ctl"+(index+2).toString().substring(1,3)+"$lnkWorkshop','')");
    }
}

function secondStep() {
	if ($("#ctl00_ContentPlaceHolder1_lblPageMsg").text() == "You have already registered this class.") {
		console.log("Already registered. Stop at second step.");
		chrome.runtime.sendMessage({type:"RegSucceed"},function(response) {
			if (response.confirmed == true) {
				console.log("btnBack clicked");
				injectCode('document.getElementById("ctl00_ContentPlaceHolder1_btnBack").click()');
			}
		});
	}
	else {
		console.log("btnRegister clicked");
		injectCode('document.getElementById("ctl00_ContentPlaceHolder1_btnRegister").click()');
	}
}

function thirdStep() {
    console.log("btnNext clicked");
	/* This part of code use the brilliant idea from https://github.com/sheepfriend/reg_dining_javascript */
    injectCode(['temp=document.getElementById("ctl00_ContentPlaceHolder1_btnCancel");',
				'temp.id="ctl00_ContentPlaceHolder1_btnNext";',
				'temp.name="ctl00$ContentPlaceHolder1$btnNext";',
				'temp.click();'].join('\n'));
}

function lastStep() {
    console.log("Reg done. Send success message to background...");
    chrome.runtime.sendMessage({type:"RegSucceed"},function(response) {
        if (response.confirmed == true) {
            console.log("btnHome clicked");
            injectCode('document.getElementById("ctl00_ContentPlaceHolder1_btnHome").click()');
		}
    });
}

function getNextReg() {
    var nextone = "Error";
    chrome.runtime.sendMessage({type:"GetNextReg"},function(response) {
        nextone = response.nextone;
        console.log("Response of next reg item: " + nextone);
        /* If to-reg list is empty */
        if (nextone == undefined) {
            console.log("Reg has never begun. Sending dining list to background...");
            var arr = new Array();
            for (var i=0;i<links.length;i++) {
                arr[i]=links[i].text;
            }
            console.log("current at page " + pagenum);
            chrome.runtime.sendMessage({type:"GotDiningList", dlist:arr, page:pagenum, name:username});

            //Show usage banner
            if ($(".fixLayout") && $(".fixLayout").html().indexOf("Communal Dining") > 0 ) {
                $("body").prepend('<h3 style="background-color:yellow;display:inline;">\
                    Click the icon in address bar to access the dining-reg plugin\
                    </h3>');
            }
        }
        /* If error */
        else if (nextone == "Error") {
            console.log("Error occurred when getting next item!!!");
        }
        /* If to-reg list is not empty */
        else {
            console.log("In reg process...Do next reg: " + nextone);
            firstStep(nextone);
        }

        return nextone;
    });
}

redpajama_set_name: RedPajamaGithub


text:
translating by lujun9972
Solve "error: failed to commit transaction (conflicting files)" In Arch Linux
======

![](https://www.ostechnix.com/wp-content/uploads/2018/06/arch_linux_wallpaper-720x340.png)

It's been a month since I upgraded my Arch Linux desktop. Today, I tried to update my Arch Linux system, and ran into an error that said **"error: failed to commit transaction (conflicting files) stfl: /usr/lib/libstfl.so.0 exists in filesystem"**. It looks like one library (/usr/lib/libstfl.so.0) that exists on my filesystem and pacman can't upgrade it. If you're encountered with the same error, here is a quick fix to resolve it.

### Solve "error: failed to commit transaction (conflicting files)" In Arch Linux

You have three options.

1. Simply ignore the problematic **stfl** library from being upgraded and try to update the system again. Refer this guide to know [**how to ignore package from being upgraded**][1].

2. Overwrite the package using command:
```
$ sudo pacman -Syu --overwrite /usr/lib/libstfl.so.0
```

3. Remove stfl library file manually and try to upgrade the system again. Please make sure the intended package is not a dependency to any important package. and check the archlinux.org whether are mentions of this conflict.
```
$ sudo rm /usr/lib/libstfl.so.0
```

Now, try to update the system:
```
$ sudo pacman -Syu
```

I chose the third option and just deleted the file and upgraded my Arch Linux system. It works now!

Hope this helps. More good stuffs to come. Stay tuned!

Cheers!

--------------------------------------------------------------------------------

via: https://www.ostechnix.com/how-to-solve-error-failed-to-commit-transaction-conflicting-files-in-arch-linux/

作者:[SK][a]
选题:[lujun9972](https://github.com/lujun9972)
译者:[lujun9972](https://github.com/lujun9972)
校对:[校对者ID](https://github.com/校对者ID)

本文由 [LCTT](https://github.com/LCTT/TranslateProject) 原创编译,[Linux中国](https://linux.cn/) 荣誉推出

[a]:https://www.ostechnix.com/author/sk/
[1]:https://www.ostechnix.com/safely-ignore-package-upgraded-arch-linux/


text:
// Copyright 2014 Google Inc. 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
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package com.google.devtools.build.lib.skyframe;

import com.google.common.collect.ImmutableSet;
import com.google.devtools.build.lib.cmdline.PackageIdentifier.RepositoryName;
import com.google.devtools.build.lib.collect.nestedset.NestedSet;
import com.google.devtools.build.lib.collect.nestedset.NestedSetBuilder;
import com.google.devtools.build.lib.collect.nestedset.Order;
import com.google.devtools.build.lib.packages.Package;
import com.google.devtools.build.lib.skyframe.RecursivePkgValue.RecursivePkgKey;
import com.google.devtools.build.lib.vfs.PathFragment;
import com.google.devtools.build.lib.vfs.RootedPath;
import com.google.devtools.build.skyframe.SkyFunction;
import com.google.devtools.build.skyframe.SkyKey;
import com.google.devtools.build.skyframe.SkyValue;

import java.util.Map;

import javax.annotation.Nullable;

/**
 * RecursivePkgFunction builds up the set of packages underneath a given directory
 * transitively.
 *
 * <p>Example: foo/BUILD, foo/sub/x, foo/subpkg/BUILD would yield transitive packages "foo" and
 * "foo/subpkg".
 */
public class RecursivePkgFunction implements SkyFunction {

  @Override
  public SkyValue compute(SkyKey skyKey, Environment env) {
    return new MyTraversalFunction().visitDirectory((RecursivePkgKey) skyKey.argument(), env);
  }

  private static class MyTraversalFunction
      extends RecursiveDirectoryTraversalFunction<MyVisitor, RecursivePkgValue> {

    @Override
    protected RecursivePkgValue getEmptyReturn() {
      return RecursivePkgValue.EMPTY;
    }

    @Override
    protected MyVisitor getInitialVisitor() {
      return new MyVisitor();
    }

    @Override
    protected SkyKey getSkyKeyForSubdirectory(RepositoryName repository, RootedPath subdirectory,
        ImmutableSet<PathFragment> excludedSubdirectoriesBeneathSubdirectory) {
      return RecursivePkgValue.key(
          repository, subdirectory, excludedSubdirectoriesBeneathSubdirectory);
    }

    @Override
    protected RecursivePkgValue aggregateWithSubdirectorySkyValues(MyVisitor visitor,
        Map<SkyKey, SkyValue> subdirectorySkyValues) {
      // Aggregate the transitive subpackages.
      for (SkyValue childValue : subdirectorySkyValues.values()) {
        if (childValue != null) {
          visitor.addTransitivePackages(((RecursivePkgValue) childValue).getPackages());
        }
      }
      return visitor.createRecursivePkgValue();
    }
  }

  private static class MyVisitor implements RecursiveDirectoryTraversalFunction.Visitor {

    private final NestedSetBuilder<String> packages = new NestedSetBuilder<>(Order.STABLE_ORDER);

    @Override
    public void visitPackageValue(Package pkg, Environment env) {
      packages.add(pkg.getName());
    }

    void addTransitivePackages(NestedSet<String> transitivePackages) {
      packages.addTransitive(transitivePackages);
    }

    RecursivePkgValue createRecursivePkgValue() {
      return RecursivePkgValue.create(packages);
    }
  }

  @Nullable
  @Override
  public String extractTag(SkyKey skyKey) {
    return null;
  }
}


text:
package syntax.parameters.named.java;

import java.awt.Color;

public class Shape {

    private final int size;
    private final Color color;
    private final String name;

    private Shape(Builder builder) {
        size = builder.size;
        color = builder.color;
        name = builder.name;
    }

    public static Builder builder() {
        return new Builder();
    }

    public static class Builder {
        private int size;
        private Color color;
        private String name;

        public Shape build() {
            return new Shape(this);
        }

        public Builder setSize(int size) {
            this.size = size;
            return this;
        }

        public Builder setColor(Color color) {
            this.color = color;
            return this;
        }

        public Builder setName(String name) {
            this.name = name;
            return this;
        }
    }

}


text:
import glob
import os

paths = []
for pattern in [ '*.actual', '*.actual-rewrite', '*.rewrite', '*.process-output' ]:
    paths += glob.glob( 'data/' + pattern )

for path in paths:
    os.unlink( path )


text:
package games.demo

object Specifics {
  type WebSocketClient = transport.javascript.WebSocketClient
  val platformName = "JS"
}


text:
/// <reference path="../typings/AreaSpawnr.d.ts" />
/// <reference path="../typings/GameStartr.d.ts" />
/// <reference path="../typings/GroupHoldr.d.ts" />
/// <reference path="../typings/InputWritr.d.ts" />
/// <reference path="../typings/ItemsHoldr.d.ts" />
/// <reference path="../typings/MapsCreatr.d.ts" />
/// <reference path="../typings/MapScreenr.d.ts" />
/// <reference path="../typings/ObjectMakr.d.ts" />
/// <reference path="../typings/PixelDrawr.d.ts" />
/// <reference path="../typings/TimeHandlr.d.ts" />

export interface IThing extends GameStartr.IThing {
    dead: boolean;

    // These attributes appear to be FSM-specific...
    outerok?: number;
}

export interface IPreThing extends MapsCreatr.IPreThing {
    thing: IThing;
    xloc: number;
    yloc: number;
}

export interface IPreThingDescriptor {
    offsetTop?: number;
    offsetLeft?: number;
    width?: IPreThingDimensionDescriptor;
    height?: IPreThingDimensionDescriptor;
    options?: {
        [i: string]: IPreThingDimensionDescriptor;
    };
}

export interface IPreThingDimensionDescriptor {
    type?: string;
    value?: any;
    Infinite?: any;
    mod?: number;
    real?: number;
}

export interface IMapRaw extends MapsCreatr.IMapRaw {
    areas: {
        [i: number]: IAreaRaw;
        [i: string]: IAreaRaw;
    };

    time?: number;
}

export interface IAreaRaw extends MapsCreatr.IAreaRaw {
    setting?: string;
}

export interface IDataMouseEvent extends MouseEvent {
    dataTransfer: DataTransfer;
}

export interface IDataProgressEvent extends ProgressEvent {
    currentTarget: IDataEventTarget;
}

export interface IDataEventTarget extends EventTarget {
    result: string;
}

export interface IThingIcon extends HTMLElement {
    options: any[];
}

export interface IDisplayContainer {
    "container": HTMLElement;
    "scrollers": {
        "container": HTMLElement;
        "left": HTMLElement;
        "right": HTMLElement;
    };
    "gui": HTMLElement;
    "head": HTMLElement;
    "namer": HTMLInputElement;
    "minimizer": HTMLElement;
    "stringer": {
        "textarea": HTMLTextAreaElement;
        "messenger": HTMLElement;
    };
    "inputDummy": HTMLInputElement;
    "sections": {
        "ClickToPlace": {
            "container": HTMLElement;
            "Things": HTMLElement;
            "Macros": HTMLElement;
            "VisualOptions": HTMLElement;
        };
        "MapSettings": {
            "container": HTMLElement;
            "Time": HTMLSelectElement;
            "Setting": {
                "Primary": HTMLSelectElement;
                "Secondary": HTMLSelectElement;
                "Tertiary": HTMLSelectElement;
            };
            "Area": HTMLSelectElement;
            "Location": HTMLSelectElement;
            "Entry": HTMLSelectElement;
        };
        "JSON": HTMLElement;
        "buttons": {
            "ClickToPlace": {
                "container": HTMLElement;
                "Things": HTMLElement;
                "Macros": HTMLElement;
            };
            "MapSettings": HTMLElement;
            "JSON": HTMLElement;
        }
    };
}

export interface ILevelEditrSettings {
    GameStarter: GameStartr.GameStartr;
    prethings: { [i: string]: IPreThing[] };
    thingGroups: string[];
    things: { [i: string]: IThing };
    macros: { [i: string]: MapsCreatr.IMacro };
    beautifier: (text: string) => string;
    mapNameDefault?: string;
    mapTimeDefault?: number;
    mapSettingDefault?: string;
    mapEntrances?: string[];
    mapDefault?: IMapRaw;
    blocksize?: number;
    keyUndefined?: string;
}

/**
 * GUI-based level creation & editing for GameStartr.
 */
export interface ILevelEditr {
    getEnabled(): boolean;
    enable(): void;
    disable(): void;
    minimize(): void;
    maximize(): void;
    startBuilding(): void;
    startPlaying(): void;
    downloadCurrentJSON(): void;
    setCurrentJSON(json: string): void;
    loadCurrentJSON(): void;
    beautify(text: string): string;
    handleUploadCompletion(event: IDataProgressEvent): void;
}


text:
"""Various TensorFlow Ops (deprecated).

This module and all its submodules are deprecated. See
[contrib/learn/README.md](https://www.tensorflow.org/code/tensorflow/contrib/learn/README.md)
for migration instructions.
"""

from __future__ import absolute_import
from __future__ import division
from __future__ import print_function

# pylint: disable=wildcard-import
from tensorflow.contrib.learn.python.learn.ops.embeddings_ops import *
from tensorflow.contrib.learn.python.learn.ops.losses_ops import *
from tensorflow.contrib.learn.python.learn.ops.seq2seq_ops import *
# pylint: enable=wildcard-import


text:
"use strict";
app.controller("CONTROLLER_NAME", function($scope, $location){

	$scope.table_name = "TABLE_NAME";
	$scope.primary_key = "PRIMARY_KEY";

	//List
	$scope.list = function(){
		basel.database.runAsync("SELECT * FROM "+$scope.table_name, function(data){
			$scope.items = data;
		});
	}

	//Saving
	$scope.save = function(){
		if($scope.form[$scope.primary_key]){
			//Edit
			var id = $scope.form[$scope.primary_key];
			delete $scope.form[$scope.primary_key];
			delete $scope.form.$$hashKey; //Apaga elemento $$hashKey do objeto
			basel.database.update($scope.table_name, $scope.form, {PRIMARY_KEY: id}); //entidade, dados, where
		}else{
			//new
			basel.database.insert($scope.table_name, $scope.form); // entidade, dados
		}
		$scope.form = {};
		$scope.list();
		$('#CONTROLLER_NAME').modal('hide');
	}

	// Cancel form
	$scope.cancel = function(){
		$scope.form = {};
	}

	//Abrindo para editar
	$scope.edit = function(data){
		$scope.form = data;
		$('#CONTROLLER_NAME').modal('show');
	}

	//Excluindo
	$scope.delete = function(data){
		if(confirm("Are you sure?")){
			basel.database.delete($scope.table_name, {PRIMARY_KEY: data[$scope.primary_key]});
			$scope.list();
		}
	}
});


text:
{% extends ../templates/admin/index.html %}
{% block title %}Instalación{% end %}

{% block style %}
	<link rel="stylesheet" type="text/css" href="/admin/static/css/normalize.css">
	<link href="//cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/3.3.2/css/bootstrap.min.css" rel="stylesheet">
	<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-material-design/0.2.2/css/material.css">
	<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-material-design/0.2.2/css/ripples.css">
	<link rel="stylesheet" type="text/css" href="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-material-design/0.2.2/css/material-wfont.css">
	<link rel="stylesheet" href="/admin/static/css/style.css">
{% end %}

{% block body %}

		{% if errors %}
	      {% for e in errors %}

	            <button type="button" class="close" data-dismiss="alert">×</button>
	            {{e}}

	      {% end %}
	    {% end %}
	    {% if messages %}
	      {% for e in messages %}

	            <button type="button" class="close" data-dismiss="alert">×</button>
	            {{e}}

	      {% end %}
	    {% end %}

Configuración de proyecto

Hola, esta sección es para poder configurar nuestro proyecto luego de haberlo descomprimido.

 Requerimientos

Hay un archivo en el directorio raiz, que se llama "config.py" es necesario:

Configurar el Debug. True o False, en caso de FALSE

Configurar la base de datos

Configurar la base de datos a utilizar.

Usuario Administrador

				{% raw _data['form'] %}

{% end %}

{% block script %}

{% end %}


text:
 - 2022-05-18 - [changes](https://github.com/snf4j/snf4j/compare/v1.9.0...v1.10.0)
 - Added support for byte buffer holder [(#85)](https://github.com/snf4j/snf4j/pull/85)
 - Enhanced handling of exceptions thrown in session handlers [(#86)](https://github.com/snf4j/snf4j/pull/86)

#### 1.9.0
 - 2022-03-09 - [changes](https://github.com/snf4j/snf4j/compare/v1.8.0...v1.9.0)
 - Support for connection through SOCKS proxy [(#81)](https://github.com/snf4j/snf4j/pull/81)
 - Added proxy basic HTTP authentication scheme [(#82)](https://github.com/snf4j/snf4j/pull/82)
 - Added builders for SSLContext and SSLEngine [(#83)](https://github.com/snf4j/snf4j/pull/83)

#### 1.8.0
 - 2021-11-01 - [changes](https://github.com/snf4j/snf4j/compare/v1.7.0...v1.8.0)
 - Migrated from Travis-CI to GitHub Action [(#67)](https://github.com/snf4j/snf4j/pull/67)
 - Generic inbound type in IBaseDecoder [(#68)](https://github.com/snf4j/snf4j/pull/68)
 - Improved output splitting produced by ZlibDecoder [(#70)](https://github.com/snf4j/snf4j/pull/70)
 - Controlling session closing by type of thrown exception [(#72)](https://github.com/snf4j/snf4j/pull/72)
 - Added direct task execution from session object [(#75)](https://github.com/snf4j/snf4j/pull/75)
 - Added support for pipeline of sessions operating on single connection [(#76)](https://github.com/snf4j/snf4j/pull/76)
 - Added support for connection through HTTP proxy [(#77)](https://github.com/snf4j/snf4j/pull/77)
 - Support for WebSocket protocol [(#78)](https://github.com/snf4j/snf4j/pull/78)

#### 1.7.0
 - 2021-03-20 - [changes](https://github.com/snf4j/snf4j/compare/v1.6.0...v1.7.0)
 - Added channel context for selector loop genericity [(#55)](https://github.com/snf4j/snf4j/pull/55)
 - Added support for SCTP protocol [(#60)](https://github.com/snf4j/snf4j/pull/60)
 - Fixed #56: Encoding does not release buffers when the last encoder has byte[] as the inbound type [(#61)](https://github.com/snf4j/snf4j/pull/61)
 - Fixed #57: Future objects returned by write/send methods of datagram-oriented sessions may signal completion too quickly [(#61)](https://github.com/snf4j/snf4j/pull/61)
 - Fixed #62: Adding/Removal of an event-driven codec to/from a codec pipeline is not signaled in open sessions [(#63)](https://github.com/snf4j/snf4j/pull/63)

#### 1.6.0
 - 2020-12-30 - [changes](https://github.com/snf4j/snf4j/compare/v1.5.0...v1.6.0)
 - Improved handling of empty buffers in engine handlers [(#48)](https://github.com/snf4j/snf4j/pull/48)
 - Added thread-local caching allocator [(#51)](https://github.com/snf4j/snf4j/pull/51)
 - Improved SSL/TLS max buffer size configuration [(#52)](https://github.com/snf4j/snf4j/pull/52)
 - Access to engine's internal session from engine-driven sessions [(#53)](https://github.com/snf4j/snf4j/pull/53)

#### 1.5.0
 - 2020-12-09 - [changes](https://github.com/snf4j/snf4j/compare/v1.4.0...v1.5.0)
 - Added ZLIB and GZIP codecs [(#41)](https://github.com/snf4j/snf4j/pull/41)
 - Performance improvements [(#43)](https://github.com/snf4j/snf4j/pull/43)

#### 1.4.0
 - 2020-08-02 - [changes](https://github.com/snf4j/snf4j/compare/v1.3.0...v1.4.0)
 - Added datagram server handler [(#34)](https://github.com/snf4j/snf4j/pull/34)
 - Added support for session timer [(#35)](https://github.com/snf4j/snf4j/pull/35)
 - Improved closing in session events [(#36)](https://github.com/snf4j/snf4j/pull/36)
 - Codec improvements for datagram server sessions [(#37)](https://github.com/snf4j/snf4j/pull/37)
 - Support for DTLS [(#38)](https://github.com/snf4j/snf4j/pull/38)
 - Added DTLS server/client example [(#39)](https://github.com/snf4j/snf4j/pull/39)

#### 1.3.0
 - 2019-12-14 - [changes](https://github.com/snf4j/snf4j/compare/v1.2.0...v1.3.0)
 - Added support for protocol engines [(#23)](https://github.com/snf4j/snf4j/pull/23)
 - Added support for codec executors [(#27)](https://github.com/snf4j/snf4j/pull/27)
 - Execution of tasks in selector loop's thread [(#28)](https://github.com/snf4j/snf4j/pull/28)
 - Logging enhancements [(#30)](https://github.com/snf4j/snf4j/pull/30)
 - Added compound decoder/encoder [(#31)](https://github.com/snf4j/snf4j/pull/31)
 - Support for jdk11 (TLS 1.3) [(#32)](https://github.com/snf4j/snf4j/pull/32)

#### 1.2.0
 - 2019-02-27 - [changes](https://github.com/snf4j/snf4j/compare/v1.1.0...v1.2.0)
 - Added logger binder for Log4j 2 API [(#21)](https://github.com/snf4j/snf4j/pull/21)
 - Fixes #19: Fixed session gentle closing [(#20)](https://github.com/snf4j/snf4j/pull/20)

 #### 1.1.0
 - 2019-02-10
 - Initial publishing


text:
<!DOCTYPE html>

        <meta charset="utf-8">
        <title></title>
        <meta name="description" content="">
        <meta name="HandheldFriendly" content="True">
        <meta name="MobileOptimized" content="320">
        <meta name="viewport" content="width=device-width, initial-scale=1">
        <meta http-equiv="cleartype" content="on">

        <link rel="stylesheet" href="css/normalize.css">
        <link rel="stylesheet" href="css/main.css">
        <link rel="stylesheet" href="css/static-styles.css">
        <link rel="stylesheet" type="text/css" href="css/common.css">
        <link rel="stylesheet" type="text/css" href="css/mobile1.css">

Quotes

Answers

Events

Images

About

Contact

My Profile

Share


text:
package spk

import org.apache.solr.client.solrj.impl.HttpSolrClient

object App {

  def main(args: Array[String]) = {
    args match {
      case Array("index", url, size, batchSize) =>
        withSpk(url) {
          _.buildIndex(size.toInt, batchSize.toInt)
        }
      case Array("search", url, count) =>
        withSpk(url) {
          _.search(count.toInt)
        }
      case _ => println("Usage: [cmd] [url]")
    }

    def withSpk(url: String)(f: SolrPerformanceKit => Unit) = {
      val solrClient = new HttpSolrClient(url)
      val spk = SolrPerformanceKit(solrClient)
      f.apply(spk)
    }
  }

}


text:
package org.eknet.neoswing.utils;

import com.tinkerpop.blueprints.Direction;
import com.tinkerpop.blueprints.Edge;
import com.tinkerpop.blueprints.Element;
import com.tinkerpop.blueprints.Vertex;
import com.tinkerpop.blueprints.util.ElementHelper;
import edu.uci.ics.jung.graph.Graph;
import edu.uci.ics.jung.graph.util.EdgeType;
import org.eknet.neoswing.ComponentFactory;
import org.eknet.neoswing.DefaultComponentFactory;
import org.eknet.neoswing.ElementId;
import org.eknet.neoswing.GraphModel;
import org.eknet.neoswing.JideComponentFactory;
import org.eknet.neoswing.NeoSwing;
import org.eknet.neoswing.loader.Neo4JEmbeddedLoader;
import org.eknet.neoswing.loader.OrientDbLoader;
import org.eknet.neoswing.loader.TitanLoader;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.swing.Action;
import javax.swing.Icon;
import javax.swing.ImageIcon;
import javax.swing.JFileChooser;
import javax.swing.border.Border;
import java.awt.Component;
import java.awt.Graphics;
import java.awt.Image;
import java.awt.Insets;
import java.awt.Window;
import java.awt.event.ActionEvent;
import java.io.File;
import java.io.IOException;
import java.net.URL;
import java.util.EventObject;
import java.util.Properties;
import java.util.prefs.Preferences;

/**
 * @author Eike Kettner
 * @since 10.01.12 18:56
 */
public final class NeoSwingUtil {
  private static final Logger log = LoggerFactory.getLogger(NeoSwingUtil.class);
  private final static Preferences prefs = Preferences.userNodeForPackage(NeoSwing.class);

  private static boolean jideAvailable;
  private static Properties neoswingProperties = new Properties();

  static {
    jideAvailable = checkForJide();

    URL url = NeoSwingUtil.class.getResource("/org/eknet/neoswing/neoswing.properties");
    if (url != null) {
      try {
        neoswingProperties.load(url.openStream());
      } catch (IOException e) {
        log.warn("Error loading neoswing.properties.");
      }
    }
  }

  public static Preferences getPrefs() {
    return prefs;
  }

  private NeoSwingUtil() {}

  public static String getApplicationName() {
    String name = neoswingProperties.getProperty("app.name");
    if (name == null || name.trim().isEmpty()) {
      return "neoswing";
    }
    if (name.equals("${project.name}")) {
      return "neoswing";
    }
    return name;
  }

  public static String getApplicationVersion() {
    String version = neoswingProperties.getProperty("app.version");
    if (version == null) {
      return "";
    }
    if (version.equals("${project.version}")) {
      return "dev";
    }
    if (version.endsWith("SNAPSHOT")) {
      String timestamp = neoswingProperties.getProperty("build.timestamp");
      if (timestamp != null) {
        version += " (" + timestamp + ")";
      }
    }
    return version;
  }

  public static ComponentFactory getFactory(boolean useJideIfAvailable) {
    if (useJideIfAvailable) {
      if (isJideAvailable()) {
        return new JideComponentFactory();
      }
    }
    return new DefaultComponentFactory();
  }

  public static boolean isJideAvailable() {
    return jideAvailable;
  }

  private static boolean checkForJide() {
    String jideClassname = "com.jidesoft.swing.JideButton";
    ClassLoader cl = NeoSwingUtil.class.getClassLoader();
    try {
      cl.loadClass(jideClassname);
      return true;
    } catch (ClassNotFoundException e) {
      cl = Thread.currentThread().getContextClassLoader();
      try {
        cl.loadClass(jideClassname);
        return true;
      } catch (ClassNotFoundException e1) {
        return false;
      }
    }
  }

  public static Image getFrameIcon() {
    URL url = NeoSwingUtil.class.getResource("../resources/chart_organisation.png");
    if (url == null) {
      return null;
    }
    return new ImageIcon(url).getImage();
  }

  public static GraphModel getGraphModel(Component component) {
    Component c = component;
    while (c != null) {
      if (c instanceof GraphModel) {
        return (GraphModel) c;
      }
      c = c.getParent();
    }
    throw new IllegalStateException("No holder found in hierarchy.");
  }

  public static Icon graphDbIcon(String name) {
    if (name.equals(Neo4JEmbeddedLoader.NAME)) {
      return icon("neo4j");
    }
    if (name.equals(TitanLoader.NAME)) {
      return icon("titan");
    }
    if (name.equals(OrientDbLoader.NAME)) {
      return icon("orientdb");
    }
    return icon("folder_database");
  }
  public static Icon icon(String name) {
    if (!name.endsWith("png")) {
      name = name + ".png";
    }
    URL url = NeoSwingUtil.class.getResource("/org/eknet/neoswing/resources/" + name);
    if (url == null) {
      log.warn("No icon found with name: " + name);
      return MissingIcon.tiny;
    }
    return new ImageIcon(url);
  }

  public static void addEdge(final Graph<Vertex, Edge> graph, final Edge relationship) {
    if (!graph.containsEdge(relationship)) {
      EdtExecutor.instance.execute(new Runnable() {
        @Override
        public void run() {
          graph.addEdge(relationship,
              relationship.getVertex(Direction.OUT),
              relationship.getVertex(Direction.IN),
              EdgeType.DIRECTED);
        }
      });
    }
  }

  public static Border topEtchBorder() {
    return new Border() {
      @Override
      public void paintBorder(Component c, Graphics g, int x, int y, int width, int height) {
        g.translate(x, y);

        g.setColor(c.getBackground().darker());
        g.drawLine(0, 0, width - 2, 0);

        g.setColor(c.getBackground().brighter());
        g.drawLine(1, 1, width -3, 1);
        g.translate(-x, -y);
      }

      @Override
      public Insets getBorderInsets(Component c) {
        return new Insets(3, 0, 0, 0);
      }

      @Override
      public boolean isBorderOpaque() {
        return true;
      }
    };
  }

  public static Window findOwner(Object component) {
    if (!(component instanceof Component)) {
      if (component instanceof EventObject) {
        return findOwner(((EventObject) component).getSource());
      } else {
        return null;
      }
    }
    Component c = (Component) component;
    while (c != null) {
      if (c instanceof Window) {
        return (Window) c;
      }
      c = c.getParent();
    }
    return null;
  }

  /**
   * Gets the id of either the node or relationship.
   *
   * @param pc
   * @return
   */
  public static String getId(Element pc) {
    return pc.getId().toString();
  }

  public static  boolean equals(ElementId<?> pc1, ElementId<?> pc2) {
    if (pc1 == null && pc2 == null) {
      return true;
    }
    if (pc1 == null) {
      return false;
    }
    if (pc2 == null) {
      return false;
    }
    if (pc1.getClass() != pc2.getClass()) {
      return false;
    }
    return pc1.equals(pc2);
  }

  /**
   * Copies the vertices and edges from new JUNG graph view into the given blueprints graph.
   * Note that this must be called inside a transaction.
   * @param view
   * @return
   */
  public static void copyView(Graph<Vertex, Edge> view, com.tinkerpop.blueprints.Graph to) {
    for (Vertex v : view.getVertices()) {
      Vertex tv = to.addVertex(v.getId());
      ElementHelper.copyProperties(v, tv);
    }
    for (final Edge fromEdge : view.getEdges()) {
      final Vertex outVertex = to.getVertex(fromEdge.getVertex(Direction.OUT).getId());
      final Vertex inVertex = to.getVertex(fromEdge.getVertex(Direction.IN).getId());
      final Edge toEdge = to.addEdge(fromEdge.getId(), outVertex, inVertex, fromEdge.getLabel());
      ElementHelper.copyProperties(fromEdge, toEdge);
    }
  }

  public static  B chooseSingleFile(Object ownerComp, String title, Function<File, B> fun) {
    final String key = "neoswing." + title.replaceAll("\\s+", "") + ".lastlocation";
    String lastLocation = prefs.get(key, null);
    JFileChooser fc = new JFileChooser(lastLocation);
    fc.setDialogTitle(title);
    fc.setAcceptAllFileFilterUsed(false);
    fc.setFileSelectionMode(JFileChooser.FILES_ONLY);
    fc.setMultiSelectionEnabled(false);
    Window owner = findOwner(ownerComp);
    int rc = fc.showOpenDialog(owner);
    if (rc == JFileChooser.APPROVE_OPTION) {
      final File f = fc.getSelectedFile();
      if (f == null) {
        return null;
      }
      return fun.apply(f);
    }
    return null;
  }

  // ~~ code below is copied from cru-swing class SwingUtil
  //    see (http://maven.raffael.ch/ch/raffael/util/cru-swing/)

  public static boolean invoke(Action action, Object source) {
    if ( action == null || !action.isEnabled() ) {
      return false;
    }
    ActionEvent evt = new ActionEvent(source, ActionEvent.ACTION_PERFORMED,
            (String)action.getValue(Action.ACTION_COMMAND_KEY), 0);
    action.actionPerformed(evt);
    return true;
  }

  public static void center(Component component, Component parent) {
    component.setLocation(parent.getX() + parent.getWidth() / 2 - component.getWidth() / 2,
            parent.getY() + parent.getHeight() / 2 - component.getWidth() / 2);
  }
}


text:
package org.galibier.netty;

import org.galibier.core.*;
import org.jboss.netty.channel.*;
import org.openflow.protocol.*;
import org.openflow.protocol.factory.BasicFactory;
import org.openflow.protocol.factory.OFMessageFactory;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.net.InetSocketAddress;
import java.util.concurrent.*;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.atomic.AtomicLong;

import static org.galibier.core.Constants.*;

public class OpenFlowControllerHandler extends SimpleChannelUpstreamHandler implements MessageDispatcher {
    private static final Logger log = LoggerFactory.getLogger(OpenFlowControllerHandler.class);
    private static final OFMessageFactory factory = new BasicFactory();
    private static final long ECHO_REQUEST_INTERVAL = 5000; // milli sec
    private static final long FEATURES_REQUEST_INTERVAL = 5000; //  milli sec
    private static final long ECHO_REQUEST_TIMEOUT = 10000;

    private final ScheduledExecutorService timer;

    private final Controller controller;
    private Switch client;
    private Channel channel;

    private final AtomicLong lastEchoRequestedTimeMillis = new AtomicLong();

    private final AtomicInteger nextTransactionId = new AtomicInteger(0);
    private final ConcurrentMap<Integer, OFMessageFuture> pendingOperations =
            new ConcurrentHashMap<Integer, OFMessageFuture>();
    private ScheduledFuture<?> featuresRequestTask;
    private ScheduledFuture<?> echoRequestTask;
    private ScheduledFuture<?> heartbeatCheckTask;

    public OpenFlowControllerHandler(Controller controller, ScheduledExecutorService timer) {
        this.controller = controller;
        this.timer = timer;
    }

    @Override
    public void messageReceived(ChannelHandlerContext ctx, MessageEvent e) throws Exception {
        if (e.getMessage() instanceof OFMessage) {
            OFMessage in = (OFMessage)e.getMessage();
            handleMessage(in);
        }
    }

    @Override
    public void channelConnected(ChannelHandlerContext ctx, ChannelStateEvent e) throws Exception {
        switchConnected(ctx.getChannel());
    }

    @Override
    public void channelDisconnected(ChannelHandlerContext ctx, ChannelStateEvent e) throws Exception {
        switchDisconnected();
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, ExceptionEvent e) throws Exception {
        log.warn("Exception occurred", e.getCause());

        e.getChannel().close();
    }

    public void handleMessage(OFMessage in) {
        Object[] args = {in.getType(), in.getXid(), client};
        log.debug("{} (xid={}) received from {}", args);
        switch(in.getType()) {
            case HELLO:
                handleHello((OFHello)in);
                break;
            case ERROR:
                handleError((OFError)in);
                break;
            case ECHO_REQUEST:
                handleEchoRequest((OFEchoRequest)in);
                break;
            case ECHO_REPLY:
                handleEchoReply((OFEchoReply)in);
                break;
            case VENDOR:
                handleVendor((OFVendor)in);
                break;
            case FEATURES_REQUEST:
                handleFeaturesRequest((OFFeaturesRequest)in);
                break;
            case FEATURES_REPLY:
                handleFeaturesReply((OFFeaturesReply)in);
                break;
            case GET_CONFIG_REQUEST:
                handleGetConfigRequest((OFGetConfigRequest)in);
                break;
            case GET_CONFIG_REPLY:
                handleGetConfigReply((OFGetConfigReply)in);
                break;
            case SET_CONFIG:
                handleSetConfig((OFSetConfig)in);
                break;
            case PACKET_IN:
                handlePacketIn((OFPacketIn)in);
                break;
            case FLOW_REMOVED:
                handleFlowRemoved((OFFlowRemoved)in);
                break;
            case PORT_STATUS:
                handlePortStatus((OFPortStatus)in);
                break;
            case PACKET_OUT:
                handlePacketOut((OFPacketOut)in);
                break;
            case FLOW_MOD:
                handleFlowModification((OFFlowMod)in);
                break;
            case PORT_MOD:
                handlePortModification((OFPortMod)in);
                break;
            case STATS_REQUEST:
                handleStatisticsRequest((OFStatisticsRequest)in);
                break;
            case STATS_REPLY:
                handleStatisticsReply((OFStatisticsReply)in);
                break;
            case BARRIER_REQUEST:
                handleBarrierRequest((OFBarrierRequest)in);
                break;
            case BARRIER_REPLY:
                handleBarrierReply((OFBarrierReply)in);
                break;
        }
    }

    private void handleHello(OFHello in) {
        send(factory.getMessage(OFType.FEATURES_REQUEST));
    }

    private void handleError(OFError in) {
        //  TODO: implement more solid codes
        log.info("OpenFlow error occurred, error type: {}, error code: {}, ",
                in.getErrorType(), in.getErrorCode());
    }

    private void handleEchoRequest(OFEchoRequest in) {
        OFMessage out = factory.getMessage(OFType.ECHO_REPLY);
        out.setXid(in.getXid());
        send(out, false);
    }

    private void handleEchoReply(OFEchoReply in) {
        terminateRequest(in);
    }

    private void handleVendor(OFVendor in) {
        controller.handleVendorExtension(client, in);
    }

    private void handleFeaturesRequest(OFFeaturesRequest in) {
        handleUnsupportedMessage(in);
    }

    private void handleFeaturesReply(OFFeaturesReply in) {
        terminateRequest(in);
        client.setFeatures(in);

        controller.switchHandshaken(client);
    }

    private void handleGetConfigRequest(OFGetConfigRequest in) {
        handleUnsupportedMessage(in);
    }

    private void handleGetConfigReply(OFGetConfigReply in) {
        terminateRequest(in);

        //  if this GET_CONFIG_REPLY is corresponds to the startSendFeatureRequestPeriodically,
        //  stop the task
        if (!featuresRequestTask.isCancelled()) {
            stopSendFeaturesRequestPeriodically();
        }
    }

    private void handleSetConfig(OFSetConfig in) {
        handleUnsupportedMessage(in);
    }

    private void handlePacketIn(OFPacketIn in) {
        controller.handlePacketIn(client, in);
    }

    private void handleFlowRemoved(OFFlowRemoved in) {
        controller.handleFlowRemoved(client, in);
    }

    private void handlePortStatus(OFPortStatus in) {
        controller.handlePortStatus(client, in);
    }

    private void handlePacketOut(OFPacketOut in) {
        handleUnsupportedMessage(in);
    }

    private void handleFlowModification(OFFlowMod in) {
        handleUnsupportedMessage(in);
    }

    private void handlePortModification(OFPortMod in) {
        handleUnsupportedMessage(in);
    }

    private void handleStatisticsRequest(OFStatisticsRequest in) {
        handleUnsupportedMessage(in);
    }

    private void handleStatisticsReply(OFStatisticsReply in) {
        terminateRequest(in);
    }

    private void handleBarrierRequest(OFBarrierRequest in) {
        handleUnsupportedMessage(in);
    }

    private void handleBarrierReply(OFBarrierReply in) {
        terminateRequest(in);
    }

    private void handleUnsupportedMessage(OFMessage in) {
        log.warn("Unsupported message ({}) received from {}", in.getType(), client);
    }

    private void switchConnected(Channel channel) {
        this.channel = channel;
        this.client = new Switch(this);
        log.info("Connected from {}", client);

        send(factory.getMessage(OFType.HELLO));

        //  sending echo request periodically
        echoRequestTask = timer.scheduleAtFixedRate(new Runnable() {
            @Override
            public void run() {
                send(factory.getMessage(OFType.ECHO_REQUEST));
                lastEchoRequestedTimeMillis.set(System.currentTimeMillis());
            }
        }, ECHO_REQUEST_INTERVAL, ECHO_REQUEST_INTERVAL, TimeUnit.MILLISECONDS);

        //  start the heartbeat check scheduled task
        heartbeatCheckTask = timer.scheduleAtFixedRate(new Runnable() {
            @Override
            public void run() {
                long current = System.currentTimeMillis();
                if (current - lastEchoRequestedTimeMillis.get() > ECHO_REQUEST_TIMEOUT) {
                    log.warn("Disconnect due to echo reply timeout");
                    stop();
                }
            }
        }, ECHO_REQUEST_TIMEOUT, ECHO_REQUEST_TIMEOUT, TimeUnit.MILLISECONDS);

        //  sending FEATURES REQUEST periodically until FEATURES REPLY is received
        featuresRequestTask = timer.scheduleAtFixedRate(new Runnable() {
            @Override
            public void run() {
                if (client.isHandshaken()) {
                    OFSetConfig config = (OFSetConfig) factory.getMessage(OFType.SET_CONFIG);
                    config.setMissSendLength((short)0xffff).setLengthU(OFSetConfig.MINIMUM_LENGTH);
                    send(config);
                    send(factory.getMessage(OFType.GET_CONFIG_REQUEST));
                } else {
                    send(factory.getMessage(OFType.FEATURES_REQUEST));
                }
            }
        }, FEATURES_REQUEST_INTERVAL, FEATURES_REQUEST_INTERVAL, TimeUnit.MILLISECONDS);
    }

    private void stopSendFeaturesRequestPeriodically() {
        if (featuresRequestTask != null) {
            featuresRequestTask.cancel(false);
        }
    }

    private void stopSendEchoRequestPeriodically() {
        if (echoRequestTask != null) {
            echoRequestTask.cancel(false);
        }
    }

    private void stopHeartbeatCheckTask() {
        if (heartbeatCheckTask != null) {
            heartbeatCheckTask.cancel(false);
        }
    }

    private void switchDisconnected() {
        log.info("Disconnected from {}", client);
        stopSendEchoRequestPeriodically();
        stopSendFeaturesRequestPeriodically();
        stopHeartbeatCheckTask();

        //  tell the parent that the connection to a switch is released
        controller.switchDisconnected(client);

        //  close the channel
        ChannelFuture future = channel.getCloseFuture();
        future.addListener(new ChannelFutureListener() {
            public void operationComplete(ChannelFuture channelFuture) throws Exception {
                client = null;
            }
        });
    }

    /**
     * Asynchronously sends a OpenFlow protocol message to the switch corresponding to this handler.
     * @param out the OpenFlow protocol message to send to the switch
     * @param autoXid true when XID of the message is automatically created, false when it is not changed
     * @return the OFMessageFuture which will be notified if the message is a kind of request messages
     */
    private OFMessageFuture send(OFMessage out, boolean autoXid) {
        if (autoXid) {
            out.setXid(nextTransactionId.incrementAndGet());
        }

        if (channel != null && channel.isConnected()) {
            ChannelFuture future = channel.write(out);
            OFMessageFuture messageFuture = new OFMessageFuture(out, future);
            if (REQUEST_TYPE.contains(out.getType())) {
                pendingOperations.putIfAbsent(out.getXid(), messageFuture);
            }
            Object[] args = {out.getType(), out.getXid(), client};
            log.debug("{} (xid={}) sent to {}", args);
            return messageFuture;
        } else {
            return new OFMessageFuture(out, null);
        }
    }

    @Override
    public OFMessageFuture send(OFMessage msg) {
        return send(msg, true);
    }

    /**
     * Stops the scheduled tasks associated with this handler and close the channel to the switch
     */
    public void stop() {
        stopSendEchoRequestPeriodically();
        stopSendFeaturesRequestPeriodically();
        stopHeartbeatCheckTask();
        channel.getCloseFuture().awaitUninterruptibly();
    }

    private boolean terminateRequest(OFMessage reply) {
        int xid = reply.getXid();
        OFMessageFuture future = pendingOperations.remove(xid);
        if (future != null) {
            //  tell that the operation is completed
            future.setReply(reply);
        } else {
            //  already removed from the map
            log.warn("The request corresponding to {} (Xid={}) was already processed",
                    reply.getType(), reply.getXid());
        }

        return future != null;
    }

    @Override
    public InetSocketAddress remoteAddress() {
        //  current OpenFlow protocol does not support UDP/IP
        return (InetSocketAddress)channel.getRemoteAddress();
    }

    @Override
    public InetSocketAddress localAddress() {
        //  current OpenFlow protocol does not support UDP/IP
        return (InetSocketAddress)channel.getLocalAddress();
    }
}


text:
module Mongoid
  module Persistence
    module Atomic

      # This class provides the ability to perform an explicit $pushAll modification
      # on a specific field.
      class PushAll
        include Operation

        # Sends the atomic $pushAll operation to the database.
        #
        # @example Persist the new values.
        #   pushAll.persist
        #
        # @return [ Object ] The new array value.
        #
        # @since 2.1.0
        def persist
          append_with("$pushAll")
        end
      end
    end
  end
end


text:
ACCEPTED

#### According to
International Plant Names Index

#### Published in
null

#### Original name
Echinopsis yungasensis F.Ritter

### Remarks
null


text:
use num::{Zero, One, Integer};
use crate::prelude::*;
use crate::Factored;
use crate::util::MoreNumCast;

/// An object for efficiently factorizing many small numbers.
///
/// A `FactorSieve` is simply a precomputed array which stores the smallest
/// prime factor `p` for each integer `x`, up to some limit.
#[derive(Clone)]
pub struct FactorSieve {
    sieve: Vec<usize>,
}

impl FactorSieve {
    /// Compute a factor sieve for numbers `< limit`.
    pub fn new<T>(limit: T) -> Self
    where
        T: MoreNumCast + Integer,
    {
        assert!(limit >= T::zero());
        FactorSieve {
            sieve: factor_sieve_simple(limit.to_usize().unwrap()),
        }
    }
}

impl FactorSieve {
    pub fn into_vec(self) -> Vec<usize> {
        self.sieve
    }
}

impl<T> TryFactor<T> for FactorSieve
where
    T: Clone + Zero + One + Integer + MoreNumCast,
{
    fn try_factor(&self, x: &T) -> Option<T> {
        if x == &T::one() {
            None
        } else {
            Some(T::from_usize(self.sieve[x.to_usize().unwrap()]).unwrap())
        }
    }
}

impl<T> SureFactor<T> for FactorSieve
where
    T: Clone + Zero + One + Integer + MoreNumCast,
{
    fn factorize(&self, x: T) -> Factored<T> {
        crate::factorizer::helper::always_smallest_factorize(self, x)
    }
}

impl<T> FirstFactor<T> for FactorSieve
where
    T: Clone + Zero + One + Integer + MoreNumCast,
{
    // TODO: delegate try_factor to first_prime rather than other way around
}

//------------------------------------------------------

fn factor_sieve_simple(limit: usize) -> Vec<usize> {
    let mut sieve: Vec<_> = (0..limit).collect();

    // a very slight wheel optimization
    for x in (2..limit).step_by(2) {
        sieve[x] = 2;
    }

    for x in (3..).step_by(2) {
        // first multiple worth marking
        let first = x * x;
        if first > limit {
            break;
        }

        // x is already marked
        if sieve[x] != x {
            continue;
        }

        // x is prime; mark any multiples that aren't marked
        for m in (first..limit).step_by(2 * x) {
            if sieve[m] == m {
                sieve[m] = x;
            }
        }
    }
    sieve
}

#[test]
fn test() {
    // a "definitely correct" sieve formed by trial division.
    // It is large enough to include values for which various certain
    // incorrectly-implemented optimizations could give the wrong prime
    // factor (e.g. a certain easy mistake results in giving 3 for 18,
    // 5 for 45, and 7 for 175; and the first incorrect value may be pushed
    // even further back if a large wheel optimization is used)
    let mut correct = vec![0, 1];
    for i in 2..2000 {
        for k in 2..(i + 1) {
            if i % k == 0 {
                correct.push(k);
                break;
            }
        }
    }
    for (i, x) in correct.clone().into_iter().enumerate() {
        if x == 3 {
            println!("{}", i);
        }
    }
    // a "definitely definitely correct" sieve to verify that one against,
    // up to a point
    assert_eq!(correct.len(), 2000);
    assert_eq!(
        &correct[..12],
        &vec![0, 1, 2, 3, 2, 5, 2, 7, 2, 3, 2, 11][..]
    );

    // try various sizes, in particular:
    for len in vec![
        0,
        1, // Obvious edge cases (length 0, 1)
        2,
        3, // More subtle edge case (no multiples to cross off)
        9,
        10,
        11,            // End in a prime square; a composite; and a prime
        correct.len(), // Catch erroneous values for larger x
    ] {
        let actual = FactorSieve::new(len as usize).into_vec();
        assert_eq!(&actual[..], &correct[..len]);
    }
}


text:
// ==========================================================================
//                          DG.ImageUtilities
//
//  Author:   Jonathan Sandoe
//
//  Copyright (c) 2017 by The Concord Consortium, Inc. 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
//
//  Unless required by applicable law or agreed to in writing, software
//  distributed under the License is distributed on an "AS IS" BASIS,
//  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
//  See the License for the specific language governing permissions and
//  limitations under the License.
// ==========================================================================

/* global Promise */
DG.ImageUtilities = (function () {
  return {

    /**
     * Converts an SVG scene into a png image.
     * @param rootEl {Element} a DOM element. Either HTML or SVG. This routine
     *   will extract SVG elements from this object and place them in the final
     *   image. HTML DOM element will not be visible.
     * @param width {number}
     * @param height {number}
     * @param asDataURL {boolean} true - image returned as data URI, otherwise as blob
     * @return {Promise} The promise of an image.
     */
    captureSVGElementsToImage: function (rootEl, width, height, title, asDataURL) {

      function getCSSText() {
        var text = [], ix, jx;
        for (ix = 0; ix < document.styleSheets.length; ix += 1) {
          try {
            var styleSheet = document.styleSheets[ix];
            if (styleSheet) {
              var rules = styleSheet.rules || styleSheet.cssRules || [];
              for (jx = 0; jx < rules.length; jx += 1) {
                var rule = rules[jx];
                text.push(rule.cssText);
              }
            }
          } catch (ex) {
            DG.logWarn('Exception retrieving stylesheet: ' + ex);
          }
        }
        return text.join('\n');
      }

      function makeDataURLFromSVGElement(svgEl) {
        var svgClone = $(svgEl).clone();
        var css = $('<style>').text(getCSSText());
        svgClone.prepend(css);
        var svgData = new XMLSerializer().serializeToString(svgClone[0]);
        // Raphael overspecifies the url for the gradient. It prepends the
        // windows.location.href. This causes problems with the data url,
        // because we are no longer in this namespace. So, we remove.
        svgData = svgData.replace(
            new RegExp('url\\(\'[^#]*#', 'g'), 'url(\'#');
        // The use of unescape and encodeURIComponent are part of a well-
        // known hack work around btoa's handling of unicode characters.
        // see, eg:
        // http://ecmanaut.blogspot.com/2006/07/encoding-decoding-utf8-in-javascript.html
        return "data:image/svg+xml;base64,"
            + window.btoa(window.unescape(window.encodeURIComponent(svgData)));
      }

      /**
       * Create a canvas element with a white background. Not yet appended to
       * the DOM.
       * @param {number} width
       * @param {number} height
       * @returns {Canvas}
       */
      function makeCanvasEl(width, height) {
        var canvas = $("<canvas>").prop({width: width, height: height})[0];
        var ctx = canvas.getContext("2d");
        ctx.fillStyle = 'white';
        ctx.fillRect(0, 0, width, height);
        return canvas;
      }

      /**
       * Add an image to the canvas at the specified location.
       * @param {Canvas} canvas DOM Element
       * @param {img} image DOM Element
       * @param {number} x
       * @param {number} y
       * @param {number} width
       * @param {number} height
       */
      function addImageToCanvas(canvas, image, x, y, width, height) {
        var ctx = canvas.getContext("2d");
        ctx.drawImage(image, x, y, width, height);
      }

      function drawRectToCanvas(canvas, color, x, y, width, height) {
        var ctx = canvas.getContext("2d");
        ctx.fillStyle = color;
        ctx.fillRect(x, y, width, height);
      }
      /**
       * Convert a canvas object to a blob.
       * @param canvas
       * @returns {*}
       */
      function makeCanvasBlob(canvas) {
        var canvasDataURL = canvas.toDataURL("image/png");
        var canvasData = atob(canvasDataURL.substring("data:image/png;base64,".length));
        var canvasAsArray = new Uint8Array(canvasData.length);  /* global Uint8Array */

        for (var i = 0, len = canvasData.length; i < len; ++i) {
          canvasAsArray[i] = canvasData.charCodeAt(i);
        }

        return new Blob([canvasAsArray.buffer], {type: "image/png"});
      }

      /**
       * @returns a promise of an image.
       * @param dataURL
       */
      function makeSVGImage(dataURL) {
        return new Promise(function (resolve, reject) {
              try {
                var img = $('<img/>')[0];
                img.onload = function () {
                  resolve(img);
                };
                img.src = dataURL;
              } catch (ex) {
                reject(ex);
              }
            }
        );
      }

      function appendTitle(canvas, bgColor, fgColor, title) {
        var ctx = canvas.getContext("2d");
        ctx.fillStyle = bgColor;
        ctx.fillRect(0, height, width, 20);
        ctx.fillStyle = fgColor;
        ctx.beginPath();
        ctx.moveTo(0, height);
        ctx.lineTo(width, height);
        ctx.stroke();
        ctx.font='10pt MuseoSans-500';
        ctx.textAlign = 'center';
        ctx.textBaseline = 'middle';
        ctx.fillText(title,width/2, height + 14, width);
      }

      //
      // ######## convertImage begin ########
      //
      // find all svg elements that are not children of hidden divs
      var elements = $(rootEl).find('div.dg-plot-view,img,div:not(.sc-hidden)>svg');
      var canvas = makeCanvasEl(width, height + (title?20:0));
      var jobList = [];
      var jobIx = 0;

      function perform(job) {
        var elType = job && job.el && job.el.nodeName.toLowerCase();
        if (!job) {
          if (title) {
            appendTitle(canvas, 'white', 'black', title);
          }
          // we have drawn all the elements resolve the promise with a data URL or blob
          try {
            return Promise.resolve(asDataURL ? canvas.toDataURL("image/png") : makeCanvasBlob(canvas));
          } catch (e) {
            return Promise.reject(e);
          }
        }
        if (elType === 'div') {
          // get the background color from the base div
          drawRectToCanvas(canvas,$(job.el).css('background-color'), job.l, job.t, job.w, job.h);
          return perform(jobList[jobIx++]);
        } else if (elType === 'svg') {
          // add the svg as an image to the canvas
          return makeSVGImage(makeDataURLFromSVGElement(job.el)).then(function (img) {
              addImageToCanvas(canvas, img, job.l, job.t, job.w, job.h);
              return perform(jobList[jobIx++]);
            },
            function (error) {
              return Promise.reject(error);
            }
          );
        } else if (elType === 'img') {
          // add an img to the canvas only if it has the crossorigin attribute.
          // otherwise we will taint the canvas
          if (!SC.none(job.el.getAttribute('crossorigin'))) {
            addImageToCanvas(canvas, job.el, job.l, job.t, job.w, job.h);
          }
          return perform(jobList[jobIx++]);
        } else {
          return perform(jobList[jobIx++]);
        }

      }
      // for each svg we calculate its geometry, then add it to the canvas
      // through a promise.
      // Note: This implementation starts a number of asynchronous operations,
      // one for each SVG in the hierarchy. If they overlap and are handled out
      // of order, it is possible that they may be written to the canvas in the
      // wrong order.
      try {
        if (elements) {
          elements.forEach(function (element) {
            var width = element.offsetWidth || (element.width.baseVal?element.width.baseVal.value:0);
            var height = element.offsetHeight || (element.height.baseVal?element.height.baseVal.value:0);
            var left = 0;
            var top = 0;
            var rect = element.getBoundingClientRect();
            var rootRect = rootEl.getBoundingClientRect();
            if (element.nodeName.toLowerCase() === "img") {
              jobList.push({
                el:element,
                w: rect.width,
                h: rect.height,
                l: rect.left - rootRect.left,
                t: rect.top - rootRect.top
              });
            } else {
              $(element).add($(element).parentsUntil(rootEl)).each(function () {
                left += this.offsetLeft || 0;
                top += this.offsetTop || 0;
              });
              jobList.push({el: element, w: width, h: height, l: left, t: top});
            }
          });

          return perform (jobList[jobIx++]);
        }
      } catch (ex) {
        DG.logError('saving image: ' + ex);
      }
      return null;

    }
  };
}());


text:
'use strict';

// toArray utillity converts @arg to array with slising from @num.
SoundJSDirector.toArray = (function (slice) {
  return function toArray (arg, num) {
    return slice.call(arg || [], num || 0);
  };
} ([].slice));


text:
<webscript>
   <shortname>Update the details of a group</shortname>
   <description><![CDATA[
      Updates the details of a group.

      You must have "administrator" privileges to change the name of a group.

      The following properties may be updated:-

displayName

The display name

   ]]>
   </description>
   <url>/api/groups/{shortName}</url>
   <format default="json">argument</format>
   <authentication>user</authentication>
   <transaction>required</transaction>
   <lifecycle>draft_public_api</lifecycle>
</webscript>


text:
package net.selenate.server
package actions
package workers

import extensions.SelenateFirefox

import net.selenate.common.comms.req.SeReqElementClick
import net.selenate.common.comms.res.SeResElementClick
import net.selenate.common.exceptions.SeActionException
import scala.util.{ Failure, Success, Try }

class ElementClickAction(val sessionID: String, val context: SessionContext, val d: SelenateFirefox)
    extends RetryableAction[SeReqElementClick, SeResElementClick]
    with ActionCommons {
  def retryableAct = { arg =>
    val result: Option[Try[Unit]] = elementInAllWindows(arg.getSelector) { (address, e) =>
      e.click
    }

    result match {
      case Some(Success(())) =>
        new SeResElementClick()
      case Some(Failure(ex)) =>
        logError(s"An error occurred while executing $name action ($arg)!", ex)
        throw new SeActionException(name, arg, ex)
      case None =>
        val msg = "element not found in any frame"
        logError(s"An error occurred while executing $name action ($arg): $msg!")
        throw new SeActionException(name, arg, msg)
    }
  }
}


text:
<?php
//This is for back end processing of video saving (after editing)
require_once('../db.php');
require_once('db.php');

session_start();
$userid = $_SESSION['userid'];

//return codes:
// 0 = fail
// 1 = valid

$id = $_POST['id'];
$title = $_POST['title'];
$url = $_POST['url'];
$year = $_POST['year'];
$poster = $_POST['poster'];
$time = $_POST['time'];
$selfrate = $_POST['selfrate'];

if (empty($id)) exit('0');
if (empty($title)) exit('2');
if (empty($url)) exit('3');
if (empty($year)) exit('4');
if (empty($selfrate)) exit('5');
if (empty($poster)) exit('6');
if (empty($time)) exit('7');

$result = updateVideo($id, $title, $userid, $url, $year, $poster, $time, $selfrate, $mysqli);
if ($result === true) exit('1');
exit('0');


text:
dconfig kitty

dsymlink modules/kitty/rc/kitty.conf ~/.config/kitty/kitty.conf
echo "font_size ${dotfiles_kitty_font_size}" > ~/.config/kitty/font_size.conf


text:
package com.facebook;

/**
 * Specifies different categories of logging messages that can be generated.
 *
 * @see FacebookSdk#addLoggingBehavior(LoggingBehavior)
 */
public enum LoggingBehavior {
    /**
     * Indicates that HTTP requests and a summary of responses should be logged.
     */
    REQUESTS,
    /**
     * Indicates that access tokens should be logged as part of the request logging; normally they
     * are not.
     */
    INCLUDE_ACCESS_TOKENS,
    /**
     * Indicates that the entire raw HTTP response for each request should be logged.
     */
    INCLUDE_RAW_RESPONSES,
    /**
     * Indicates that cache operations should be logged.
     */
    CACHE,
    /**
     * Indicates the App Events-related operations should be logged.
     */
    APP_EVENTS,
    /**
     * Indicates that likely developer errors should be logged.  (This is set by default in
     * LoggingBehavior.)
     */
    DEVELOPER_ERRORS,

    /**
     * Log debug warnings from API response, e.g. when friends fields requested, but user_friends
     * permission isn't granted.
     */
    GRAPH_API_DEBUG_WARNING,

    /**
     * Log warnings from API response, e.g. when requested feature will be deprecated in next
     * version of API. Info is the lowest level of severity, using it will result in logging all
     * GRAPH_API_DEBUG levels.
     */
    GRAPH_API_DEBUG_INFO
    ;
}


text:
/**
 * BSD-style license; for more info see http://pmd.sourceforge.net/license.html
 */
package net.sourceforge.pmd.lang.java.typeresolution;

import java.io.IOException;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;

import net.sourceforge.pmd.lang.java.typeresolution.visitors.PMDASMVisitor;

import org.objectweb.asm.ClassReader;

/*
 * I've refactored this class to not cache the results any more. This is a
 * tradeoff in testing I've found the CPU tradeoff is negligeable. With the
 * cache, large codebases consumed a lot of memory and slowed down greatly when
 * approaching 3,000 classes. I'm adding this comment in case someone is looking
 * at this code and thinks a cache may help.
 */
public class PMDASMClassLoader extends ClassLoader {

    public PMDASMClassLoader(ClassLoader parent) {
    	super(parent);
    }

    private Set<String> dontBother = new HashSet<String>();

    public synchronized Map<String, String> getImportedClasses(String name) throws ClassNotFoundException {

        if (dontBother.contains(name)) {
            throw new ClassNotFoundException(name);
        }
        try {
            ClassReader reader = new ClassReader(getResourceAsStream(name.replace('.', '/') + ".class"));
            PMDASMVisitor asmVisitor = new PMDASMVisitor();
            reader.accept(asmVisitor, 0);

            List<String> inner = asmVisitor.getInnerClasses();
            if (inner != null && !inner.isEmpty()) {
                inner = new ArrayList<String>(inner); // to avoid ConcurrentModificationException
                for (String str: inner) {
                    reader = new ClassReader(getResourceAsStream(str.replace('.', '/') + ".class"));
                    reader.accept(asmVisitor, 0);
                }
            }
            return asmVisitor.getPackages();
        } catch (IOException e) {
            dontBother.add(name);
            throw new ClassNotFoundException(name, e);
        }
    }
}


text:
app.controller('ResetCtrl', function($scope, MetaSettings, Auth, $stateParams, $mdDialog, $state){
  MetaSettings.setTitle('Reset password');

  $scope.submitForm = function(){
    $scope.error = '';

    Auth.resetPassword({
      password: $scope.form.password,
      resetToken: $stateParams.forgotPasswordToken
    })
      .then(function success(res){
        var msg;

        if(res.data.message == 'success') {
          msg = 'Success! Your password has been changed.';
          $state.go('login');
        }

        $mdDialog.show(
          $mdDialog.alert()
            .parent(angular.element(document.querySelector('#popupContainer')))
            .clickOutsideToClose(true)
            .title('Reset password')
            .content(msg)
            .ariaLabel('Reset passord')
            .ok('Got it!')
            .targetEvent()
        );

      })
      .catch(function(err){
        $scope.error = err.data;
      });
  };
});


text:
	Copyright (C) 2006-2007 Nymbia
	Copyright (C) 2010 Hendrik "Nevcairiel" Leppkes < h.leppkes@gmail.com >

	This program is free software; you can redistribute it and/or modify
	it under the terms of the GNU General Public License as published by
	the Free Software Foundation; either version 2 of the License, or
	(at your option) any later version.

	This program is distributed in the hope that it will be useful,
	but WITHOUT ANY WARRANTY; without even the implied warranty of
	MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
	GNU General Public License for more details.

	You should have received a copy of the GNU General Public License along
	with this program; if not, write to the Free Software Foundation, Inc.,
	51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
]]
local Quartz3 = LibStub("AceAddon-3.0"):GetAddon("Quartz3")
local L = LibStub("AceLocale-3.0"):GetLocale("Quartz3")
local media = LibStub("LibSharedMedia-3.0")

----------------------------
-- Upvalues
-- GLOBALS: LibStub, InterfaceOptionsFrame_OpenToCategory
local pairs, unpack, type = pairs, unpack, type

local getOpt, setOpt, getColor, setColor
do
	function getOpt(info)
		local key = info[#info]
		return Quartz3.db.profile[key]
	end

	function setOpt(info, value)
		local key = info[#info]
		Quartz3.db.profile[key] = value
		Quartz3:ApplySettings()
	end

	function getColor(info)
		return unpack(getOpt(info))
	end

	function setColor(info, r, g, b, a)
		setOpt(info, {r, g, b, a})
	end
end

local options, moduleOptions = nil, {}
local function getOptions()
	if not options then
		 options = {
			type = "group",
			args = {
				general = {
					type = "group",
					inline = true,
					name = "",
					args = {
						unlock = {
							type = "execute",
							name = L["Toggle Bar Lock"],
							desc = L["Unlock the Bars to be able to move them around."],
							func = function()
								Quartz3:ToggleLock(true)
							end,
							order = 50,
						},
						nllock = {
							type = "description",
							name = "",
							order = 51,
						},
						hidesamwise = {
							type = "toggle",
							name = L["Hide Samwise Icon"],
							desc = L["Hide the icon for spells with no icon"],
							order = 101,
							get = getOpt,
							set = setOpt,
						},
						casttimeprecision = {
							type = "range",
							name = L["Cast Time Precision"],
							desc = L["Number of decimals to show for the Cast Time"],
							min = 0, max = 3, step = 1,
							get = getOpt,
							set = setOpt,
							order = 102,
						},
						colors = {
							type = "group",
							name = L["Colors"],
							desc = L["Colors"],
							guiInline = true,
							order = 450,
							get = getColor,
							set = setColor,
							args = {
								spelltextcolor = {
									type = "color",
									name = L["Spell Text"],
									desc = L["Set the color of the %s"]:format(L["Spell Text"]),
									order = 98,
								},
								timetextcolor = {
									type = "color",
									name = L["Time Text"],
									desc = L["Set the color of the %s"]:format(L["Time Text"]),
									order = 98,
								},
								header = {
									type = "header",
									name = "",
									order = 99,
								},
								castingcolor = {
									type = "color",
									name = L["Casting"],
									desc = L["Set the color of the cast bar when %s"]:format(L["Casting"]),
								},
								channelingcolor = {
									type = "color",
									name = L["Channeling"],
									desc = L["Set the color of the cast bar when %s"]:format(L["Channeling"]),
								},
								completecolor = {
									type = "color",
									name = L["Complete"],
									desc = L["Set the color of the cast bar when %s"]:format(L["Complete"]),
								},
								failcolor = {
									type = "color",
									name = L["Failed"],
									desc = L["Set the color of the cast bar when %s"]:format(L["Failed"]),
								},
								sparkcolor = {
									type = "color",
									name = L["Spark Color"],
									desc = L["Set the color of the casting bar spark"],
									hasAlpha = true,
								},
								nl1 = {
									type = "description",
									name = "",
									order = 101,
								},
								backgroundcolor = {
									type = "color",
									name = L["Background"],
									desc = L["Set the color of the casting bar background"],
									order = 102,
								},
								backgroundalpha = {
									type = "range",
									name = L["Background Alpha"],
									desc = L["Set the alpha of the casting bar background"],
									isPercent = true,
									min = 0, max = 1, bigStep = 0.025,
									get = getOpt,
									set = setOpt,
									order = 103,
								},
								bordercolor = {
									type = "color",
									name = L["Border"],
									desc = L["Set the color of the casting bar border"],
									order = 104,
								},
								borderalpha = {
									type = "range",
									name = L["Border Alpha"],
									desc = L["Set the alpha of the casting bar border"],
									isPercent = true,
									min = 0, max = 1, bigStep = 0.025,
									get = getOpt,
									set = setOpt,
									order = 105,
								},
							},
						},
					},
				},
			},
		}
		for k,v in pairs(moduleOptions) do
			options.args[k] = (type(v) == "function") and v() or v
		end
	end
	return options
end

function Quartz3:ChatCommand(input)
	if not input or input:trim() == "" then
		InterfaceOptionsFrame_OpenToCategory(Quartz3.optFrames.Profiles)
		InterfaceOptionsFrame_OpenToCategory(Quartz3.optFrames.Quartz3)
	else
		LibStub("AceConfigCmd-3.0").HandleCommand(Quartz3, "quartz", "Quartz3", input)
	end
end

function Quartz3:SetupOptions()
	self.optFrames = {}
	LibStub("AceConfigRegistry-3.0"):RegisterOptionsTable("Quartz3", getOptions)
	self.optFrames.Quartz3 = LibStub("AceConfigDialog-3.0"):AddToBlizOptions("Quartz3", "Quartz 3", nil, "general")
	self:RegisterModuleOptions("Profiles", LibStub("AceDBOptions-3.0"):GetOptionsTable(self.db), "Profiles")
	self:RegisterChatCommand("quartz", "ChatCommand")
	self:RegisterChatCommand("q3", "ChatCommand")
end

function Quartz3:RegisterModuleOptions(name, optTable, displayName)
	moduleOptions[name] = optTable
	self.optFrames[name] = LibStub("AceConfigDialog-3.0"):AddToBlizOptions("Quartz3", displayName or name, "Quartz 3", name)
end


text:
class Foo; end
Foo.ancestors # => [Foo, Object, Kernel, BasicObject]

# So we can see we can add what looks to be a language provided feature like so:
module Kernel
  def foobar
    puts "I'm not a language keyword, I'm just a fake"
  end
end

# Now from any where in our program we can call
foobar # => I'm not a language keyword, I'm just a fake


text:
'use strict';

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

/**
 * @param {string} path
 * @return {boolean}
 */
function isDir(path) {
  try {
    return fs.statSync(path).isDirectory();
  } catch (error) {
    return false;
  }
}

/**
 * @param {string} path
 * @return {boolean}
 */
function isFile(path) {
  try {
    return fs.statSync(path).isFile();
  } catch (error) {
    return false;
  }
}

/**
 * @param {!Array} array
 */
function shuffle(array) {
  for (let i = array.length - 1; i > 0; i--) {
    const j = Math.floor(Math.random() * (i + 1));
    [array[i], array[j]] = [array[j], array[i]];
  }
}

/**
 * @param {string} src
 * @param {string} dest
 */
function copy(src, dest) {
  try {
    const targetFilePath = path.resolve(dest, path.basename(src));
    fs.writeFileSync(targetFilePath, fs.readFileSync(src));
  } catch (error) {
    throw new Error(`Received an error: [${error}] while trying to copy: ${src} -> ${dest}`);
  }
}

module.exports = {
  isDir,
  isFile,
  shuffle,
  copy,
};


text:
class PrdCtgryM < ActiveRecord::Base
end


text:
SYNONYM

#### According to
The Catalogue of Life, 3rd January 2011

#### Published in
Method. Lich. 206 (1803)

#### Original name
Lichen centrifugus L.

### Remarks
null


text:
Scala bindings for [Bokeh][bokeh] plotting library.

[![Build Status][travis]](https://travis-ci.org/bokeh/bokeh-scala)

## Requirements

* [Java](http://wwww.java.com) JRE 1.7+

## Usage

Binary release artifacts are published to Sonatype OSS and synced to [Maven
Central][central]. To include latest stable version of bokeh in your project,
use:

```scala
libraryDependencies += "io.continuum.bokeh" %% "bokeh" % "0.6"
```

Development snapshots are available as well. To use this you have to add
Sonatype's snapshots repository to your build:

```scala
resolvers += Opts.resolver.sonatypeSnapshots
libraryDependencies += "io.continuum.bokeh" %% "bokeh" % "0.7-SNAPSHOT"
```

See [this][sample] sample project for detailed integration example.

## Documentation

API documentation (scaladoc) is available for [stable][api-stable] and
[development][api-devel] versions.

## Development

Install [nodejs][nodejs]. This is required to build bokehjs. Then:

```bash
$ git clone --recursive https://github.com/bokeh/bokeh-scala.git
$ cd bokeh-scala
$ ./sbt
> examples/runMain io.continuum.bokeh.examples.models.Anscombe
```
or
```bash
> examples/runAll
```

## Support

Submit any questions and suggestions to Bokeh's [mailing list][group] and report
any Scala-specific issues in the [issue tracker][issues]. Issues directly related
bokeh or bokehjs, please report in the [bokeh's issue tracker][bokeh-issues].

## License

Copyright © 2014-2016 by Mateusz Paprocki and contributors.

Published under [The MIT License][license], see LICENSE.

[bokeh]: http://bokeh.pydata.org
[central]: http://search.maven.org/#search%7Cga%7C1%7Cbokeh
[sample]: https://github.com/bokeh/bokeh-scala-sample
[api-stable]: https://s3.amazonaws.com/bokeh-scala/docs/2.11/0.6/index.html
[api-devel]: https://s3.amazonaws.com/bokeh-scala/docs/2.11/0.7-SNAPSHOT/index.html
[nodejs]: https://nodejs.org/download/
[group]: https://groups.google.com/a/continuum.io/forum/#!forum/bokeh
[issues]: https://github.com/bokeh/bokeh-scala/issues
[bokeh-issues]: https://github.com/bokeh/bokeh/issues
[travis]: https://api.travis-ci.org/bokeh/bokeh-scala.png?branch=master
[license]: http://www.opensource.org/licenses/mit-license.php


text:
import {isNullOrUndefined} from 'util';
import {ITranslationMessagesFile} from '../api/i-translation-messages-file';
import {INormalizedMessage} from '../api/i-normalized-message';
import {ITransUnit} from '../api/i-trans-unit';
import {INote} from '../api/i-note';
import {DOMUtilities} from './dom-utilities';
import {AbstractTransUnit} from './abstract-trans-unit';
import {XmbMessageParser} from './xmb-message-parser';
import {ParsedMessage} from './parsed-message';
import {AbstractMessageParser} from './abstract-message-parser';
/**
 * Created by martin on 23.05.2017.
 * A Translation Unit in an XTB file.
 */

export class XtbTransUnit extends AbstractTransUnit implements ITransUnit {

    private _sourceTransUnitFromMaster: AbstractTransUnit;

    constructor(_element: Element, _id: string, _translationMessagesFile: ITranslationMessagesFile,
                _sourceTransUnitFromMaster: AbstractTransUnit) {
        super(_element, _id, _translationMessagesFile);
        this._sourceTransUnitFromMaster = _sourceTransUnitFromMaster;
    }

    /**
     * Get content to translate.
     * Source parts are excluded here.
     * @return content to translate.
     */
    public sourceContent(): string {
        if (this._sourceTransUnitFromMaster) {
            return this._sourceTransUnitFromMaster.sourceContent();
        } else {
            return null;
        }
    }

    /**
     * Test, wether setting of source content is supported.
     * If not, setSourceContent in trans-unit will do nothing.
     * xtb does not support this, all other formats do.
     */
    supportsSetSourceContent(): boolean {
        return false;
    }

    /**
     * Set new source content in the transunit.
     * Normally, this is done by ng-extract.
     * Method only exists to allow xliffmerge to merge missing changed source content.
     * @param newContent the new content.
     */
    public setSourceContent(newContent: string) {
        // xtb has no source content, they are part of the master
    }

    /**
     * Return a parser used for normalized messages.
     */
    protected messageParser(): AbstractMessageParser {
        return new XmbMessageParser(); // no typo!, Same as for Xmb
    }

    /**
     * The original text value, that is to be translated, as normalized message.
     */
    public createSourceContentNormalized(): ParsedMessage {
        if (this._sourceTransUnitFromMaster) {
            return this._sourceTransUnitFromMaster.createSourceContentNormalized();
        } else {
            return null;
        }
    }

    /**
     * the translated value (containing all markup, depends on the concrete format used).
     */
    public targetContent(): string {
        return DOMUtilities.getXMLContent(this._element);
    }

    /**
     * the translated value, but all placeholders are replaced with {{n}} (starting at 0)
     * and all embedded html is replaced by direct html markup.
     */
    targetContentNormalized(): INormalizedMessage {
        return this.messageParser().createNormalizedMessageFromXML(this._element, this.sourceContentNormalized());
    }

    /**
     * State of the translation.
     * (not supported in xmb)
     * If we have a master, we assumed it is translated if the content is not the same as the masters one.
     */
    public nativeTargetState(): string {
        if (this._sourceTransUnitFromMaster) {
            const sourceContent = this._sourceTransUnitFromMaster.sourceContent();
            if (!sourceContent || sourceContent === this.targetContent() || !this.targetContent()) {
                return 'new';
            } else {
                return 'final';
            }
        }
        return null; // not supported in xmb
    }

    /**
     * Map an abstract state (new, translated, final) to a concrete state used in the xml.
     * Returns the state to be used in the xml.
     * @param state one of Constants.STATE...
     * @returns a native state (depends on concrete format)
     * @throws error, if state is invalid.
     */
    protected mapStateToNativeState(state: string): string {
        return state;
    }

    /**
     * Map a native state (found in the document) to an abstract state (new, translated, final).
     * Returns the abstract state.
     * @param nativeState nativeState
     */
    protected mapNativeStateToState(nativeState: string): string {
        return nativeState;
    }

    /**
     * set state in xml.
     * (not supported in xmb)
     * @param nativeState nativeState
     */
    protected setNativeTargetState(nativeState: string) {
        // TODO some logic to store it anywhere
    }

    /**
     * All the source elements in the trans unit.
     * The source element is a reference to the original template.
     * It contains the name of the template file and a line number with the position inside the template.
     * It is just a help for translators to find the context for the translation.
     * This is set when using Angular 4.0 or greater.
     * Otherwise it just returns an empty array.
     */
    public sourceReferences(): { sourcefile: string, linenumber: number }[] {
        if (this._sourceTransUnitFromMaster) {
            return this._sourceTransUnitFromMaster.sourceReferences();
        } else {
            return [];
        }
    }

    /**
     * Test, wether setting of source refs is supported.
     * If not, setSourceReferences will do nothing.
     * xtb does not support this, all other formats do.
     */
    public supportsSetSourceReferences(): boolean {
        return false;
    }

    /**
     * Set source ref elements in the transunit.
     * Normally, this is done by ng-extract.
     * Method only exists to allow xliffmerge to merge missing source refs.
     * @param sourceRefs the sourcerefs to set. Old ones are removed.
     */
    public setSourceReferences(sourceRefs: {sourcefile: string, linenumber: number}[]) {
        // xtb has no source refs, they are part of the master
    }

    /**
     * The description set in the template as value of the i18n-attribute.
     * e.g. i18n="mydescription".
     * In xtb only the master stores it.
     */
    public description(): string {
        if (this._sourceTransUnitFromMaster) {
            return this._sourceTransUnitFromMaster.description();
        } else {
            return null;
        }
    }

    /**
     * The meaning (intent) set in the template as value of the i18n-attribute.
     * This is the part in front of the | symbol.
     * e.g. i18n="meaning|mydescription".
     * In xtb only the master stores it.
     */
    public meaning(): string {
        if (this._sourceTransUnitFromMaster) {
            return this._sourceTransUnitFromMaster.meaning();
        } else {
            return null;
        }
    }

    /**
     * Test, wether setting of description and meaning is supported.
     * If not, setDescription and setMeaning will do nothing.
     * xtb does not support this, all other formats do.
     */
    public supportsSetDescriptionAndMeaning(): boolean {
        return false;
    }

    /**
     * Change description property of trans-unit.
     * @param description description
     */
    public setDescription(description: string) {
        // not supported, do nothing
    }

    /**
     * Change meaning property of trans-unit.
     * @param meaning meaning
     */
    public setMeaning(meaning: string) {
        // not supported, do nothing
    }

    /**
     * Get all notes of the trans-unit.
     * There are NO notes in xmb/xtb
     */
    public notes(): INote[] {
        return [];
    }

    /**
     * Test, wether setting of notes is supported.
     * If not, setNotes will do nothing.
     * xtb does not support this, all other formats do.
     */
    public supportsSetNotes(): boolean {
        return false;
    }

    /**
     * Add notes to trans unit.
     * @param newNotes the notes to add.
     * NOT Supported in xmb/xtb
     */
    public setNotes(newNotes: INote[]) {
        // not supported, do nothing
    }

    /**
     * Copy source to target to use it as dummy translation.
     * Returns a changed copy of this trans unit.
     * receiver is not changed.
     * (internal usage only, a client should call importNewTransUnit on ITranslationMessageFile)
     * In xtb there is nothing to do, because there is only a target, no source.
     */
    public cloneWithSourceAsTarget(isDefaultLang: boolean, copyContent: boolean, targetFile: ITranslationMessagesFile): AbstractTransUnit {
        return this;
    }

    /**
     * Copy source to target to use it as dummy translation.
     * (internal usage only, a client should call createTranslationFileForLang on ITranslationMessageFile)
     */
    public useSourceAsTarget(isDefaultLang: boolean, copyContent: boolean) {
        // do nothing
    }

    /**
     * Set the translation to a given string (including markup).
     * @param translation translation
     */
    protected translateNative(translation: string) {
        const target = this._element;
        if (isNullOrUndefined(translation)) {
            translation = '';
        }
        DOMUtilities.replaceContentWithXMLContent(target, translation);
    }

}