text:
var MONGOCLIENT=require("mongodb").MongoClient,
		Q=require("q"),
	  LOGGER=require("../../config/logger.js");

//FACTORY
module.exports=function(){
  return new Mongodb();
}

//CLASS
var Mongodb=function(){
  //properties
  //cached database connection to increase the performance
  this.cacheDB={};
}

/**
 * Connect Mongo
 * @param {String} url
 * @param {Number} port
 * @param {String} dbname
 * @param {callback} callback function. return db object
 */
Mongodb.prototype.connect=function(url, dbname, callback){
			url=url || "";
			dbname=dbname || "";

			//defer
			var $q=Q.defer(),
					mongodb=this.cacheDB;

			if(url!='' && dbname!=""){
				var path="mongodb://"+url+"/"+dbname;

				if(mongodb[url] && mongodb[url][dbname]){
					$q.resolve(mongodb[url][dbname])

					LOGGER.info('*************************************************************************')
					LOGGER.info("mongodb connected (existed): "+ path)

					/**
					if(callback){
						callback(mongodb[url][dbname]);

						LOGGER.info('*************************************************************************')
						LOGGER.info("mongodb connected (existed): "+ path)
					}
					*/

				}else{
					MONGOCLIENT.connect(path, function(error, db){
						if(error) {
							$q.reject(err)
						}else{
							if(!mongodb[url]){mongodb[url]={}}

							if(!mongodb[url][dbname]){mongodb[url][dbname]=db}

							$q.resolve(mongodb[url][dbname])
							/**
							if(callback){
								callback(mongodb[url][dbname])
							}
							*/

							LOGGER.info('*************************************************************************')
							LOGGER.info("mongodb connected (new): "+ path)
						}

					})
				}
			}else{
				$q.reject("[ERROR] hdma.utilities.connectMongo: no URL, PORT, and DBNAME")
				LOGGER.error("[ERROR] hdma.utilities.connectMongo: no URL, PORT, and DBNAME");
			}

			//return promise
			return $q.promise.nodeify(callback)
}

/**
 * query collection in a mongodb
 * @param (mongodb) mongodb object
 * @param {String} collectionName: collection name
 * @param {Object} query
 * @param {Object} options
 * @param {callback} callback function. return error and results array
 */
Mongodb.prototype.query=function(db, collectionName, query, options, callback){
			LOGGER.info('*************************************************************************')
			LOGGER.info('querying MongoDb. collection=' + collectionName)
			var startQuery=new Date();
			LOGGER.info('query at= '+startQuery)
			LOGGER.info('query params=')
            //CHRIS: I changed this to only print out the first 100 characters of the query
            //because I am doing some queries with a list of many IDs, which take a while
            //to print to the command line...
			//Calvin: extend to 500 characters..need to see some parameters
			LOGGER.info(JSON.stringify(query).substring(0, 500));
			LOGGER.info('query options=')
			LOGGER.info(options)

			var err={
				"a":"[ERROR] hdma.mongodb.query: no db, collection,or query object.",
				"b":"[ERROR] hdma.mongodb.query: no collection in db."
			}, defer=Q.defer();

			if(!options){options={}}
			options.fields=options.fields || null;
			options.sort=options.sort || null;
			options.limit=options.limit || 1000;
			options.batchSize=parseInt(options.batchSize) || null;
			options.onEachTweet=options.onEachTweet || null

			if(db && collectionName && collectionName!='' && query){
				var col=db.collection(collectionName)

				if(col){
					var cursor=col.find(query, options);

					//explain cursor
					cursor.explain(function(err, result){
						LOGGER.info('*************************************************************************')
						LOGGER.info('Index:')
						if(result){
							var out={};
							["cursor","isMultiKey","n","nscannedObjects","nscanned","nscannedObjectsAllPlans","nscannedAllPlans", "scanAndOrder","indexOnly","nYields", "nChunkSkips", "millis"].forEach(function(k){
								if(result[k]){out[k]=result[k]}
							})
							LOGGER.info(out)
						}
					})

					if(options.limit<=10000){
						/** directly convert to Array, but not good for large datasets
						col.find(query, options).toArray(function(error, results){
							if(error){
								LOGGER.error("[ERROR] hdma.mongodb.query:" + error);
								if(callback){callback(error, null)}
								return;
							}else{
								LOGGER.info("QueryTime= "+ (new Date()-startQuery)/1000+ "s")
								if(callback){callback(null, results)}
							}
						});
						*/

						//on each
						var results=[], num=0;
						cursor.each(function(err, doc){
							if(err){
								LOGGER.error("[ERROR] hdma.mongodb.query:" + err);
								defer.reject(err);

								//if(callback){callback(err, null)}
								return;
							}

							process.nextTick(function(){
								if(doc){
										if(options.onEachTweet){
											var obj=options.onEachTweet(doc, num);
											if(obj&&obj!=null){
												results.push(obj)
											}
										}else{
											results.push(doc)
										}
										num++;

								}else{
									LOGGER.info("QueryTime= "+ (new Date()-startQuery)/1000+ "s")
									LOGGER.info('result.length='+results.length)

									defer.resolve(results);
									//if(callback){callback(null, results)}
								}
							})
						})

					}else{
						LOGGER.info("use Streaming to retrieve mongo data");
						var results=[],num=0;
						//options.explain=true;

						//if options.sort exists, it will decrease performance especially when query lots of datasets (more than 20000)
						//need to set options.sort=null
						//however, it can be improved by setting compound index (set index on two more field at the same time. such as keywords+created_at_local)

						/** streaming */
						var stream=cursor.stream();
						stream.on("error", function(err){LOGGER.error("[ERROR] hdma.mongodb.query:" + err); if(callback){callback(err,null)}})
						stream.on("data", function(doc){
							process.nextTick(function(){
								if(options.onEachTweet){
									var obj=options.onEachTweet(doc, num);
									if(obj&&obj!=null){
										results.push(obj)
									}
								}else{
									results.push(doc)
								}
								num++;

								if(num%10000==0){
									console.log(num)
								}
							});

						})
						stream.on("close", function(){
							LOGGER.info("QueryTime= "+ (new Date()-startQuery)/1000+ "s");
							startQuery=new Date();

							defer.resolve(results);
							//if(callback){callback(null, results)}
							LOGGER.info("ProcessTime= "+ (new Date()-startQuery)/1000+ "s");
						});

					}

				}else{
					LOGGER.error(err["b"])
					defer.reject(err["b"]);
					//if(callback){callback(err["b"], null)}
					return;
				}
			}else{
				LOGGER.error(err["a"]);
				defer.reject(err["a"]);
				//if(callback){
					//callback(err["a"], null)
				//}
			}

		return defer.promise.nodeify(callback)
}

/**
 * update collection
 * @param (mongodb) mongodb object
 * @param {String} collectionName: collection name
 * @param {Object} selector
 * @param {Object} params
 * @param {Object} options
 * @param {callback} callback function. return error and result
 */
Mongodb.prototype.update=function(db, collectionName, selector, params, options, callback){
			LOGGER.info('*************************************************************************')
			LOGGER.info('updating MongoDb. collection=' + collectionName)
			LOGGER.info('update on= ')
			LOGGER.info(selector)
			//LOGGER.info('where params=')
			//LOGGER.info(JSON.stringify(params));
			LOGGER.info('query options=')
			LOGGER.info(options)

			var collection=db.collection(collectionName, function(err, col){
				col.update(selector, params, options, function(e, result, status){
					if(callback){
						callback(e, result, status)
					}
				})
			});

}

/**
 * insert collection
 * @param (mongodb) mongodb object
 * @param {String} collectionName: collection name
 * @param {Object or array}
 * @param {Object} options
 * @param {callback} callback function. return error and result
 */
Mongodb.prototype.insert=function(db, collectionName, docs, options, callback){
			LOGGER.info('*************************************************************************')
			LOGGER.info('inserting MongoDb. collection=' + collectionName)
			LOGGER.info('insert options=')
			LOGGER.info(options)

			var collection=db.collection(collectionName, function(err, col){
				col.insert(docs, options, function(e, result){
					if(callback){
						callback(e, result)
					}
				})
			});
}

/**
 * save collection
 * @param (mongodb) mongodb object
 * @param {String} collectionName: collection name
 * @param {Object}
 * @param {Object} options
 * @param {callback} callback function. return error and result
 */
Mongodb.prototype.save=function(db, collectionName, doc, options, callback){
			LOGGER.info('*************************************************************************')
			LOGGER.info('saving MongoDb. collection=' + collectionName)
			LOGGER.info('save options=')
			LOGGER.info(options)

			var collection=db.collection(collectionName, function(err, col){

				//return;
				col.save(doc, options, function(e, result){
					if(callback){
						callback(e, result)
					}
				})
			});
}

/**
 * count collection in a mongodb
 * @param (mongodb) mongodb object
 * @param {String} collectionName: collection name
 * @param {Object} query
 * @param {Object} options
 * @param {callback} callback function. return error and count
 */
Mongodb.prototype.count=function(db, collectionName, query, options, callback){
			LOGGER.info('*************************************************************************')
			LOGGER.info('count MongoDb. collection=' + collectionName)
			var startQuery=new Date();
			LOGGER.info('count at= '+startQuery)
			LOGGER.info('count params=')
			LOGGER.info(query)

			if(!options){options={}}
			//options.fields=options.fields || null;
			//options.sort=options.sort || null;
			//options.limit=options.limit || 1000;
			//options.batchSize=parseInt(options.batchSize) || null;

			if(db && collectionName && collectionName!='' && query){
				var col=db.collection(collectionName);

				col.find(query).count(callback)
			}
}


text:
/* paletteview.cpp
 * implementation of the palette view */

#include <stdio.h>
#include <QMouseEvent>
#include <QMessageBox>
#include <QScrollBar>
#include <QFileDialog>
#include "editorwindow.h"
#include "newdialog.h"
#include "ui_mainwindow.h"
#include "ui_newmap.h"

/* constructors for the view objects */
PaletteView::PaletteView(QWidget* parent) : QGraphicsView(parent) {

}

/* tell the component about the window it's in */
void PaletteView::set_window(EditorWindow* window) {
    this->window = window;
}

/* called when the mouse is pressed in this area */
void PaletteView::mousePressEvent(QMouseEvent* e) {
    if (e->button() != Qt::LeftButton) {
        return;
    }

    /* find the position of our scroll bar */
    int scroll_x = horizontalScrollBar()->value();
    int scroll_y = verticalScrollBar()->value();

    /* apply this palette click - taking scrolling into account */
    window->palette_click(e->x() + scroll_x, e->y() + scroll_y);
}

redpajama_set_name: RedPajamaGithub


text:
#ifndef WebDataSource_h
#define WebDataSource_h

#include "../platform/WebCommon.h"
#include "WebNavigationType.h"
#include "WebTextDirection.h"

namespace WebKit {

class WebApplicationCacheHost;
class WebString;
class WebURL;
class WebURLRequest;
class WebURLResponse;
template <typename T> class WebVector;

class WebDataSource {
public:
    class ExtraData {
    public:
        virtual ~ExtraData() { }
    };

    // Returns the original request that resulted in this datasource.
    virtual const WebURLRequest& originalRequest() const = 0;

    // Returns the request corresponding to this datasource.  It may
    // include additional request headers added by WebKit that were not
    // present in the original request.  This request may also correspond
    // to a location specified by a redirect that was followed.
    virtual const WebURLRequest& request() const = 0;

    // Returns the response associated with this datasource.
    virtual const WebURLResponse& response() const = 0;

