text:
declare namespace javax {
  namespace print {
    namespace event {

      interface PrintServiceAttributeListener$$lambda {
        (arg0: javax.print.event.PrintServiceAttributeEvent): void
      }

      interface PrintServiceAttributeListener {
        attributeUpdate(arg0: javax.print.event.PrintServiceAttributeEvent): void
      }

    }
  }
}


text:
from __future__ import unicode_literals

import os
import sys
import shutil
import tempfile
import textwrap
import contextlib

try:
    from contextlib import ExitStack
except ImportError:
    from contextlib2 import ExitStack

try:
    import pathlib
except ImportError:
    import pathlib2 as pathlib

__metaclass__ = type

@contextlib.contextmanager
def tempdir():
    tmpdir = tempfile.mkdtemp()
    try:
        yield pathlib.Path(tmpdir)
    finally:
        shutil.rmtree(tmpdir)

@contextlib.contextmanager
def save_cwd():
    orig = os.getcwd()
    try:
        yield
    finally:
        os.chdir(orig)

@contextlib.contextmanager
def tempdir_as_cwd():
    with tempdir() as tmp:
        with save_cwd():
            os.chdir(str(tmp))
            yield tmp

class SiteDir:
    def setUp(self):
        self.fixtures = ExitStack()
        self.addCleanup(self.fixtures.close)
        self.site_dir = self.fixtures.enter_context(tempdir())

class OnSysPath:
    @staticmethod
    @contextlib.contextmanager
    def add_sys_path(dir):
        sys.path[:0] = [str(dir)]
        try:
            yield
        finally:
            sys.path.remove(str(dir))

    def setUp(self):
        super(OnSysPath, self).setUp()
        self.fixtures.enter_context(self.add_sys_path(self.site_dir))

class DistInfoPkg(OnSysPath, SiteDir):
    files = {
        "distinfo_pkg-1.0.0.dist-info": {
            "METADATA": """
                Name: distinfo-pkg
                Author: Steven Ma
                Version: 1.0.0
                Requires-Dist: wheel >= 1.0
                Requires-Dist: pytest; extra == 'test'
                """,
            "RECORD": "mod.py,sha256=abc,20\n",
            "entry_points.txt": """
                [entries]
                main = mod:main
                ns:sub = mod:main
            """
            },
        "mod.py": """
            def main():
                print("hello world")
            """,
        }

    def setUp(self):
        super(DistInfoPkg, self).setUp()
        build_files(DistInfoPkg.files, self.site_dir)

class DistInfoPkgOffPath(SiteDir):
    def setUp(self):
        super(DistInfoPkgOffPath, self).setUp()
        build_files(DistInfoPkg.files, self.site_dir)

class EggInfoPkg(OnSysPath, SiteDir):
    files = {
        "egginfo_pkg.egg-info": {
            "PKG-INFO": """
                Name: egginfo-pkg
                Author: Steven Ma
                License: Unknown
                Version: 1.0.0
                Classifier: Intended Audience :: Developers
                Classifier: Topic :: Software Development :: Libraries
                """,
            "SOURCES.txt": """
                mod.py
                egginfo_pkg.egg-info/top_level.txt
            """,
            "entry_points.txt": """
                [entries]
                main = mod:main
            """,
            "requires.txt": """
                wheel >= 1.0; python_version >= "2.7"
                [test]
                pytest
            """,
            "top_level.txt": "mod\n"
            },
        "mod.py": """
            def main():
                print("hello world")
            """,
        }

    def setUp(self):
        super(EggInfoPkg, self).setUp()
        build_files(EggInfoPkg.files, prefix=self.site_dir)

class EggInfoFile(OnSysPath, SiteDir):
    files = {
        "egginfo_file.egg-info": """
            Metadata-Version: 1.0
            Name: egginfo_file
            Version: 0.1
            Summary: An example package
            Home-page: www.example.com
            Author: Eric Haffa-Vee
            Author-email: eric@example.coms
            License: UNKNOWN
            Description: UNKNOWN
            Platform: UNKNOWN
            """,
        }

    def setUp(self):
        super(EggInfoFile, self).setUp()
        build_files(EggInfoFile.files, prefix=self.site_dir)

def build_files(file_defs, prefix=pathlib.Path()):
    """Build a set of files/directories, as described by the

    file_defs dictionary.  Each key/value pair in the dictionary is
    interpreted as a filename/contents pair.  If the contents value is a
    dictionary, a directory is created, and the dictionary interpreted
    as the files within it, recursively.

    For example:

    {"README.txt": "A README file",
     "foo": {
        "__init__.py": "",
        "bar": {
            "__init__.py": "",
        },
        "baz.py": "# Some code",
     }
    }
    """
    for name, contents in file_defs.items():
        full_name = prefix / name
        if isinstance(contents, dict):
            full_name.mkdir()
            build_files(contents, prefix=full_name)
        else:
            if isinstance(contents, bytes):
                with full_name.open('wb') as f:
                    f.write(contents)
            else:
                with full_name.open('w') as f:
                    f.write(DALS(contents))

def DALS(str):
    "Dedent and left-strip"
    return textwrap.dedent(str).lstrip()

redpajama_set_name: RedPajamaGithub


text:
<?php

namespace App\Controller\Web;

use App\Controller\BaseController;
use Symfony\Component\HttpFoundation\Response;

/**
 * Class DefaultController
 */
class DefaultController extends BaseController
{
    /**
     * @return Response
     */
    public function indexAction(): Response
    {
        return $this->render('web/default/index.html.twig');
    }
}


text:
ACCEPTED

#### According to
Index Fungorum

#### Published in
Schlechtendalia 13: 27 (2006)

#### Original name
Cladosporium exobasidii var. verruculosum Heuchert, U. Braun & K. Schub.

### Remarks
null


text:
/* jslint node: true */
'use strict';

const FullScreenEditorModule = require('./fse.js').FullScreenEditorModule;
const persistMessage = require('./message_area.js').persistMessage;
const UserProps = require('./user_property.js');
const { hasMessageConfAndAreaWrite } = require('./message_area.js');

const async = require('async');

exports.moduleInfo = {
    name: 'Message Area Post',
    desc: 'Module for posting a new message to an area',
    author: 'NuSkooler',
};

exports.getModule = class AreaPostFSEModule extends FullScreenEditorModule {
    constructor(options) {
        super(options);

        const self = this;

        //  we're posting, so always start with 'edit' mode
        this.editorMode = 'edit';

        this.menuMethods.editModeMenuSave = function (formData, extraArgs, cb) {
            var msg;
            async.series(
                [
                    function getMessageObject(callback) {
                        self.getMessage(function gotMsg(err, msgObj) {
                            msg = msgObj;
                            return callback(err);
                        });
                    },
                    function saveMessage(callback) {
                        return persistMessage(msg, callback);
                    },
                    function updateStats(callback) {
                        self.updateUserAndSystemStats(callback);
                    },
                ],
                function complete(err) {
                    if (err) {
                        //  :TODO:... sooooo now what?
                    } else {
                        //  note: not logging 'from' here as it's part of client.log.xxxx()
                        self.client.log.info(
                            {
                                to: msg.toUserName,
                                subject: msg.subject,
                                uuid: msg.messageUuid,
                            },
                            `User "${self.client.user.username}" posted message to "${msg.toUserName}" (${msg.areaTag})`
                        );
                    }

                    return self.nextMenu(cb);
                }
            );
        };
    }

    enter() {
        this.messageAreaTag =
            this.messageAreaTag || this.client.user.getProperty(UserProps.MessageAreaTag);

        super.enter();
    }

    initSequence() {
        if (!hasMessageConfAndAreaWrite(this.client, this.messageAreaTag)) {
            const noAcsMenu =
                this.menuConfig.config.messageBasePostMessageNoAccess ||
                'messageBasePostMessageNoAccess';

            return this.gotoMenuOrShowMessage(
                noAcsMenu,
                'You do not have the proper access to post here!'
            );
        }

        super.initSequence();
    }
};


text:
#import <UIKit/UIKit.h>

@class MyViewController;

@interface HelloWorldAppDelegate : NSObject <UIApplicationDelegate> {

	IBOutlet UIWindow *window;
	MyViewController *myViewController;
}

@property (nonatomic, retain) UIWindow *window;
@property (nonatomic, retain) MyViewController *myViewController;

@end


text:
/**
 * @file 原生实现 https + http2
 */

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

// SSL options
var httpsOptions = {
  key: fs.readFileSync('./ssl/privkey.pem'),
  cert: fs.readFileSync('./ssl/server.pem')
};

const server = http2.createSecureServer(httpsOptions, (request, response) => {
  const encoding = 'utf-8';

  response.writeHead(200, {
    'Content-Type': 'application/javascript; charset=utf-8;'
  });

  response.write('{"a": "a"}', encoding);
  response.end();
});

const port = 8443;
server.listen(port);
console.log('启动成功,127.0.0.1:', port);


text:
from ingenico.connect.sdk.data_object import DataObject

class CaptureStatusOutput(DataObject):

    __status_code = None

    @property
    def status_code(self):
        """
        | Numeric status code of the legacy API. It is returned to ease the migration from the legacy APIs to Worldline Connect. You should not write new business logic based on this property as it will be deprecated in a future version of the API. The value can also be found in the GlobalCollect Payment Console, in the Ogone BackOffice and in report files.

        Type: int
        """
        return self.__status_code

    @status_code.setter
    def status_code(self, value):
        self.__status_code = value

    def to_dictionary(self):
        dictionary = super(CaptureStatusOutput, self).to_dictionary()
        if self.status_code is not None:
            dictionary['statusCode'] = self.status_code
        return dictionary

    def from_dictionary(self, dictionary):
        super(CaptureStatusOutput, self).from_dictionary(dictionary)
        if 'statusCode' in dictionary:
            self.status_code = dictionary['statusCode']
        return self


text:
<?php
namespace Aws\DirectoryService;

use Aws\AwsClient;

/**
 * AWS Directory Service client
 */
class DirectoryServiceClient extends AwsClient {}


text:
<!DOCTYPE html>
{% if USE_OPEN_GRAPH is not defined %}
    {% set USE_OPEN_GRAPH = True %}
{% endif %}

    <title>{% block title %}{{ SITENAME }}{% endblock %}</title>

    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">

    {% if 'liquid_tags.notebook' in PLUGINS %}
        {% include 'includes/liquid_tags_nb_header.html' %}
    {% endif %}

    {# Favicons are a touchy subject. For reasoning for the following code, see: http://stackoverflow.com/a/23851464/872397 #}
    {% if FAVICON %}
    <link href="{{ SITEURL }}/{{ FAVICON }}" rel="icon">
    {% endif %}
    {% if FAVICON_IE %}

    {% endif %}
    {% if TOUCHICON %}
    <link rel="apple-touch-icon" href="{{ SITEURL }}/{{ TOUCHICON }}">
    {% endif %}

    {% block canonical_rel %}{% endblock %}

    {% block meta %}
        <meta name="author" content="{{ AUTHOR }}" />
    {% endblock %}

    {# Open Graph tags #}
    {% if USE_OPEN_GRAPH %}
    {% block opengraph %}

        {% if OPEN_GRAPH_FB_APP_ID %}
            <meta property="fb:app_id" content="{{ OPEN_GRAPH_FB_APP_ID }}"/>
        {% endif %}
        <meta property="og:site_name" content="{{ SITENAME }}" />
        <meta property="og:type" content="website"/>
        <meta property="og:title" content="{{ SITENAME }}"/>
        <meta property="og:url" content="{{ SITEURL }}"/>
        <meta property="og:description" content="{{ SITENAME }}"/>
        {% if OPEN_GRAPH_IMAGE %}
            <meta property="og:image"
                  content="{{ SITEURL }}/{{ OPEN_GRAPH_IMAGE }}"/>
        {% endif %}
    {% endblock %}
    {% endif %}

    {# Twitter Cards tags #}
    {% include 'includes/twitter_cards.html' %}

    {% if BOOTSTRAP_THEME %}
        <link rel="stylesheet" href="{{ SITEURL }}/{{ THEME_STATIC_DIR }}/css/bootstrap.{{ BOOTSTRAP_THEME }}.min.css" type="text/css"/>
    {% else %}
        <link rel="stylesheet" href="{{ SITEURL }}/{{ THEME_STATIC_DIR }}/css/bootstrap.min.css" type="text/css"/>
    {% endif %}
    <link href="{{ SITEURL }}/{{ THEME_STATIC_DIR }}/css/font-awesome.min.css" rel="stylesheet">

    <link href="{{ SITEURL }}/{{ THEME_STATIC_DIR }}/css/pygments/{{ PYGMENTS_STYLE|default('native') }}.css" rel="stylesheet">
    {% if 'tipue_search' in PLUGINS %}
    <link href="{{ SITEURL}}/{{ THEME_STATIC_DIR }}/tipuesearch/tipuesearch.css" rel="stylesheet">
    {% endif %}
    {% if DOCUTIL_CSS %}
        <link href="{{ SITEURL }}/{{ THEME_STATIC_DIR }}/css/html4css1.css" rel="stylesheet">
    {% endif %}
    {% if TYPOGRIFY %}
        <link href="{{ SITEURL }}/{{ THEME_STATIC_DIR }}/css/typogrify.css" rel="stylesheet">
    {% endif %}
    <link rel="stylesheet" href="{{ SITEURL }}/{{ THEME_STATIC_DIR }}/css/style.css" type="text/css"/>
    {% if CUSTOM_CSS %}
        <link href="{{ SITEURL }}/{{ CUSTOM_CSS }}" rel="stylesheet">
    {% endif %}
    {% if SHARIFF %}
        <link href="{{ SITEURL }}/{{ THEME_STATIC_DIR }}/css/shariff/shariff.min.css" rel="stylesheet">
    {% endif %}

    {% if FEED_ALL_ATOM %}
        <link href="{{ SITEURL }}/{{ FEED_ALL_ATOM }}" type="application/atom+xml" rel="alternate"
              title="{{ SITENAME }} ATOM Feed"/>
    {% endif %}

    {% if FEED_ALL_RSS %}
        <link href="{{ SITEURL }}/{{ FEED_ALL_RSS }}" type="application/rss+xml" rel="alternate"
              title="{{ SITENAME }} RSS Feed"/>
    {% endif %}

    {% if tag and TAG_FEED_ATOM %}
        <link href="{{ SITEURL }}/{{ TAG_FEED_ATOM|format(tag.slug) }}" type="application/atom+xml" rel="alternate"
              title="{{ SITENAME }} {{ tag }} ATOM Feed"/>
    {% endif %}

    {% if category and CATEGORY_FEED_ATOM %}
        <link href="{{ SITEURL }}/{{ CATEGORY_FEED_ATOM|format(category.slug) }}" type="application/atom+xml" rel="alternate"
              title="{{ SITENAME }} {{ category }} ATOM Feed"/>
    {% endif %}

            {% if MENUITEMS or (pages and DISPLAY_PAGES_ON_MENU) or (categories and DISPLAY_CATEGORIES_ON_MENU) %}
            <button type="button" class="navbar-toggle" data-toggle="collapse" data-target=".navbar-ex1-collapse">
                Toggle navigation

            </button>
            {% endif %}

                {% if SITELOGO %} {% endif %}
                {% if not HIDE_SITENAME %}{{ SITENAME }}{% endif %}

                {% for title, link in MENUITEMS %}

{{ title }}

                {% endfor %}
                {% if not PAGES_SORT_ATTRIBUTE -%}
                    {% set PAGES_SORT_ATTRIBUTE = 'title' %}
                {%- endif %}
                {% if DISPLAY_PAGES_ON_MENU %}
                    {% for p in pages | sort(attribute=PAGES_SORT_ATTRIBUTE) %}
                        {% if p.url %}

                             {{ p.menulabel|default(p.title) }}

                        {% endif %}
                      {% endfor %}
                {% endif %}
                {% if DISPLAY_CATEGORIES_ON_MENU %}
                    {% for cat, null in categories %}

                            {{ cat | capitalize }}

                    {% endfor %}
                {% endif %}

            {% if 'tipue_search' in PLUGINS %}

                <form class="navbar-search" action="{{ SEARCH_URL | default('/search.html') }}">
                  <input type="text" class="search-query" placeholder="Search" name="q" id="tipue_search_input" required>
                </form>

            {% endif %}
            {% if ARCHIVES_SAVE_AS %}

{{ _('Archives') }}

            {% endif %}

{% if BANNER and BANNER_ALL_PAGES %}
    {% include 'includes/banner.html' %}
{% elif BANNER and not BANNER_ALL_PAGES %}
    {% block banner %}{% endblock %}
{% endif %}

        {% if not HIDE_SIDEBAR or ABOUT_ME or AVATAR %}

        {% else %}

        {% endif %}
        {% block breadcrumbs %}
        {% endblock %}
        {% block content %}
        {% endblock %}

        {% if not HIDE_SIDEBAR or ABOUT_ME or AVATAR %}

            {% if ABOUT_ME or AVATAR %}
                {% include 'includes/aboutme.html' %}
            {% endif %}
            {% if not HIDE_SIDEBAR %}
                {% include 'includes/sidebar.html' %}
            {% endif %}

        {% endif %}

{% include 'includes/footer.html' %}

{% if BANNER %}

{% endif %}
{% include 'includes/github-js.html' %}
{% include 'includes/disqus_script.html' %}
{% include 'includes/ga.html' %}
{% include 'includes/piwik.html' %}

{% block scripts %}{% endblock %}


text:
import {
  ChangeDetectionStrategy,
  Component,
  Input,
  OnInit,
  forwardRef,
} from '@angular/core';
import { SkyLogService } from '@skyux/core';
import { AsyncList, ListItemModel, getValue } from '@skyux/list-builder-common';

import { Observable } from 'rxjs';
import {
  distinctUntilChanged,
  map as observableMap,
  scan,
} from 'rxjs/operators';

import { ListPagingComponent } from '../list/list-paging.component';
import { ListStateDispatcher } from '../list/state/list-state.rxstate';
import { ListState } from '../list/state/list-state.state-node';
import { ListPagingSetItemsPerPageAction } from '../list/state/paging/set-items-per-page.action';
import { ListPagingSetMaxPagesAction } from '../list/state/paging/set-max-pages.action';
import { ListPagingSetPageNumberAction } from '../list/state/paging/set-page-number.action';

/* istanbul ignore next */
const listPagingComponentRef = forwardRef(() => SkyListPagingComponent);

/**
 * Displays a pagination control for a SKY UX-themed list of data.
 * @deprecated
 */
@Component({
  selector: 'sky-list-paging',
  templateUrl: './list-paging.component.html',
  providers: [
    { provide: ListPagingComponent, useExisting: listPagingComponentRef },
  ],
  changeDetection: ChangeDetectionStrategy.OnPush,
})
export class SkyListPagingComponent
  extends ListPagingComponent
  implements OnInit
{
  /**
   * Specifies the number of list items per page.
   * @default 10
   */
  @Input()
  public pageSize: Observable<number> | number = 10;

  /**
   * Specifies the maximum pages to display.
   * @default 5
   */
  @Input()
  public maxPages: Observable<number> | number = 5;

  /**
   * Specifies the current page number.
   * @default 1
   */
  @Input()
  public pageNumber: Observable<number> | number = 1;

  public currentPageNumber: Observable<number>;

  public maxDisplayedPages: Observable<number>;

  public itemsPerPage: Observable<number>;

  public itemCount: Observable<number>;

  constructor(
    state: ListState,
    dispatcher: ListStateDispatcher,
    logger: SkyLogService
  ) {
    super(state, dispatcher);
    logger.deprecated('SkyListPagingComponent', {
      deprecationMajorVersion: 6,
      moreInfoUrl:
        'https://developer.blackbaud.com/skyux/components/data-manager',
      replacementRecommendation:
        'Use data manager and the paging component instead.',
    });
  }

  public ngOnInit() {
    this.currentPageNumber = this.state.pipe(
      observableMap((s) => s.paging.pageNumber)
    );

    this.maxDisplayedPages = this.state.pipe(
      observableMap((s) => s.paging.maxDisplayedPages)
    );

    this.itemsPerPage = this.state.pipe(
      observableMap((s) => s.paging.itemsPerPage)
    );

    this.itemCount = this.state.pipe(
      observableMap((s) => {
        return s.items;
      }),
      scan(
        (
          previousValue: AsyncList<ListItemModel>,
          newValue: AsyncList<ListItemModel>
        ) => {
          if (previousValue.lastUpdate > newValue.lastUpdate) {
            return previousValue;
          } else {
            return newValue;
          }
        }
      ),
      observableMap((result: AsyncList<ListItemModel>) => {
        return result.count;
      }),
      distinctUntilChanged()
    );

    // subscribe to or use inputs
    getValue(this.pageSize, (pageSize: number) =>
      this.dispatcher.next(
        new ListPagingSetItemsPerPageAction(Number(pageSize))
      )
    );
    getValue(this.maxPages, (maxPages: number) =>
      this.dispatcher.next(new ListPagingSetMaxPagesAction(Number(maxPages)))
    );
    getValue(this.pageNumber, (pageNumber: number) =>
      this.dispatcher.next(
        new ListPagingSetPageNumberAction(Number(pageNumber))
      )
    );
  }

  public pageChange(currentPage: number) {
    // Paging must be updated after list data has been updated.
    // Adding a setTimeout will pull it out of the stream.
    setTimeout(() => {
      this.dispatcher.next(
        new ListPagingSetPageNumberAction(Number(currentPage))
      );
    });
  }
}


text:
<?php
/**
 * Contains \garethp\ews\API\Enumeration\SensitivityChoicesType.
 */

namespace garethp\ews\API\Enumeration;

use garethp\ews\API\Enumeration;

/**
 * Class representing SensitivityChoicesType
 *
 *
 * XSD Type: SensitivityChoicesType
 */
class SensitivityChoicesType extends Enumeration
{

    const CONFIDENTIAL = 'Confidential';

    const NORMAL = 'Normal';

    const PERSONAL = 'Personal';

    const PRIVATE_ITEM = 'Private';

    const PRIVATE_CONSTANT = 'Private';
}


text:
namespace tippbot
{
	namespace db
	{
		namespace dao
		{
			class LeagueDao
			{
			public:
				LeagueDao(tippbot::db::Database *db) : db_(db)
				{
				}

				bool insert(tippbot::model::League *league);
				bool exists(tippbot::model::League *league);
				tippbot::model::League* findById(const char *id);
				tippbot::model::League* findAny();
			private:
				tippbot::db::Database *db_;
			};
		}
	}
}


text:
package com.cra.figaro.library.atomic.continuous

import com.cra.figaro.language.Atomic
import com.cra.figaro.language.ElementCollection
import com.cra.figaro.language.Element
import com.cra.figaro.language.Name
import com.cra.figaro.language._
import com.cra.figaro.util._
import annotation.tailrec
import scala.math.{ exp, log, pow }
import JSci.maths.SpecialMath.{ gamma, logGamma }

/**
 * A Gamma distribution in which both the k and theta parameters are constants.
 * Theta defaults to 1.
 */
class AtomicInverseGamma(name: Name[Double], shape: Double, scale: Double = 1.0, collection: ElementCollection)
  extends Element[Double](name, collection) with Atomic[Double] {

  type Randomness = Double

  def generateRandomness() = Util.generateGamma(shape)

  def generateValue(rand: Randomness) = 1.0 / (rand * scale) // due to scaling property of Gamma

  /**
   * The normalizing factor.
   */
  private val normalizer = pow(scale, shape) / (gamma(shape))

  /**
   * Density of a value.
   */
  def density(x: Double) = {
    if (x < 0.0) 0.0 else {
      //Convert to logarithms if this is too large.
      val numer = pow(x, -1.0 * shape - 1) * exp(-1.0 * scale / x)
      numer * normalizer
    }
  }

  override def toString =
    if (scale == 1.0) "InverseGamma(" + shape + ")"
    else "InverseGamma(" + shape + ", " + scale + ")"
}

object InverseGamma {
    /**
   * Create an InverseGamma element.
   */
  def apply(shape: Double, scale: Double)(implicit name: Name[Double], collection: ElementCollection) =
    new AtomicInverseGamma(name, shape, scale, collection)

}


text:
Hem

Integritetspolicy

Integritetspolicy

        Västtrafik Utvecklarportal är mån om att bevara din integritet. Därför sparar vi ingen information om dig som inte är nödvändig för
        att webbplatsen ska fungera som det är tänkt.

      För att kunna använda dig av alla tjänster som vi erbjuder krävs att Du registrerar ett konto
      varpå viss information sparas, se nedan.

Cookies

      Utvecklarportalen använder sig inte av cookies.

      Mer information om cookies

Konto - Utvecklarportalen

      Att skapa ett konto på Utvecklarportalen är nödvändigt för att kunna ta del av tjänsterna som erbjuds.
      Om du väljer att lämna dina personuppgifter är Västtrafik ansvarig för dem. Informationen kommer att behandlas konfidentiellt och enligt Personuppgiftslagen.
      Kontorelated information som vi sparar är förnamn, efternamn, epostadress och lösenord vilket är nödvändigt för att Du ska komma åt våra tjänster.

Till vad används kontouppgifter?

      Lämnad information används enbart till att ge dig tillgång till samtliga tjänster på Utvecklarportalen.

Kan mina uppgifter spridas?

      Dina uppgifter lagras i en databas internt på Västtrafik och lämnas aldrig ut till tredje part. Uppgifterna kan således enbart
      hanteras av personal på Västtrafik och lämnar aldrig Sverige.

Hur länge sparar Västtrafik mina uppgifter?

      Dina kontouppgifter kommer att sparas hos Västtrafik tills du väljer att avsluta ditt konto.
      För att avsluta ditt konto, var vänlig gå in på "Min Profil" och ta bort dina kontaktuppgifter där.

      Mer information om Västtrafiks Integritetspolicy hittar du här.


text:
class Autnum < ActiveRecord::Base
end


text:
<!DOCTYPE html>

<meta http-equiv="content-type" content="text/html; charset=UTF-8">

<meta charset="utf-8">

<title>PWG May 2020 Face-to-Face Meeting - Summary</title>

<meta name="author" content="PWG">

 The PWG held its May 2020 Virtual Face-to-Face Meeting
      on May 5-8, 2020 via WebEx teleconferences. This event was held in collaboration with Linux Foundation OpenPrinting
Workgroup. Sessions were presented by both organizations over the
event's 3 days. Representatives
      from Apple, Artifex, Canon, Canonical, Google, Gutenprint, High
North, HP Inc., Kyocera,
Lakeside Robotics,      Lexmark, Qualcomm, Red Hat, Ricoh, TIC, TCS and
Xerox attended the meetings, as well as several independent individuals.
      Attendees reviewed work in progress, including drafts of a number
      of in-progress specifications, and discussed liaisons with partner
      groups. Here is a summary of the proceedings.

Linux Foundation OpenPrinting Workgroup

The Linux Foundation OpenPrinting Workgroup sessions were presented
on the first
day. Ira McDonald reviewed the Linux OpenPrinting project's
accomplishments from 2019 and surveyed the efforts under way for 2020.
Work continues to move from CUPS 2.2.x to 2.3, and to fully support IPP
System Service. Ira reviewed the status of OP Google Summer of Code
(GSoC) work to occur in 2020, as well as Google Season of Docs.

Aveek Basu presented a review of the Linux OpenPrinting
Workgroup's projects that are active in 2020. He discussed in more
detail the upcoming
"Google Summer of Code 2020" projects that will implement frameworks for
 developing CUPS Printer Applications,
a Linux GUI application to administer multi-function devices via the IPP
 System Service, an IPP Scan server, cups-browsed optimizations, and PDF
 raster extraction. He also covered
 the Linux OpenPrinting Workgroup's engagement in the "Linux Plumbers
Conference", "Linux Foundation Members Summit 2020", and the "Open
Printing Mini Conference" at Indian Institute of Technology in November
2019. Mike Sweet presented on two CUPS Printer Application projects he
is working on (ippeveprinter and LPrint), as well as the PAPPL Printer
Application framework he has developed to make it easier to write CUPS
printer applications. He described the value that Printer Applications
provide as a more self-contained replacement for legacy printer drivers.
 His PAPPL project is a C-based framework for developing new Printer
Applications.

After a short lunch break, Michael
Vrhel reviewed the status of Ghostscript, MuPDF and
associated projects such as MuJS and MuPDF WebAssembly. A large focus of
 the work over the last year has been pruning seldom used or incomplete
features, especially those that cause a disproportionate number of
defects. Sean Kau presented "Printing in Chrome OS", covering system
details
that differ from other operating system environments and how that
affects printing support. Many of the software components developed
by the Linux Foundation OpenPrinting Workgroup, as well as an unmodified
 CUPS release, are deployed as the core components of the Chrome OS
print system. IPP Everywhere is supported out-of-box and helps to enable
 universal printing. Sean reviewed the changes made since he presented
last in May 2019.

After another break, Till Kamppeter presented a detailed survey of
completed, in-process and future work in the "cups-filters" and
"ippusbxd" projects and related work on Driverless Scanning, CUPS in a
Snap, and patches contributed to Avahi, a commonly used open source
implementation of mDNS / DNS-SD. Many bug fixes were made in 2018, and
work
continues on both of these projects.

Minutes are available here: https://ftp.pwg.org/pub/pwg/liaison/openprinting/minutes/OP-Summit-Minutes-20200505.htm

 PWG Plenary

 The PWG sessions began on the second day with the PWG Chair presenting the PWG Plenary.
      We reviewed the overall state of the PWG,
      its programs and initiatives, and briefly discussed upcoming
      face-to-face meeting scheduling. We noted that  there are currently 412 printers certified
 under the PWG's IPP Everywhere™
      Self Certification program, which hasn't changed in some time, but
 more certifications are believed to
      be in progress from multiple vendors pending the release of IPP
Everywhere™v1.1. We discussed the PWG Steering Committee's
activities and initiatives, including its 2020 goals, the status of
Process 4.0 and updated policies, public relations efforts, recently
approved
documents, process document updates, the website migration initiative,
and "toolset" alternatives for producing specifications. Each active PWG
 workgroup (IDS Workgroup
      and IPP
        Workgroup) summarized their current status. Finally, we
      reviewed the status of our partners' work in Trusted Computing
      Group (TCG), IETF, Linux Foundation OpenPrinting Workgroup, Mopria Alliance and INCITS.

 Complete minutes are available here: https://ftp.pwg.org/pub/pwg/general/minutes/pwg-plenary-minutes-20200506.htm

Internet Printing Protocol (IPP) Workgroup

 On the first day, Ira McDonald (IPP WG Co-Chair) and Mike Sweet
(IPP WG Secretary) surveyed the
      status of current IPP Workgroup works in progress, noting that
there will be an update to the charter in 2020. IPP Everywhere v1.1 and
IPP Everywhere Self Certification v1.1 are both in PWG Call for
Objections, ending on May 15,
2020, and the new JSON based self-certification submission portal is
live. After
 a break, we reviewed the latest draft of Job Accounting with IPP v1.0,
and tangentially discussed whether a PWG Best Practices document can
contain normative language, which will be further clarified in PWG
policy documents following Steering Committee discussion.

On the second day, after the IDS Workgroup session, the group
reviewed the latest draft of IPP Enterprise Printing Extensions v2.0.
After reviewing changes to earlier portions of the specification, the
group observed that the "job-hold-until" attribute is not suitable for
specifying a persistent release method in a Job, and moved to instead
define a new attribute to satisfy this requirement. Differences with job
 state on Logical Device Printers vs. Physical Device Printers was also
discussed.

On the third day, the  IPP
Workgroup sessions started with a
      review of IPP Production Printing Extensions v2.0, which is
nearing completion. We then discussed IPP Driverless Printing Extensions
 v2.0 and specifically had a more detailed discussion about how to address the issue of "print-quality" extensibility,
 and discussed its meaning, scope and related issues. An incremental
path forward was proposed at the end of the discussion, that will be
added to the next draft, as a path forward. After a break,
Paul Tykodi (IPP WG Co-Chair and lead PWG 3D Printing Liaison) led a
discussion on the status of the PWG's 3D Printing liaisons and the
guidance we will be providing to our partners. We spent some time
discussing how to bridge the "perception gaps" between what IPP 3D
provides and what the industry is asking for, and we discussed updating
our slides and topic page with more interaction models and other
diagrams to paint a more complete picture. We concluded the
IPP WG
 sessions with next steps.

 Complete minutes are available here: https://ftp.pwg.org/pub/pwg/ipp/minutes/ippv2-f2f-minutes-20200506.pdf

 Imaging Device Security (IDS) Workgroup

At the start of the second day, Alan Sukert (acting IDS WG Chair) led
 the IDS Workgroup
 status and progress discussion. We went through the minutes of the
latest HCD international
TC (iTC) meetings, discussed the 31-step cPP development plan and some
thoughts on what the content of HCD collaborative
Protection Profile (cPP) v1.0 should include. The scope should cover
what is needed by 2022, to keep it on a reasonable schedule. A v1.1
should be expected, to pick up any key SFRs not included in v1.0.
Publishing the HCD cPP/SD 1.0 in a timely manner will establish it in
the community and provide a foundation for further updates. Ira
discussed Compact TLS and noted that, though it won't be in the HCD cPP
v1.0 or the Network Device (ND) cPP in the near term, it should be
monitored. The group then shifted to discussing Ira's draft HCD Security
 Guidelines v1.0 document, which is being written as a PWG Best
Practices document. The group discussed which topics were in scope. Alan
 then discussed standards activities outside the HCD iTC that were
deserving of attention, such as the IETF's RATS (Remote ATtestation
ProcedureS) and SAAG (Security Area Advisory Group). We wrapped up with
next steps.

 Complete minutes are available here: https://ftp.pwg.org/pub/pwg/ids/minutes/ids-f2f-minutes-20200507.pdf

 Next PWG Face-to-Face Meeting

 The next PWG Face-to-Face meeting will be August 26-27, 2020 via WebEx teleconference. Please check the  PWG Meetings page  for updates on plans
      for upcoming meetings.


text:
package jiguang.chat.activity.receiptmessage;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ListView;

import cn.jpush.im.android.api.model.UserInfo;
import jiguang.chat.R;
import jiguang.chat.activity.FriendInfoActivity;
import jiguang.chat.activity.GroupNotFriendActivity;
import jiguang.chat.activity.fragment.BaseFragment;
import jiguang.chat.application.JGApplication;

/**
 * Created by ${chenyn} on 2017/9/5.
 */

public class MessageAlreadyReadFragment extends BaseFragment {
    private Activity mContext;
    private View mRootView;
    private ListView mReceipt_alreadyRead;
    private AlreadyReadAdapter mAdapter;
    private long mGroupId;

    public MessageAlreadyReadFragment(long groupIdForReceipt) {
        this.mGroupId = groupIdForReceipt;
    }

    public MessageAlreadyReadFragment() {
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        this.mContext = getActivity();

        initView();
        initListViewClick();
    }

    private void initView() {
        mRootView = LayoutInflater.from(mContext).inflate(R.layout.fragment_receipt_already_read,
                (ViewGroup) mContext.findViewById(R.id.main_view), false);
        mReceipt_alreadyRead = (ListView) mRootView.findViewById(R.id.receipt_alreadyRead);
        mAdapter = new AlreadyReadAdapter(this);
        mReceipt_alreadyRead.setAdapter(mAdapter);
    }

    private void initListViewClick() {
        mReceipt_alreadyRead.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                UserInfo userInfo = (UserInfo) parent.getItemAtPosition(position);
                Intent intent = new Intent();
                if (userInfo.isFriend()) {
                    intent.setClass(mContext, FriendInfoActivity.class);
                }else {
                    intent.setClass(mContext, GroupNotFriendActivity.class);
                }
                intent.putExtra(JGApplication.TARGET_ID, userInfo.getUserName());
                intent.putExtra(JGApplication.TARGET_APP_KEY, userInfo.getAppKey());
                intent.putExtra(JGApplication.GROUP_ID, mGroupId);
                startActivity(intent);
            }
        });
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        ViewGroup p = (ViewGroup) mRootView.getParent();
        if (p != null) {
            p.removeAllViewsInLayout();
        }
        return mRootView;
    }
}