    // When this datasource was created as a result of WebFrame::loadData,
    // there may be an associated unreachableURL.
    virtual bool hasUnreachableURL() const = 0;
    virtual WebURL unreachableURL() const = 0;

    // Returns all redirects that occurred (both client and server) before
    // at last committing the current page.  This will contain one entry
    // for each intermediate URL, and one entry for the last URL (so if
    // there are no redirects, it will contain exactly the current URL, and
    // if there is one redirect, it will contain the source and destination
    // URL).
    virtual void redirectChain(WebVector<WebURL>&) const = 0;

    // Returns whether the navigation associated with this datasource is a
    // client redirect that should replace the current history item.
    virtual bool isClientRedirect() const = 0;

    // Returns the title for the current page.
    virtual WebString pageTitle() const = 0;

    // Returns the text direction of the title for the current page.
    virtual WebTextDirection pageTitleDirection() const = 0;

    // The type of navigation that triggered the creation of this datasource.
    virtual WebNavigationType navigationType() const = 0;

    // The time in seconds (since the epoch) of the event that triggered
    // the creation of this datasource.  Returns 0 if unknown.
    virtual double triggeringEventTime() const = 0;

    // Extra data associated with this datasource.  If non-null, the extra
    // data pointer will be deleted when the datasource is destroyed.
    // Setting the extra data pointer will cause any existing non-null
    // extra data pointer to be deleted.
    virtual ExtraData* extraData() const = 0;
    virtual void setExtraData(ExtraData*) = 0;

    // The application cache host associated with this datasource.
    virtual WebApplicationCacheHost* applicationCacheHost() = 0;

    // Set deferMainResourceDataLoad flag on the loader.  This is used for
    // testing.
    virtual void setDeferMainResourceDataLoad(bool) = 0;

    // Sets the navigation start time for this datasource. Ordinarily,
    // navigation start is determined in WebCore. But, in some situations,
    // the embedder might have a better value and can override it here. This
    // should be called before WebFrameClient::didCommitProvisionalLoad.
    // Calling it later may confuse users, because JavaScript may have run and
    // the user may have already recorded the original value.
    virtual void setNavigationStartTime(double) = 0;

protected:
    ~WebDataSource() { }
};

} // namespace WebKit

#endif


text:
import React from "react";
import GreetingMaster from "./GreetingMaster";
import GreetingDetail from "./GreetingDetail";

let currentId = 0;

const sampleGreetings = [
  {
    id: currentId++,
    name: "Olli",
    greeting: "Huhu"
  },
  {
    id: currentId++,
    name: "Oma",
    greeting: "Hallo"
  }
];

const MODE_MASTER = "MODE_MASTER";
const MODE_DETAIL = "MODE_DETAIL";

export default class GreetingController extends React.Component {
  render() {
    const { mode, greetings } = this.state;
    return (
      <div>
        {mode === MODE_MASTER ? (
          <GreetingMaster greetings={greetings} onAdd={() => this.setState({ mode: MODE_DETAIL })} />
        ) : null
        /*
                        1a. Hier statt null deine GreetingDetail-Komponente einbinden
                        1b. Eine Callback-Funktion für das Hinzufügen eines Grußes an die GreetingDetail-Komponente übergeben
                        1c. Die Callback-Funktion soll addGreeting (s.u.) aufrufen

                        2a. In GreetingDetail einen Knopf zum Hinzufügen einbauen
                        2b. Beim Drücken auf den Knopf soll die übergebene Callback-Funktion (1b) mit dem eingegebenen
                            Gruß aufgerufen werden (Parameter: ein Objekt { name: ..., greeting: ... })
                     */
        }
      </div>
    );
  }
  constructor(props) {
    super(props);
    this.state = {
      greetings: sampleGreetings,
      mode: MODE_MASTER
    };
  }

  addGreeting(greetingToBeAdded) {
    // Aktuelle Liste mit Greetings aus dem State holen
    const { greetings } = this.state;

    // dem übergebenen (neuen) Greeting eine "eindeutige" Id hinzufügen
    greetingToBeAdded.id = currentId++;

    // Ein neues Array mit den alten Greetings und dem neuen Greeting erzeugen
    const newGreetings = [...greetings, greetingToBeAdded];

    // den State mit den neuen Greetings setzen, außerdem wieder die MASTER-View anzeigen
    this.setState({
      greetings: newGreetings,
      mode: MODE_MASTER
    });
  }
}


text:
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Threading;
using Steamworks;

namespace PlayGround
{
    public class SteamManager
    {
        private static SteamManager _Instance;
        public static SteamManager Instance => _Instance ?? new SteamManager();

        public readonly Dictionary<ulong,string> PendingDownloads = new Dictionary<ulong, string>();

        public SteamManager()
        {
            if (_Instance == null)
                _Instance = this;

            if (SteamAPI.RestartAppIfNecessary((AppId)432200))
                Environment.Exit(0);
            if (!SteamAPI.Init())
                Environment.Exit(0);

            SteamUGC.OnDownloadCompleted += DownloadCompleted;
            SteamUGC.OnItemInstalled += ItemInstalled;
            SteamUGC.OnItemSubscribed += ItemSubscribed;
            SteamUGC.OnItemUnsubscribed += ItemUnsubscribed;
        }

        public async void Download()
        {
            var downloadItem = new PublishedFileId(597864941);
            //await SteamUGC.UnsubscribeItemAsync(downloadItem);
            //await SteamUGC.SubscribeItemAsync(downloadItem);

            await SteamUGC.DownloadAsync(downloadItem);

            //Console.WriteLine("Download queued");
            //SteamUGC.DownloadItem(downloadItem, true);
            //while (true)
            //{
            //    ulong downloaded;
            //    ulong total;
            //    if (SteamUGC.GetItemDownloadInfo(downloadItem, out downloaded, out total))
            //    {
            //        if (downloaded > 0 && total > 0)
            //            Console.WriteLine($"DL: {downloaded/1024}/{total/1024}kb");
            //        if (downloaded > 0 && total > 0 && downloaded == total)
            //            break;
            //    }
            //    Thread.Sleep(10);
            //}
        }

        public async void GetAllContent()
        {
            var contentDetails = await SteamUGC.QueryAllUGCAsync(UGCQuery.RankedByPublicationDate, MatchingUGCType.All, AppId.Invalid, (AppId) 432200, 1);

            foreach (var details in contentDetails)
                Console.WriteLine($"Title: {details.Title} - Type: {details.FileType} - Votes: {details.VotesUp}");
        }
        public uint CountWorkshopStuff() => SteamUGC.GetNumSubscribedItems();

        public void GetWorkshopStuff()
        {
            var numSubscribedItems = CountWorkshopStuff();
            var items = new PublishedFileId[numSubscribedItems];
            var numFound = SteamUGC.GetSubscribedItems(items, numSubscribedItems);
            Array.Resize(ref items, (int)numFound);

            CheckWorkshopStuff(items);
        }

        private async void CheckWorkshopStuff(IEnumerable<PublishedFileId> items)
        {
            foreach (var item in items)
            {
                var state = SteamUGC.GetItemState(item);

                //await SteamUGC.UnsubscribeItemAsync(item);

                VerifyStuff(item);

                Console.WriteLine("State: " + state);
            }
        }

        private void VerifyStuff(PublishedFileId item)
        {
            uint timeStamp;
            ulong sizeOnDisk;
            string folderPath;
            if (!SteamUGC.GetItemInstallInfo(item, out sizeOnDisk, out folderPath, 1024*1024*16, out timeStamp))
            {
                Console.WriteLine("Steam said its not there.");
                QueueDownload(item);
            }
            else if (!Directory.Exists(folderPath))
            {
                Console.WriteLine("Folder not found");
                QueueDownload(item);
            }
            else if (!Directory.EnumerateFiles(folderPath).Any())
            {
                Console.WriteLine("No files in folder.");
                QueueDownload(item);
            }
            else
            {
                Console.WriteLine($"{item.Id} already installed.");
            }
        }

        private async void QueueDownload(PublishedFileId item)
        {
            var result = await SteamUGC.GetItemDetailsAsync(item);
            Console.WriteLine($"{result.Details.Description} - Is {(result.CachedData ? "" : "not")} on your hdd!");

            if (!SteamUGC.DownloadItem(item, true))
                return;

            Console.WriteLine("Download queued");
            PendingDownloads.Add(result.Details.Field.Id, result.Details.Title);
        }

        private void DownloadCompleted(DownloadItemResult param)
        {
            string name;
            if (PendingDownloads.TryGetValue(param.PublishedField.Id, out name))
                Console.WriteLine($"{name} - download result: {param.ResultType}");
        }

        private async void ItemInstalled(ItemInstalled item)
        {
            var result = await SteamUGC.GetItemDetailsAsync(item.PublishedFile);
            Console.WriteLine("Installed: "+result.Details.Title);
        }

        private async void ItemUnsubscribed(RemoteStoragePublishedFileUnsubscribed item)
        {
            var result = await SteamUGC.GetItemDetailsAsync(item.PublishedFile);
            Console.WriteLine("Unsubscribed: " + result.Details.Title);
        }

        private async void ItemSubscribed(RemoteStoragePublishedFileSubscribed item)
        {
            var result = await SteamUGC.GetItemDetailsAsync(item.PublishedField);
            Console.WriteLine("Subscribed: " + result.Details.Title);
        }

        public void Update() => SteamAPI.RunCallbacks();
    }
}


text:
Free and open source anime viewer for Android

NOTE:

This is the early alpha build of the android app. It is still a WIP, because features like viewing and downloading work but it's still far from complete.

My Anime Viewer is an app that aims to make watching anime easier by taking the hassle of browsing to site and then being bombarded with ads.

Current Features:
  - Watching episodes from GoGoAnime
  - Favorites to keep track of what you're watching
  - Library to keep anime on the go
  - History of episodes watched

Planned Features:
  - Additional Sources

## License

    Copyright 2017 Salman T. Khan

    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.

## Disclaimer

The developer of this application does not have any affiliation with the content providers available.


text:
var mongoose = require('mongoose');
require('./db.js')

const profileSchema = new mongoose.Schema({
	username: String,
	headline: String,
	following: [String],
	email: String,
	dob: String,
	zipcode: String,
	avatar: String
})

var userSchema = new mongoose.Schema({
	username:String,
	hash: String,
	salt: String
})

var commentSchema = new mongoose.Schema({
	commentId: String,
	text: String,
	date: Date,
	author: String
})

var articleSchema = new mongoose.Schema({
	author: String,
	img:String,
	text: String,
	date: Date,
	comments: [commentSchema]
})

exports.Profile = mongoose.model("Profile",profileSchema);
exports.User = mongoose.model("User",userSchema);
exports.Comment = mongoose.model('Comment', commentSchema)
exports.Article = mongoose.model('Article', articleSchema)