text:
package org.seqcode.gsebricks.verbs.motifs;

import java.util.*;

import org.seqcode.data.motifdb.*;
import org.seqcode.genome.location.Region;
import org.seqcode.genome.sequence.SequenceGenerator;
import org.seqcode.genome.sequence.SequenceUtils;
import org.seqcode.gsebricks.verbs.Expander;
import org.seqcode.gsebricks.verbs.Mapper;
import org.seqcode.gseutils.Pair;
import org.seqcode.math.stats.StatUtil;

public class WeightMatrixScorer implements Mapper<Region,WeightMatrixScoreProfile> {

    private WeightMatrix matrix;
    private SequenceGenerator seqgen;

    public WeightMatrixScorer(WeightMatrix m) {
    	matrix = m;
        seqgen = new SequenceGenerator();
    }

    public WeightMatrixScorer(WeightMatrix m, SequenceGenerator sg) {
    	matrix = m;
        seqgen = sg;
    }

    public WeightMatrixScoreProfile execute(Region r) {
        String seq = seqgen.execute(r);
        seq = seq.toUpperCase();
        double[] fscores = null, rscores = null;

        try {
        	fscores = score(matrix, seq.toCharArray(), '+');
            seq = SequenceUtils.reverseComplement(seq);
            rscores = score(matrix, seq.toCharArray(), '-');

        } catch (ArrayIndexOutOfBoundsException e) {
            e.printStackTrace(System.err);
        }

        return new WeightMatrixScoreProfile(matrix, fscores, rscores);
    }