text:
<!DOCTYPE html>

    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>SBERT.net Models</title>

    <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/css/bootstrap.min.css"
          integrity="sha384-Vkoo8x4CGsO3+Hhxv8T/Q5PaXtkKtu6ug5TOeNV6gBiFeWPGFN9MuhOf23Q9Ifjh" crossorigin="anonymous">

    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/5.15.3/css/all.min.css"
          integrity="sha512-iBBXm8fW90+nuLcSKlbmrPcLa0OT92xO1BIsZ+ywDWZCvqsWgccV3gFoRBv0z+8dLJgyAHIhR35VZc2oM/gI1w=="
          crossorigin="anonymous" referrerpolicy="no-referrer"/>

            All modelsAll models

                    Model Name

                     Performance Sentence Embeddings (14 Datasets)

                    Performance Semantic Search (6 Datasets)

                    Avg. Performance

                    Speed

                    Model Size

            <template  v-for="item in sortedModels">

                        {{ item.name }}

                    {{ item.sentence_performance > 0 ? item.sentence_performance.toFixed(2) : "" }}
                    {{ item.semantic_search > 0 ? item.semantic_search.toFixed(2) : "" }}
                    {{ (item.sentence_performance > 0 && item.semantic_search > 0) ? item.avg_performance.toFixed(2) : "" }}
                    {{ item.speed }}
                    {{ item.size }} MB

                                    {{ item.name }}
                                    <button title="Copy model name" type="button" class="btn btn-link p-0" v-on:click="copyClipboard(item.name)" data-toggle="tooltip" data-placement="bottom" data-trigger="hover" :id="item.name+'-copy-btn'" style="border: 0;">
                                        <svg class="" xmlns="http://www.w3.org/2000/svg" aria-hidden="true" fill="currentColor" focusable="false" role="img" width="1em" height="1em" preserveAspectRatio="xMidYMid meet" viewBox="0 0 32 32"><path d="M28,10V28H10V10H28m0-2H10a2,2,0,0,0-2,2V28a2,2,0,0,0,2,2H28a2,2,0,0,0,2-2V10a2,2,0,0,0-2-2Z" transform="translate(0)"></path><path d="M4,18H2V4A2,2,0,0,1,4,2H18V4H4Z" transform="translate(0)"></path><rect fill="none" width="32" height="32"></rect></svg>
                                    </button>

                                Description:
                                {{item.description}}

                                Base Model:

                                Max Sequence Length:
                                {{item.max_seq_length || ''}}

                                Dimensions:
                                {{item.dim }}

                                Normalized Embeddings:
                                {{item.normalized_embeddings}}

                                Suitable Score Functions:

                                Size:
                                {{item.size}} MB

                                Pooling:
                                {{item.pooling}}

                                Training Data:
                                {{item.training_data}}

                                Model Card:
                                https://huggingface.co/sentence-transformers/{{item.name}}

            </template>


text:
package io.machinecode.chainlink.spi.inject;

/**
 * @author Brent Douglas
 * @since 1.0
 */
public interface InjectablesProvider {

    void setInjectables(Injectables injectables);

    void releaseInjectables();

    Injectables getInjectables();
}


text:
.class Landroid/app/ActivityView$2;
.super Ljava/lang/Object;
.source "ActivityView.java"

# interfaces
.implements Ljava/lang/Runnable;

# annotations
.annotation system Ldalvik/annotation/EnclosingMethod;
    value = Landroid/app/ActivityView;->setSurfaceAsync(Landroid/view/Surface;IIIZ)V
.end annotation

.annotation system Ldalvik/annotation/InnerClass;
    accessFlags = 0x0
    name = null
.end annotation

# instance fields
.field final synthetic this$0:Landroid/app/ActivityView;

.field final synthetic val$callback:Z

.field final synthetic val$densityDpi:I

.field final synthetic val$height:I

.field final synthetic val$surface:Landroid/view/Surface;

.field final synthetic val$width:I

# direct methods
.method constructor <init>(Landroid/app/ActivityView;Landroid/view/Surface;IIIZ)V
    .locals 0
    .param p1, "this$0"    # Landroid/app/ActivityView;
    .param p2, "val$surface"    # Landroid/view/Surface;
    .param p3, "val$width"    # I
    .param p4, "val$height"    # I
    .param p5, "val$densityDpi"    # I
    .param p6, "val$callback"    # Z

    .prologue
    .line 294
    iput-object p1, p0, Landroid/app/ActivityView$2;->this$0:Landroid/app/ActivityView;

    iput-object p2, p0, Landroid/app/ActivityView$2;->val$surface:Landroid/view/Surface;

    iput p3, p0, Landroid/app/ActivityView$2;->val$width:I

    iput p4, p0, Landroid/app/ActivityView$2;->val$height:I

    iput p5, p0, Landroid/app/ActivityView$2;->val$densityDpi:I

    iput-boolean p6, p0, Landroid/app/ActivityView$2;->val$callback:Z

    invoke-direct {p0}, Ljava/lang/Object;-><init>()V

    return-void
.end method

# virtual methods
.method public run()V
    .locals 7

    .prologue
    .line 297
    :try_start_0
    iget-object v1, p0, Landroid/app/ActivityView$2;->this$0:Landroid/app/ActivityView;

    invoke-static {v1}, Landroid/app/ActivityView;->-get1(Landroid/app/ActivityView;)Ljava/lang/Object;

    move-result-object v2

    monitor-enter v2
    :try_end_0
    .catch Landroid/os/RemoteException; {:try_start_0 .. :try_end_0} :catch_0

    .line 298
    :try_start_1
    iget-object v1, p0, Landroid/app/ActivityView$2;->this$0:Landroid/app/ActivityView;

    invoke-static {v1}, Landroid/app/ActivityView;->-get0(Landroid/app/ActivityView;)Landroid/app/ActivityView$ActivityContainerWrapper;

    move-result-object v1

    if-eqz v1, :cond_0

    .line 299
    iget-object v1, p0, Landroid/app/ActivityView$2;->this$0:Landroid/app/ActivityView;

    invoke-static {v1}, Landroid/app/ActivityView;->-get0(Landroid/app/ActivityView;)Landroid/app/ActivityView$ActivityContainerWrapper;

    move-result-object v1

    iget-object v3, p0, Landroid/app/ActivityView$2;->val$surface:Landroid/view/Surface;

    iget v4, p0, Landroid/app/ActivityView$2;->val$width:I

    iget v5, p0, Landroid/app/ActivityView$2;->val$height:I

    iget v6, p0, Landroid/app/ActivityView$2;->val$densityDpi:I

    invoke-virtual {v1, v3, v4, v5, v6}, Landroid/app/ActivityView$ActivityContainerWrapper;->setSurface(Landroid/view/Surface;III)V
    :try_end_1
    .catchall {:try_start_1 .. :try_end_1} :catchall_0

    :cond_0
    :try_start_2
    monitor-exit v2
    :try_end_2
    .catch Landroid/os/RemoteException; {:try_start_2 .. :try_end_2} :catch_0

    .line 307
    iget-boolean v1, p0, Landroid/app/ActivityView$2;->val$callback:Z

    if-eqz v1, :cond_1

    .line 308
    iget-object v1, p0, Landroid/app/ActivityView$2;->this$0:Landroid/app/ActivityView;

    new-instance v2, Landroid/app/ActivityView$2$1;

    iget-object v3, p0, Landroid/app/ActivityView$2;->val$surface:Landroid/view/Surface;

    invoke-direct {v2, p0, v3}, Landroid/app/ActivityView$2$1;-><init>(Landroid/app/ActivityView$2;Landroid/view/Surface;)V

    invoke-virtual {v1, v2}, Landroid/app/ActivityView;->post(Ljava/lang/Runnable;)Z

    .line 295
    :cond_1
    return-void

    .line 297
    :catchall_0
    move-exception v1

    :try_start_3
    monitor-exit v2

    throw v1
    :try_end_3
    .catch Landroid/os/RemoteException; {:try_start_3 .. :try_end_3} :catch_0

    .line 302
    :catch_0
    move-exception v0

    .line 303
    .local v0, "e":Landroid/os/RemoteException;
    new-instance v1, Ljava/lang/RuntimeException;

    .line 304
    const-string/jumbo v2, "ActivityView: Unable to set surface of ActivityContainer. "

    .line 303
    invoke-direct {v1, v2, v0}, Ljava/lang/RuntimeException;-><init>(Ljava/lang/String;Ljava/lang/Throwable;)V

    throw v1
.end method


text:
using std::vector;

namespace browser_sync {

PostCommitMessageCommand::PostCommitMessageCommand() {}
PostCommitMessageCommand::~PostCommitMessageCommand() {}

SyncerError PostCommitMessageCommand::ExecuteImpl(
    sessions::SyncSession* session) {
  if (session->status_controller().commit_ids().empty())
    return SYNCER_OK;  // Nothing to commit.
  ClientToServerResponse response;
  syncable::Directory* dir = session->context()->directory();
  sessions::StatusController* status = session->mutable_status_controller();
  SyncerError result = SyncerProtoUtil::PostClientToServerMessage(
      status->commit_message(), &response, session);
  if (result != SYNCER_OK) {
    // None of our changes got through.  Clear the SYNCING bit which was
    // set to true during BuildCommitCommand, and which may still be true.
    // Not to be confused with IS_UNSYNCED, this bit is used to detect local
    // changes to items that happen during the server Commit operation.
    syncable::WriteTransaction trans(FROM_HERE, syncable::SYNCER, dir);
    const vector<syncable::Id>& commit_ids = status->commit_ids();
    for (size_t i = 0; i < commit_ids.size(); i++) {
      syncable::MutableEntry entry(&trans, syncable::GET_BY_ID, commit_ids[i]);
      entry.Put(syncable::SYNCING, false);
    }
    return result;
  }

  status->set_items_committed();
  status->mutable_commit_response()->CopyFrom(response);
  return SYNCER_OK;
}

}  // namespace browser_sync


text:
__author__ = 'Sergey Sobko'
__email__ = 'S.Sobko@profitware.ru'
__copyright__ = 'Copyright 2013, The Profitware Group'

from circuitry.adapters import AbstractAdapter
from circuitry.adapters.graph import GraphAdapter