    public WeightMatrixScoreProfile execute(String seq) {
    	seq = seq.toUpperCase();
        double[] fscores = null, rscores = null;
    	fscores = score(matrix, seq.toCharArray(), '+');
        seq = SequenceUtils.reverseComplement(seq);
        rscores = score(matrix, seq.toCharArray(), '-');
        return new WeightMatrixScoreProfile(matrix, fscores, rscores);
    }

    public static double[] score(WeightMatrix matrix, char[] sequence, char strand) {
        double[] results = new double[sequence.length];
        /* scan through the sequence */
        int length = matrix.length();
       	for (int i = 0; i < sequence.length; i++) {
       		results[i] = (float)matrix.getMinScore();
       	}
       	if (sequence.length<length)
     		return results;

        for (int i = 0; i <= sequence.length - length; i++) {
            float score = (float)0.0;
            for (int j = 0; j < length; j++) {
                score += matrix.matrix[j][sequence[i+j]];
            }

            if(strand=='-') {
            	results[sequence.length-length-i] = score;
            } else {
            	results[i] = score;
            }
        }
        return results;
    }

    /**
     * Return the maximum motif score of the input sequence (both direction)
     * @param matrix
     * @param sequence
     * @return
     */
    public static double getMaxSeqScore(WeightMatrix matrix, String sequence){
    	if (sequence.length()<matrix.length())
    		return matrix.getMinScore();

    	double[] scores = score(matrix, sequence.toCharArray(), '+');
    	Pair<Double, TreeSet<Integer>> max = StatUtil.findMax(scores);
    	double maxScore = max.car();
    	scores = score(matrix, SequenceUtils.reverseComplement(sequence).toCharArray(), '-');
    	max = StatUtil.findMax(scores);
    	maxScore = Math.max(maxScore, max.car());
    	return maxScore;
    }

    /**
     * Return the highest scoring sequence in the region
     */
    public String getMaxScoreSequence(Region r, double threshold, int extend){
        int length = matrix.length();
        String seq = seqgen.execute(r.expand(0, length));
        seq = seq.toUpperCase();
        String hit=null;

        char[] sequence = seq.toCharArray();
        for (int i = 0; i <= sequence.length - length; i++) {
            float score = (float)0.0;
            for (int j = 0; j < length; j++) {
                score += matrix.matrix[j][sequence[i+j]];
            }
            if (score>threshold){
            	int start = i-extend;
            	if (start<0) continue;
            	int end = i+length-1+extend;
            	if (end>sequence.length - length) continue;
            	hit = seq.substring(start, end);
            	threshold = score;
            }
        }
        seq = SequenceUtils.reverseComplement(seq);
        sequence = seq.toCharArray();
        for (int i = 0; i <= sequence.length - length; i++) {
            float score = (float)0.0;
            for (int j = 0; j < length; j++) {
                score += matrix.matrix[j][sequence[i+j]];
            }
            if (score>threshold){
            	int start = i-extend;
            	if (start<0) continue;
            	int end = i+length-1+extend;
            	if (end>sequence.length - length) continue;
            	hit = seq.substring(start, end);
            	threshold = score;
            }
        }

        return hit;
    }
}


text:
X.Media.WebPlayer
=================
[![NuGet version (xmediawebplayer)](https://img.shields.io/nuget/v/xmediawebplayer.svg?style=flat-square)](https://www.nuget.org/packages/xmediawebplayer/)

Generate players for YouTube, Vimeo, etc


text:
package cache

import (
	"hash/fnv"
	"sync"
)

// Hash returns the FNV hash of what.
func Hash(what []byte) uint64 {
	h := fnv.New64()
	h.Write(what)
	return h.Sum64()
}

// Cache is cache.
type Cache struct {
	shards [shardSize]*shard
}

// shard is a cache with random eviction.
type shard struct {
	items map[uint64]interface{}
	size  int

	sync.RWMutex
}

// New returns a new cache.
func New(size int) *Cache {
	ssize := size / shardSize
	if ssize < 4 {
		ssize = 4
	}

	c := &Cache{}

	// Initialize all the shards
	for i := 0; i < shardSize; i++ {
		c.shards[i] = newShard(ssize)
	}
	return c
}

// Add adds a new element to the cache. If the element already exists it is overwritten.
func (c *Cache) Add(key uint64, el interface{}) {
	shard := key & (shardSize - 1)
	c.shards[shard].Add(key, el)
}

// Get looks up element index under key.
func (c *Cache) Get(key uint64) (interface{}, bool) {
	shard := key & (shardSize - 1)
	return c.shards[shard].Get(key)
}

// Remove removes the element indexed with key.
func (c *Cache) Remove(key uint64) {
	shard := key & (shardSize - 1)
	c.shards[shard].Remove(key)
}

// Len returns the number of elements in the cache.
func (c *Cache) Len() int {
	l := 0
	for _, s := range c.shards {
		l += s.Len()
	}
	return l
}

// newShard returns a new shard with size.
func newShard(size int) *shard { return &shard{items: make(map[uint64]interface{}), size: size} }

// Add adds element indexed by key into the cache. Any existing element is overwritten
func (s *shard) Add(key uint64, el interface{}) {
	l := s.Len()
	if l+1 > s.size {
		s.Evict()
	}

	s.Lock()
	s.items[key] = el
	s.Unlock()
}

// Remove removes the element indexed by key from the cache.
func (s *shard) Remove(key uint64) {
	s.Lock()
	delete(s.items, key)
	s.Unlock()
}

// Evict removes a random element from the cache.
func (s *shard) Evict() {
	hasKey := false
	var key uint64

	s.RLock()
	for k := range s.items {
		key = k
		hasKey = true
		break
	}
	s.RUnlock()

	if !hasKey {
		// empty cache
		return
	}

	// If this item is gone between the RUnlock and Lock race we don't care.
	s.Remove(key)
}

// Get looks up the element indexed under key.
func (s *shard) Get(key uint64) (interface{}, bool) {
	s.RLock()
	el, found := s.items[key]
	s.RUnlock()
	return el, found
}

// Len returns the current length of the cache.
func (s *shard) Len() int {
	s.RLock()
	l := len(s.items)
	s.RUnlock()
	return l
}

const shardSize = 256


text:
import java.awt.Color;

public class RectState extends State{
	StateManager stateManager;
	Mediator mediator;
	MyDrawing rect;
	int x1,x2,y1,y2;
	public RectState(StateManager stateManager){
		this.stateManager = stateManager;
		this.mediator = stateManager.getMediator();

	}

	public void mouseDown(int x, int y){
		x1 = x;
		y1 = y;
		rect = new MyRectangle(x,y,0,0,Color.black,Color.black,1);
		stateManager.addDrawing(rect);
	}

	public void mouseUp(int x, int y){
		if(Math.abs(x2) < 5 || Math.abs(y2) < 5){
			stateManager.removeDrawing(rect);
		}
	}

	public void mouseDrag(int x, int y){
		x2 = x - x1;
		y2 = y - y1;
		rect.setLocation(x1,y1);
		rect.setSize(x2,y2);
	}
}


text:
import hex.models as models
import hex.valuecodecs as valuecodecs
import hex.formatters as formatters
import hex.columnproviders as columnproviders
import hex.utils as utils
from PyQt4.QtCore import Qt
from PyQt4.QtGui import QDoubleValidator, QWidget, QFormLayout, QSpinBox, QComboBox, QSizePolicy, QValidator
import struct

class FloatColumnModel(models.RegularValueColumnModel):
    def __init__(self, document, valuecodec=None, formatter=None, columns_on_row=4):
        models.RegularValueColumnModel.__init__(self, document, valuecodec or valuecodecs.FloatCodec(),
                                                   formatter or formatters.FloatFormatter(), columns_on_row,
                                                   delegate_type=FloatColumnEditDelegate)

    @property
    def regularTextLength(self):
        return self.formatter.maximalWidth

    def virtualIndexData(self, index, role=Qt.DisplayRole):
        if role == Qt.EditRole:
            return '0'
        return models.RegularValueColumnModel.virtualIndexData(self, index, role)

    @property
    def preferSpaced(self):
        return True

    # def textForDocumentData(self, document_data, index, role=Qt.DisplayRole):
    #     d = models.RegularValueColumnModel.textForDocumentData(self, document_data, index, role)
    #     return d

    def _dataForNewIndex(self, input_text, before_index):
        if self.createValidator().validate(input_text, len(input_text)) != QDoubleValidator.Invalid:
            try:
                text = input_text or '0'
                return self.valuecodec.encode(self.formatter.parse(text)), text, max(len(input_text), 1)
            except (ValueError, struct.error):
                pass
        return b'', '', -1

    @property
    def defaultInsertMode(self):
        return True

    def createValidator(self):
        return FloatColumnValidator()

class FloatColumnEditDelegate(models.StandardEditDelegate):
    @property
    def minimalCursorOffset(self):
        return len(self.data()) - len(self.data().lstrip())

class FloatColumnValidator(QValidator):
    def __init__(self):
        QValidator.__init__(self)
        self._qvalidator = QDoubleValidator()

    def validate(self, text, cursor_pos):
        adjusted_cursor_pos = cursor_pos - (len(text) - len(text.lstrip()))
        status, text, new_cursor_pos = self._qvalidator.validate(text.strip(), adjusted_cursor_pos)
        return status

class FloatColumnProvider(columnproviders.AbstractColumnProvider):
    def __init__(self):
        columnproviders.AbstractColumnProvider.__init__(self)
        self.name = utils.tr('Floating point column')
        self.columnModelType = FloatColumnModel

    def createConfigurationWidget(self, parent, hex_widget, column=None):
        return FloatColumnConfigurationWidget(parent, hex_widget, column)

class FloatColumnConfigurationWidget(QWidget, columnproviders.AbstractColumnConfigurationWidget):
    def __init__(self, parent, hex_widget, column):
        QWidget.__init__(self, parent)
        columnproviders.AbstractColumnConfigurationWidget.__init__(self)
        self.hexWidget = hex_widget
        self.column = column

        self.cmbBinaryFormat = QComboBox(self)
        self.cmbBinaryFormat.setSizePolicy(QSizePolicy.Expanding, QSizePolicy.Preferred)

        for fmt in (valuecodecs.FloatCodec.FormatFloat, valuecodecs.FloatCodec.FormatDouble):
            self.cmbBinaryFormat.addItem(valuecodecs.FloatCodec.formatName(fmt), fmt)
            if column is not None and column.valuecodec.binaryFormat == fmt:
                self.cmbBinaryFormat.setCurrentIndex(self.cmbBinaryFormat.count() - 1)

        self.spnPrecision = QSpinBox(self)
        self.spnPrecision.setMinimum(0)
        self.spnPrecision.setMaximum(12)
        if column is not None:
            self.spnPrecision.setValue(column.formatter.precision)
        else:
            self.spnPrecision.setValue(6)

        self.spnColumnsOnRow = QSpinBox(self)
        self.spnColumnsOnRow.setSizePolicy(QSizePolicy.Expanding, QSizePolicy.Preferred)
        self.spnColumnsOnRow.setMinimum(1)
        self.spnColumnsOnRow.setMaximum(32)
        if column is not None:
            self.spnColumnsOnRow.setValue(column.columnsOnRow)
        else:
            self.spnColumnsOnRow.setValue(4)

        self.setLayout(QFormLayout())
        self.layout().setContentsMargins(0, 0, 0, 0)
        self.layout().addRow(utils.tr('Binary format:'), self.cmbBinaryFormat)
        self.layout().addRow(utils.tr('Digits after point:'), self.spnPrecision)
        self.layout().addRow(utils.tr('Columns on row:'), self.spnColumnsOnRow)

    @property
    def _valueCodec(self):
        c = valuecodecs.FloatCodec()
        c.binaryFormat = self.cmbBinaryFormat.itemData(self.cmbBinaryFormat.currentIndex())
        return c

    @property
    def _formatter(self):
        f = formatters.FloatFormatter()
        f.precision = self.spnPrecision.value()
        return f

    def createColumnModel(self, hex_widget):
        return FloatColumnModel(hex_widget.document, self._valueCodec, self._formatter, self.spnColumnsOnRow.value())

    def saveToColumn(self, column):
        column.valuecodec = self._valueCodec
        column.formatter = self._formatter
        column.columnsOnRow = self.spnColumnsOnRow.value()
        column.reset()


text:
const Grim = require('grim')
const {Disposable} = require('event-kit')

const AnyConstructor = Symbol('any-constructor')

// Essential: `ViewRegistry` handles the association between model and view
// types in Atom. We call this association a View Provider. As in, for a given
// model, this class can provide a view via {::getView}, as long as the
// model/view association was registered via {::addViewProvider}
//
// If you're adding your own kind of pane item, a good strategy for all but the
// simplest items is to separate the model and the view. The model handles
// application logic and is the primary point of API interaction. The view
// just handles presentation.
//
// Note: Models can be any object, but must implement a `getTitle()` function
// if they are to be displayed in a {Pane}
//
// View providers inform the workspace how your model objects should be
// presented in the DOM. A view provider must always return a DOM node, which
// makes [HTML 5 custom elements](http://www.html5rocks.com/en/tutorials/webcomponents/customelements/)
// an ideal tool for implementing views in Atom.
//
// You can access the `ViewRegistry` object via `atom.views`.
module.exports =
class ViewRegistry {
  constructor (atomEnvironment) {
    this.animationFrameRequest = null
    this.documentReadInProgress = false
    this.performDocumentUpdate = this.performDocumentUpdate.bind(this)
    this.atomEnvironment = atomEnvironment
    this.clear()
  }

  clear () {
    this.views = new WeakMap()
    this.providers = []
    this.clearDocumentRequests()
  }

  // Essential: Add a provider that will be used to construct views in the
  // workspace's view layer based on model objects in its model layer.
  //
  // ## Examples
  //
  // Text editors are divided into a model and a view layer, so when you interact
  // with methods like `atom.workspace.getActiveTextEditor()` you're only going
  // to get the model object. We display text editors on screen by teaching the
  // workspace what view constructor it should use to represent them:
  //
  // ```coffee
  // atom.views.addViewProvider TextEditor, (textEditor) ->
  //   textEditorElement = new TextEditorElement
  //   textEditorElement.initialize(textEditor)
  //   textEditorElement
  // ```
  //
  // * `modelConstructor` (optional) Constructor {Function} for your model. If
  //   a constructor is given, the `createView` function will only be used
  //   for model objects inheriting from that constructor. Otherwise, it will
  //   will be called for any object.
  // * `createView` Factory {Function} that is passed an instance of your model
  //   and must return a subclass of `HTMLElement` or `undefined`. If it returns
  //   `undefined`, then the registry will continue to search for other view
  //   providers.
  //
  // Returns a {Disposable} on which `.dispose()` can be called to remove the
  // added provider.
  addViewProvider (modelConstructor, createView) {
    let provider
    if (arguments.length === 1) {
      switch (typeof modelConstructor) {
        case 'function':
          provider = {createView: modelConstructor, modelConstructor: AnyConstructor}
          break
        case 'object':
          Grim.deprecate('atom.views.addViewProvider now takes 2 arguments: a model constructor and a createView function. See docs for details.')
          provider = modelConstructor
          break
        default:
          throw new TypeError('Arguments to addViewProvider must be functions')
      }
    } else {
      provider = {modelConstructor, createView}
    }

    this.providers.push(provider)
    return new Disposable(() => {
      this.providers = this.providers.filter(p => p !== provider)
    })
  }

  getViewProviderCount () {
    return this.providers.length
  }

  // Essential: Get the view associated with an object in the workspace.
  //
  // If you're just *using* the workspace, you shouldn't need to access the view
  // layer, but view layer access may be necessary if you want to perform DOM
  // manipulation that isn't supported via the model API.
  //
  // ## View Resolution Algorithm
  //
  // The view associated with the object is resolved using the following
  // sequence
  //
  //  1. Is the object an instance of `HTMLElement`? If true, return the object.
  //  2. Does the object have a method named `getElement` that returns an
  //     instance of `HTMLElement`? If true, return that value.
  //  3. Does the object have a property named `element` with a value which is
  //     an instance of `HTMLElement`? If true, return the property value.
  //  4. Is the object a jQuery object, indicated by the presence of a `jquery`
  //     property? If true, return the root DOM element (i.e. `object[0]`).
  //  5. Has a view provider been registered for the object? If true, use the
  //     provider to create a view associated with the object, and return the
  //     view.
  //
  // If no associated view is returned by the sequence an error is thrown.
  //
  // Returns a DOM element.
  getView (object) {
    if (object == null) { return }

    let view = this.views.get(object)
    if (!view) {
      view = this.createView(object)
      this.views.set(object, view)
    }
    return view
  }

  createView (object) {
    if (object instanceof HTMLElement) { return object }

    let element
    if (object && (typeof object.getElement === 'function')) {
      element = object.getElement()
      if (element instanceof HTMLElement) {
        return element
      }
    }

    if (object && object.element instanceof HTMLElement) {
      return object.element
    }

    if (object && object.jquery) {
      return object[0]
    }

    for (let provider of this.providers) {
      if (provider.modelConstructor === AnyConstructor) {
        element = provider.createView(object, this.atomEnvironment)
        if (element) { return element }
        continue
      }

      if (object instanceof provider.modelConstructor) {
        element = provider.createView && provider.createView(object, this.atomEnvironment)
        if (element) { return element }

        let ViewConstructor = provider.viewConstructor
        if (ViewConstructor) {
          element = new ViewConstructor()
          if (element.initialize) {
            element.initialize(object)
          } else if (element.setModel) {
            element.setModel(object)
          }
          return element
        }
      }
    }

    if (object && object.getViewClass) {
      let ViewConstructor = object.getViewClass()
      if (ViewConstructor) {
        const view = new ViewConstructor(object)
        return view[0]
      }
    }

    throw new Error(`Can't create a view for ${object.constructor.name} instance. Please register a view provider.`)
  }

  updateDocument (fn) {
    this.documentWriters.push(fn)
    if (!this.documentReadInProgress) { this.requestDocumentUpdate() }
    return new Disposable(() => {
      this.documentWriters = this.documentWriters.filter(writer => writer !== fn)
    })
  }

  readDocument (fn) {
    this.documentReaders.push(fn)
    this.requestDocumentUpdate()
    return new Disposable(() => {
      this.documentReaders = this.documentReaders.filter(reader => reader !== fn)
    })
  }

  getNextUpdatePromise () {
    if (this.nextUpdatePromise == null) {
      this.nextUpdatePromise = new Promise(resolve => {
        this.resolveNextUpdatePromise = resolve
      })
    }

    return this.nextUpdatePromise
  }

  clearDocumentRequests () {
    this.documentReaders = []
    this.documentWriters = []
    this.nextUpdatePromise = null
    this.resolveNextUpdatePromise = null
    if (this.animationFrameRequest != null) {
      cancelAnimationFrame(this.animationFrameRequest)
      this.animationFrameRequest = null
    }
  }

  requestDocumentUpdate () {
    if (this.animationFrameRequest == null) {
      this.animationFrameRequest = requestAnimationFrame(this.performDocumentUpdate)
    }
  }

  performDocumentUpdate () {
    const { resolveNextUpdatePromise } = this
    this.animationFrameRequest = null
    this.nextUpdatePromise = null
    this.resolveNextUpdatePromise = null

    var writer = this.documentWriters.shift()
    while (writer) {
      writer()
      writer = this.documentWriters.shift()
    }

    var reader = this.documentReaders.shift()
    this.documentReadInProgress = true
    while (reader) {
      reader()
      reader = this.documentReaders.shift()
    }
    this.documentReadInProgress = false

    // process updates requested as a result of reads
    writer = this.documentWriters.shift()
    while (writer) {
      writer()
      writer = this.documentWriters.shift()
    }

    if (resolveNextUpdatePromise) { resolveNextUpdatePromise() }
  }
}


text:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<title></title>
<meta http-equiv="Content-Type" content="text/xhtml;charset=UTF-8"/>
<link rel="stylesheet" type="text/css" href="search.css"/>

载入中...

  DEFAULT_SIZE
  atype.h

搜索中...

未找到


text:
package gov.va.cpe.vpr.queryeng.dynamic.columns;

import com.fasterxml.jackson.annotation.JsonIgnore;
import gov.va.cpe.vpr.Order;
import gov.va.cpe.vpr.Result;
import gov.va.cpe.vpr.queryeng.RenderTask;
import gov.va.hmp.healthtime.PointInTime;
import gov.va.hmp.healthtime.Precision;
import gov.va.hmp.healthtime.format.PointInTimeFormat;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import java.util.*;

@Component(value = "gov.va.cpe.vpr.queryeng.dynamic.columns.LabDraws")
@Scope("prototype")
public class LabDraws extends ViewDefBasedBoardColumn {

    public LabDraws() {
    	super(null);
    }

    public LabDraws(Map<String, Object> vals) {
		super(vals);
	}

	@PostConstruct
	public void init() {
		fieldName = "Lab Collections
Today";
	}

	@Override
	public String getViewdefCode() {
		return "gov.va.cpe.vpr.queryeng.OrdersViewDef";
	}

	@Override
	public String getRenderClass() {
		return "brList";
	}

	@Override
	public String getName() {
		return "Lab Collections
Today";
	}

	@JsonIgnore
	protected String uiAlias(String prop) {
		if(prop.equals("filter_group")) {
			return "";
		} else {
			return prop;
		}
	}

	// Mandatory Imaging filter
	@Override
	public Map<String, Object> getViewdefFilters() {
		/*
		 *  Mandatory displayGroup values gleaned from FileMan Laboratory structure.
		 *  TODO: Confirm that these four values cover all inpatient nursing lab draw types that will be applicable.
		 */
		viewdefFilters.put("filter_group", Arrays.asList("LAB","CH","HEMA","MI"));
		return viewdefFilters;
	}

	public boolean getTitleEditable() {
		return false;
	}

	@Override
	public String getDescription() {
		return "All lab orders that have a start time of today and fall into lab-type display groups (\"LAB\",\"CH\",\"HEMA\",\"MI\")";
	}

	public ArrayList<String> getDomainClasses() {
		ArrayList<String> rslt = new ArrayList<String>();
		rslt.add(Result.class.getSimpleName());
        rslt.add(Order.class.getSimpleName());
		return rslt;
	}

    @Override
    protected void appendResults(List results, RenderTask task, Map<String,Object> params) {
        Iterator<Map<String, Object>> iter = task.iterator();
        while(iter.hasNext()) {
            Map<String, Object> itm = iter.next();
            PointInTime start = itm.get("start")==null?PointInTime.now():new PointInTime(itm.get("start").toString());
            if(start.getDate() == PointInTime.now().getDate() && start.getMonth() == PointInTime.now().getMonth() && start.getYear() == PointInTime.now().getYear()) {
                String time = start.getPrecision().greaterThan(Precision.HOUR)?"Anytime": PointInTimeFormat.dateTime().print(start);
                String detail = (itm.get("summary")!=null?itm.get("summary"):itm.get("content")!=null?itm.get("content"):itm.get("oiName")).toString();
                results.add("<text title='"+detail+"'>"+time+"</text>
");
            }
        }
    }
}


text:
from GMXToPython import GMXToPython
from PythonToGMX import PythonToGMX
from RawElement import *
import xml.etree.ElementTree as ET
import os
import xml.dom.minidom
import shutil
import sys
import msvcrt

#import osnav
class Importer(object):
	def __init__(self):
		self._initVar()

		if self.getInput():

			self.sourcedir = self.getDir(self.sourceGMX) + os.sep
			self.targetdir = self.getDir(self.targetGMX) + os.sep

			self.source = GMXToPython(self.sourceGMX)
			self.target = GMXToPython(self.targetGMX)

			# Merge files

			self.merge()

			# Output to target

			self.writeMergedGMX()

			#copy files in GM directories

			self.copyFiles(self.source.root)
			self.copyTrees()

	def getInput(self):
		print("""GMProjectImporter

Copyright (c) 2015 Julian Pritchard

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.""")

		print("""\n\nSecond Disclaimer:
This program is a functional prototype.
It is likely that there are bugs and glitches, and things might break...
HORRIBLY.
For your own sanity please use version control or make a backup of your project\n""")

		var = input("Do you have a backup of your project? (Y/N): ")
		var = var.lower()
		if var[0] == 'y':
			print("Just remember you said you had a backup!\n")
			print("You can type exit to exit")
			print("You will need to a completely directory to the .project.gmx file")
			print("You should be entering something like:")
			print("C:\\GameDev\\MyCoolGame\\MyCoolGame.gmx\\MyCoolGame.project.gmx")
			source = input("Enter source for insert: ")
			if source.lower == 'exit':
				print("User want program to stop. Ok.")
				return False
			if '.project.gmx' not in source:
				print("This doesn't look like a .project.gmx program will now hide from user")
				return False
			else:
				target = input("Target to insert source into: ")
				if target.lower() == 'exit':
					print("Don't worry, it's me, not you")
					return False
				if '.project.gmx' not in target:
					print("Program is scared of files that aren't .project.gmx")
					print("Press any key to exit")
					return False
				else:
					self.sourceGMX = source
					self.targetGMX = target
					return True
		else:
			print("Go make a back up, or add your project to version control\nThen we can talk")
			return False

	def _initVar(self):
		self.ignoredTags = []
		self.rawfilegmx  = []
		self.hasrawfile  = []
		self.taglist     = []
		self.dircopy     = []
		self.treecopy    = []

		self.ignoredTags.append("\'Configs\'")
		self.ignoredTags.append("\'help\'")
		self.ignoredTags.append("\'TutorialState\'")

		self.hasrawfile.append("\'sprite\'")
		self.hasrawfile.append("\'background\'")
		self.hasrawfile.append("\'sound\'")
		self.hasrawfile.append("\'font\'")

		self.taglist.append("\'Configs\'")
		self.taglist.append("\'help\'")
		self.taglist.append("\'TutorialState\'")
		self.taglist.append("\'sound\'")
		self.taglist.append("\'sprite\'")
		self.taglist.append("\'background\'")
		self.taglist.append("\'object\'")
		self.taglist.append("\'room\'")
		self.taglist.append("\'trigger\'")
		self.taglist.append("\'font\'")

	def getDir(self, string):
		string = string.replace('.project.gmx', '')
		pos = 0

		if os.sep in string:
			for i in range(1, len(string)):
				if string[-i] == os.sep:
					pos = i
					break
			string = string[:len(string)-pos]
		return string

	def merge(self):
		for _1stgen in self.source.root.children:
			if _1stgen.tag not in self.ignoredTags:
				bIndex = self.findRootElementIndex(self.target.root, _1stgen.tag)
				for _2ndgen in _1stgen.children:
					if bIndex != -1:
						self.target.root.children[bIndex].children.append(_2ndgen)

	def copyFiles(self, elem):
		if elem.cleantext != "":
			if elem.tag != "\'name\'":
				# You're checking a descendant tag again a primogen
				if self.findRootElementIndex(self.target.root, elem.primogen) != -1:
					shutil.copyfile(self.sourcedir+elem.cleantext, self.targetdir + elem.cleantext)
					if elem.tag in self.hasrawfile:
						raw = RawFile(elem.tag, self.sourcedir + elem.cleantext)
						rawfiledir = elem.tag.replace("\'","")
						if rawfiledir != "sound":
							rawfiledir += "s" + os.sep
						raw.copyto(self.targetdir+rawfiledir)
				else:
					print(elem.tag,elem.cleantext)
					self.treeCopyAdd(elem.tag)
		for child in elem.children:
			self.copyFiles(child)

	def treeCopyAdd(self, tag):
		print(self.treecopy)
		tag = tag.replace("\'", "")
		if tag not in self.treecopy:
			self.treecopy.append(tag)

	def copyTrees(self):
		if self.findRootElementIndex(self.source.root, "\'datafiles\'") != -1:
			self.treecopy.append('datafile')
			for branch in self.treecopy:
				if branch != 'sound':
					branch += 's'
				shutil.copytree(self.sourcedir + branch, self.targetdir + branch)

	def findRootElementIndex(self, root, tag):
		result = -1
		for child in root.children:
			if child.tag == tag:
				return root.children.index(child)
		return result

	def findPrimogen(self, elem, string = ""):
		curElem = elem
		for i in range(elem.generation):
			if curElem.tag == "\'datafiles\'":
				string = str(curElem.attrib["name"]) + os.sep + string
			curElem = curElem.parent
		return string

	def writeMergedGMX(self):
		gmxroot = PythonToGMX(self.target.root).root
		gmx = xml.dom.minidom.parseString(ET.tostring(gmxroot))
		pretty_xml_as_string = gmx.toprettyxml()
		gmxfile = open(self.targetGMX,'w')
		gmxfile.write(pretty_xml_as_string)
		gmxfile.close()
		gmxfile = open(self.targetGMX,'r')
		lines = gmxfile.readlines()
		gmxfile.close()
		if lines[0] != "<assets>":
			lines[0] = "<!--This Document is generated by GameMaker, if you edit it by hand then you do so at your own risk!-->\n"
		gmxfile = open(self.targetGMX,'w')
		for line in lines:
			line = line.expandtabs(2)
			if line.rstrip():
				gmxfile.write(line)
		gmxfile.close()

def main():
	importer = Importer()

if __name__ == '__main__':
	main()


text:
@interface DownloadManager : NSObject

@property (strong, nonatomic) NSMutableDictionary * downloadOperationCache;
@property (strong, nonatomic) NSMutableDictionary * imageCache;
@property (strong, nonatomic) NSOperationQueue * writeToDiskQueue;

+ (instancetype)sharedDownloadManager;

- (void)downloadOperationWithURLString:(NSString *)urlString didFinished:(void (^)(UIImage * image))didFinished;
- (void)cancelDownloadOperationWithURLString:(NSString *)urlString;
@end


text:
#pragma once
#include "library/io_state.h"

namespace lean {
class elaborator_exception : public formatted_exception {
public:
    elaborator_exception(expr const & e, format const & fmt):formatted_exception(e, fmt) {}
    elaborator_exception(expr const & e, sstream const & strm):formatted_exception(e, format(strm.str())) {}
    elaborator_exception(expr const & e, char const * msg):formatted_exception(e, format(msg)) {}
};
}


text:
package grpcthrottlerserver

import (
	"golang.org/x/net/context"
	"google.golang.org/grpc"

	"github.com/youtube/vitess/go/vt/servenv"
	"github.com/youtube/vitess/go/vt/throttler"

	"github.com/youtube/vitess/go/vt/proto/throttlerdata"
	"github.com/youtube/vitess/go/vt/proto/throttlerservice"
)

// Server is the gRPC server implementation of the Throttler service.
type Server struct {
	manager throttler.Manager
}

// NewServer creates a new RPC server for a given throttler manager.
func NewServer(m throttler.Manager) *Server {
	return &Server{m}
}

// MaxRates implements the gRPC server interface. It returns the current max
// rate for each throttler of the process.
func (s *Server) MaxRates(_ context.Context, request *throttlerdata.MaxRatesRequest) (_ *throttlerdata.MaxRatesResponse, err error) {
	defer servenv.HandlePanic("throttler", &err)

	rates := s.manager.MaxRates()
	return &throttlerdata.MaxRatesResponse{
		Rates: rates,
	}, nil
}

// SetMaxRate implements the gRPC server interface. It sets the rate on all
// throttlers controlled by the manager.
func (s *Server) SetMaxRate(_ context.Context, request *throttlerdata.SetMaxRateRequest) (_ *throttlerdata.SetMaxRateResponse, err error) {
	defer servenv.HandlePanic("throttler", &err)

	names := s.manager.SetMaxRate(request.Rate)
	return &throttlerdata.SetMaxRateResponse{
		Names: names,
	}, nil
}

// StartServer registers the Server instance with the gRPC server.
func StartServer(s *grpc.Server, m throttler.Manager) {
	throttlerservice.RegisterThrottlerServer(s, NewServer(m))
}

func init() {
	servenv.OnRun(func() {
		if servenv.GRPCCheckServiceMap("throttler") {
			StartServer(servenv.GRPCServer, throttler.GlobalManager)
		}
	})
}


text:
package pokeraidbot.domain.feedback;

import com.jagrosh.jdautilities.command.CommandEvent;
import net.dv8tion.jda.api.entities.MessageEmbed;
import net.dv8tion.jda.api.events.message.guild.GuildMessageReceivedEvent;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import pokeraidbot.domain.config.LocaleService;
import pokeraidbot.infrastructure.jpa.config.Config;

import java.util.concurrent.TimeUnit;

public interface FeedbackStrategy {
    Logger LOGGER = LoggerFactory.getLogger(FeedbackStrategy.class);

    default void replyThenDeleteFeedbackAndOriginMessageAfterXTime(CommandEvent commandEvent,
                                                                   MessageEmbed messageEmbed,
                                                                   int timeToRemoveMessages,
                                                                   TimeUnit timeUnit) {
        try {
            commandEvent.reply(messageEmbed, msg -> {
                try {
                    commandEvent.getMessage().delete()
                            .queueAfter(timeToRemoveMessages, timeUnit); // Clean up origin message
                    msg.delete()
                            .queueAfter(timeToRemoveMessages, timeUnit); // Clean up feedback after x time
                } catch (Throwable t) {
                    LOGGER.warn("Exception when deleting messages in server " + msg.getGuild().getName() + ": " +
                            t.getMessage());
                }
            });
        } catch (Throwable t) {
            LOGGER.warn("Exception when replying to raw message " + commandEvent.getMessage().getContentRaw() +
                    " in server " + commandEvent.getGuild().getName() + ": " +
                    t.getMessage());
        }
    }

    default void sendMessageThenDeleteAfterXSeconds(CommandEvent commandEvent, MessageEmbed messageEmbed,
                                                    int timeToRemoveFeedback, TimeUnit timeUnit) {
        commandEvent.reply(messageEmbed, msg -> {
            msg.delete().queueAfter(timeToRemoveFeedback, timeUnit); // Clean up feedback after x time
        });
    }

    void reply(Config config, CommandEvent commandEvent, String message);

    void reply(Config config, CommandEvent commandEvent, MessageEmbed message);

    void replyError(Config config, CommandEvent commandEvent, Throwable throwable, LocaleService localeService);

    void reply(Config config, CommandEvent commandEvent, String message, int numberOfSecondsBeforeRemove,
               LocaleService localeService);

    void replyMap(Config config, CommandEvent commandEvent, MessageEmbed message);

    void replyMapInChat(Config config, CommandEvent commandEvent, MessageEmbed message);

    void handleOriginMessage(CommandEvent commandEvent);

    void handleOriginMessage(GuildMessageReceivedEvent event);

    void replyAndKeep(Config config, CommandEvent commandEvent, String message);
}


text:
package storage

import (
	"github.com/cloudconsole/cloudspider/log"
	"gopkg.in/mgo.v2/bson"
)

// Checks if the document exists with the given ID
func DocExists(id string, collName string) bool {
	coll := DBConnection().C(collName)

	query := coll.FindId(id)
	count, err := query.Count()
	if err != nil {
		log.Fatal(map[string]interface{}{
			"DBError": err,
		}, "Database error")
	}

	if count >= 1 {
		return true
	} else {
		return false
	}
}

// Get the host document by id
func GetHosts(query string) (*[]NodeDoc, error) {
	coll := DBConnection().C("hosts")

	result := []NodeDoc{}
	coll.Find(bson.M{"$text": bson.M{"$search": query}}).All(&result)

	return &result, nil
}

// Get the host document by id
func GetHostById(id string) (*NodeDoc, error) {
	coll := DBConnection().C("hosts")

	result := NodeDoc{}
	coll.Find(bson.M{"_id": id}).One(&result)

	return &result, nil
}

// Get the host document by FQDN
func GetHostByFqdn(fqdn string) (*NodeDoc, error) {
	coll := DBConnection().C("hosts")

	result := NodeDoc{}
	coll.Find(bson.M{"public_dns": fqdn}).One(&result)

	return &result, nil
}

// Get the loadbalancer by host id
func GetLbsByHostId(id string) (*[]LBDoc, error) {
	coll := DBConnection().C("lbs")

	result := []LBDoc{}
	coll.Find(bson.M{"backends": id}).All(&result)

	return &result, nil
}

// Get the DNS by host fqdn
func GetDnsByFqdn(fqdn string) (*[]DNSDoc, error) {
	coll := DBConnection().C("dns")

	result := []DNSDoc{}
	coll.Find(bson.M{"records": fqdn}).All(&result)

	return &result, nil
}


text:
using System.Collections.Generic;
using System.Linq;
using NetDevPL.Features.Facebook;

namespace NetDevPL.Features.Reporting
{
    public class FacebookStats
    {
        public List<UserKarma> UserKarma()
        {
            Repository repository = new Repository();

            var users = repository.UsersGetList();
            var likesGrouped = repository.LikesGetList().GroupBy(l => l.UserId).ToList();

            return users.Select(u => new UserKarma
            {
                Name = u.Name,
                KarmaPoints = likesGrouped.Any(lg => lg.Key == u.Id) ? likesGrouped.FirstOrDefault(lg => lg.Key == u.Id).ToList().Count : 0
            })
                .OrderByDescending(k => k.KarmaPoints)
                .ToList();
        }
    }
}


text:
/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package com.eas.client.forms;

import javax.swing.SwingConstants;

/**
 *
 * @author mg
 */
public class Orientation {

    public static final int HORIZONTAL = SwingConstants.HORIZONTAL;
    public static final int VERTICAL = SwingConstants.VERTICAL;

    public static int getHORIZONTAL() {
        return HORIZONTAL;
    }

    public static int getVERTICAL() {
        return VERTICAL;
    }
}


text:
//
//  LCBaseViewController.m
//  MoGoWeiBo
//
//  Created by 李策 on 16/4/7.
//  Copyright © 2016年 李策. All rights reserved.
//

#import "LCBaseViewController.h"
#import "MBProgressHUD.h"
#import "UIBarButtonItem+Extension.h"

@interface LCBaseViewController ()

@end

@implementation LCBaseViewController

- (void)viewDidLoad {
    [super viewDidLoad];

    /**
     *  调整导航栏对self.view.size的影响
        但是设置这两个属性之后View导航栏的透明效果就会消失
     */
//    self.edgesForExtendedLayout = UIRectEdgeNone;
//    self.automaticallyAdjustsScrollViewInsets = NO;
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(netStateChanged:) name:kNotificationNetStateChanged object:nil];
    if (self.navigationController.viewControllers.count > 1) {
         self.navigationItem.leftBarButtonItem = [UIBarButtonItem itemWithTarget:self action:@selector(backButtonAction:) image:kNavigationbar_back highImage:kNavigationbar_back_highlighted];
    }

    self.view.backgroundColor = kBgWhiteColor;

}

- (void)setRightButtonTitle:(NSString *)rightButtonTitle{
    _rightButtonTitle = rightButtonTitle;
     self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc]initWithTitle:self.rightButtonTitle style:UIBarButtonItemStyleDone target:self action:@selector(rightButtonAction:)];
    self.navigationItem.rightBarButtonItem.tintColor = kBgWhiteColor;
    [self.navigationItem.rightBarButtonItem setTitleTextAttributes:[NSDictionary dictionaryWithObjectsAndKeys:[UIFont boldSystemFontOfSize:14], NSFontAttributeName, nil] forState:UIControlStateNormal];

}