class MatlabAdapter(AbstractAdapter):
    public_methods = ('matlab_code',)
    default_method = lambda self: '\n'.join(self.matlab_code())

    def _matlab_code_handle_counters(self, counters, device_type, device_func_name, device_height, position_x):
        counters['current_position_x'] = position_x

        # Inputs @ position=1, inverted inputs @ position=2
        if device_type == 'input':
            counters['current_position_x'] = 1
            if device_func_name == 'not':
                counters['current_position_x'] = 2

        # # Shift output to position + 1
        # if device_type == 'output' and counters['prev_type'] == 'common':
        #     counters['current_position_x'] += 1
        #
        # # Shift common to position + 1
        # if device_type == 'common' and counters['prev_type'] == 'input':
        #     counters['current_position_x'] += 1
        #
        # if device_type == '' and counters['prev_type'] == 'output':
        #     counters['current_position_x'] += 1

        counters['prev_type'] = device_type

        # Get device start y-position by device type
        if not counters['current_position_x'] in counters['current_position_y_by_x']:
            if device_type == 'input':
                counters['current_position_y_by_x'][counters['current_position_x']] = 0
            elif device_type == 'common':
                counters['current_position_y_by_x'][counters['current_position_x']] = counters['inputs_max_y']
            else:
                counters['current_position_y_by_x'][counters['current_position_x']] = counters['common_max_y']

        # Count maximal y for inputs
        if device_type == 'input':
            _new_max_y = counters['current_position_y_by_x'][counters['current_position_x']] + device_height + 50
            counters['inputs_max_y'] = max(_new_max_y, counters['inputs_max_y'])

        # Count maximal y for common
        if device_type == 'common':
            _new_max_y = counters['current_position_y_by_x'][counters['current_position_x']] + device_height + 50
            # if _new_max_y > counters['inputs_max_y'] * 2:
            #     counters['current_position_x'] += 1
            #     counters['current_position_y_by_x'][counters['current_position_x']] = counters['inputs_max_y']
            counters['common_max_y'] = max(_new_max_y, counters['common_max_y'])

        return counters

    def _matlab_code_generate(self, matlab_code_lines, matlab_code_template):
        # Counters are used at each step to handle current and previous data
        _counters = {
            'inport': 0,
            'outport': 0,
            'and': 0,
            'or': 0,
            'not': 0,
            'current_position_x': 1,
            'current_position_y_by_x': dict(),
            'inputs_max_y': 0,
            'common_max_y': 0,
            'prev_type': '',
            'edges': dict()
        }

        _graph_type_order = {
            'input': 1,
            'common': 2,
            'output': 3
        }

        _matlab_device_name_and_id = ''

        graph_adapter = GraphAdapter(self._device)
        graph = graph_adapter.graph

        def _sorting_function(rec):
            second_param = 0
            if graph.node[rec]['type'] == 'input' and not 'device' in graph.node[rec]:
                second_param = map(str, reduce(list.__add__, map(list, self._device.input_signals))).index(rec)
            if graph.node[rec]['type'] == 'output':
                second_param = graph.node[rec]['global_device_number']
            return _graph_type_order[graph.node[rec]['type']], second_param

        _output_device_list = list()

        for graph_node in sorted(graph.nodes(), key=_sorting_function):
            node = graph.node[graph_node]
            _device, _device_type, _device_func_name, _device_height, _device_ports_count = \
                None, node['type'], '', 10, 1

            # not is_Atom
            if 'device' in node:
                _device = node['device']
                _device_ports_count = len(_device.input_signals[0])
                _device_func_name = str(_device.functions[0].func).lower()
                _device_height = 10 * (_device_ports_count + 1)

            _counters = self._matlab_code_handle_counters(_counters, _device_type, _device_func_name, _device_height,
                                                          graph_adapter.max_distance - node['distance'] + 2)

            # Count position
            matlab_code_lines.append(matlab_code_template['position'] % {
                'x': 100 * (_counters['current_position_x'] * 2),
                'y': _counters['current_position_y_by_x'][_counters['current_position_x']],
                'width': 30,
                'height': _device_height
            })

            # Y-distance between between current and next device
            _counters['current_position_y_by_x'][_counters['current_position_x']] += _device_height + 20

            _matlab_device_name_and_id = ''
            # Straight inputs
            if _device_type == 'input' and _device_func_name != 'not':
                _counters['inport'] += 1
                _device_options = {
                    'device_id': graph_node # _counters['inport']
                }
                matlab_code_lines.append(matlab_code_template['add_block_input'] % _device_options)
                _matlab_device_name_and_id = graph_node  # 'In%(device_id)s' % _device_options

            # Not, And, Or
            if _device_func_name in _counters:
                _counters[_device_func_name] += 1
                _matlab_device_name = _device_func_name[:1].upper() + _device_func_name[1:]
                _device_options = {
                    'device_name': _matlab_device_name,
                    'device_id': _counters[_device_func_name]
                }
                matlab_code_lines.append(matlab_code_template['add_block_logical'] % {
                    'device_name': _matlab_device_name,
                    'device_name_upper': _matlab_device_name.upper(),
                    'ports_number': _device_ports_count,
                    'device_id': _counters[_device_func_name]
                })
                _matlab_device_name_and_id = '%(device_name)s%(device_id)s' % _device_options
            _counters['edges'][graph_node] = _matlab_device_name_and_id

            if node['type'] == 'output':
                _output_device_list.append(_matlab_device_name_and_id)

        # Add output
        _counters = self._matlab_code_handle_counters(_counters, '', '', 0, graph_adapter.max_distance + 3)

        for _matlab_device_name_and_id in _output_device_list:
            matlab_code_lines.append(matlab_code_template['position'] % {
                'x': 100 * (_counters['current_position_x'] * 2),
                'y': _counters['current_position_y_by_x'][_counters['current_position_x']],
                'width': 30,
                'height': 20
            })

            # Y-distance between between current and next device
            _counters['current_position_y_by_x'][_counters['current_position_x']] += 40

            _counters['outport'] += 1
            _device_options = {
                'device_id': _counters['outport']
            }
            matlab_code_lines.append(matlab_code_template['add_block_output'] % _device_options)

            matlab_code_lines.append(matlab_code_template['add_line'] % {
                'connect_from': '%s/1' % _matlab_device_name_and_id,
                'connect_to': 'Out%s/1' % _counters['outport']
            })

        # Connect devices using edges
        _connection_ports = dict()
        for edge in graph.edges_iter():
            _connect_from = '%s/1' % _counters['edges'][edge[0]]
            if not _counters['edges'][edge[1]] in _connection_ports:
                _connection_ports[_counters['edges'][edge[1]]] = 1
            _connect_to = '%s/%s' % (_counters['edges'][edge[1]], _connection_ports[_counters['edges'][edge[1]]])
            _connection_ports[_counters['edges'][edge[1]]] += 1

            matlab_code_lines.append(matlab_code_template['add_line'] % {
                'connect_from': _connect_from,
                'connect_to': _connect_to
            })
        return matlab_code_lines

    def matlab_code(self, **kwargs):
        model_dict = kwargs
        _matlab_code_template = {
            'position': r"pos = [%(x)s %(y)s %(x)s + %(width)s %(y)s + %(height)s]",
            'add_block_logical': r"add_block('built-in/Logical Operator', " +
                                 r"[sys '/%(device_name)s%(device_id)s'], 'Position', pos, " +
                                 r"'Operator', '%(device_name_upper)s', 'Number of input ports', '%(ports_number)s')",
            # 'add_block_input': r"add_block('built-in/Inport', [sys '/In%(device_id)s'], 'Position', pos)",
            'add_block_input': r"add_block('built-in/Inport', [sys '/%(device_id)s'], 'Position', pos)",
            'add_line': r"add_line(sys, '%(connect_from)s', '%(connect_to)s', 'autorouting','on')",
            'add_block_output': r"add_block('built-in/Outport', [sys '/Out%(device_id)s'], 'Position', pos)",
            'add_block_subsystem': r"add_block('built-in/SubSystem', sys, 'Position', pos)"
        }
        if model_dict is None or len(model_dict) == 0:
            model_dict = {
                'newModel1/straight': 'straight'
            }
        _matlab_code_lines = list()
        root_created = False
        position_y_counter = 0
        for model_name in model_dict:
            _model_name_part_full_list = list()
            for model_name_part in model_name.split('/'):
                _model_name_part_full_list.append(model_name_part)
                _model_name_part_full = '/'.join(_model_name_part_full_list)
                _matlab_code_lines.append(r"sys = '%(model_name)s'" % {
                    'model_name': _model_name_part_full
                })
                if len(_model_name_part_full_list) == 1:
                    if not root_created:
                        _matlab_code_lines += [
                            r"new_system(sys)",
                            r"open_system(sys)"
                        ]
                        root_created = True
                else:
                    # Count position
                    _device_height = (sum(map(len, self._device.input_signals)) + 1) * 15
                    _matlab_code_lines.append(_matlab_code_template['position'] % {
                        'x': 100,
                        'y': position_y_counter,
                        'width': 70,
                        'height': _device_height
                    })
                    position_y_counter += _device_height + 50
                    _matlab_code_lines.append(_matlab_code_template['add_block_subsystem'])
            self._matlab_code_generate(_matlab_code_lines, _matlab_code_template)

        return _matlab_code_lines


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

<TITLE>
TokenMgrError
</TITLE>

<META NAME="keywords" CONTENT="wdb.parser.TokenMgrError class">

<LINK REL ="stylesheet" TYPE="text/css" HREF="../../stylesheet.css" TITLE="Style">

      Overview
      Package
    Class
      Use
      Tree
      Deprecated
      Index
      Help

 PREV CLASS
 NEXT CLASS

  FRAMES
 NO FRAMES

  All Classes

  SUMMARY: NESTED | FIELD | CONSTR | METHOD

DETAIL: FIELD | CONSTR | METHOD

wdb.parser

Class TokenMgrError

java.lang.Object
  java.lang.Throwable
      java.lang.Error
          wdb.parser.TokenMgrError

All Implemented Interfaces:
java.io.Serializable

public class TokenMgrError
extends java.lang.Error

See Also:
Serialized Form

Field Summary

(package private)  int
errorCode

          Indicates the reason why the exception is thrown.

(package private) static int
INVALID_LEXICAL_STATE

          Tried to change to an invalid lexical state.

(package private) static int
LEXICAL_ERROR

          Lexical error occured.

(package private) static int
LOOP_DETECTED

          Detected (and bailed out of) an infinite loop in the token manager.

(package private) static int
STATIC_LEXER_ERROR

          An attempt wass made to create a second instance of a static token manager.

Constructor Summary

TokenMgrError()

TokenMgrError(boolean EOFSeen,
              int lexState,
              int errorLine,
              int errorColumn,
              java.lang.String errorAfter,
              char curChar,
              int reason)

TokenMgrError(java.lang.String message,
              int reason)

Method Summary

protected static java.lang.String
addEscapes(java.lang.String str)

          Replaces unprintable characters by their espaced (or unicode escaped)
 equivalents in the given string

 java.lang.String
getMessage()

          You can also modify the body of this method to customize your error messages.

protected static java.lang.String
LexicalError(boolean EOFSeen,
             int lexState,
             int errorLine,
             int errorColumn,
             java.lang.String errorAfter,
             char curChar)

          Returns a detailed message for the Error when it is thrown by the
 token manager to indicate a lexical error.

Methods inherited from class java.lang.Throwable

fillInStackTrace, getCause, getLocalizedMessage, getStackTrace, initCause, printStackTrace, printStackTrace, printStackTrace, setStackTrace, toString

Methods inherited from class java.lang.Object

clone, equals, finalize, getClass, hashCode, notify, notifyAll, wait, wait, wait

Field Detail

LEXICAL_ERROR

static final int LEXICAL_ERROR

Lexical error occured.

See Also:
Constant Field Values

STATIC_LEXER_ERROR

static final int STATIC_LEXER_ERROR

An attempt wass made to create a second instance of a static token manager.

See Also:
Constant Field Values

INVALID_LEXICAL_STATE

static final int INVALID_LEXICAL_STATE

Tried to change to an invalid lexical state.

See Also:
Constant Field Values

LOOP_DETECTED

static final int LOOP_DETECTED

Detected (and bailed out of) an infinite loop in the token manager.

See Also:
Constant Field Values

errorCode

int errorCode

Indicates the reason why the exception is thrown. It will have
 one of the above 4 values.

Constructor Detail

TokenMgrError

public TokenMgrError()

TokenMgrError

public TokenMgrError(java.lang.String message,
                     int reason)

TokenMgrError

public TokenMgrError(boolean EOFSeen,
                     int lexState,
                     int errorLine,
                     int errorColumn,
                     java.lang.String errorAfter,
                     char curChar,
                     int reason)

Method Detail

addEscapes

protected static final java.lang.String addEscapes(java.lang.String str)

Replaces unprintable characters by their espaced (or unicode escaped)
 equivalents in the given string

LexicalError

protected static java.lang.String LexicalError(boolean EOFSeen,
                                               int lexState,
                                               int errorLine,
                                               int errorColumn,
                                               java.lang.String errorAfter,
                                               char curChar)

Returns a detailed message for the Error when it is thrown by the
 token manager to indicate a lexical error.
 Parameters :
    EOFSeen     : indicates if EOF caused the lexicl error
    curLexState : lexical state in which this error occured
    errorLine   : line number when the error occured
    errorColumn : column number when the error occured
    errorAfter  : prefix that was seen before this error occured
    curchar     : the offending character
 Note: You can customize the lexical error message by modifying this method.

getMessage

public java.lang.String getMessage()

You can also modify the body of this method to customize your error messages.
 For example, cases like LOOP_DETECTED and INVALID_LEXICAL_STATE are not
 of end-users concern, so you can return something like :

     "Internal Error : Please file a bug report .... "

 from this method for such cases in the release version of your parser.

Overrides:
getMessage in class java.lang.Throwable

      Overview
      Package
    Class
      Use
      Tree
      Deprecated
      Index
      Help

 PREV CLASS
 NEXT CLASS

  FRAMES
 NO FRAMES

  All Classes

  SUMMARY: NESTED | FIELD | CONSTR | METHOD

DETAIL: FIELD | CONSTR | METHOD


text:
CREATE TABLE `webapps_contentrating` (
    `id` int(11) unsigned AUTO_INCREMENT NOT NULL PRIMARY KEY,
    `created` datetime NOT NULL,
    `modified` datetime NOT NULL,
    `addon_id` int(11) unsigned NOT NULL,
    `ratings_body` integer UNSIGNED NOT NULL,
    `rating` integer UNSIGNED NOT NULL
    ) ENGINE=InnoDB CHARACTER SET utf8 COLLATE utf8_general_ci;

;
ALTER TABLE `webapps_contentrating` ADD CONSTRAINT `addon_id_refs_id_4fa22f5e` FOREIGN KEY (`addon_id`) REFERENCES `addons` (`id`);


text:
import pytest

import angus.client
from angus.client.rest import Resource

__updated__ = "2017-08-23"
__author__ = "Aurélien Moreau"
__copyright__ = "Copyright 2015-2017, Angus.ai"
__credits__ = ["Aurélien Moreau", "Gwennael Gate", "Raphaël Lumbroso"]
__license__ = "Apache v2.0"
__maintainer__ = "Aurélien Moreau"
__status__ = "Production"

SND_1 = "soundloc.wav"

@pytest.fixture(scope="module")
def root(server, client, token, verify):
    return angus.connect(
        url=server, client_id=client, access_token=token, verify=verify)

@pytest.fixture(scope="module")
def service(root):
    return root.services.get_service('sound_localization', version=1)

@pytest.fixture(scope="module")
def image_res(root):
    return root.blobs.create(open(SND_1, 'rb'))

def check_result_res(result_res, where=None):
    isinstance(result_res, Resource)
    assert result_res.status == Resource.CREATED
    assert result_res.representation == result_res.result

    assert 'nb_sources' in result_res.representation
    assert 'sources' in result_res.representation
    assert result_res.representation['nb_sources'] == 36

def test_embedded_sync(service):
    result_res_fut = service.process_async(
        parameters={
            'sensitivity': 1.0,
            'baseline': 1.0,
            'sound': open(SND_1, 'rb')},
        async=False)
    res = result_res_fut.result()
    check_result_res(res)

def test_href_sync(service, image_res):
    print(image_res.endpoint)
    result_res_fut = service.process_async(
        parameters={
            'sensitivity': 1.0,
            'baseline': 1.0,
            'sound': image_res},
        async=False)
    res = result_res_fut.result()
    check_result_res(res)


text:
            <form name="answerForm" novalidate ng-submit="answerFormSubmit(audio)">

                    What's this song?

                <input type="text" ng-model="audio.name" class="answer-input" required>
                <button type="submit" class="btn btn-info pull-right" ng-disabled="answerForm.$invalid">Submit</button>
            </form>


text:
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics;
using System.Globalization;
using System.Net;

namespace System.Security.Authentication.ExtendedProtection
{
    public class ServiceNameCollection : ICollection
    {
        // Ideally this would be List<string>, but we want the behavior of members like
        // CopyTo(Array, int) to behave the same as ArrayList to match the behavior of
        // the full framework (e.g. throw InvalidCastException for mismatched array types
        // instead of ArgumentException). Thus, List<object> is used so that the backing
        // array is typed as object[] like ArrayList.
        private readonly List<object> _list;

        public ServiceNameCollection(ICollection items)
        {
            if (items == null)
            {
                throw new ArgumentNullException(nameof(items));
            }

            _list = new List<object>(items.Count);

            // Normalize and filter for duplicates.
            AddIfNew(items, expectStrings: true);
        }

        /// <summary>
        /// Merges <paramref name="list"/> and <paramref name="serviceName"/> into a new collection.
        /// </summary>
        private ServiceNameCollection(List<object> list, string serviceName)
            : this(list, additionalCapacity: 1)
        {
            AddIfNew(serviceName);
        }

        /// <summary>
        /// Merges <paramref name="list"/> and <paramref name="serviceNames"/> into a new collection.
        /// </summary>
        private ServiceNameCollection(List<object> list, IEnumerable serviceNames)
            : this(list, additionalCapacity: GetCountOrOne(serviceNames))
        {
            // We have a pretty bad performance here: O(n^2), but since service name lists should
            // be small (<<50) and Merge() should not be called frequently, this shouldn't be an issue.
            AddIfNew(serviceNames, expectStrings: false);
        }

        private ServiceNameCollection(List<object> list, int additionalCapacity)
        {
            Debug.Assert(list != null);
            Debug.Assert(additionalCapacity >= 0);

            _list = new List<object>(list.Count + additionalCapacity);

            foreach (string item in list)
            {
                _list.Add(item);
            }
        }

        public int Count => _list.Count;

        public bool Contains(string searchServiceName)
        {
            string searchName = NormalizeServiceName(searchServiceName);

            foreach (string serviceName in _list)
            {
                if (string.Equals(serviceName, searchName, StringComparison.OrdinalIgnoreCase))
                {
                    return true;
                }
            }

            return false;
        }

        public IEnumerator GetEnumerator() => _list.GetEnumerator();

        public ServiceNameCollection Merge(string serviceName) => new ServiceNameCollection(_list, serviceName);

        public ServiceNameCollection Merge(IEnumerable serviceNames) => new ServiceNameCollection(_list, serviceNames);

        /// <summary>
        /// Normalize, check for duplicates, and add each unique value.
        /// </summary>
        private void AddIfNew(IEnumerable serviceNames, bool expectStrings)
        {
            List<string> list = serviceNames as List<string>;
            if (list != null)
            {
                AddIfNew(list);
                return;
            }

            ServiceNameCollection snc = serviceNames as ServiceNameCollection;
            if (snc != null)
            {
                AddIfNew(snc._list);
                return;
            }

            // NullReferenceException is thrown when serviceNames is null,
            // which is consistent with the behavior of the full framework.
            foreach (object item in serviceNames)
            {
                // To match the behavior of the full framework, when an item
                // in the collection is not a string:
                //  - Throw InvalidCastException when expectStrings is true.
                //  - Throw ArgumentException when expectStrings is false.
                AddIfNew(expectStrings ? (string)item : item as string);
            }
        }

        /// <summary>
        /// Normalize, check for duplicates, and add each unique value.
        /// </summary>
        private void AddIfNew(List<string> serviceNames)
        {
            Debug.Assert(serviceNames != null);

            foreach (string serviceName in serviceNames)
            {
                AddIfNew(serviceName);
            }
        }

        /// <summary>
        /// Normalize, check for duplicates, and add each unique value.
        /// </summary>
        private void AddIfNew(List<object> serviceNames)
        {
            Debug.Assert(serviceNames != null);

            foreach (string serviceName in serviceNames)
            {
                AddIfNew(serviceName);
            }
        }

        /// <summary>
        /// Normalize, check for duplicates, and add if the value is unique.
        /// </summary>
        private void AddIfNew(string serviceName)
        {
            if (string.IsNullOrEmpty(serviceName))
            {
                throw new ArgumentException(SR.security_ServiceNameCollection_EmptyServiceName);
            }

            serviceName = NormalizeServiceName(serviceName);

            if (!Contains(serviceName))
            {
                _list.Add(serviceName);
            }
        }

        /// <summary>
        /// Gets the collection Count, if available, otherwise 1.
        /// </summary>
        private static int GetCountOrOne(IEnumerable collection)
        {
            ICollection<string> c = collection as ICollection<string>;
            return c != null ? c.Count : 1;
        }

        // Normalizes any punycode to Unicode in an Service Name (SPN) host.
        // If the algorithm fails at any point then the original input is returned.
        // ServiceName is in one of the following forms:
        // prefix/host
        // prefix/host:port
        // prefix/host/DistinguishedName
        // prefix/host:port/DistinguishedName
        private static string NormalizeServiceName(string inputServiceName)
        {
            if (string.IsNullOrWhiteSpace(inputServiceName))
            {
                return inputServiceName;
            }

            // Separate out the prefix
            int slashIndex = inputServiceName.IndexOf('/');
            if (slashIndex < 0)
            {
                return inputServiceName;
            }

            string prefix = inputServiceName.Substring(0, slashIndex + 1); // Includes slash
            string hostPortAndDistinguisher = inputServiceName.Substring(slashIndex + 1); // Excludes slash

            if (string.IsNullOrWhiteSpace(hostPortAndDistinguisher))
            {
                return inputServiceName;
            }

            string host = hostPortAndDistinguisher;
            string port = string.Empty;
            string distinguisher = string.Empty;

            // Check for the absence of a port or distinguisher.
            UriHostNameType hostType = Uri.CheckHostName(hostPortAndDistinguisher);
            if (hostType == UriHostNameType.Unknown)
            {
                string hostAndPort = hostPortAndDistinguisher;

                // Check for distinguisher.
                int nextSlashIndex = hostPortAndDistinguisher.IndexOf('/');
                if (nextSlashIndex >= 0)
                {
                    // host:port/distinguisher or host/distinguisher
                    hostAndPort = hostPortAndDistinguisher.Substring(0, nextSlashIndex); // Excludes Slash
                    distinguisher = hostPortAndDistinguisher.Substring(nextSlashIndex); // Includes Slash
                    host = hostAndPort; // We don't know if there is a port yet.
                    // No need to validate the distinguisher.
                }

                // Check for port.
                int colonIndex = hostAndPort.LastIndexOf(':'); // Allow IPv6 addresses.
                if (colonIndex >= 0)
                {
                    // host:port
                    host = hostAndPort.Substring(0, colonIndex); // Excludes colon
                    port = hostAndPort.Substring(colonIndex + 1); // Excludes colon

                    // Loosely validate the port just to make sure it was a port and not something else.
                    ushort portValue;
                    if (!ushort.TryParse(port, NumberStyles.Integer, CultureInfo.InvariantCulture, out portValue))
                    {
                        return inputServiceName;
                    }

                    // Re-include the colon for the final output.  Do not change the port format.
                    port = hostAndPort.Substring(colonIndex);
                }

                hostType = Uri.CheckHostName(host); // Re-validate the host.
            }

            if (hostType != UriHostNameType.Dns)
            {
                // UriHostNameType.IPv4, UriHostNameType.IPv6: Do not normalize IPv4/6 hosts.
                // UriHostNameType.Basic: This is never returned by CheckHostName today
                // UriHostNameType.Unknown: Nothing recognizable to normalize
                // default Some new UriHostNameType?
                return inputServiceName;
            }

            // Now we have a valid DNS host, normalize it.

            Uri constructedUri;

            // We need to avoid any unexpected exceptions on this code path.
            if (!Uri.TryCreate(UriScheme.Http + UriScheme.SchemeDelimiter + host, UriKind.Absolute, out constructedUri))
            {
                return inputServiceName;
            }

            string normalizedHost = constructedUri.GetComponents(
                UriComponents.NormalizedHost, UriFormat.SafeUnescaped);

            string normalizedServiceName = prefix + normalizedHost + port + distinguisher;

            // Don't return the new one unless we absolutely have to.  It may have only changed casing.
            if (string.Equals(inputServiceName, normalizedServiceName, StringComparison.OrdinalIgnoreCase))
            {
                return inputServiceName;
            }

            return normalizedServiceName;
        }