- (void)setRightButtonNormalImage:(NSString *)normalImage highImage:(NSString *)highImage{
    self.navigationItem.leftBarButtonItem = [UIBarButtonItem itemWithTarget:self action:@selector(rightButtonAction:) image:normalImage highImage:highImage];
}
- (void)backButtonAction:(UIButton *)button{

    [self.navigationController popViewControllerAnimated:YES];
}
- (void)rightButtonAction:(UIButton *)button{

}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/
/**
 *  数据请求成功的回调
 *
 *  @param reformer reformer
 */
-(void)reformerSuccessWith:(LCBaseReformer *)reformer object:(id)object{

}
/**
 *  数据请求失败的回调
 *
 *  @param reformer reformer
 */
- (void)reformerFailureWith:(LCBaseReformer *)reformer
{

}
/**
 *  读取本地缓存的回调
 *
 *  @param reformer reformer
 */
- (void)reformerGetAppCacheWith:(LCBaseReformer *)reformer{

}
#pragma mark - public methods
#pragma mark - 用HUD显示错误信息
- (void)showHudMes:(NSString *)mes hiddenDelay:(CGFloat)time
{

#pragma mark -- 解决键盘会遮挡提示信息的问题 未测试不知道会出什么问题
    UIWindow *lastWindow = [[UIApplication sharedApplication].windows  lastObject];
    MBProgressHUD *hud = [[MBProgressHUD alloc]initWithWindow:lastWindow];
    [lastWindow addSubview:hud];
//    MBProgressHUD *hud = [MBProgressHUD showHUDAddedTo:self.view animated:YES];
    hud.mode = MBProgressHUDModeText;
//        hud.labelText = mes;
    hud.animationType =   MBProgressHUDAnimationFade;

    //by guozhenqing  解决文字过多不能折行的问题
    hud.detailsLabelText = mes;
    hud.detailsLabelFont = kBigTextFont;

    hud.margin = 10.f;
    hud.removeFromSuperViewOnHide = YES;
    hud.alpha = 0.7;

    [hud show:YES];
    [hud hide:YES afterDelay:time];
}
#pragma mark - 添加错误界面
- (void)showNetExceptionOn:(UIView *)container
              refreshStyle:(RefreshStyle)style
                showHeader:(BOOL)showHeader
                showFooter:(BOOL)showfooter
                 showFrame:(CGRect)showFrame
              refreshBlock:(void(^)())refreshBlock
{
    [self.showTool showNetBreakIn:container refreshStyle:style showHeader:showHeader showFooter:showfooter showFrame:showFrame refreshBlock:refreshBlock];
}