        bool ICollection.IsSynchronized => false;

        object ICollection.SyncRoot => NonGenericList.SyncRoot;

        void ICollection.CopyTo(Array array, int index) => NonGenericList.CopyTo(array, index);

        private IList NonGenericList => _list;
    }
}


text:
package cz.cuni.mff.spl.evaluator.graphs;

import org.apache.commons.math3.stat.descriptive.StatisticalSummary;

import cz.cuni.mff.spl.evaluator.statistics.ComparisonEvaluator;
import cz.cuni.mff.spl.evaluator.statistics.MeasurementSample;
import cz.cuni.mff.spl.utils.EqualsUtils;

/**
 * The Class MeasurementSampleData.
 *
 * @author Martin Lacina
 */
public class MeasurementSampleDescriptor {

    /** The apply lambda. */
    private final boolean           applyLambda;

    /** The lambda. */
    private final double            lambdaMultiplier;

    /** The measurement sample. */
    private final MeasurementSample measurementSample;

    /**
     * Checks if is applies the lambda.
     *
     * @return True, if is applies the lambda.
     */
    public boolean isApplyLambda() {
        return applyLambda;
    }

    /**
     * Gets the lambda multiplier it it should be applied, or value {@code 1} if
     * not.
     *
     * @return The lambda multiplier.
     */
    public double getLambdaMultiplier() {
        if (applyLambda) {
            return lambdaMultiplier;
        } else {
            return 1;
        }
    }

    /**
     * Gets the measurement sample.
     *
     * @return The measurement sample.
     */
    public MeasurementSample getMeasurementSample() {
        return measurementSample;
    }

    /**
     * Instantiates a new measurement sample data.
     *
     * @param applyLambda
     *            The apply lambda flag.
     * @param lambdaMultiplier
     *            The lambda multiplier.
     * @param measurementSample
     *            The measurement sample.
     */
    public MeasurementSampleDescriptor(boolean applyLambda, double lambdaMultiplier, MeasurementSample measurementSample) {
        if (applyLambda) {
            this.applyLambda = applyLambda;
            this.lambdaMultiplier = lambdaMultiplier;
        } else {
            this.applyLambda = false;
            this.lambdaMultiplier = -1;
        }
        this.measurementSample = measurementSample;
    }

    /**
     * Instantiates a new measurement sample data with no lambda to apply.
     *
     * @param measurementSample
     *            The measurement sample.
     */
    public MeasurementSampleDescriptor(MeasurementSample measurementSample) {
        this(false, 1, measurementSample);
    }

    @Override
    public int hashCode() {
        final int prime = 31;
        int result = 1;
        result = prime * result + (applyLambda ? 1231 : 1237);
        long temp;
        temp = Double.doubleToLongBits(lambdaMultiplier);
        result = prime * result + (int) (temp ^ (temp >>> 32));
        result = prime * result + ((measurementSample == null) ? 0 : measurementSample.hashCode());
        return result;
    }

    /**
     * Note that two measurement descriptors are equal, when they have same
     * lambda and measurement in measurement sample.
     */
    @Override
    public boolean equals(Object obj) {
        if (this == obj) {
            return true;
        }
        if (obj == null) {
            return false;
        }
        if (getClass() != obj.getClass()) {
            return false;
        }
        MeasurementSampleDescriptor other = (MeasurementSampleDescriptor) obj;
        if (applyLambda != other.applyLambda) {
            return false;
        }
        if (Double.doubleToLongBits(lambdaMultiplier) != Double.doubleToLongBits(other.lambdaMultiplier)) {
            return false;
        }

        if (measurementSample == null) {
            if (other.measurementSample != null) {
                return false;
            } else {
                return true;
            }
        } else if (other.measurementSample == null) {
            return false;
        } else {
            return EqualsUtils.safeEquals(measurementSample.getMeasurement(), other.measurementSample.getMeasurement());
        }
    }

    @Override
    public String toString() {
        return getSpecification();
    }

    /**
     * @return
     */
    public StatisticalSummary getStatisticalSummary() {
        if (applyLambda) {
            return ComparisonEvaluator.transformStatisticalSummary(measurementSample.getStatisticalSummary(), lambdaMultiplier);
        } else {
            return measurementSample.getStatisticalSummary();
        }

    }

    /**
     * @return
     */
    public String getSpecification() {
        String prefix = applyLambda ? Double.toString(lambdaMultiplier) + " * " : "";
        return prefix + measurementSample.getSpecification();
    }

}


text:
No changes.

## [1.1.0](https://github.com/flarum/approval/compare/v1.0.0...v1.1.0)

No changes.

## [1.0.0](https://github.com/flarum/approval/compare/v0.1.0-beta.16...v1.0.0)

### Changed
- Compatibility with Flarum v1.0.0.
- Simplified TagPolicy.

### Fixed
- Unpredictable behaviour existed with discussions marked `is_private` (https://github.com/flarum/approval/pull/26)

## [0.1.0-beta.16](https://github.com/flarum/approval/compare/v0.1.0-beta.15...v0.1.0-beta.16)

### Changed
- Updated admin category from moderation to feature (https://github.com/flarum/approval/pull/24)
- Moved locale files from translation pack to extension (https://github.com/flarum/approval/pull/22)

### Fixed
- Comment and discussion count not updated after post approval (https://github.com/flarum/approval/pull/16)

## [0.1.0-beta.15](https://github.com/flarum/approval/compare/v0.1.0-beta.14...v0.1.0-beta.15)

### Changed
- Updated composer.json and admin javascript for new admin area.
- Updated extend.php with latest extenders.

## [0.1.0-beta.14](https://github.com/flarum/approval/compare/v0.1.0-beta.13...v0.1.0-beta.14)

### Changed
- Updated mithril to version 2
- Load language strings correctly on en-/disable
- Updated JS dependencies

### Removed
- Removed AssertPermissionTrait (#19)

## [0.1.0-beta.13](https://github.com/flarum/approval/compare/v0.1.0-beta.12...v0.1.0-beta.13)

### Changed
- Updated JS dependencies
- Stop using deprecated core events, use extenders instead


text:
using System;
using System.Diagnostics.CodeAnalysis;

namespace starshipxac.Shell.Search.Interop
{
    /// <summary>
    /// </summary>
    /// <remarks>
    ///     http://msdn.microsoft.com/en-us/library/windows/desktop/aa965700(v=vs.85).aspx
    /// </remarks>
    [SuppressMessage("ReSharper", "InconsistentNaming")]
    internal enum QUERY_PARSER_MANAGER_OPTION
    {
        QPMO_SCHEMA_BINARY_NAME = 0,
        QPMO_PRELOCALIZED_SCHEMA_BINARY_PATH = (QPMO_SCHEMA_BINARY_NAME + 1),
        QPMO_UNLOCALIZED_SCHEMA_BINARY_PATH = (QPMO_PRELOCALIZED_SCHEMA_BINARY_PATH + 1),
        QPMO_LOCALIZED_SCHEMA_BINARY_PATH = (QPMO_UNLOCALIZED_SCHEMA_BINARY_PATH + 1),
        QPMO_APPEND_LCID_TO_LOCALIZED_PATH = (QPMO_LOCALIZED_SCHEMA_BINARY_PATH + 1),
        QPMO_LOCALIZER_SUPPORT = (QPMO_APPEND_LCID_TO_LOCALIZED_PATH + 1)
    }
}


text:
package com.example;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.scheduling.annotation.EnableAsync;

@SpringBootApplication
@EnableAsync
public class DemoApplication {

    public static void main(String[] args) {
        SpringApplication.run(DemoApplication.class, args);
    }
}


text:
namespace arrow {

class Buffer;
class MemoryPool;
class Table;
class RecordBatch;
class Array;
class DataType;

namespace io {
class InputStream;
}  // namespace io

namespace json {

/// A class that reads an entire JSON file into a Arrow Table
///
/// The file is expected to consist of individual line-separated JSON objects
class ARROW_EXPORT TableReader {
 public:
  virtual ~TableReader() = default;

  /// Read the entire JSON file and convert it to a Arrow Table
  virtual Result<std::shared_ptr<Table>> Read() = 0;

  /// Create a TableReader instance
  static Result<std::shared_ptr<TableReader>> Make(MemoryPool* pool,
                                                   std::shared_ptr<io::InputStream> input,
                                                   const ReadOptions&,
                                                   const ParseOptions&);
};

ARROW_EXPORT Result<std::shared_ptr<RecordBatch>> ParseOne(ParseOptions options,
                                                           std::shared_ptr<Buffer> json);

}  // namespace json
}  // namespace arrow


text:
require File.expand_path('../../fixtures/classes', __FILE__)

platform_is :windows do
  require 'win32ole'

  def default_handler(event, *args)
    @event += event
  end

  def alternate_handler(event, *args)
    @event2 = "alternate"
  end

  def handler3(event, *args)
    @event3 += event
  end

  describe "WIN32OLE_EVENT#on_event with no argument" do
    before :each do
      @ie     = WIN32OLESpecs.new_ole('InternetExplorer.Application')
      @ev     = WIN32OLE_EVENT.new(@ie, 'DWebBrowserEvents')
      @event  = ''
      @event2 = ''
      @event3 = ''
      @ie.StatusBar = true
    end

    after :each do
      @ie.Quit
    end

    it "sets event handler properly, and the handler is invoked by event loop" do
      @ev.on_event { |*args| default_handler(*args) }
      @ie.StatusText='hello'
      WIN32OLE_EVENT.message_loop
      @event.should =~ /StatusTextChange/
    end

    it "accepts a String argument, sets event handler properly, and the handler is invoked by event loop" do
      @ev.on_event("StatusTextChange") { |*args| @event = 'foo' }
      @ie.StatusText='hello'
      WIN32OLE_EVENT.message_loop
      @event.should =~ /foo/
    end

    it "registers multiple event handlers for the same event" do
      @ev.on_event("StatusTextChange") { |*args| default_handler(*args) }
      @ev.on_event("StatusTextChange") { |*args| alternate_handler(*args) }
      @ie.StatusText= 'hello'
      WIN32OLE_EVENT.message_loop
      @event2.should == 'alternate'
    end

    it "accepts a Symbol argument, sets event handler properly, and the handler is invoked by event loop" do
      @ev.on_event(:StatusTextChange) { |*args| @event = 'foo' }
      @ie.StatusText='hello'
      WIN32OLE_EVENT.message_loop
      @event.should =~ /foo/
    end
  end
end


text:
package nodejs

import (
	"strings"
	"testing"

	"discovery-artifact-manager/snippetgen/compilecheck/internal/filesys"
	"discovery-artifact-manager/snippetgen/compilecheck/internal/langutil"
)

func TestReadFilesBadName(t *testing.T) {
	opener := filesys.MapFS{}
	const fname = "foo"
	if _, err := readFiles([]string{fname}, opener); err == nil {
		t.Errorf("expected error since file %q is not in proper format", fname)
	}
}

func TestReadFilesNotExist(t *testing.T) {
	opener := filesys.MapFS{}
	const fname = "myservice/v1/1234/myservice.mymethod.frag.njs"
	if _, err := readFiles([]string{fname}, opener); err == nil {
		t.Errorf("expected error since file %q does not exist", fname)
	}
}

func TestReadFiles(t *testing.T) {
	files := []struct {
		path, content, initText string
		id                      langutil.MethodID
	}{
		{
			path: "/path/to/appengine/v1beta4/1234/appengine.apps.get.frag.njs",
			id:   langutil.MethodID{APIName: "appengine", APIVersion: "v1beta4", FragmentName: "appengine.apps.get"},
			initText: `
var request = {
// TODO: Change placeholders below to values for parameters to the 'get' method:

// Part of name. Name of the application to get. For example: "apps/myapp".
appsId: "",
// Auth client
auth: authClient
};`,
			content: `
var google = require('googleapis');
var GoogleAuth = require('google-auth-library');

var authFactory = new GoogleAuth();
var appengine = google.appengine('v1beta4');

authFactory.getApplicationDefault(function(err, authClient) {
  if (err) {
    console.log('Authentication failed because of ', err);
    return;
  }
  if (authClient.createScopedRequired && authClient.createScopedRequired()) {
    var scopes = ['https://www.googleapis.com/auth/cloud-platform'];
    authClient = authClient.createScoped(scopes);
  }

  var request = {
    // TODO: Change placeholders below to values for parameters to the 'get' method:

    // Part of name. Name of the application to get. For example: "apps/myapp".
    appsId: "",
    // Auth client
    auth: authClient
  };

  appengine.apps.get(request, function(err, result) {
    if (err) {
      console.log(err);
    } else {
      console.log(result);
    }
  });
});
`,
		},
		{
			path: "/path/to/foo/v1/1234/foo.bar.frag.njs",
			id:   langutil.MethodID{APIName: "foo", APIVersion: "v1", FragmentName: "foo.bar"},
			initText: `
var request = {
appsId: "",
resource: {},
auth: authClient
};
`,
			content: `
var request = {
appsId: "",
resource: {},
auth: authClient
};
`,
		},
	}

	opener := filesys.MapFS{}
	var fileNames []string
	for _, f := range files {
		opener[f.path] = f.content
		fileNames = append(fileNames, f.path)
	}

	sampleMethods, err := readFiles(fileNames, opener)
	if err != nil {
		t.Fatalf("unexpected error: %s", err)
	}
	for _, f := range files {
		switch initText, ok := sampleMethods[f.id]; {
		case !ok:
			t.Errorf("method not found: %q", f.id)
		case strings.TrimSpace(initText) != strings.TrimSpace(f.initText):
			t.Errorf("%s: wrong init text: got %q, want %q", f.id, initText, f.initText)
		}
		delete(sampleMethods, f.id)
	}
	for id := range sampleMethods {
		t.Errorf("method should not exist: %q", id)
	}
}


text:
/*
 *  jquery-speakable - v0.0.0
 *  A jump-start for jQuery plugins development.
 *  http://jqueryboilerplate.com
 *
 *  Made by JP DeVries @jpdevries
 *  Under MIT License
 */
;(function ( $, window, document, undefined ) {

	"use strict";

		var pluginName = "speakable",
				defaults = {
				voice: null,
				lang:'en-US',
				msg:null,
                rate:null,
                pitch:null,
                volume:null,
				transcript:'',
				tidyTranscript:true,
				unspeakable:'[muted]',
				enunciate:'enunciate',
                onstart:function(){},
                onend:function(){},
                onerror:function(){},
                onpause:function(){},
                onresume:function(){},
                onmark:function(){},
                onboundary:function(){}
		};

		function Plugin ( element, options ) {
				this.element = element;

				this.settings = $.extend( {}, defaults, options );
				this._defaults = defaults;
				this._name = pluginName;
				this.init();
		}

		$.extend(Plugin.prototype, {
				init: function () {
                        if(!window.speechSynthesis) return;
						var _that = this;
						var _element = $(this.element);
				},
				speak: function () {
                    var voices = window.speechSynthesis.getVoices();
                    var _element = $(this.element);
                    var _settings = this.settings;

                    if(_element[0].dataset.voice) {_settings.voice = _element[0].dataset.voice;}
                    if(_element[0].dataset.lang) {_settings.lang = _element[0].dataset.lang;}
                    if(_element[0].dataset.transcript) {_settings.transcript = _element[0].dataset.transcript;}
                    if(_element[0].dataset.text) {_settings.text = _element[0].dataset.text;}
                    if(_element[0].dataset.rate) {_settings.rate = _element[0].dataset.rate;}
                    if(_element[0].dataset.pitch) {_settings.pitch = _element[0].dataset.pitch;}
                    if(_element[0].dataset.volume) {_settings.volume = _element[0].dataset.volume;}

                    var _voice = _settings.voice || null;
                    var _ns = [];
                    var _transcript;
                    var _msg = (_settings.text || $(_element).data('text')) || null;

                    function formulateSpokenMessage(_element) {
                        var _t = $(_element).clone();
                        if(!_settings.tidyTranscript) {return _t.text();}
                        if(_t.data(_settings.enunciate)) {return _t.data(_settings.enunciate);}
                        if(_settings.enunciate) {
                            _t.find('*[data-' + _settings.enunciate + ']').each(function(){
                                $(this).text($(this).attr('data-' + _settings.enunciate));
                            });
                        }
                        if(_settings.unspeakable) {_t.find(_settings.unspeakable).empty().remove();}
                        return _t.text();
                    }

                    if(!_msg) {
                        if(document.getElementById(_settings.transcript)) {
                            _transcript = formulateSpokenMessage(document.getElementById(_settings.transcript));
                        } else if(_settings.transcript) {
                            _transcript = _settings.transcript;
                        } else { // we have nothing
                            _transcript = formulateSpokenMessage(_element);
                        }
                    } else {
                        _transcript = _msg;
                    }

                    var msg = new SpeechSynthesisUtterance();
                    msg.text = _transcript;
                    msg.lang = _settings.lang;
                    if(_voice !== null) msg.voice = voices.filter(function(voice) { return voice.name === (_voice); })[0];

                    if(_settings.rate !== null) {msg.rate = _settings.rate;}
                    if(_settings.pitch !== null) {msg.pitch = _settings.pitch;}
                    if(_settings.volume !== null) {msg.volume = _settings.volume;}

                    if(typeof(_settings.onstart) === "function") {msg.onstart = _settings.onstart;}
                    if(typeof(_settings.onend) === "function") {msg.onend = _settings.onend;}
                    if(typeof(_settings.onerror) === "function") {msg.onerror = _settings.onerror;}
                    if(typeof(_settings.onpause) === "function") {msg.onpause = _settings.onpause;}
                    if(typeof(_settings.onresume) === "function") {msg.onresume = _settings.onresume;}
                    if(typeof(_settings.onmark) === "function") {msg.onmark = _settings.onmark;}
                    if(typeof(_settings.onboundary) === "function") {msg.onboundary = _settings.onboundary;}

                    window.speechSynthesis.speak(msg);
				}
		});

		$.fn[ pluginName ] = function ( options ) {
				return this.each(function() {
						if ( !$.data( this, "plugin_" + pluginName ) ) {
								$.data( this, "plugin_" + pluginName, new Plugin( this, options ) );
						}
				});
		};

})( jQuery, window, document );


text:
package toh

import (
	"bytes"
	"fmt"
	"io"
	"io/ioutil"
	"math/rand"
	"net"
	"net/http"
	"strconv"
	"strings"
	"sync"
	"sync/atomic"
	"time"

	"github.com/coyove/common/sched"
	"github.com/coyove/goflyway/v"
)

type ClientConn struct {
	idx    uint64
	dialer *Dialer

	write struct {
		sync.Mutex
		counter uint32
		sched   sched.SchedKey
		buf     []byte
		survey  struct {
			lastIsPositive bool
			pendingSize    int
			reschedCount   int64
		}
		respCh     chan io.ReadCloser
		respChOnce sync.Once
	}

	read *readConn
}

func (d *Dialer) Dial() (net.Conn, error) {
	if d.WebSocket {
		return d.wsHandshake()
	}
	return d.newClientConn()
}

func (d *Dialer) newClientConn() (net.Conn, error) {

	c := &ClientConn{dialer: d}
	c.idx = newConnectionIdx()
	c.write.survey.pendingSize = 1
	c.write.respCh = make(chan io.ReadCloser, 128)
	c.read = newReadConn(c.idx, d.blk, 'c')

	// Say hello
	resp, err := c.send(frame{
		idx:     rand.Uint32(),
		connIdx: c.idx,
		options: optSyncConnIdx,
		next: &frame{
			connIdx: c.idx,
			options: optHello,
		}})
	if err != nil {
		return nil, err
	}
	resp.Body.Close()

	c.write.sched = sched.Schedule(c.schedSending, time.Second)

	go c.respLoop()
	return c, nil
}

func (c *ClientConn) SetDeadline(t time.Time) error {
	c.SetReadDeadline(t)
	return nil
}

func (c *ClientConn) SetReadDeadline(t time.Time) error {
	c.read.ready.SetWaitDeadline(t)
	return nil
}

func (c *ClientConn) SetWriteDeadline(t time.Time) error {
	return nil
}

func (c *ClientConn) LocalAddr() net.Addr {
	return &net.TCPAddr{}
}

func (c *ClientConn) RemoteAddr() net.Addr {
	return &net.TCPAddr{}
}

func (c *ClientConn) Close() error {
	if c.read.closed {
		return nil
	}

	v.VVprint(c, " closing")
	c.write.sched.Cancel()
	c.read.close()
	c.write.respChOnce.Do(func() {
		close(c.write.respCh)
		go c.send(frame{
			connIdx: c.idx,
			options: optClosed,
		})
	})
	return nil
}

func (c *ClientConn) Write(p []byte) (n int, err error) {
REWRITE:
	if c.read.err != nil {
		return 0, c.read.err
	}

	if c.read.closed {
		return 0, errClosedConn
	}

	if len(c.write.buf) > c.dialer.MaxWriteBuffer {
		v.Eprint(c, " write buffer is full")
		time.Sleep(time.Second)
		goto REWRITE
	}

	c.write.Lock()
	c.write.sched.Reschedule(func() {
		c.write.survey.pendingSize = 1
		c.schedSending()
	}, time.Second)
	c.write.buf = append(c.write.buf, p...)
	c.write.Unlock()

	if len(c.write.buf) < c.write.survey.pendingSize {
		return len(p), nil
	}

	c.schedSending()
	return len(p), nil
}

func (c *ClientConn) schedSending() {
	atomic.AddInt64(&c.write.survey.reschedCount, 1)

	if c.read.err != nil || c.read.closed {
		c.Close()
		return
	}

	c.dialer.orchSendWriteBuf(c)
	c.write.sched.Reschedule(func() {
		c.write.survey.pendingSize = 1
		c.schedSending()
	}, time.Second)
}

func (c *ClientConn) sendWriteBuf() {
	c.write.Lock()
	defer c.write.Unlock()

	if c.write.survey.pendingSize *= 2; c.write.survey.pendingSize > 1024 {
		c.write.survey.pendingSize = 1024
	}

	if c.read.err != nil {
		return
	}

	if c.read.closed {
		return
	}

	f := frame{
		idx:     rand.Uint32(),
		connIdx: c.idx,
		options: optSyncConnIdx,
		next: &frame{
			idx:     c.write.counter + 1,
			connIdx: c.idx,
			data:    c.write.buf,
		},
	}

	deadline := time.Now().Add(c.dialer.Timeout - time.Second)
	for {
		if resp, err := c.send(f); err != nil {
			if time.Now().After(deadline) {
				c.read.feedError(err)
				return
			}
		} else {
			c.write.buf = c.write.buf[:0]
			c.write.counter++
			func() {
				defer func() { recover() }()
				select {
				case c.write.respCh <- resp.Body:
				default:
					go func(resp *http.Response) {
						c.read.feedframes(resp.Body)
						resp.Body.Close()
					}(resp)
				}
			}()
			break
		}
	}
}

func (c *ClientConn) send(f frame) (resp *http.Response, err error) {
	client := &http.Client{
		Timeout:   c.dialer.Timeout,
		Transport: c.dialer.Transport,
	}

	body := f.marshal(c.read.blk)
	path := "http://" + c.dialer.endpoint + c.dialer.Path()
	req, _ := http.NewRequest("POST", path, bytes.NewReader(body))

	if parts := strings.Split(c.dialer.URLHeader, "="); len(parts) == 2 {
		v.Vprint(parts)
		req.Header.Add(parts[0], parts[1])
	}

	if len(body) > 1024*4 {
		// log of sending big payload
		v.VVVprint(c, " heavy sending ", float64(len(body))/1024, "K")
	}

	resp, err = client.Do(req)
	if err != nil {
		return nil, err
	}
	if resp.StatusCode != http.StatusOK {
		xx, _ := ioutil.ReadAll(resp.Body)
		resp.Body.Close()
		return nil, fmt.Errorf("remote is unavailable: %s, resp: %v", resp.Status, strconv.Quote(string(xx)))
	}
	return resp, nil
}

func (c *ClientConn) respLoop() {
	for body := range c.write.respCh {
		k := sched.Schedule(func() { body.Close() }, c.dialer.Timeout)
		if n, _ := c.read.feedframes(body); n == 0 {
			c.write.survey.lastIsPositive = false
		}
		k.Cancel()
		body.Close()
	}
	v.VVprint(c, " resp out")
}

func (c *ClientConn) Read(p []byte) (n int, err error) {
	return c.read.Read(p)
}

func (c *ClientConn) String() string {
	return fmt.Sprintf("<C:%s,r:%d,w:%d>", formatConnIdx(c.idx), c.read.counter, c.write.counter)
}


text:
id: 1114
title: 'Runlevel – init'
author: Stefano Marzorati
layout: post
guid: http://ubbunti.wordpress.com/?p=1114
permalink: /runlevel-init/
publicize_results:
  - 'a:1:{s:7:"twitter";a:1:{i:396682267;a:2:{s:7:"user_id";s:13:"marzorati_ste";s:7:"post_id";s:18:"172602001153204224";}}}'
  - 'a:1:{s:7:"twitter";a:1:{i:396682267;a:2:{s:7:"user_id";s:13:"marzorati_ste";s:7:"post_id";s:18:"172602001153204224";}}}'
authorsure_include_css:
  -
dsq_thread_id:
  - 2199045946
categories:
  - Linux
tags:
  - init
  - runlevel
---
**Runlevel 0** : Avvia la sequenza di arresto del sistema (shutdown)

**Runlevel 1**: Rappresenta la modalità singolo utente, nessun altro utente può collegarsi, il servizio di rete è disabilitato.

**Runlevel 2**: Rappresenta lo stato multiutente, il servizio rete è attivo ma è disabilitato il file sharing.

**Runlevel 3**: In genere è quello predefinito quando si opera in modalità testuale, tutti i servizi sono attivi.

**Runlevel 4**: Inutilizzato. Può essere dedicato ad usi personali

**Runlevel 5**: E' il predefinito quando si vuole avviare Linux in modalità grafica

**Runlevel 6**: serve a riavviare la macchina

Per cambiare runlevel si utilizza il comando** init**


text:
In order to completely control the serialization, allow the user to
specify the DataContract namespace for generated types.

## Reference out-of-namespace known types without qualification
The DSL should know all declared types allowed, and be able
to reference them without writing the fully qualified type name.

## Declare Bounded Contexts
Commands and Domain Events should then have DataContract namespaces
corresponding to the bounded context's name.

## Support for C# keyword Identifiers
Support for Identifiers like `@event` and other reserved C# keywords.

## Emit DebuggerDisplay for types with more than one field
Currently, this is emitted only for single-field types.

## Configurable DebuggerDisplay on types
Allow a way to configure the DebuggerDisplay on the generated types, e.g.
declaring a way to generate `[DebuggerDisplay("{FirstName} {LastName}")]`
on a value type, `(defvaluetype StudentName (string FirstName, string LastName))`.

## Validate model before generation

### Validate allowed types in DTO types (Commands, Events, DTOs).
Commands and Domain events should only be able to have properties that are primitive types,
arrays of these or other Data Transfer Objects.

### Emit friendly error when code is not generatable
E.g. for multi-dimensional arrays in Equality.

## Multi-dimensional array equality
Currently one single-dimensional arrays are supported when generating equality members.
Implement these, too:

		(namespace TestCases.TypeDeclarations
			(defcommand PrintArraySimple2D (int[,] Value))
			(defcommand PrintArraySimpleMulti (int[][,] Value))

## ToString Generation on Value Types for Array properties
Currently, the ToString does not expand and print the values of arrays in the generated ToString
method. Add this (see GeneratedValueTypeWithArrayTest for ToString).


text:
package us.dot.its.jpo.ode.stomp;

public class RegistrationMessage {

    private String name;

    public RegistrationMessage(String name) {
        this.name = name;
    }

    public String getName() {
        return name;
    }

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


text:
package com.wenshao.dal.bean;

import com.wenshao.dal.thriftgen.User;

import java.sql.Timestamp;
import java.util.HashSet;
import java.util.Set;

/**
 * Created by wenshao on 2017/8/28.
 * 用户类接口
 */
public class UserBean extends User {
    private Timestamp create_time_bean;
    private Timestamp update_time_bean;
    private Timestamp register_time_bean;
    private QueryBean queryBean;
    public static final String TABLE_PREFIX = "user_";
    private Set<String> tables = new HashSet<String>();

    public UserBean() {
        super();
    }

    public UserBean(User user) {
        super();
        this.id = user.id;
        this.setCreate_time(user.create_time);
        this.setUpdate_time(user.update_time);
        this.setRegister_time(user.register_time);
        this.name = user.name;
        this.head = user.head;
        this.tel = user.tel;
        this.device_uuid = user.device_uuid;
        this.password = user.password;
        this.role_id = user.role_id;
    }

    public Timestamp getCreate_time_bean() {
        return create_time_bean;
    }

    public void setCreate_time_bean(Timestamp create_time_bean) {
        this.create_time = String.valueOf(create_time_bean.getTime());
        this.create_time_bean = create_time_bean;
    }

    public Timestamp getUpdate_time_bean() {
        return update_time_bean;
    }
    public void setUpdate_time_bean(Timestamp update_time_bean) {
        this.update_time = String.valueOf(update_time_bean.getTime());
        this.update_time_bean = update_time_bean;
    }

    public Timestamp getRegister_time_bean() {
        return register_time_bean;
    }

    public void setRegister_time_bean(Timestamp register_time_bean) {
        this.register_time = String.valueOf(register_time_bean.getTime());
        this.register_time_bean = register_time_bean;
    }

    public QueryBean getQueryBean() {
        return queryBean;
    }

    public void setQueryBean(QueryBean queryBean) {
        this.queryBean = queryBean;
    }

    @Override
    public User setCreate_time(String create_time) {
        if (create_time!=null)this.create_time_bean = new Timestamp(Long.parseLong(create_time));
        return super.setCreate_time(create_time);
    }

    @Override
    public User setUpdate_time(String update_time) {
        if (update_time!=null)this.update_time_bean = new Timestamp(Long.parseLong(create_time));
        return super.setUpdate_time(update_time);
    }

    @Override
    public User setRegister_time(String register_time) {
        if (register_time!=null)this.register_time_bean = new Timestamp(Long.parseLong(register_time));
        return super.setRegister_time(register_time);
    }

    public Set<String> getTables() {
        return tables;
    }

    public void setTables(Set<String> tables) {
        this.tables = tables;
    }
}


text:
<!DOCTYPE suite SYSTEM "http://testng.org/testng-1.0.dtd" >

<suite name="Suite1" verbose="1" >
	<test name="Regression1"   >
	    <packages>
	      	<package name="com.vmware.moviebase" />
	   	</packages>
	</test>
	<!--  tests for junit -->
	<test name="JUnit-testss" junit="true" >
	   	<packages>
	      	<package name="com.vmware.moviebase" />
	   	</packages>
	</test>
</suite>


text:
using System.Web.Mvc;
using MBCorpHealth.Aplicacao.Servico;
using MBCorpHealth.Dominio.Contratos;
using MBCorpHealth.Infraestrutura.Repositorio;
using MBCorpHealth.View.ViewModel;
using Microsoft.Practices.Unity;
using NHibernate;

namespace MBCorpHealthWEB.Controllers
{
    public class PacienteController : Controller
    {
        private UnityContainer _unityContainer;
        // GET: Paciente
        public PacienteController()
        {
            _unityContainer = new UnityContainer();
            _unityContainer.RegisterType<IRepositorioPaciente, RepositorioPaciente>();
            _unityContainer.RegisterInstance<ISession>(ConfiguracaoNHibernate.Criar().OpenSession());
        }

        public ActionResult Index()
        {

            ServicoDePaciente servicoDePaciente = _unityContainer.Resolve<ServicoDePaciente>();

            var listaDePacientes = servicoDePaciente.ListarPorTrecho("");

            return View(listaDePacientes);
        }

        public ActionResult Criar()
        {
            return View();
        }

        [HttpPost]
        public ActionResult Criar(PacienteViewModel pacienteViewModel)
        {
            ServicoDePaciente servicoDePaciente = _unityContainer.Resolve<ServicoDePaciente>();

            servicoDePaciente.Gravar(pacienteViewModel);

            return RedirectToAction("Index");

        }

        public ActionResult Excluir(string cpf)
        {
            ServicoDePaciente servicoDePaciente = _unityContainer.Resolve<ServicoDePaciente>();

            servicoDePaciente.Excluir(new PacienteViewModel {Cpf = cpf,Nome = "  "});
            return RedirectToAction("Index");
        }
    }
}


text:
HOME

Inspiration

Style guide

        Lorem ipsum dolor sit amet, consectetur adipiscing elit.
        Vestibulum lobortis, risus quis luctus vehicula, neque diam iaculis erat, at laoreet lacus turpis eget velit.
        Pellentesque vitae auctor massa. Suspendisse posuere vitae turpis id pretium.
        Sed eget dui et risus maximus ultricies eget nec sapien. Nam hendrerit varius sem, eget tincidunt odio.

                <button class="btn btn-gray btn-wide" ui-sref="design">CLASSIC</button>

                <button class="btn btn-gray btn-wide" ui-sref="design">TEAMS</button>

                <button class="btn btn-gray btn-wide" ui-sref="design">GEOMETRIC</button>

                <button class="btn btn-gray btn-wide" ui-sref="design">ILLUSTRATIONS</button>

                <button class="btn btn-gray btn-wide" ui-sref="design">MINIMALIST</button>

                <button class="btn btn-gray btn-wide" ui-sref="design">MINIPRINT</button>

                <button class="btn btn-gray btn-wide" ui-sref="design">MTB</button>

                <button class="btn btn-gray btn-wide" ui-sref="design">TRIATHLON</button>