- (void)showLoadFaildIn:(UIView *)contentV showFrame:(CGRect)rect refreshBlock:(void(^)())refreshBlock{
    [self.showTool showLoadFaildIn:contentV showFrame:rect refreshBlock:refreshBlock];
}
#pragma mark - 移除异常界面
- (void)removeExceptionFrom:(UIView *)container
{
    [self.showTool hiddenLoadFaildFrom:container];
    [self.showTool hiddenNetBreakFrom:container];
}
#pragma mark - event methods

#pragma mark - 收到网络状态改变的通知后调用的方法 此方法类去调用,将添加、刷新、消失的代码写在这个里边
- (void)netStateChanged:(NSNotification *)notification
{

    NSDictionary *info = notification.userInfo;
    if ([info[kNetStateKey] isEqualToString:kNetBroken]) {
        [self showHudMes:@"网络断开连接" hiddenDelay:1.25];
        [self netStateChangedMessage:kNetBroken];
    }else if ([info[kNetStateKey] isEqualToString:kNetConnected]){
//        [self showHudMes:@"网络回复连接" hiddenDelay:1.25];
        [self netStateChangedMessage:kNetConnected];
    }
}
- (void)netStateChangedMessage:(NSString *)netState{

}
- (void)dealloc
{
    [[NSNotificationCenter defaultCenter] removeObserver:self name:kNotificationNetStateChanged object:nil];
}

- (LCShowErrorViewTool *)showTool
{
    if (_showTool == nil) {
        _showTool = [[LCShowErrorViewTool alloc]init];
    }
    return _showTool;
}

@end


text:
import type { FunctionWithMultiCallbacks, FunctionWithMultiCallbacksReturnType, ParametersWithoutLast2 } from "./_internal";
import type { Async } from "./_types";

/**
 * @public
 *
 * Build a function that transform a multi-callback style function to a Promise version.
 *
 * @param fn - The function to promisify
 */
export default function cbpromisify<T extends FunctionWithMultiCallbacks>(fn: T): (...args: ParametersWithoutLast2<T>) => Async<FunctionWithMultiCallbacksReturnType<T>>;

/**
 * @public
 *
 * Build a function that transform a multi-callback style function to a Promise version.
 *
 * @param owner - The `this` context to use when calling `fn`
 * @param fn - The function to promisify
 */
export default function cbpromisify<O, T extends FunctionWithMultiCallbacks>(owner: O, fn: T): (...args: ParametersWithoutLast2<T>) => Async<FunctionWithMultiCallbacksReturnType<T>>;

export default function cbpromisify<T extends FunctionWithMultiCallbacks>(owner: Record<string, unknown> | undefined, fn?: T): (...args: ParametersWithoutLast2<T>) => Async<FunctionWithMultiCallbacksReturnType<T>> {
    if (typeof owner === "function" && typeof fn !== "function") {
        fn = owner;
        owner = undefined;
    }

    if (!fn) {
        throw new TypeError("fn should be provided!");
    }

    const executor = fn;
    return (...args) => {
        return new Promise((resolve, reject) => {
            executor.apply(owner, [...args, success, error]);

            function success(...results: any[]): void {
                if (results.length === 0) return resolve();
                if (results.length === 1) return resolve(results[0]);
                resolve(results as any);
            }

            function error(...errors: any[]): void {
                if (errors.length === 1) {
                    return reject(errors[0]);
                }

                reject(errors);
            }
        });
    };
}


text:
<?php

namespace common\models;

use Yii;

/**
 * This is the model class for table "gallery".
 *
 * @property integer $id
 * @property integer $gallery_category_id
 * @property string $image
 * @property string $description
 */
class Gallery extends \yii\db\ActiveRecord
{
    /**
     * @inheritdoc
     */
    public static function tableName()
    {
        return 'gallery';
    }

    /**
     * @inheritdoc
     */
    public function rules()
    {
        return [
            [['gallery_category_id'], 'integer'],
            [['image', 'description'], 'string', 'max' => 255]
        ];
    }

    /**
     * @inheritdoc
     */
    public function attributeLabels()
    {
        return [
            'id' => 'ID',
            'gallery_category_id' => 'Gallery Category ID',
            'image' => 'Image',
            'description' => 'Description',
        ];
    }

    public function foname($id){
       $folder= GalleryCategory::findOne(['id'=>$id]);
        return $folder['alias'];
    }

      public function getImgSmall() {
        if (empty($this->image)) {
            return Yii::$app->params['urlImg'] . '/150x150-noimage.jpg';
        } else {
            return Yii::$app->params['urlImg'] . '/gallery/'.$this->foname($this->gallery_category_id) .'/'. $this->id . '-150x150-' . Yii::$app->landa->urlParsing($this->image);
        }
    }

    public function getImgMedium() {
        if (empty($this->image)) {
            return Yii::$app->params['urlImg'] . '/350x350-noimage.jpg';
        } else {
            $folder= GalleryCategory::findOne(['id'=>$this->id]);
        $dd= $folder['alias'];
            return Yii::$app->params['urlImg'] . '/gallery/'.$this->foname($this->gallery_category_id) .'/'. $this->id . '-350x350-' . Yii::$app->landa->urlParsing($this->image);
        }
    }

    public function getImgBig() {
        if (empty($this->image)) {
            return Yii::$app->params['urlImg'] . '/700x700-noimage.jpg';
        } else {
            return Yii::$app->params['urlImg'] . '/gallery/'.$this->foname($this->gallery_category_id) .'/'. $this->id . '-700x700-' . Yii::$app->landa->urlParsing($this->image);
        }
    }
}


text:
<?xml version='1.0' encoding='UTF-8'?>
<ti:app xmlns:ti='http://ti.appcelerator.org'>
<!-- These values are edited/maintained by Titanium Developer -->
<id>com.appcelerator.phpmysqldemo</id>
<name>php_mysql_demo</name>
<version>1.0</version>
<publisher>marshall</publisher>
<url>www.appcelerator.com</url>
<icon>default_app_logo.png</icon>
<copyright>2010 by marshall</copyright>
<!-- Window Definition - these values can be edited -->
<window>
<id>initial</id>
<title>mysql_demo</title>
<url>app://index.html</url>
<width>400</width>
<max-width>3000</max-width>
<min-width>0</min-width>
<height>400</height>
<max-height>3000</max-height>
<min-height>0</min-height>
<fullscreen>false</fullscreen>
<resizable>true</resizable>
<chrome scrollbars="true">true</chrome>
<maximizable>true</maximizable>
<minimizable>true</minimizable>
<closeable>true</closeable>
</window>
</ti:app>


text:
import 'angular';
import Inflector from '../src/xing-inflector.js';

describe('Inflector class', function() {
  var camelCase, underscore, dasherized, humanized, plural_humanized, inflector;
  beforeEach(function() {
    inflector = new Inflector();
    camelCase = "awesomeTime";
    underscore = "awesome_time";
    humanized = "Awesome Time";
    dasherized = "awesome-time";
    plural_humanized = "Awesome Times";
  });

  it("should convert camelCase to understore", function() {
    expect(inflector.underscore(camelCase)).toEqual(underscore);
  });

  it("should convert camelCase to dasherized", function() {
    expect(inflector.dasherize(camelCase)).toEqual(dasherized);
  });

  it("should convert underscore to camelCase", function() {
    expect(inflector.camelize(underscore)).toEqual(camelCase);
  });

  it("should convert underscore to humanized", function() {
    expect(inflector.humanize(underscore)).toEqual(humanized);
  });

  it("should convert anything to a plural version", function() {
    expect(inflector.pluralize(humanized)).toEqual(plural_humanized);
  });
});


text:
namespace async_web_server_cpp
{

WebsocketConnection::WebsocketConnection(HttpConnectionPtr connection)
  : connection_(connection) {}

void WebsocketConnection::set_message_handler(MessageHandler& handler)
{
  handler_ = handler;
}

bool WebsocketConnection::sendTextMessage(const std::string& content)
{
  async_web_server_cpp::WebsocketMessage m;
  m.type = async_web_server_cpp::WebsocketMessage::type_text;
  m.content = content;
  return sendMessage(m);
}
bool WebsocketConnection::sendPingMessage(const std::string& content)
{
  async_web_server_cpp::WebsocketMessage m;
  m.type = async_web_server_cpp::WebsocketMessage::type_ping;
  m.content = content;
  return sendMessage(m);
}

bool WebsocketConnection::sendMessage(const WebsocketMessage& message)
{
  WebsocketFrame frame;
  if (frame.fromMessage(message))
  {
    return sendFrame(frame);
  }
  return false;
}

bool WebsocketConnection::sendFrame(WebsocketFrame& frame)
{
  std::vector<unsigned char> buffer;
  if (frame.serialize(buffer))
  {
    connection_->write_and_clear(buffer);
    return true;
  }
  return false;
}

void WebsocketConnection::static_handle_read(WebsocketConnectionWeakPtr weak_this, const char* begin, const char* end)
{
  WebsocketConnectionPtr _this = weak_this.lock();
  if (_this)
    _this->handle_read(begin, end);
}
void WebsocketConnection::handle_read(const char* begin, const char* end)
{
  boost::tribool frame_result;
  const char* parse_end = begin;
  while (parse_end < end)
  {
    boost::tie(frame_result, parse_end) = frame_parser_.parse(frame_, parse_end, end);
    if (frame_result)
    {
      frame_parser_.reset();
      boost::tribool message_result = frame_buffer_.consume(message_, frame_);

      if (message_result)
      {
        if (handler_)
          handler_(message_);
      }
    }
    else if (!frame_result)
    {
      frame_parser_.reset();
      message_.type = WebsocketMessage::type_unknown;
    }
  }
  WebsocketConnectionWeakPtr this_weak(shared_from_this());
  connection_->async_read(boost::bind(&WebsocketConnection::static_handle_read, this_weak, _1, _2));
}

}


text:
module Stackprofiler
  class Run
    attr_accessor :url
    attr_accessor :profile
    attr_accessor :timestamp

    def initialize(url, profile, timestamp)
      @url = url
      @profile = profile
      @timestamp = timestamp
    end

    def code_cache
      @code_cache ||= RunCodeCache.new @profile
    end

    def stacks use_weights=false
      @stacks ||= begin
        off = 0
        stacks = []
        raw = @profile[:raw]
        while off < raw.length
          len = raw[off]
          these_frames = raw[off + 1..off + len]
          weight = raw[off + len + 1]
          off += len + 2

          times = use_weights ? weight : 1
          times.times { stacks.push these_frames }
        end
        stacks
      end
    end

    def duration
      profile[:samples] * profile[:interval] / 1e6
    end

    def gem_breakdown
      bottom_frames = stacks.map &:last
      frames = bottom_frames.map {|addr| profile[:frames][addr] }

      gems = frames.map do |frame|
        case frame[:file]
          when %r{gems/(\D\w+)}
            $1
          when %r{#{RbConfig::CONFIG['rubylibdir']}}
            'stdlib'
          else
            '(app)'
        end
      end

      gems.group_by {|g| g }.map {|k, v| [k, v.count] }.sort_by(&:last).reverse.to_h
    end
  end

  class RunDataSource
    class << self
      RUNS = []

      def runs
        RUNS
      end
    end
  end
end


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace BB.Poker.Common
{
    [Serializable]
    public class ForcedPlayerLogoutNotice
    {
        public string Message { get; set; }
    }
}


text:
title: Logging
identification: logging
layout: default
---

Logging request flow

The client is using Common Logging API for .NET as an abstraction for logging. It is up to the user to implement the API with a logging framework.

Common Logging API is a lightweight infrastructure logging platform that allows developers to focus on the logging requirements instead of the logging tools and required configuration. The Common Logging API abstracts the logging requirements of any project making it easy to swap logging providers.

Enabling logging on level `DEBUG` will output results of requests, `WARN` only failed requests or worse. These loggers will be under the `Digipost.Api.Client` namespace.

Example with Log4Net

1. Let's assume that [log4net [1.2.13] 2.0.3](https://www.nuget.org/packages/log4net/2.0.3) is installed in project.
1. Since _log4net_ has version _[1.2.13]_, `Common.Logging.Log4Net1213` is the correct logging adapter. Install this package.
1. In some cases the adapter may install or update Log4Net to a incorrect version. If installing the adapter for _log4net 2.0.3_, _Common.Logging.Log4Net1213_ must be the installed version.
1. Following is a complete App.config with the Log4Net adapter containing a `RollingFileAppender`. Note the version of the adapter specified in the `<factoryAdapter/>` node:

{% highlight xml %}
<?xml version="1.0" encoding="utf-8"?>
<configuration>
  <configSections>
    <sectionGroup name="common">

    </sectionGroup>

  </configSections>

  <common>
    <logging>
      <factoryAdapter type="Common.Logging.Log4Net.Log4NetLoggerFactoryAdapter, Common.Logging.Log4net1213">
        <arg key="configType" value="INLINE" />
      </factoryAdapter>
    </logging>
  </common>

   <log4net>
    <appender name="RollingFileAppender" type="log4net.Appender.RollingFileAppender">
      <lockingModel type="log4net.Appender.FileAppender+MinimalLock" />
      <file value="${AppData}\Digipost\Client\" />
      <appendToFile value="true" />
      <rollingStyle value="Date" />
      <staticLogFileName value="false" />
      <rollingStyle value="Composite" />
      <param name="maxSizeRollBackups" value="10" />
      <datePattern value="yyyy.MM.dd' digipost-api-client-dotnet.log'" />
      <maximumFileSize value="100MB" />
      <layout type="log4net.Layout.PatternLayout">
        <conversionPattern value="%date [%thread] %-5level %logger - %message%newline" />
      </layout>
    </appender>
   <root>
      <appender-ref ref="RollingFileAppender"/>
    </root>
  </log4net>
</configuration>

{% endhighlight %}


text:
static MP_INLINE char *
mpxs_apr_sockaddr_ip_get(pTHX_ apr_sockaddr_t *sockaddr)
{
    char *addr = NULL;

    (void)apr_sockaddr_ip_get(&addr, sockaddr);

    return addr;
}


text:
from __future__ import annotations

import sys

class Letter:
    def __init__(self, letter: str, freq: int):
        self.letter: str = letter
        self.freq: int = freq
        self.bitstring: dict[str, str] = {}

    def __repr__(self) -> str:
        return f"{self.letter}:{self.freq}"

class TreeNode:
    def __init__(self, freq: int, left: Letter | TreeNode, right: Letter | TreeNode):
        self.freq: int = freq
        self.left: Letter | TreeNode = left
        self.right: Letter | TreeNode = right

def parse_file(file_path: str) -> list[Letter]:
    """
    Read the file and build a dict of all letters and their
    frequencies, then convert the dict into a list of Letters.
    """
    chars: dict[str, int] = {}
    with open(file_path) as f:
        while True:
            c = f.read(1)
            if not c:
                break
            chars[c] = chars[c] + 1 if c in chars else 1
    return sorted((Letter(c, f) for c, f in chars.items()), key=lambda l: l.freq)

def build_tree(letters: list[Letter]) -> Letter | TreeNode:
    """
    Run through the list of Letters and build the min heap
    for the Huffman Tree.
    """
    response: list[Letter | TreeNode] = letters  # type: ignore
    while len(response) > 1:
        left = response.pop(0)
        right = response.pop(0)
        total_freq = left.freq + right.freq
        node = TreeNode(total_freq, left, right)
        response.append(node)
        response.sort(key=lambda l: l.freq)
    return response[0]

def traverse_tree(root: Letter | TreeNode, bitstring: str) -> list[Letter]:
    """
    Recursively traverse the Huffman Tree to set each
    Letter's bitstring dictionary, and return the list of Letters
    """
    if isinstance(root, Letter):
        root.bitstring[root.letter] = bitstring
        return [root]
    treenode: TreeNode = root  # type: ignore
    letters = []
    letters += traverse_tree(treenode.left, bitstring + "0")
    letters += traverse_tree(treenode.right, bitstring + "1")
    return letters

def huffman(file_path: str) -> None:
    """
    Parse the file, build the tree, then run through the file
    again, using the letters dictionary to find and print out the
    bitstring for each letter.
    """
    letters_list = parse_file(file_path)
    root = build_tree(letters_list)
    letters = {
        k: v for letter in traverse_tree(root, "") for k, v in letter.bitstring.items()
    }
    print(f"Huffman Coding  of {file_path}: ")
    with open(file_path) as f:
        while True:
            c = f.read(1)
            if not c:
                break
            print(letters[c], end=" ")
    print()

if __name__ == "__main__":
    # pass the file path to the huffman function
    huffman(sys.argv[1])


text:
module MetricsSatellite
  class BrakemanCollector < Collector
    EXT = "html"

    def collect
      system(
        "brakeman",
        "--output", filepath
      )
    end
  end
end