repo_name stringlengths 4 116 | path stringlengths 4 379 | size stringlengths 1 7 | content stringlengths 3 1.05M | license stringclasses 15
values |
|---|---|---|---|---|
hechunwen/elasticsearch | core/src/main/java/org/elasticsearch/indices/InvalidAliasNameException.java | 1459 | /*
* Licensed to Elasticsearch under one or more contributor
* license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright
* ownership. Elasticsearch licenses this file to you under
* the Apache License, Version 2.0 (the "License"); you may
* not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.elasticsearch.indices;
import org.elasticsearch.common.io.stream.StreamInput;
import org.elasticsearch.index.Index;
import org.elasticsearch.index.IndexException;
import org.elasticsearch.rest.RestStatus;
import java.io.IOException;
/**
*
*/
public class InvalidAliasNameException extends IndexException {
public InvalidAliasNameException(Index index, String name, String desc) {
super(index, "Invalid alias name [" + name + "], " + desc);
}
public InvalidAliasNameException(StreamInput in) throws IOException{
super(in);
}
@Override
public RestStatus status() {
return RestStatus.BAD_REQUEST;
}
} | apache-2.0 |
AutorestCI/azure-sdk-for-node | lib/services/insights/lib/operations/index.js | 708 | /*
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for
* license information.
*
* Code generated by Microsoft (R) AutoRest Code Generator.
* Changes may cause incorrect behavior and will be lost if the code is
* regenerated.
*/
/* jshint latedef:false */
/* jshint forin:false */
/* jshint noempty:false */
'use strict';
exports.UsageMetrics = require('./usageMetrics');
exports.EventCategories = require('./eventCategories');
exports.Events = require('./events');
exports.TenantEvents = require('./tenantEvents');
exports.MetricDefinitions = require('./metricDefinitions');
exports.Metrics = require('./metrics');
| apache-2.0 |
pecko/cft | org.eclipse.cft.server.ui/src/org/eclipse/cft/server/ui/internal/Logger.java | 5681 | /*******************************************************************************
* Copyright (c) 2014 IBM Corporation and others
*
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* and Apache License v2.0 which accompanies this distribution.
*
* The Eclipse Public License is available at
*
* http://www.eclipse.org/legal/epl-v10.html
*
* and the Apache License v2.0 is available at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* You may elect to redistribute this code under either of these licenses.
*
* Contributors:
* IBM Corporation - initial API and implementation
********************************************************************************/
package org.eclipse.cft.server.ui.internal;
import java.util.Date;
import org.eclipse.osgi.service.debug.DebugOptions;
import org.eclipse.osgi.service.debug.DebugOptionsListener;
public class Logger implements DebugOptionsListener {
public void optionsChanged(DebugOptions options) {
Logger.ERROR = options.getBooleanOption(CloudFoundryServerUiPlugin.PLUGIN_ID + Logger.ERROR_LEVEL, false);
Logger.WARNING = options.getBooleanOption(CloudFoundryServerUiPlugin.PLUGIN_ID + Logger.WARNING_LEVEL, false);
Logger.INFO = options.getBooleanOption(CloudFoundryServerUiPlugin.PLUGIN_ID + Logger.INFO_LEVEL, false);
Logger.DETAILS = options.getBooleanOption(CloudFoundryServerUiPlugin.PLUGIN_ID + Logger.DETAILS_LEVEL, false);
}
/**
* Trace a specific message. Remember to always wrap this call in an if statement and check for the corresponding
* enablement flag.
*
* @param level
* The tracing level.
* @param curClass
* The class being traced.
* @param methodName
* The method being traced.
* @param msgStr
* The trace string
*/
public final static void println(final String level, @SuppressWarnings("rawtypes") Class curClass, final String methodName, final String msgStr) {
Logger.print(level, curClass, methodName, msgStr, null);
}
/**
* Trace a specific message and {@link Throwable}. Remember to always wrap this call in an if statement and check
* for the corresponding enablement flag.
*
* @param level
* The tracing level.
* @param curClass
* The class being traced.
* @param methodName
* The method being traced.
* @param msgStr
* The trace string
* @param t
* The {@link Throwable} to print as part of the tracing.
*/
public final static void println(final String level, @SuppressWarnings("rawtypes") Class curClass, final String methodName, final String msgStr,
final Throwable t) {
Logger.print(level, curClass, methodName, msgStr, t);
}
/**
* Trace a specific message. Remember to always wrap this call in an if statement and check for the corresponding
* enablement flag.
*
* @param level
* The tracing level.
* @param obj
* The {@link Object} being traced.
* @param methodName
* The method being traced.
* @param msgStr
* The trace string
*/
public final static void println(final String level, final Object obj, final String methodName, final String msgStr) {
Class<?> objClass = (obj != null) ? obj.getClass() : null;
Logger.print(level, objClass, methodName, msgStr, null);
}
/**
* Trace a specific message and {@link Throwable}. Remember to always wrap this call in an if statement and check
* for the corresponding enablement flag.
*
* @param level
* The tracing level.
* @param obj
* The {@link Object} being traced.
* @param methodName
* The method being traced.
* @param msgStr
* The trace string
* @param t
* The {@link Throwable} to print as part of the tracing.
*/
public final static void println(final String level, final Object obj, final String methodName,
final String msgStr, final Throwable t) {
Class<?> objClass = (obj != null) ? obj.getClass() : null;
Logger.print(level, objClass, methodName, msgStr, t);
}
private final static void print(final String level, final Class<?> clazz, final String methodName,
final String msgStr, final Throwable t) {
final StringBuffer printStrBuf = new StringBuffer();
printStrBuf.append(new Date());
printStrBuf.append(" "); //$NON-NLS-1$
printStrBuf.append(level);
printStrBuf.append(" "); //$NON-NLS-1$
if (clazz != null) {
printStrBuf.append(clazz.getName());
}
if (methodName != null) {
printStrBuf.append("."); //$NON-NLS-1$
printStrBuf.append(methodName);
printStrBuf.append(": "); //$NON-NLS-1$
}
if (msgStr != null) {
printStrBuf.append(msgStr);
}
// write the output to the System.out stream
System.out.println(printStrBuf.toString());
if (t != null) {
System.out.print(level + " " + t); //$NON-NLS-1$
t.printStackTrace(System.out);
}
}
// tracing enablement flags
public static boolean ERROR = false;
public static boolean WARNING = false;
public static boolean INFO = false;
public static boolean DETAILS = false;
// tracing levels
public final static String ERROR_LEVEL = "/debug/error"; //$NON-NLS-1$
public final static String WARNING_LEVEL = "/debug/warning"; //$NON-NLS-1$
public final static String INFO_LEVEL = "/debug/info"; //$NON-NLS-1$
public final static String DETAILS_LEVEL = "/debug/details"; //$NON-NLS-1$
} | apache-2.0 |
EivindEE/a-cms | public/redactor/langs/ua.js | 2565 | var RELANG = {};
RELANG['ua'] = {
html: 'Код',
video: 'Відео',
image: 'Зображення',
table: 'Таблиця',
link: 'Посилання',
link_insert: 'Вставити посилання ...',
unlink: 'Видалити посилання',
formatting: 'Стилі',
paragraph: 'Звичайний текст',
quote: 'Цитата',
code: 'Код',
header1: 'Заголовок 1',
header2: 'Заголовок 2',
header3: 'Заголовок 3',
header4: 'Заголовок 4',
bold: 'Жирний',
italic: 'Похилий',
fontcolor: 'Колір тексту',
backcolor: 'Заливка тексту',
unorderedlist: 'Звичайний список',
orderedlist: 'Нумерований список',
outdent: 'Зменшити відступ',
indent: 'Збільшити відступ',
cancel: 'Скасувати',
insert: 'Вставити',
save: 'Зберегти',
_delete: 'Видалити',
insert_table: 'Вставити таблицю',
insert_row_above: 'Додати рядок зверху',
insert_row_below: 'Додати рядок знизу',
insert_column_left: 'Додати стовпець ліворуч',
insert_column_right: 'Додати стовпець праворуч',
delete_column: 'Видалити стовпець',
delete_row: 'Видалити рядок',
delete_table: 'Видалити таблицю',
rows: 'Рядки',
columns: 'Стовпці',
add_head: 'Додати заголовок',
delete_head: 'Видалити заголовок',
title: 'Підказка',
image_view: 'Завантажити зображення',
image_position: 'Обтікання текстом',
none: 'ні',
left: 'ліворуч',
right: 'праворуч',
image_web_link: 'Посилання на зображення',
text: 'Текст',
mailto: 'Ел. пошта',
web: 'URL',
video_html_code: 'Код відео ролика',
file: 'Файл',
upload: 'Завантажити',
download: 'Завантажити',
choose: 'Вибрати',
or_choose: 'Або виберіть',
drop_file_here: 'Перетягніть файл сюди',
align_left: 'По лівому краю',
align_center: 'По центру',
align_right: 'По правому краю',
align_justify: 'Вирівняти текст по ширині',
horizontalrule: 'Горизонтальная лінійка',
fullscreen: 'На весь екран',
deleted: 'Закреслений',
anchor: 'Anchor'
}; | apache-2.0 |
leandrocr/kops | cmd/kops/get_federation.go | 2665 | /*
Copyright 2016 The Kubernetes Authors.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package main
import (
"fmt"
"io"
"os"
"strings"
"github.com/spf13/cobra"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
api "k8s.io/kops/pkg/apis/kops"
"k8s.io/kops/util/pkg/tables"
)
type GetFederationOptions struct {
}
func init() {
var options GetFederationOptions
cmd := &cobra.Command{
Use: "federations",
Aliases: []string{"federation"},
Short: "get federations",
Long: `List or get federations.`,
Run: func(cmd *cobra.Command, args []string) {
err := RunGetFederations(&rootCommand, os.Stdout, &options)
if err != nil {
exitWithError(err)
}
},
}
getCmd.cobraCommand.AddCommand(cmd)
}
func RunGetFederations(context Factory, out io.Writer, options *GetFederationOptions) error {
client, err := context.Clientset()
if err != nil {
return err
}
list, err := client.Federations().List(metav1.ListOptions{})
if err != nil {
return err
}
var federations []*api.Federation
for i := range list.Items {
federations = append(federations, &list.Items[i])
}
if len(federations) == 0 {
fmt.Fprintf(out, "No federations found\n")
return nil
}
switch getCmd.output {
case OutputTable:
t := &tables.Table{}
t.AddColumn("NAME", func(f *api.Federation) string {
return f.ObjectMeta.Name
})
t.AddColumn("CONTROLLERS", func(f *api.Federation) string {
return strings.Join(f.Spec.Controllers, ",")
})
t.AddColumn("MEMBERS", func(f *api.Federation) string {
return strings.Join(f.Spec.Members, ",")
})
return t.Render(federations, out, "NAME", "CONTROLLERS", "MEMBERS")
case OutputYaml:
for i, f := range federations {
if i != 0 {
_, err = out.Write([]byte("\n\n---\n\n"))
if err != nil {
return fmt.Errorf("error writing to stdout: %v", err)
}
}
if err := marshalToWriter(f, marshalYaml, os.Stdout); err != nil {
return err
}
}
case OutputJSON:
for _, f := range federations {
if err := marshalToWriter(f, marshalJSON, os.Stdout); err != nil {
return err
}
}
default:
return fmt.Errorf("Unknown output format: %q", getCmd.output)
}
return nil
}
| apache-2.0 |
vsch/pegdown | src/main/java/org/pegdown/PegDownProcessor.java | 7387 | /*
* Copyright (C) 2010-2011 Mathias Doenitz
*
* Based on peg-markdown (C) 2008-2010 John MacFarlane
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.pegdown;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import org.parboiled.Parboiled;
import org.pegdown.ast.RootNode;
import org.pegdown.plugins.PegDownPlugins;
import org.pegdown.plugins.ToHtmlSerializerPlugin;
/**
* A clean and lightweight Markdown-to-HTML filter based on a PEG parser implemented with parboiled.
* Note: A PegDownProcessor is not thread-safe (since it internally reused the parboiled parser instance).
* If you need to process markdown source in parallel create one PegDownProcessor per thread!
*
* @see <a href="http://daringfireball.net/projects/markdown/">Markdown</a>
* @see <a href="http://www.parboiled.org/">parboiled.org</a>
*/
public class PegDownProcessor {
public static final long DEFAULT_MAX_PARSING_TIME = 2000;
public final Parser parser;
/**
* Creates a new processor instance without any enabled extensions and the default parsing timeout.
*/
public PegDownProcessor() {
this(DEFAULT_MAX_PARSING_TIME);
}
/**
* Creates a new processor instance without any enabled extensions and the given parsing timeout.
*/
public PegDownProcessor(long maxParsingTimeInMillis) {
this(Extensions.NONE, maxParsingTimeInMillis);
}
/**
* Creates a new processor instance with the given {@link org.pegdown.Extensions} and the default parsing timeout.
*
* @param options the flags of the extensions to enable as a bitmask
*/
public PegDownProcessor(int options) {
this(options, DEFAULT_MAX_PARSING_TIME, PegDownPlugins.NONE);
}
/**
* Creates a new processor instance with the given {@link org.pegdown.Extensions} and parsing timeout.
*
* @param options the flags of the extensions to enable as a bitmask
* @param maxParsingTimeInMillis the parsing timeout
*/
public PegDownProcessor(int options, long maxParsingTimeInMillis) {
this(options, maxParsingTimeInMillis, PegDownPlugins.NONE);
}
/**
* Creates a new processor instance with the given {@link org.pegdown.Extensions} and plugins.
*
* @param options the flags of the extensions to enable as a bitmask
* @param plugins the plugins to use
*/
public PegDownProcessor(int options, PegDownPlugins plugins) {
this(options, DEFAULT_MAX_PARSING_TIME, plugins);
}
/**
* Creates a new processor instance with the given {@link org.pegdown.Extensions}, parsing timeout and plugins.
*
* @param options the flags of the extensions to enable as a bitmask
* @param maxParsingTimeInMillis the parsing timeout
* @param plugins the plugins to use
*/
public PegDownProcessor(int options, long maxParsingTimeInMillis, PegDownPlugins plugins) {
this(Parboiled.createParser(Parser.class, options, maxParsingTimeInMillis, Parser.DefaultParseRunnerProvider, plugins));
}
/**
* Creates a new processor instance using the given Parser.
*
* @param parser the parser instance to use
*/
public PegDownProcessor(Parser parser) {
this.parser = parser;
}
/**
* Converts the given markdown source to HTML.
* If the input cannot be parsed within the configured parsing timeout the method returns null.
*
* @param markdownSource the markdown source to convert
* @return the HTML
*/
public String markdownToHtml(String markdownSource) {
return markdownToHtml(markdownSource.toCharArray());
}
/**
* Converts the given markdown source to HTML.
* If the input cannot be parsed within the configured parsing timeout the method returns null.
*
* @param markdownSource the markdown source to convert
* @param linkRenderer the LinkRenderer to use
* @return the HTML
*/
public String markdownToHtml(String markdownSource, LinkRenderer linkRenderer) {
return markdownToHtml(markdownSource.toCharArray(), linkRenderer);
}
public String markdownToHtml(String markdownSource, LinkRenderer linkRenderer, Map<String, VerbatimSerializer> verbatimSerializerMap) {
return markdownToHtml(markdownSource.toCharArray(), linkRenderer, verbatimSerializerMap);
}
/**
* Converts the given markdown source to HTML.
* If the input cannot be parsed within the configured parsing timeout the method returns null.
*
* @param markdownSource the markdown source to convert
* @return the HTML
*/
public String markdownToHtml(char[] markdownSource) {
return markdownToHtml(markdownSource, new LinkRenderer());
}
/**
* Converts the given markdown source to HTML.
* If the input cannot be parsed within the configured parsing timeout the method returns null.
*
* @param markdownSource the markdown source to convert
* @param linkRenderer the LinkRenderer to use
* @return the HTML
*/
public String markdownToHtml(char[] markdownSource, LinkRenderer linkRenderer) {
return markdownToHtml(markdownSource, linkRenderer, Collections.<String, VerbatimSerializer>emptyMap());
}
public String markdownToHtml(char[] markdownSource, LinkRenderer linkRenderer, Map<String, VerbatimSerializer> verbatimSerializerMap) {
return markdownToHtml(markdownSource, linkRenderer,
verbatimSerializerMap, parser.plugins.getHtmlSerializerPlugins());
}
public String markdownToHtml(char[] markdownSource,
LinkRenderer linkRenderer,
Map<String, VerbatimSerializer> verbatimSerializerMap,
List<ToHtmlSerializerPlugin> plugins) {
try {
RootNode astRoot = parseMarkdown(markdownSource);
return new ToHtmlSerializer(linkRenderer, verbatimSerializerMap, plugins).toHtml(astRoot);
} catch(ParsingTimeoutException e) {
return null;
}
}
/**
* Parses the given markdown source and returns the root node of the generated Abstract Syntax Tree.
* If the input cannot be parsed within the configured parsing timeout the method throws a ParsingTimeoutException.
*
* @param markdownSource the markdown source to convert
* @return the AST root
*/
public RootNode parseMarkdown(char[] markdownSource) {
return parser.parse(prepareSource(markdownSource));
}
/**
* Adds two trailing newlines.
*
* @param source the markdown source to process
* @return the processed source
*/
public char[] prepareSource(char[] source) {
char[] src = new char[source.length + 2];
System.arraycopy(source, 0, src, 0, source.length);
src[source.length] = '\n';
src[source.length + 1] = '\n';
return src;
}
}
| apache-2.0 |
thariyarox/carbon-identity | components/authentication-framework/org.wso2.carbon.identity.application.authentication.framework/src/main/java/org/wso2/carbon/identity/application/authentication/framework/inbound/InboundAuthenticationConstants.java | 1535 | /*
* Copyright (c) 2015, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
*
* WSO2 Inc. licenses this file to you under the Apache License,
* Version 2.0 (the "License"); you may not use this file except
* in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.wso2.carbon.identity.application.authentication.framework.inbound;
public final class InboundAuthenticationConstants {
public final static String HTTP_PATH_PARAM_REQUEST = "/request";
public final static String HTTP_PATH_PARAM_RESPONSE = "/response";
public static class StatusCode {
public static final int SUCCESS = 200;
public static final int REDIRECT = 302;
public static final int ERROR = 500;
private StatusCode() {
}
}
public static class RequestProcessor {
public static final String RELYING_PARTY = "RelyingPartyId";
public static final String CALL_BACK_PATH = "CallBackPath";
public static final String AUTH_NAME = "Name";
public static final String SESSION_DATA_KEY = "sessionDataKey";
private RequestProcessor() {
}
}
} | apache-2.0 |
consulo/consulo-java | java-analysis-impl/testsrc/com/siyeh/ig/assignment/AssignmentToSuperclassFieldInspectionTest.java | 929 | /*
* Copyright 2000-2013 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.siyeh.ig.assignment;
import com.siyeh.ig.IGInspectionTestCase;
public class AssignmentToSuperclassFieldInspectionTest extends IGInspectionTestCase {
public void test() throws Exception {
doTest("com/siyeh/igtest/assignment/assignment_to_superclass_field", new AssignmentToSuperclassFieldInspection());
}
} | apache-2.0 |
jackgr/kubernetes | pkg/api/copy_test.go | 2014 | /*
Copyright 2015 The Kubernetes Authors All rights reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package api_test
import (
"math/rand"
"reflect"
"testing"
"k8s.io/kubernetes/pkg/api"
"k8s.io/kubernetes/pkg/api/testapi"
apitesting "k8s.io/kubernetes/pkg/api/testing"
"k8s.io/kubernetes/pkg/api/unversioned"
"k8s.io/kubernetes/pkg/util"
"github.com/google/gofuzz"
)
func TestDeepCopyApiObjects(t *testing.T) {
for i := 0; i < *fuzzIters; i++ {
for _, gv := range []unversioned.GroupVersion{testapi.Default.InternalGroupVersion(), *testapi.Default.GroupVersion()} {
f := apitesting.FuzzerFor(t, gv.String(), rand.NewSource(rand.Int63()))
for kind := range api.Scheme.KnownTypes(gv) {
doDeepCopyTest(t, gv.String(), kind, f)
}
}
}
}
func doDeepCopyTest(t *testing.T, version, kind string, f *fuzz.Fuzzer) {
item, err := api.Scheme.New(version, kind)
if err != nil {
t.Fatalf("Could not create a %s: %s", kind, err)
}
f.Fuzz(item)
itemCopy, err := api.Scheme.DeepCopy(item)
if err != nil {
t.Errorf("Could not deep copy a %s: %s", kind, err)
return
}
if !reflect.DeepEqual(item, itemCopy) {
t.Errorf("\nexpected: %#v\n\ngot: %#v\n\ndiff: %v", item, itemCopy, util.ObjectDiff(item, itemCopy))
}
}
func TestDeepCopySingleType(t *testing.T) {
for i := 0; i < *fuzzIters; i++ {
for _, version := range []string{"", testapi.Default.Version()} {
f := apitesting.FuzzerFor(t, version, rand.NewSource(rand.Int63()))
doDeepCopyTest(t, version, "Pod", f)
}
}
}
| apache-2.0 |
mfraezz/osf.io | tests/identifiers/test_crossref.py | 13143 | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
import os
import mock
import lxml
import pytest
import responses
from nose.tools import * # noqa
from website import settings
from website.identifiers.clients import crossref
from osf.models import NodeLicense
from osf_tests.factories import (
ProjectFactory,
PreprintFactory,
PreprintProviderFactory,
AuthUserFactory
)
from framework.flask import rm_handlers
from framework.auth.core import Auth
from framework.auth.utils import impute_names
@pytest.fixture()
def crossref_client():
return crossref.CrossRefClient(base_url='http://test.osf.crossref.test')
@pytest.fixture()
def preprint():
node_license = NodeLicense.objects.get(name='CC-By Attribution 4.0 International')
user = AuthUserFactory()
provider = PreprintProviderFactory()
provider.doi_prefix = '10.31219'
provider.save()
license_details = {
'id': node_license.license_id,
'year': '2017',
'copyrightHolders': ['Jeff Hardy', 'Matt Hardy']
}
preprint = PreprintFactory(provider=provider, article_doi='10.31219/FK2osf.io/test!', is_published=True, license_details=license_details)
preprint.license.node_license.url = 'https://creativecommons.org/licenses/by/4.0/legalcode'
return preprint
@pytest.fixture()
def crossref_success_response():
return b"""
\n\n\n\n<html>\n<head><title>SUCCESS</title>\n</head>\n<body>\n<h2>SUCCESS</h2>\n<p>
Your batch submission was successfully received.</p>\n</body>\n</html>\n
"""
@pytest.mark.django_db
class TestCrossRefClient:
@responses.activate
def test_crossref_create_identifiers(self, preprint, crossref_client, crossref_success_response):
responses.add(
responses.Response(
responses.POST,
crossref_client.base_url,
body=crossref_success_response,
content_type='text/html;charset=ISO-8859-1',
status=200,
),
)
res = crossref_client.create_identifier(preprint=preprint, category='doi')
doi = settings.DOI_FORMAT.format(prefix=preprint.provider.doi_prefix, guid=preprint._id)
assert res['doi'] == doi
@responses.activate
def test_crossref_update_identifier(self, preprint, crossref_client, crossref_success_response):
responses.add(
responses.Response(
responses.POST,
crossref_client.base_url,
body=crossref_success_response,
content_type='text/html;charset=ISO-8859-1',
status=200
)
)
res = crossref_client.update_identifier(preprint, category='doi')
doi = settings.DOI_FORMAT.format(prefix=preprint.provider.doi_prefix, guid=preprint._id)
assert res['doi'] == doi
def test_crossref_build_doi(self, crossref_client, preprint):
doi_prefix = preprint.provider.doi_prefix
assert crossref_client.build_doi(preprint) == settings.DOI_FORMAT.format(prefix=doi_prefix, guid=preprint._id)
def test_crossref_build_metadata(self, crossref_client, preprint):
test_email = 'test-email@osf.io'
with mock.patch('website.settings.CROSSREF_DEPOSITOR_EMAIL', test_email):
crossref_xml = crossref_client.build_metadata(preprint, pretty_print=True)
root = lxml.etree.fromstring(crossref_xml)
# header
assert root.find('.//{%s}doi_batch_id' % crossref.CROSSREF_NAMESPACE).text == preprint._id
assert root.find('.//{%s}depositor_name' % crossref.CROSSREF_NAMESPACE).text == crossref.CROSSREF_DEPOSITOR_NAME
assert root.find('.//{%s}email_address' % crossref.CROSSREF_NAMESPACE).text == test_email
# body
contributors = root.find('.//{%s}contributors' % crossref.CROSSREF_NAMESPACE)
assert len(contributors.getchildren()) == len(preprint.visible_contributors)
assert root.find('.//{%s}group_title' % crossref.CROSSREF_NAMESPACE).text == preprint.provider.name
assert root.find('.//{%s}title' % crossref.CROSSREF_NAMESPACE).text == preprint.title
assert root.find('.//{%s}item_number' % crossref.CROSSREF_NAMESPACE).text == 'osf.io/{}'.format(preprint._id)
assert root.find('.//{%s}abstract/' % crossref.JATS_NAMESPACE).text == preprint.description
assert root.find('.//{%s}license_ref' % crossref.CROSSREF_ACCESS_INDICATORS).text == 'https://creativecommons.org/licenses/by/4.0/legalcode'
assert root.find('.//{%s}license_ref' % crossref.CROSSREF_ACCESS_INDICATORS).get('start_date') == preprint.date_published.strftime('%Y-%m-%d')
assert root.find('.//{%s}intra_work_relation' % crossref.CROSSREF_RELATIONS).text == preprint.article_doi
assert root.find('.//{%s}doi' % crossref.CROSSREF_NAMESPACE).text == settings.DOI_FORMAT.format(prefix=preprint.provider.doi_prefix, guid=preprint._id)
assert root.find('.//{%s}resource' % crossref.CROSSREF_NAMESPACE).text == settings.DOMAIN + preprint._id
metadata_date_parts = [elem.text for elem in root.find('.//{%s}posted_date' % crossref.CROSSREF_NAMESPACE)]
preprint_date_parts = preprint.date_published.strftime('%Y-%m-%d').split('-')
assert set(metadata_date_parts) == set(preprint_date_parts)
@responses.activate
@mock.patch('osf.models.preprint.update_or_enqueue_on_preprint_updated', mock.Mock())
def test_metadata_for_deleted_node(self, crossref_client, preprint):
responses.add(
responses.Response(
responses.POST,
crossref_client.base_url,
body=crossref_success_response,
content_type='text/html;charset=ISO-8859-1',
status=200
)
)
with mock.patch('osf.models.Preprint.get_doi_client') as mock_get_doi_client:
mock_get_doi_client.return_value = crossref_client
preprint.is_public = False
preprint.save()
crossref_xml = crossref_client.build_metadata(preprint, status='unavailable')
root = lxml.etree.fromstring(crossref_xml)
# body
assert not root.find('.//{%s}contributors' % crossref.CROSSREF_NAMESPACE)
assert root.find('.//{%s}group_title' % crossref.CROSSREF_NAMESPACE).text == preprint.provider.name
assert not root.find('.//{%s}title' % crossref.CROSSREF_NAMESPACE).text
assert not root.find('.//{%s}abstract/' % crossref.JATS_NAMESPACE)
assert not root.find('.//{%s}license_ref' % crossref.CROSSREF_ACCESS_INDICATORS)
assert root.find('.//{%s}doi' % crossref.CROSSREF_NAMESPACE).text == settings.DOI_FORMAT.format(prefix=preprint.provider.doi_prefix, guid=preprint._id)
assert not root.find('.//{%s}resource' % crossref.CROSSREF_NAMESPACE)
def test_process_crossref_name(self, crossref_client):
contributor = AuthUserFactory()
# Given name and no family name
contributor.given_name = 'Hey'
contributor.family_name = ''
contributor.save()
meta = crossref_client._process_crossref_name(contributor)
imputed_names = impute_names(contributor.fullname)
assert meta == {'surname': imputed_names['family'], 'given_name': imputed_names['given']}
# Just one name
contributor.fullname = 'Ke$ha'
contributor.given_name = ''
contributor.family_name = ''
contributor.save()
meta = crossref_client._process_crossref_name(contributor)
assert meta == {'surname': contributor.fullname}
# Number and ? in given name
contributor.fullname = 'Scotty2Hotty? Ronald Garland II'
contributor.given_name = ''
contributor.family_name = ''
contributor.save()
meta = crossref_client._process_crossref_name(contributor)
assert meta == {'given_name': 'ScottyHotty Ronald', 'surname': 'Garland', 'suffix': 'II'}
# Long suffix is truncated to 10 characters
long_suffix = 'PhD MD Esq MPH IV'
contributor.given_name = 'Mark'
contributor.family_name = 'Henry'
contributor.suffix = long_suffix
contributor.save()
meta = crossref_client._process_crossref_name(contributor)
assert meta['suffix'] == long_suffix[:crossref.CROSSREF_SUFFIX_LIMIT]
# Long given_names and surnames are truncated to limit
long_given = 'Maaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaark'
long_surname = 'Henryyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyy'
contributor.given_name = long_given
contributor.family_name = long_surname
contributor.save()
meta = crossref_client._process_crossref_name(contributor)
assert meta['given_name'] == long_given[:crossref.CROSSREF_GIVEN_NAME_LIMIT]
assert meta['surname'] == long_surname[:crossref.CROSSREF_SURNAME_LIMIT]
# Unparsable given or surname just returns fullname as surname
unparsable_fullname = 'Author (name withheld until double-blind peer review completes and this name is also really long)'
contributor.given_name = ''
contributor.family_name = ''
contributor.fullname = unparsable_fullname
contributor.save()
meta = crossref_client._process_crossref_name(contributor)
assert meta == {'surname': unparsable_fullname[:crossref.CROSSREF_SURNAME_LIMIT]}
def test_metadata_for_single_name_contributor_only_has_surname(self, crossref_client, preprint):
contributor = preprint.creator
contributor.fullname = 'Madonna'
contributor.given_name = ''
contributor.family_name = ''
contributor.save()
crossref_xml = crossref_client.build_metadata(preprint, pretty_print=True)
root = lxml.etree.fromstring(crossref_xml)
contributors = root.find('.//{%s}contributors' % crossref.CROSSREF_NAMESPACE)
assert contributors.find('.//{%s}surname' % crossref.CROSSREF_NAMESPACE).text == 'Madonna'
assert not contributors.find('.//{%s}given_name' % crossref.CROSSREF_NAMESPACE)
def test_metadata_contributor_orcid(self, crossref_client, preprint):
ORCID = '1234-5678-2345-6789'
# verified ORCID
contributor = preprint.creator
contributor.external_identity = {
'ORCID': {
ORCID: 'VERIFIED'
}
}
contributor.save()
crossref_xml = crossref_client.build_metadata(preprint, pretty_print=True)
root = lxml.etree.fromstring(crossref_xml)
contributors = root.find('.//{%s}contributors' % crossref.CROSSREF_NAMESPACE)
assert contributors.find('.//{%s}ORCID' % crossref.CROSSREF_NAMESPACE).text == 'https://orcid.org/{}'.format(ORCID)
assert contributors.find('.//{%s}ORCID' % crossref.CROSSREF_NAMESPACE).attrib == {'authenticated': 'true'}
# unverified (only in profile)
contributor.external_identity = {}
contributor.social = {
'orcid': ORCID
}
contributor.save()
crossref_xml = crossref_client.build_metadata(preprint, pretty_print=True)
root = lxml.etree.fromstring(crossref_xml)
contributors = root.find('.//{%s}contributors' % crossref.CROSSREF_NAMESPACE)
assert contributors.find('.//{%s}ORCID' % crossref.CROSSREF_NAMESPACE) is None
def test_metadata_none_license_update(self, crossref_client, preprint):
crossref_xml = crossref_client.build_metadata(preprint, pretty_print=True)
root = lxml.etree.fromstring(crossref_xml)
assert root.find('.//{%s}license_ref' % crossref.CROSSREF_ACCESS_INDICATORS).text == 'https://creativecommons.org/licenses/by/4.0/legalcode'
assert root.find('.//{%s}license_ref' % crossref.CROSSREF_ACCESS_INDICATORS).get('start_date') == preprint.date_published.strftime('%Y-%m-%d')
license_detail = {
'copyrightHolders': ['The Carters'],
'id': 'NONE',
'year': '2018'
}
preprint.set_preprint_license(license_detail, Auth(preprint.creator), save=True)
crossref_xml = crossref_client.build_metadata(preprint, pretty_print=True)
root = lxml.etree.fromstring(crossref_xml)
assert root.find('.//{%s}license_ref' % crossref.CROSSREF_ACCESS_INDICATORS) is None
assert root.find('.//{%s}program' % crossref.CROSSREF_ACCESS_INDICATORS).getchildren() == []
def test_metadata_for_non_included_relation(self, crossref_client, preprint):
crossref_xml = crossref_client.build_metadata(preprint)
root = lxml.etree.fromstring(crossref_xml)
assert root.find('.//{%s}intra_work_relation' % crossref.CROSSREF_RELATIONS).text == preprint.article_doi
xml_without_relation = crossref_client.build_metadata(preprint, include_relation=False)
root_without_relation = lxml.etree.fromstring(xml_without_relation)
assert root_without_relation.find('.//{%s}intra_work_relation' % crossref.CROSSREF_RELATIONS) is None
| apache-2.0 |
ravisantoshgudimetla/kubernetes | openshift-kube-apiserver/authorization/scopeauthorizer/authorizer_test.go | 5188 | package scopeauthorizer
import (
"context"
"strings"
"testing"
"k8s.io/apiserver/pkg/authentication/user"
kauthorizer "k8s.io/apiserver/pkg/authorization/authorizer"
authorizationv1 "github.com/openshift/api/authorization/v1"
)
func TestAuthorize(t *testing.T) {
testCases := []struct {
name string
attributes kauthorizer.AttributesRecord
expectedAllowed kauthorizer.Decision
expectedErr string
expectedMsg string
}{
{
name: "no user",
attributes: kauthorizer.AttributesRecord{
ResourceRequest: true,
Namespace: "ns",
},
expectedAllowed: kauthorizer.DecisionNoOpinion,
expectedErr: `user missing from context`,
},
{
name: "no extra",
attributes: kauthorizer.AttributesRecord{
User: &user.DefaultInfo{},
ResourceRequest: true,
Namespace: "ns",
},
expectedAllowed: kauthorizer.DecisionNoOpinion,
},
{
name: "empty extra",
attributes: kauthorizer.AttributesRecord{
User: &user.DefaultInfo{Extra: map[string][]string{}},
ResourceRequest: true,
Namespace: "ns",
},
expectedAllowed: kauthorizer.DecisionNoOpinion,
},
{
name: "empty scopes",
attributes: kauthorizer.AttributesRecord{
User: &user.DefaultInfo{Extra: map[string][]string{authorizationv1.ScopesKey: {}}},
ResourceRequest: true,
Namespace: "ns",
},
expectedAllowed: kauthorizer.DecisionNoOpinion,
},
{
name: "bad scope",
attributes: kauthorizer.AttributesRecord{
User: &user.DefaultInfo{Extra: map[string][]string{authorizationv1.ScopesKey: {"does-not-exist"}}},
ResourceRequest: true,
Namespace: "ns",
},
expectedAllowed: kauthorizer.DecisionDeny,
expectedMsg: `scopes [does-not-exist] prevent this action, additionally the following non-fatal errors were reported: no scope evaluator found for "does-not-exist"`,
},
{
name: "bad scope 2",
attributes: kauthorizer.AttributesRecord{
User: &user.DefaultInfo{Extra: map[string][]string{authorizationv1.ScopesKey: {"role:dne"}}},
ResourceRequest: true,
Namespace: "ns",
},
expectedAllowed: kauthorizer.DecisionDeny,
expectedMsg: `scopes [role:dne] prevent this action, additionally the following non-fatal errors were reported: bad format for scope role:dne`,
},
{
name: "scope doesn't cover",
attributes: kauthorizer.AttributesRecord{
User: &user.DefaultInfo{Extra: map[string][]string{authorizationv1.ScopesKey: {"user:info"}}},
ResourceRequest: true,
Namespace: "ns",
Verb: "get", Resource: "users", Name: "harold"},
expectedAllowed: kauthorizer.DecisionDeny,
expectedMsg: `scopes [user:info] prevent this action`,
},
{
name: "scope covers",
attributes: kauthorizer.AttributesRecord{
User: &user.DefaultInfo{Extra: map[string][]string{authorizationv1.ScopesKey: {"user:info"}}},
ResourceRequest: true,
Namespace: "ns",
Verb: "get", Resource: "users", Name: "~"},
expectedAllowed: kauthorizer.DecisionNoOpinion,
},
{
name: "scope covers for discovery",
attributes: kauthorizer.AttributesRecord{
User: &user.DefaultInfo{Extra: map[string][]string{authorizationv1.ScopesKey: {"user:info"}}},
ResourceRequest: false,
Namespace: "ns",
Verb: "get", Path: "/api"},
expectedAllowed: kauthorizer.DecisionNoOpinion,
},
{
name: "user:full covers any resource",
attributes: kauthorizer.AttributesRecord{
User: &user.DefaultInfo{Extra: map[string][]string{authorizationv1.ScopesKey: {"user:full"}}},
ResourceRequest: true,
Namespace: "ns",
Verb: "update", Resource: "users", Name: "harold"},
expectedAllowed: kauthorizer.DecisionNoOpinion,
},
{
name: "user:full covers any non-resource",
attributes: kauthorizer.AttributesRecord{
User: &user.DefaultInfo{Extra: map[string][]string{authorizationv1.ScopesKey: {"user:full"}}},
ResourceRequest: false,
Namespace: "ns",
Verb: "post", Path: "/foo/bar/baz"},
expectedAllowed: kauthorizer.DecisionNoOpinion,
},
}
for _, tc := range testCases {
t.Run(tc.name, func(t *testing.T) {
authorizer := NewAuthorizer(nil)
actualAllowed, actualMsg, actualErr := authorizer.Authorize(context.TODO(), tc.attributes)
switch {
case len(tc.expectedErr) == 0 && actualErr == nil:
case len(tc.expectedErr) == 0 && actualErr != nil:
t.Errorf("%s: unexpected error: %v", tc.name, actualErr)
case len(tc.expectedErr) != 0 && actualErr == nil:
t.Errorf("%s: missing error: %v", tc.name, tc.expectedErr)
case len(tc.expectedErr) != 0 && actualErr != nil:
if !strings.Contains(actualErr.Error(), tc.expectedErr) {
t.Errorf("expected %v, got %v", tc.expectedErr, actualErr)
}
}
if tc.expectedMsg != actualMsg {
t.Errorf("expected %v, got %v", tc.expectedMsg, actualMsg)
}
if tc.expectedAllowed != actualAllowed {
t.Errorf("expected %v, got %v", tc.expectedAllowed, actualAllowed)
}
})
}
}
| apache-2.0 |
chmouel/gofabric8 | vendor/github.com/kubernetes/minikube/pkg/localkube/kubelet.go | 1953 | /*
Copyright 2016 The Kubernetes Authors All rights reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package localkube
import (
"k8s.io/apiserver/pkg/util/flag"
kubelet "k8s.io/kubernetes/cmd/kubelet/app"
"k8s.io/kubernetes/cmd/kubelet/app/options"
"k8s.io/minikube/pkg/util"
)
func (lk LocalkubeServer) NewKubeletServer() Server {
return NewSimpleServer("kubelet", serverInterval, StartKubeletServer(lk), noop)
}
func StartKubeletServer(lk LocalkubeServer) func() error {
config := options.NewKubeletServer()
// Master details
config.KubeConfig = flag.NewStringFlag(util.DefaultKubeConfigPath)
config.RequireKubeConfig = true
// Set containerized based on the flag
config.Containerized = lk.Containerized
config.AllowPrivileged = true
config.PodManifestPath = "/etc/kubernetes/manifests"
// Networking
config.ClusterDomain = lk.DNSDomain
config.ClusterDNS = []string{lk.DNSIP.String()}
// For kubenet plugin.
config.PodCIDR = "10.180.1.0/24"
config.NodeIP = lk.NodeIP.String()
if lk.NetworkPlugin != "" {
config.NetworkPluginName = lk.NetworkPlugin
}
// Runtime
if lk.ContainerRuntime != "" {
config.ContainerRuntime = lk.ContainerRuntime
}
lk.SetExtraConfigForComponent("kubelet", &config)
// Use the host's resolver config
if lk.Containerized {
config.ResolverConfig = "/rootfs/etc/resolv.conf"
} else {
config.ResolverConfig = "/etc/resolv.conf"
}
return func() error {
return kubelet.Run(config, nil)
}
}
| apache-2.0 |
reaction1989/roslyn | src/Compilers/Core/Portable/Symbols/LanguageNames.cs | 988 | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable enable
namespace Microsoft.CodeAnalysis
{
/// <summary>
/// A class that provides constants for common language names.
/// </summary>
public static class LanguageNames
{
/// <summary>
/// The common name used for the C# language.
/// </summary>
public const string CSharp = "C#";
/// <summary>
/// The common name used for the Visual Basic language.
/// </summary>
public const string VisualBasic = "Visual Basic";
/// <summary>
/// The common name used for the F# language.
/// </summary>
/// <remarks>
/// F# is not a supported compile target for the Roslyn compiler.
/// </remarks>
public const string FSharp = "F#";
}
}
| apache-2.0 |
tylertian/Openstack | openstack F/nova/nova/tests/fake_imagebackend.py | 1823 | # vim: tabstop=4 shiftwidth=4 softtabstop=4
# Copyright 2012 Grid Dynamics
# All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
# License for the specific language governing permissions and limitations
# under the License.
import os
from nova.virt.libvirt import config
from nova.virt.libvirt import imagebackend
class Backend(object):
def __init__(self, use_cow):
pass
def image(self, instance, name, image_type=''):
class FakeImage(imagebackend.Image):
def __init__(self, instance, name):
self.path = os.path.join(instance, name)
def create_image(self, prepare_template, base,
size, *args, **kwargs):
pass
def cache(self, fetch_func, filename, size=None, *args, **kwargs):
pass
def libvirt_info(self, disk_bus, disk_dev, device_type,
cache_mode):
info = config.LibvirtConfigGuestDisk()
info.source_type = 'file'
info.source_device = device_type
info.target_bus = disk_bus
info.target_dev = disk_dev
info.driver_cache = cache_mode
info.driver_format = 'raw'
info.source_path = self.path
return info
return FakeImage(instance, name)
| apache-2.0 |
ancchaimongkon/xamarin-forms-book-preview-2 | Chapter09/DisplayPlatformInfoSap1/DisplayPlatformInfoSap1/DisplayPlatformInfoSap1.WinPhone81/MainPage.xaml.cs | 1784 | using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Runtime.InteropServices.WindowsRuntime;
using Windows.Foundation;
using Windows.Foundation.Collections;
using Windows.UI.Xaml;
using Windows.UI.Xaml.Controls;
using Windows.UI.Xaml.Controls.Primitives;
using Windows.UI.Xaml.Data;
using Windows.UI.Xaml.Input;
using Windows.UI.Xaml.Media;
using Windows.UI.Xaml.Navigation;
// The Blank Page item template is documented at http://go.microsoft.com/fwlink/?LinkId=391641
namespace DisplayPlatformInfoSap1.WinPhone81
{
/// <summary>
/// An empty page that can be used on its own or navigated to within a Frame.
/// </summary>
public sealed partial class MainPage : Xamarin.Forms.Platform.WinRT.WindowsPhonePage
{
public MainPage()
{
this.InitializeComponent();
this.NavigationCacheMode = NavigationCacheMode.Required;
LoadApplication(new DisplayPlatformInfoSap1.App());
}
/// <summary>
/// Invoked when this page is about to be displayed in a Frame.
/// </summary>
/// <param name="e">Event data that describes how this page was reached.
/// This parameter is typically used to configure the page.</param>
protected override void OnNavigatedTo(NavigationEventArgs e)
{
// TODO: Prepare page for display here.
// TODO: If your application contains multiple pages, ensure that you are
// handling the hardware Back button by registering for the
// Windows.Phone.UI.Input.HardwareButtons.BackPressed event.
// If you are using the NavigationHelper provided by some templates,
// this event is handled for you.
}
}
}
| apache-2.0 |
fengshao0907/incubator-geode | gemfire-core/src/test/java/com/gemstone/gemfire/internal/cache/ClearDAckDUnitTest.java | 9856 | /*=========================================================================
* Copyright (c) 2010-2014 Pivotal Software, Inc. All Rights Reserved.
* This product is protected by U.S. and international copyright
* and intellectual property laws. Pivotal products are covered by
* one or more patents listed at http://www.pivotal.io/patents.
*=========================================================================
*/
/*
* ClearDAckDUnitTest.java
*
* Created on September 6, 2005, 2:57 PM
*/
package com.gemstone.gemfire.internal.cache;
import com.gemstone.gemfire.cache.AttributesFactory;
import com.gemstone.gemfire.cache.Cache;
import com.gemstone.gemfire.cache.CacheException;
import com.gemstone.gemfire.cache.CacheFactory;
import com.gemstone.gemfire.cache.CacheTransactionManager;
import com.gemstone.gemfire.cache.DataPolicy;
import com.gemstone.gemfire.cache.Region;
import com.gemstone.gemfire.cache.RegionAttributes;
import com.gemstone.gemfire.cache.RegionEvent;
import com.gemstone.gemfire.distributed.DistributedMember;
import com.gemstone.gemfire.distributed.DistributedSystem;
import com.gemstone.gemfire.internal.cache.versions.VersionSource;
import com.gemstone.gemfire.cache.Scope;
import dunit.*;
import java.util.Properties;
/**
*
* @author vjadhav
*/
public class ClearDAckDUnitTest extends DistributedTestCase {
/** Creates a new instance of ClearDAckDUnitTest */
public ClearDAckDUnitTest(String name) {
super(name);
}
static Cache cache;
static Properties props = new Properties();
static Properties propsWork = new Properties();
static DistributedSystem ds = null;
static Region region;
static Region paperWork;
static CacheTransactionManager cacheTxnMgr;
static boolean IsAfterClear=false;
static boolean flag = false;
static DistributedMember vm0ID, vm1ID;
@Override
public void setUp() throws Exception {
super.setUp();
Host host = Host.getHost(0);
VM vm0 = host.getVM(0);
VM vm1 = host.getVM(1);
vm0ID = (DistributedMember)vm0.invoke(ClearDAckDUnitTest.class, "createCacheVM0");
vm1ID = (DistributedMember)vm1.invoke(ClearDAckDUnitTest.class, "createCacheVM1");
getLogWriter().info("Cache created in successfully");
}
public void tearDown2(){
Host host = Host.getHost(0);
VM vm0 = host.getVM(0);
VM vm1 = host.getVM(1);
VM vm2 = host.getVM(2);
vm0.invoke(ClearDAckDUnitTest.class, "closeCache");
vm1.invoke(ClearDAckDUnitTest.class, "resetClearCallBack");
vm1.invoke(ClearDAckDUnitTest.class, "closeCache");
vm2.invoke(ClearDAckDUnitTest.class, "closeCache");
cache = null;
invokeInEveryVM(new SerializableRunnable() { public void run() { cache = null; } });
}
public static long getRegionVersion(DistributedMember memberID) {
return ((LocalRegion)region).getVersionVector().getVersionForMember((VersionSource)memberID);
}
private static CacheObserver origObserver;
public static void resetClearCallBack()
{
LocalRegion.ISSUE_CALLBACKS_TO_CACHE_OBSERVER=false;
CacheObserverHolder.setInstance(origObserver);
}
public static DistributedMember createCacheVM0() {
try{
// props.setProperty("mcast-port", "1234");
// ds = DistributedSystem.connect(props);
getLogWriter().info("I am vm0");
ds = (new ClearDAckDUnitTest("temp")).getSystem(props);
cache = CacheFactory.create(ds);
AttributesFactory factory = new AttributesFactory();
factory.setScope(Scope.DISTRIBUTED_ACK);
factory.setDataPolicy(DataPolicy.REPLICATE);
//[bruce]introduces bad race condition if mcast is used, so
// the next line is disabled
//factory.setEarlyAck(true);
//DistributedSystem.setThreadsSocketPolicy(false);
RegionAttributes attr = factory.create();
region = cache.createRegion("map", attr);
getLogWriter().info("vm0 map region: " + region);
paperWork = cache.createRegion("paperWork", attr);
return cache.getDistributedSystem().getDistributedMember();
} catch (CacheException ex){
throw new RuntimeException("createCacheVM0 exception", ex);
}
} //end of create cache for VM0
public static DistributedMember createCacheVM1(){
try{
// props.setProperty("mcast-port", "1234");
// ds = DistributedSystem.connect(props);
getLogWriter().info("I am vm1");
ds = (new ClearDAckDUnitTest("temp")).getSystem(props);
//DistributedSystem.setThreadsSocketPolicy(false);
CacheObserverImpl observer = new CacheObserverImpl();
origObserver = CacheObserverHolder.setInstance(observer);
LocalRegion.ISSUE_CALLBACKS_TO_CACHE_OBSERVER=true;
cache = CacheFactory.create(ds);
AttributesFactory factory = new AttributesFactory();
factory.setScope(Scope.DISTRIBUTED_ACK);
factory.setDataPolicy(DataPolicy.REPLICATE);
RegionAttributes attr = factory.create();
region = cache.createRegion("map", attr);
getLogWriter().info("vm1 map region: " + region);
paperWork = cache.createRegion("paperWork", attr);
return cache.getDistributedSystem().getDistributedMember();
} catch (CacheException ex){
throw new RuntimeException("createCacheVM1 exception", ex);
}
}
public static void createCacheVM2AndLocalClear(){
try{
// props.setProperty("mcast-port", "1234");
// ds = DistributedSystem.connect(props);
getLogWriter().info("I am vm2");
ds = (new ClearDAckDUnitTest("temp")).getSystem(props);
//DistributedSystem.setThreadsSocketPolicy(false);
CacheObserverImpl observer = new CacheObserverImpl();
origObserver = CacheObserverHolder.setInstance(observer);
LocalRegion.ISSUE_CALLBACKS_TO_CACHE_OBSERVER=true;
cache = CacheFactory.create(ds);
AttributesFactory factory = new AttributesFactory();
factory.setScope(Scope.DISTRIBUTED_ACK);
factory.setDataPolicy(DataPolicy.NORMAL);
RegionAttributes attr = factory.create();
region = cache.createRegion("map", attr);
getLogWriter().info("vm2 map region: " + region);
paperWork = cache.createRegion("paperWork", attr);
region.put("vm2Key", "vm2Value");
region.localClear();
} catch (CacheException ex){
throw new RuntimeException("createCacheVM1 exception", ex);
}
}
public static void closeCache(){
try{
cache.close();
ds.disconnect();
} catch (Exception ex){
ex.printStackTrace();
}
}
//test methods
public void testClearMultiVM(){
Host host = Host.getHost(0);
VM vm0 = host.getVM(0);
VM vm1 = host.getVM(1);
Object[] objArr = new Object[1];
for (int i=1; i<4; i++){
objArr[0] = ""+i;
vm0.invoke(ClearDAckDUnitTest.class, "putMethod", objArr);
}
getLogWriter().info("Did all puts successfully");
long regionVersion = (Long)vm1.invoke(ClearDAckDUnitTest.class, "getRegionVersion", new Object[]{vm0ID});
vm0.invoke(ClearDAckDUnitTest.class,"clearMethod");
boolean flag = vm1.invokeBoolean(ClearDAckDUnitTest.class,"getVM1Flag");
getLogWriter().fine("Flag in VM1="+ flag);
assertTrue(flag);
long newRegionVersion = (Long)vm1.invoke(ClearDAckDUnitTest.class, "getRegionVersion", new Object[]{vm0ID});
assertEquals("expected clear() to increment region version by 1 for " + vm0ID, regionVersion+1, newRegionVersion);
// test that localClear does not distribute
VM vm2 = host.getVM(2);
vm2.invoke(ClearDAckDUnitTest.class, "createCacheVM2AndLocalClear");
flag = vm1.invokeBoolean(ClearDAckDUnitTest.class,"getVM1Flag");
getLogWriter().fine("Flag in VM1="+ flag);
assertFalse(flag);
}//end of test case
public static Object putMethod(Object ob){
Object obj=null;
// try{
if(ob != null){
String str = "first";
obj = region.put(ob, str);
}
// }catch(Exception ex){
// ex.printStackTrace();
// fail("Failed while region.put");
// }
return obj;
}
// public static boolean clearMethod(){
public static void clearMethod(){
try{
long start = System.currentTimeMillis();
region.clear();
long end = System.currentTimeMillis();
long diff = end - start;
getLogWriter().info("Clear Thread proceeded before receiving the ack message in (milli seconds): "+diff);
}catch (Exception e){
e.printStackTrace();
}
}
public static class CacheObserverImpl extends CacheObserverAdapter {
public void afterRegionClear(RegionEvent event){
IsAfterClear = true;
}
}
public static boolean getVM1Flag() {
boolean result = IsAfterClear;
IsAfterClear = false;
return result;
}
}// end of test class
| apache-2.0 |
wwjiang007/flink | flink-runtime/src/test/java/org/apache/flink/runtime/jobmaster/DefaultJobMasterServiceProcessTest.java | 13381 | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.flink.runtime.jobmaster;
import org.apache.flink.api.common.JobID;
import org.apache.flink.api.common.JobStatus;
import org.apache.flink.core.testutils.FlinkAssertions;
import org.apache.flink.runtime.client.JobInitializationException;
import org.apache.flink.runtime.executiongraph.ArchivedExecutionGraph;
import org.apache.flink.runtime.executiongraph.ErrorInfo;
import org.apache.flink.runtime.jobmaster.factories.TestingJobMasterServiceFactory;
import org.apache.flink.runtime.jobmaster.utils.TestingJobMasterGateway;
import org.apache.flink.runtime.jobmaster.utils.TestingJobMasterGatewayBuilder;
import org.apache.flink.runtime.rest.handler.legacy.utils.ArchivedExecutionGraphBuilder;
import org.apache.flink.runtime.scheduler.ExecutionGraphInfo;
import org.apache.flink.runtime.scheduler.exceptionhistory.RootExceptionHistoryEntry;
import org.apache.flink.util.SerializedThrowable;
import org.apache.flink.util.TestLogger;
import org.apache.flink.shaded.guava30.com.google.common.collect.Iterables;
import org.junit.jupiter.api.Test;
import java.time.Duration;
import java.util.UUID;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;
import java.util.function.Function;
import static org.assertj.core.api.Assertions.assertThat;
/** Tests for the {@link DefaultJobMasterServiceProcess}. */
public class DefaultJobMasterServiceProcessTest extends TestLogger {
private static final Duration TIMEOUT = Duration.ofSeconds(10);
private static final JobID jobId = new JobID();
private static final Function<Throwable, ArchivedExecutionGraph>
failedArchivedExecutionGraphFactory =
(throwable ->
ArchivedExecutionGraph.createFromInitializingJob(
jobId, "test", JobStatus.FAILED, throwable, null, 1337));
@Test
public void testInitializationFailureCompletesResultFuture() {
final CompletableFuture<JobMasterService> jobMasterServiceFuture =
new CompletableFuture<>();
DefaultJobMasterServiceProcess serviceProcess = createTestInstance(jobMasterServiceFuture);
final RuntimeException originalCause = new RuntimeException("Init error");
jobMasterServiceFuture.completeExceptionally(originalCause);
final JobManagerRunnerResult actualJobManagerResult =
serviceProcess.getResultFuture().join();
assertThat(actualJobManagerResult.isInitializationFailure()).isTrue();
final Throwable initializationFailure = actualJobManagerResult.getInitializationFailure();
assertThat(initializationFailure)
.isInstanceOf(JobInitializationException.class)
.hasCause(originalCause);
}
@Test
public void testInitializationFailureSetsFailureInfoProperly()
throws ExecutionException, InterruptedException {
final CompletableFuture<JobMasterService> jobMasterServiceFuture =
new CompletableFuture<>();
DefaultJobMasterServiceProcess serviceProcess = createTestInstance(jobMasterServiceFuture);
final RuntimeException originalCause = new RuntimeException("Expected RuntimeException");
long beforeFailureTimestamp = System.currentTimeMillis();
jobMasterServiceFuture.completeExceptionally(originalCause);
long afterFailureTimestamp = System.currentTimeMillis();
final JobManagerRunnerResult result = serviceProcess.getResultFuture().get();
final ErrorInfo executionGraphFailure =
result.getExecutionGraphInfo().getArchivedExecutionGraph().getFailureInfo();
assertThat(executionGraphFailure).isNotNull();
assertInitializationException(
executionGraphFailure.getException(),
originalCause,
executionGraphFailure.getTimestamp(),
beforeFailureTimestamp,
afterFailureTimestamp);
}
@Test
public void testInitializationFailureSetsExceptionHistoryProperly()
throws ExecutionException, InterruptedException {
final CompletableFuture<JobMasterService> jobMasterServiceFuture =
new CompletableFuture<>();
DefaultJobMasterServiceProcess serviceProcess = createTestInstance(jobMasterServiceFuture);
final RuntimeException originalCause = new RuntimeException("Expected RuntimeException");
long beforeFailureTimestamp = System.currentTimeMillis();
jobMasterServiceFuture.completeExceptionally(originalCause);
long afterFailureTimestamp = System.currentTimeMillis();
final RootExceptionHistoryEntry entry =
Iterables.getOnlyElement(
serviceProcess
.getResultFuture()
.get()
.getExecutionGraphInfo()
.getExceptionHistory());
assertInitializationException(
entry.getException(),
originalCause,
entry.getTimestamp(),
beforeFailureTimestamp,
afterFailureTimestamp);
assertThat(entry.isGlobal()).isTrue();
}
private static void assertInitializationException(
SerializedThrowable actualException,
Throwable expectedCause,
long actualTimestamp,
long expectedLowerTimestampThreshold,
long expectedUpperTimestampThreshold) {
final Throwable deserializedException =
actualException.deserializeError(Thread.currentThread().getContextClassLoader());
assertThat(deserializedException)
.isInstanceOf(JobInitializationException.class)
.hasCause(expectedCause);
assertThat(actualTimestamp)
.isGreaterThanOrEqualTo(expectedLowerTimestampThreshold)
.isLessThanOrEqualTo(expectedUpperTimestampThreshold);
}
@Test
public void testCloseAfterInitializationFailure() throws Exception {
final CompletableFuture<JobMasterService> jobMasterServiceFuture =
new CompletableFuture<>();
DefaultJobMasterServiceProcess serviceProcess = createTestInstance(jobMasterServiceFuture);
jobMasterServiceFuture.completeExceptionally(new RuntimeException("Init error"));
serviceProcess.closeAsync().get();
assertThat(serviceProcess.getResultFuture())
.isCompletedWithValueMatching(JobManagerRunnerResult::isInitializationFailure);
assertThat(serviceProcess.getJobMasterGatewayFuture()).isCompletedExceptionally();
}
@Test
public void testCloseAfterInitializationSuccess() throws Exception {
final CompletableFuture<JobMasterService> jobMasterServiceFuture =
new CompletableFuture<>();
DefaultJobMasterServiceProcess serviceProcess = createTestInstance(jobMasterServiceFuture);
TestingJobMasterService testingJobMasterService = new TestingJobMasterService();
jobMasterServiceFuture.complete(testingJobMasterService);
serviceProcess.closeAsync().get();
assertThat(testingJobMasterService.isClosed()).isTrue();
assertThat(serviceProcess.getResultFuture())
.failsWithin(TIMEOUT)
.withThrowableOfType(ExecutionException.class)
.extracting(FlinkAssertions::chainOfCauses, FlinkAssertions.STREAM_THROWABLE)
.anySatisfy(t -> assertThat(t).isInstanceOf(JobNotFinishedException.class));
}
@Test
public void testJobMasterTerminationIsHandled() {
final CompletableFuture<JobMasterService> jobMasterServiceFuture =
new CompletableFuture<>();
DefaultJobMasterServiceProcess serviceProcess = createTestInstance(jobMasterServiceFuture);
CompletableFuture<Void> jobMasterTerminationFuture = new CompletableFuture<>();
TestingJobMasterService testingJobMasterService =
new TestingJobMasterService("localhost", jobMasterTerminationFuture, null);
jobMasterServiceFuture.complete(testingJobMasterService);
RuntimeException testException = new RuntimeException("Fake exception from JobMaster");
jobMasterTerminationFuture.completeExceptionally(testException);
assertThat(serviceProcess.getResultFuture())
.failsWithin(TIMEOUT)
.withThrowableOfType(ExecutionException.class)
.extracting(FlinkAssertions::chainOfCauses, FlinkAssertions.STREAM_THROWABLE)
.anySatisfy(t -> assertThat(t).isEqualTo(testException));
}
@Test
public void testJobMasterGatewayGetsForwarded() {
final CompletableFuture<JobMasterService> jobMasterServiceFuture =
new CompletableFuture<>();
DefaultJobMasterServiceProcess serviceProcess = createTestInstance(jobMasterServiceFuture);
TestingJobMasterGateway testingGateway = new TestingJobMasterGatewayBuilder().build();
TestingJobMasterService testingJobMasterService =
new TestingJobMasterService("localhost", null, testingGateway);
jobMasterServiceFuture.complete(testingJobMasterService);
assertThat(serviceProcess.getJobMasterGatewayFuture()).isCompletedWithValue(testingGateway);
}
@Test
public void testLeaderAddressGetsForwarded() throws Exception {
final CompletableFuture<JobMasterService> jobMasterServiceFuture =
new CompletableFuture<>();
DefaultJobMasterServiceProcess serviceProcess = createTestInstance(jobMasterServiceFuture);
String testingAddress = "yolohost";
TestingJobMasterService testingJobMasterService =
new TestingJobMasterService(testingAddress, null, null);
jobMasterServiceFuture.complete(testingJobMasterService);
assertThat(serviceProcess.getLeaderAddressFuture()).isCompletedWithValue(testingAddress);
}
@Test
public void testIsNotInitialized() {
DefaultJobMasterServiceProcess serviceProcess =
createTestInstance(new CompletableFuture<>());
assertThat(serviceProcess.isInitializedAndRunning()).isFalse();
}
@Test
public void testIsInitialized() {
final CompletableFuture<JobMasterService> jobMasterServiceFuture =
new CompletableFuture<>();
DefaultJobMasterServiceProcess serviceProcess = createTestInstance(jobMasterServiceFuture);
jobMasterServiceFuture.complete(new TestingJobMasterService());
assertThat(serviceProcess.isInitializedAndRunning()).isTrue();
}
@Test
public void testIsNotInitializedAfterClosing() {
final CompletableFuture<JobMasterService> jobMasterServiceFuture =
new CompletableFuture<>();
DefaultJobMasterServiceProcess serviceProcess = createTestInstance(jobMasterServiceFuture);
jobMasterServiceFuture.complete(new TestingJobMasterService());
serviceProcess.closeAsync();
assertThat(serviceProcess.isInitializedAndRunning()).isFalse();
}
@Test
public void testSuccessOnTerminalState() throws Exception {
final CompletableFuture<JobMasterService> jobMasterServiceFuture =
new CompletableFuture<>();
DefaultJobMasterServiceProcess serviceProcess = createTestInstance(jobMasterServiceFuture);
jobMasterServiceFuture.complete(new TestingJobMasterService());
ArchivedExecutionGraph archivedExecutionGraph =
new ArchivedExecutionGraphBuilder().setState(JobStatus.FINISHED).build();
serviceProcess.jobReachedGloballyTerminalState(
new ExecutionGraphInfo(archivedExecutionGraph));
assertThat(serviceProcess.getResultFuture())
.isCompletedWithValueMatching(JobManagerRunnerResult::isSuccess)
.isCompletedWithValueMatching(
r ->
r.getExecutionGraphInfo().getArchivedExecutionGraph().getState()
== JobStatus.FINISHED);
}
private DefaultJobMasterServiceProcess createTestInstance(
CompletableFuture<JobMasterService> jobMasterServiceFuture) {
return new DefaultJobMasterServiceProcess(
jobId,
UUID.randomUUID(),
new TestingJobMasterServiceFactory(() -> jobMasterServiceFuture),
failedArchivedExecutionGraphFactory);
}
}
| apache-2.0 |
walteryang47/ovirt-engine | frontend/webadmin/modules/webadmin/src/main/java/org/ovirt/engine/ui/webadmin/section/main/presenter/popup/provider/ProviderSecretPopupPresenterWidget.java | 722 | package org.ovirt.engine.ui.webadmin.section.main.presenter.popup.provider;
import org.ovirt.engine.ui.common.presenter.AbstractModelBoundPopupPresenterWidget;
import org.ovirt.engine.ui.uicommonweb.models.storage.LibvirtSecretModel;
import com.google.gwt.event.shared.EventBus;
import com.google.inject.Inject;
public class ProviderSecretPopupPresenterWidget extends AbstractModelBoundPopupPresenterWidget<LibvirtSecretModel, ProviderSecretPopupPresenterWidget.ViewDef> {
public interface ViewDef extends AbstractModelBoundPopupPresenterWidget.ViewDef<LibvirtSecretModel> {
}
@Inject
public ProviderSecretPopupPresenterWidget(EventBus eventBus, ViewDef view) {
super(eventBus, view);
}
}
| apache-2.0 |
ewestfal/rice-svn2git-test | rice-middleware/kns/src/main/java/org/kuali/rice/krad/service/impl/PersistenceStructureServiceImpl.java | 8752 | /**
* Copyright 2005-2014 The Kuali Foundation
*
* Licensed under the Educational Community License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.opensource.org/licenses/ecl2.php
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.kuali.rice.krad.service.impl;
import org.kuali.rice.krad.bo.DataObjectRelationship;
import org.kuali.rice.krad.bo.PersistableBusinessObject;
import org.kuali.rice.krad.service.PersistenceStructureService;
import org.kuali.rice.krad.util.ForeignKeyFieldsPopulationState;
import org.kuali.rice.krad.util.LegacyDataFramework;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
/**
* This class was originally introduced a proxy to decide between OJB and JPA implementations, but new work on krad-data
* module has rendered this service deprecated so this implementation is largely vestigial.
*
* @author Kuali Rice Team (rice.collab@kuali.org)
*
* @deprecated use new KRAD Data framework {@link org.kuali.rice.krad.data.DataObjectService}
*/
@Deprecated
@LegacyDataFramework
public class PersistenceStructureServiceImpl extends PersistenceServiceImplBase implements PersistenceStructureService {
/**
*
* special case when the attributeClass passed in doesnt match the class of
* the reference-descriptor as defined in ojb-repository. Currently the only
* case of this happening is ObjectCode vs. ObjectCodeCurrent.
*
* NOTE: This method makes no real sense and is a product of a hack
* introduced by KFS for an unknown reason. If you find yourself using this
* map stop and go do something else.
*
* @param from
* the class in the code
* @param to
* the class in the repository
*/
public static Map<Class, Class> referenceConversionMap = new HashMap<Class, Class>();
private PersistenceStructureService persistenceStructureServiceOjb;
public void setPersistenceStructureServiceOjb(PersistenceStructureService persistenceStructureServiceOjb) {
this.persistenceStructureServiceOjb = persistenceStructureServiceOjb;
}
private PersistenceStructureService getService(Class clazz) {
//return (isJpaEnabledForKradClass(clazz)) ?
// persistenceStructureServiceJpa : persistenceStructureServiceOjb;
// TODO remove this entirely, we are no longer sending any JPA stuff through this class as this class is now legacy!
return persistenceStructureServiceOjb;
}
/**
* @see org.kuali.rice.krad.service.PersistenceService#isPersistable(java.lang.Class)
*/
@Override
public boolean isPersistable(Class clazz) {
return getService(clazz).isPersistable(clazz);
}
/**
* @see org.kuali.rice.krad.service.PersistenceService#getPrimaryKeys(java.lang.Class)
*/
@Override
public List getPrimaryKeys(Class clazz) {
return getService(clazz).getPrimaryKeys(clazz);
}
/**
* @see org.kuali.rice.krad.service.PersistenceMetadataExplorerService#listFieldNames(java.lang.Class)
*/
@Override
public List listFieldNames(Class clazz) {
return getService(clazz).listFieldNames(clazz);
}
/**
* @see org.kuali.rice.krad.service.PersistenceMetadataService#clearPrimaryKeyFields(java.lang.Object)
*/
// Unit tests only
@Override
public Object clearPrimaryKeyFields(Object persistableObject) {
return getService(persistableObject.getClass()).clearPrimaryKeyFields(persistableObject);
}
/**
* @see org.kuali.rice.krad.service.PersistenceMetadataExplorerService#listPersistableSubclasses(java.lang.Class)
*/
// Unit tests only
@Override
public List listPersistableSubclasses(Class superclazz) {
return getService(superclazz).listPersistableSubclasses(superclazz);
}
/**
* @see org.kuali.rice.krad.service.PersistenceService#getRelationshipMetadata(java.lang.Class,
* java.lang.String)
*/
@Override
public Map<String, DataObjectRelationship> getRelationshipMetadata(Class persistableClass, String attributeName, String attributePrefix) {
return getService(persistableClass).getRelationshipMetadata(persistableClass, attributeName, attributePrefix);
}
// Unit tests only
@Override
public Map<String, DataObjectRelationship> getRelationshipMetadata(Class persistableClass, String attributeName) {
return getService(persistableClass).getRelationshipMetadata(persistableClass, attributeName);
}
/**
* @see org.kuali.rice.krad.service.PersistenceService#getForeignKeyFieldName(java.lang.Object,
* java.lang.String, java.lang.String)
*/
@Override
public String getForeignKeyFieldName(Class persistableObjectClass, String attributeName, String pkName) {
return getService(persistableObjectClass).getForeignKeyFieldName(persistableObjectClass, attributeName, pkName);
}
/**
* @see org.kuali.rice.krad.service.PersistenceService#getReferencesForForeignKey(java.lang.Class,
* java.lang.String)
*/
@Override
public Map getReferencesForForeignKey(Class persistableObjectClass, String attributeName) {
return getService(persistableObjectClass).getReferencesForForeignKey(persistableObjectClass, attributeName);
}
/**
* @see org.kuali.rice.krad.service.PersistenceService#getForeignKeysForReference(java.lang.Class, java.lang.String)
*/
@Override
public Map getForeignKeysForReference(Class clazz, String attributeName) {
return getService(clazz).getForeignKeysForReference(clazz, attributeName);
}
@Override
public Map<String, String> getInverseForeignKeysForCollection(Class boClass, String collectionName) {
return getService(boClass).getInverseForeignKeysForCollection(boClass, collectionName);
}
/**
* @see org.kuali.rice.krad.service.PersistenceService#getNestedForeignKeyMap(java.lang.Class)
*/
@Override
public Map getNestedForeignKeyMap(Class persistableObjectClass) {
return getService(persistableObjectClass).getNestedForeignKeyMap(persistableObjectClass);
}
/**
* @see org.kuali.rice.krad.service.PersistenceMetadataService#hasPrimaryKeyFieldValues(java.lang.Object)
*/
@Override
public boolean hasPrimaryKeyFieldValues(Object persistableObject) {
return getService(persistableObject.getClass()).hasPrimaryKeyFieldValues(persistableObject);
}
/**
* @see org.kuali.rice.krad.service.PersistenceService#getForeignKeyFieldsPopulationState(org.kuali.rice.krad.bo.BusinessObject,
* java.lang.String)
*/
@Override
public ForeignKeyFieldsPopulationState getForeignKeyFieldsPopulationState(PersistableBusinessObject bo, String referenceName) {
return getService(bo.getClass()).getForeignKeyFieldsPopulationState(bo, referenceName);
}
/**
* @see org.kuali.rice.krad.service.PersistenceStructureService#listReferenceObjectFieldNames(java.lang.Class)
*/
@Override
public Map<String, Class> listReferenceObjectFields(Class boClass) {
return getService(boClass).listReferenceObjectFields(boClass);
}
@Override
public Map<String, Class> listCollectionObjectTypes(Class boClass) {
return getService(boClass).listCollectionObjectTypes(boClass);
}
@Override
public Map<String, Class> listCollectionObjectTypes(PersistableBusinessObject bo) {
return getService(bo.getClass()).listCollectionObjectTypes(bo);
}
/**
* @see org.kuali.rice.krad.service.PersistenceStructureService#listReferenceObjectFieldNames(org.kuali.rice.krad.bo.BusinessObject)
*/
@Override
public Map<String, Class> listReferenceObjectFields(PersistableBusinessObject bo) {
return getService(bo.getClass()).listReferenceObjectFields(bo);
}
@Override
public boolean isReferenceUpdatable(Class boClass, String referenceName) {
return getService(boClass).isReferenceUpdatable(boClass, referenceName);
}
@Override
public boolean isCollectionUpdatable(Class boClass, String collectionName) {
return getService(boClass).isCollectionUpdatable(boClass, collectionName);
}
@Override
public boolean hasCollection(Class boClass, String collectionName) {
return getService(boClass).hasCollection(boClass, collectionName);
}
@Override
public boolean hasReference(Class boClass, String referenceName) {
return getService(boClass).hasReference(boClass, referenceName);
}
/**
* This overridden method ...
*
* @see org.kuali.rice.krad.service.PersistenceStructureService#getTableName(java.lang.Class)
*/
@Override
public String getTableName(
Class<? extends PersistableBusinessObject> boClass) {
return getService(boClass).getTableName(boClass);
}
}
| apache-2.0 |
BiryukovVA/ignite | modules/web-console/frontend/app/components/list-editable/components/list-editable-one-way/directive.ts | 1710 | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import isMatch from 'lodash/isMatch';
import {default as ListEditableController, ID} from '../../controller';
export default function listEditableOneWay(): ng.IDirective {
return {
require: {
list: 'listEditable'
},
bindToController: {
onItemChange: '&?',
onItemRemove: '&?'
},
controller: class Controller<T> {
list: ListEditableController<T>;
onItemChange: ng.ICompiledExpression;
onItemRemove: ng.ICompiledExpression;
$onInit() {
this.list.save = (item: T, id: ID) => {
if (!isMatch(this.list.getItem(id), item)) this.onItemChange({$event: item});
};
this.list.remove = (id: ID) => this.onItemRemove({
$event: this.list.getItem(id)
});
}
}
};
}
| apache-2.0 |
yonglehou/spring-net | src/Spring/Spring.Core/Context/Attributes/ConfigurationClassEnhancer.cs | 11489 | #region License
/*
* Copyright © 2010-2011 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#endregion
using System;
using System.Collections;
using System.Reflection;
using System.Reflection.Emit;
using Spring.Objects.Factory.Config;
using Spring.Util;
using Spring.Proxy;
using Common.Logging;
namespace Spring.Context.Attributes
{
/// <summary>
/// Enhances Configuration classes by generating a dynamic proxy capable of
/// interacting with the Spring container to respect object semantics.
/// </summary>
/// <author>Chris Beams</author>
/// <author>Juergen Hoeller</author>
/// <author>Bruno Baia (.NET)</author>
/// <seealso cref="ConfigurationClassPostProcessor"/>
public class ConfigurationClassEnhancer
{
private IConfigurationClassInterceptor interceptor;
/// <summary>
/// Creates a new instance of the <see cref="ConfigurationClassEnhancer"/> class.
/// </summary>
/// <param name="objectFactory">
/// The supplied ObjectFactory to check for the existence of object definitions.
/// </param>
public ConfigurationClassEnhancer(IConfigurableListableObjectFactory objectFactory)
{
AssertUtils.ArgumentNotNull(objectFactory, "objectFactory");
this.interceptor = new ConfigurationClassInterceptor(objectFactory);
}
/// <summary>
/// Generates a dynamic subclass of the specified Configuration class with a
/// container-aware interceptor capable of respecting scoping and other bean semantics.
/// </summary>
/// <param name="configClass">The Configuration class.</param>
/// <returns>The enhanced subclass.</returns>
public Type Enhance(Type configClass)
{
ConfigurationClassProxyTypeBuilder proxyTypeBuilder = new ConfigurationClassProxyTypeBuilder(configClass, this.interceptor);
return proxyTypeBuilder.BuildProxyType();
}
/// <summary>
/// Intercepts the invocation of any <see cref="ObjectDefAttribute"/>-decorated methods in order
/// to ensure proper handling of object semantics such as scoping and AOP proxying.
/// </summary>
public interface IConfigurationClassInterceptor
{
/// <summary>
/// Process the <see cref="ObjectDefAttribute"/>-decorated method to check
/// for the existence of this object.
/// </summary>
/// <param name="method">The method providing the object definition.</param>
/// <param name="instance">When this method returns true, contains the object definition.</param>
/// <returns>true if the object exists; otherwise, false.</returns>
bool ProcessDefinition(MethodInfo method, out object instance);
}
private sealed class ConfigurationClassInterceptor : IConfigurationClassInterceptor
{
#region Logging
private static readonly ILog Logger = LogManager.GetLogger<ConfigurationClassInterceptor>();
#endregion
private readonly IConfigurableListableObjectFactory _configurableListableObjectFactory;
public ConfigurationClassInterceptor(IConfigurableListableObjectFactory configurableListableObjectFactory)
{
this._configurableListableObjectFactory = configurableListableObjectFactory;
}
public bool ProcessDefinition(MethodInfo method, out object instance)
{
instance = null;
string objectName = method.Name;
if (objectName.StartsWith("set_") || objectName.StartsWith("get_"))
{
return false;
}
object[] attribs = method.GetCustomAttributes(typeof(ObjectDefAttribute), true);
if (attribs.Length == 0)
{
return false;
}
if (this._configurableListableObjectFactory.IsCurrentlyInCreation(objectName))
{
Logger.Debug(m => m("Object '{0}' currently in creation, created one", objectName));
return false;
}
Logger.Debug(m => m("Object '{0}' not in creation, asked the application context for one", objectName));
instance = this._configurableListableObjectFactory.GetObject(objectName);
return true;
}
}
#region Proxy builder classes definition
private sealed class ConfigurationClassProxyTypeBuilder : InheritanceProxyTypeBuilder
{
private FieldBuilder interceptorField;
private IConfigurationClassInterceptor interceptor;
public ConfigurationClassProxyTypeBuilder(Type configurationClassType, IConfigurationClassInterceptor interceptor)
{
if (configurationClassType.IsSealed)
{
throw new ArgumentException(String.Format(
"[Configuration] classes '{0}' cannot be sealed [{0}].", configurationClassType.FullName));
}
this.Name = "ConfigurationClassProxy";
this.DeclaredMembersOnly = false;
this.BaseType = configurationClassType;
this.TargetType = configurationClassType;
this.interceptor = interceptor;
}
public override Type BuildProxyType()
{
IDictionary targetMethods = new Hashtable();
TypeBuilder typeBuilder = CreateTypeBuilder(Name, BaseType);
// apply custom attributes to the proxy type.
//ApplyTypeAttributes(typeBuilder, BaseType);
// declare interceptor field
interceptorField = typeBuilder.DefineField("__Interceptor", typeof(IConfigurationClassInterceptor),
FieldAttributes.Private | FieldAttributes.Static | FieldAttributes.InitOnly);
// create constructors
ImplementConstructors(typeBuilder);
// proxy base virtual methods
InheritType(typeBuilder,
new ConfigurationClassProxyMethodBuilder(typeBuilder, this, false, targetMethods),
BaseType, this.DeclaredMembersOnly);
Type proxyType = typeBuilder.CreateType();
// set target method references
foreach (DictionaryEntry entry in targetMethods)
{
FieldInfo targetMethodFieldInfo = proxyType.GetField((string)entry.Key, BindingFlags.NonPublic | BindingFlags.Static);
targetMethodFieldInfo.SetValue(proxyType, entry.Value);
}
// set interceptor
FieldInfo interceptorFieldInfo = proxyType.GetField("__Interceptor", BindingFlags.NonPublic | BindingFlags.Static);
interceptorFieldInfo.SetValue(proxyType, this.interceptor);
return proxyType;
}
public void PushInterceptor(ILGenerator il)
{
il.Emit(OpCodes.Ldarg_0);
il.Emit(OpCodes.Ldfld, interceptorField);
}
}
private sealed class ConfigurationClassProxyMethodBuilder : AbstractProxyMethodBuilder
{
public static readonly MethodInfo ProcessDefinitionMethod =
typeof(IConfigurationClassInterceptor).GetMethod("ProcessDefinition", BindingFlags.Instance | BindingFlags.Public);
private ConfigurationClassProxyTypeBuilder customProxyGenerator;
private IDictionary targetMethods;
public ConfigurationClassProxyMethodBuilder(
TypeBuilder typeBuilder, ConfigurationClassProxyTypeBuilder proxyGenerator,
bool explicitImplementation, IDictionary targetMethods)
: base(typeBuilder, proxyGenerator, explicitImplementation)
{
this.customProxyGenerator = proxyGenerator;
this.targetMethods = targetMethods;
}
protected override void GenerateMethod(
ILGenerator il, MethodInfo method, MethodInfo interfaceMethod)
{
// Declare local variables
LocalBuilder interceptedReturnValue = il.DeclareLocal(typeof(Object));
//#if DEBUG
// interceptedReturnValue.SetLocalSymInfo("interceptedReturnValue");
//#endif
LocalBuilder returnValue = null;
if (method.ReturnType != typeof(void))
{
returnValue = il.DeclareLocal(method.ReturnType);
//#if DEBUG
// returnValue.SetLocalSymInfo("returnValue");
//#endif
}
// Declare static field that will cache base method
string methodId = "_m" + Guid.NewGuid().ToString("N");
targetMethods.Add(methodId, method);
FieldBuilder targetMethodCacheField = typeBuilder.DefineField(methodId, typeof(MethodInfo),
FieldAttributes.Private | FieldAttributes.Static | FieldAttributes.InitOnly);
// Call IConfigurationClassInterceptor.TryGetObject method
il.Emit(OpCodes.Ldnull);
il.Emit(OpCodes.Stloc, interceptedReturnValue);
customProxyGenerator.PushInterceptor(il);
il.Emit(OpCodes.Ldsfld, targetMethodCacheField);
il.Emit(OpCodes.Ldloca_S, interceptedReturnValue);
il.EmitCall(OpCodes.Callvirt, ProcessDefinitionMethod, null);
Label jmpBaseCall = il.DefineLabel();
Label jmpEndIf = il.DefineLabel();
il.Emit(OpCodes.Brfalse_S, jmpBaseCall);
// if true
if (returnValue != null)
{
il.Emit(OpCodes.Ldloc, interceptedReturnValue);
if (method.ReturnType.IsValueType || method.ReturnType.IsGenericParameter)
{
il.Emit(OpCodes.Unbox_Any, method.ReturnType);
}
il.Emit(OpCodes.Stloc, returnValue);
il.Emit(OpCodes.Br, jmpEndIf);
}
// if false
il.MarkLabel(jmpBaseCall);
CallDirectBaseMethod(il, method);
if (returnValue != null)
{
il.Emit(OpCodes.Stloc, returnValue);
}
// end if
il.MarkLabel(jmpEndIf);
// return value
if (returnValue != null)
{
il.Emit(OpCodes.Ldloc, returnValue);
}
}
}
#endregion
}
}
| apache-2.0 |
aljoscha/flink | flink-table/flink-table-planner-blink/src/main/java/org/apache/flink/table/planner/plan/nodes/exec/batch/BatchExecValues.java | 1492 | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.flink.table.planner.plan.nodes.exec.batch;
import org.apache.flink.table.data.RowData;
import org.apache.flink.table.planner.plan.nodes.exec.ExecNode;
import org.apache.flink.table.planner.plan.nodes.exec.common.CommonExecValues;
import org.apache.flink.table.types.logical.RowType;
import org.apache.calcite.rex.RexLiteral;
import java.util.List;
/** Batch {@link ExecNode} that read records from given values. */
public class BatchExecValues extends CommonExecValues implements BatchExecNode<RowData> {
public BatchExecValues(List<List<RexLiteral>> tuples, RowType outputType, String description) {
super(tuples, outputType, description);
}
}
| apache-2.0 |
selckin/wicket | wicket-extensions/src/main/java/org/apache/wicket/extensions/markup/html/form/select/IOptionRenderer.java | 1671 | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.wicket.extensions.markup.html.form.select;
import org.apache.wicket.model.IDetachable;
import org.apache.wicket.model.IModel;
/**
* @param <T>
* the model object's type
* @author Igor Vaynberg (ivaynberg)
*
*/
public interface IOptionRenderer<T> extends IDetachable
{
/**
* Get the value for displaying to the user.
*
* @param object
* SelectOption model object
* @return the value for displaying to the user.
*/
String getDisplayValue(T object);
/**
* Gets the model that will be used to represent the value object.
*
* This is a good place to wrap the value object with a detachable model one is desired
*
* @param value
* @return model that will contain the value object
*/
IModel<T> getModel(T value);
/**
* Override when needed.
*/
@Override
default void detach()
{
}
}
| apache-2.0 |
paulbroek/ScheduleUs | ScheduleUs/app/libs/TwoWayView/layouts/src/main/java/org/lucasr/twowayview/widget/ListLayoutManager.java | 1677 | /*
* Copyright (C) 2014 Lucas Rocha
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.lucasr.twowayview.widget;
import android.content.Context;
import android.support.v7.widget.RecyclerView.Recycler;
import android.support.v7.widget.RecyclerView.State;
import android.util.AttributeSet;
import org.lucasr.twowayview.widget.Lanes.LaneInfo;
public class ListLayoutManager extends BaseLayoutManager {
private static final String LOGTAG = "ListLayoutManager";
public ListLayoutManager(Context context, AttributeSet attrs) {
this(context, attrs, 0);
}
public ListLayoutManager(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
}
public ListLayoutManager(Context context, Orientation orientation) {
super(orientation);
}
@Override
int getLaneCount() {
return 1;
}
@Override
void getLaneForPosition(LaneInfo outInfo, int position, Direction direction) {
outInfo.set(0, 0);
}
@Override
void moveLayoutToPosition(int position, int offset, Recycler recycler, State state) {
getLanes().reset(offset);
}
}
| artistic-2.0 |
winkelsdorf/homebrew-cask | Casks/hachidori.rb | 486 | cask 'hachidori' do
version '3.1.8'
sha256 '41cc21439ec4485eb84d96ffe489ff3529a5af218c44d86f465835947b9c22c3'
# github.com/Atelier-Shiori/hachidori was verified as official when first introduced to the cask
url "https://github.com/Atelier-Shiori/hachidori/releases/download/#{version}/hachidori-#{version}.dmg"
appcast 'https://github.com/Atelier-Shiori/hachidori/releases.atom'
name 'Hachidori'
homepage 'https://hachidori.ateliershiori.moe/'
app 'Hachidori.app'
end
| bsd-2-clause |
ylluminarious/homebrew-core | Formula/ucspi-tcp.rb | 1379 | class UcspiTcp < Formula
desc "Tools for building TCP client-server applications"
homepage "https://cr.yp.to/ucspi-tcp.html"
url "https://cr.yp.to/ucspi-tcp/ucspi-tcp-0.88.tar.gz"
sha256 "4a0615cab74886f5b4f7e8fd32933a07b955536a3476d74ea087a3ea66a23e9c"
bottle do
cellar :any_skip_relocation
sha256 "b3f2714c61a157eb31ef53915901c29c24ad3dc5cf7d7c3403dcd501399e26b4" => :high_sierra
sha256 "46d324e867e5a35cbb17e8a215ff33f693651d11645eed116e4e4a6c02085b34" => :sierra
sha256 "a57368e57812063bc4e1450c0bef5cad8392c44e54abf3c8ca950ea51abe7ae9" => :el_capitan
sha256 "727e93394b415da772b43ce5028ad54dcb569f695e6c8c4cdf05dc462b2febbe" => :yosemite
sha256 "67eb31db588a2299c5e69a4a60f3c56d07624a58e52e77cff2e58be554085d9f" => :mavericks
end
# IPv6 patch
# Used to be https://www.fefe.de/ucspi/ucspi-tcp-0.88-ipv6.diff19.bz2
patch do
url "https://raw.githubusercontent.com/homebrew/patches/2b3e4da/ucspi-tcp/patch-0.88-ipv6.diff"
sha256 "c2d6ce17c87397253f298cc28499da873efe23afe97e855bdcf34ae66374036a"
end
def install
(buildpath/"conf-home").unlink
(buildpath/"conf-home").write prefix
system "make"
bin.mkpath
system "make", "setup"
system "make", "check"
share.install prefix/"man"
end
test do
assert_match(/usage: tcpserver/,
shell_output("#{bin}/tcpserver 2>&1", 100))
end
end
| bsd-2-clause |
epiqc/ScaffCC | clang/test/OpenMP/taskloop_simd_linear_messages.cpp | 12210 | // RUN: %clang_cc1 -verify -fopenmp %s -Wuninitialized
// RUN: %clang_cc1 -verify -fopenmp-simd %s -Wuninitialized
typedef void **omp_allocator_handle_t;
extern const omp_allocator_handle_t omp_default_mem_alloc;
extern const omp_allocator_handle_t omp_large_cap_mem_alloc;
extern const omp_allocator_handle_t omp_const_mem_alloc;
extern const omp_allocator_handle_t omp_high_bw_mem_alloc;
extern const omp_allocator_handle_t omp_low_lat_mem_alloc;
extern const omp_allocator_handle_t omp_cgroup_mem_alloc;
extern const omp_allocator_handle_t omp_pteam_mem_alloc;
extern const omp_allocator_handle_t omp_thread_mem_alloc;
void xxx(int argc) {
int i, lin, step; // expected-note {{initialize the variable 'lin' to silence this warning}} expected-note {{initialize the variable 'step' to silence this warning}}
#pragma omp taskloop simd linear(i, lin : step) // expected-warning {{variable 'lin' is uninitialized when used here}} expected-warning {{variable 'step' is uninitialized when used here}}
for (i = 0; i < 10; ++i)
;
}
namespace X {
int x;
};
struct B {
static int ib; // expected-note {{'B::ib' declared here}}
static int bfoo() { return 8; }
};
int bfoo() { return 4; }
int z;
const int C1 = 1;
const int C2 = 2;
void test_linear_colons()
{
int B = 0;
#pragma omp taskloop simd linear(B:bfoo())
for (int i = 0; i < 10; ++i) ;
// expected-error@+1 {{unexpected ':' in nested name specifier; did you mean '::'}}
#pragma omp taskloop simd linear(B::ib:B:bfoo())
for (int i = 0; i < 10; ++i) ;
// expected-error@+1 {{use of undeclared identifier 'ib'; did you mean 'B::ib'}}
#pragma omp taskloop simd linear(B:ib)
for (int i = 0; i < 10; ++i) ;
// expected-error@+1 {{unexpected ':' in nested name specifier; did you mean '::'?}}
#pragma omp taskloop simd linear(z:B:ib)
for (int i = 0; i < 10; ++i) ;
#pragma omp taskloop simd linear(B:B::bfoo())
for (int i = 0; i < 10; ++i) ;
#pragma omp taskloop simd linear(X::x : ::z)
for (int i = 0; i < 10; ++i) ;
#pragma omp taskloop simd linear(B,::z, X::x)
for (int i = 0; i < 10; ++i) ;
#pragma omp taskloop simd linear(::z)
for (int i = 0; i < 10; ++i) ;
// expected-error@+1 {{expected variable name}}
#pragma omp taskloop simd linear(B::bfoo())
for (int i = 0; i < 10; ++i) ;
#pragma omp taskloop simd linear(B::ib,B:C1+C2)
for (int i = 0; i < 10; ++i) ;
}
template<int L, class T, class N> T test_template(T* arr, N num) {
N i;
T sum = (T)0;
T ind2 = - num * L; // expected-note {{'ind2' defined here}}
// expected-error@+1 {{argument of a linear clause should be of integral or pointer type}}
#pragma omp taskloop simd linear(ind2:L)
for (i = 0; i < num; ++i) {
T cur = arr[(int)ind2];
ind2 += L;
sum += cur;
}
return T();
}
template<int LEN> int test_warn() {
int ind2 = 0;
// expected-warning@+1 {{zero linear step (ind2 should probably be const)}}
#pragma omp taskloop simd linear(ind2:LEN)
for (int i = 0; i < 100; i++) {
ind2 += LEN;
}
return ind2;
}
struct S1; // expected-note 2 {{declared here}} expected-note 2 {{forward declaration of 'S1'}}
extern S1 a;
class S2 {
mutable int a;
public:
S2():a(0) { }
};
const S2 b; // expected-note 2 {{'b' defined here}}
const S2 ba[5];
class S3 {
int a;
public:
S3():a(0) { }
};
const S3 ca[5];
class S4 {
int a;
S4();
public:
S4(int v):a(v) { }
};
class S5 {
int a;
S5():a(0) {}
public:
S5(int v):a(v) { }
};
S3 h;
#pragma omp threadprivate(h) // expected-note 2 {{defined as threadprivate or thread local}}
template<class I, class C> int foomain(I argc, C **argv) {
I e(4);
I g(5);
int i, z;
int &j = i;
#pragma omp taskloop simd linear // expected-error {{expected '(' after 'linear'}}
for (int k = 0; k < argc; ++k) ++k;
#pragma omp taskloop simd linear ( // expected-error {{expected expression}} expected-error {{expected ')'}} expected-note {{to match this '('}}
for (int k = 0; k < argc; ++k) ++k;
#pragma omp taskloop simd linear (val // expected-error {{use of undeclared identifier 'val'}} expected-error {{expected ')'}} expected-note {{to match this '('}}
for (int k = 0; k < argc; ++k) ++k;
#pragma omp taskloop simd linear (uval( // expected-error {{expected expression}} expected-error 2 {{expected ')'}} expected-note 2 {{to match this '('}}
for (int k = 0; k < argc; ++k) ++k;
#pragma omp taskloop simd linear (ref() // expected-error {{expected expression}} expected-error {{expected ')'}} expected-note {{to match this '('}}
for (int k = 0; k < argc; ++k) ++k;
#pragma omp taskloop simd linear (foo() // expected-error {{expected expression}} expected-error {{expected ')'}} expected-note {{to match this '('}}
for (int k = 0; k < argc; ++k) ++k;
#pragma omp taskloop simd linear () // expected-error {{expected expression}}
for (int k = 0; k < argc; ++k) ++k;
#pragma omp taskloop simd linear (argc // expected-error {{expected ')'}} expected-note {{to match this '('}}
for (int k = 0; k < argc; ++k) ++k;
#pragma omp taskloop simd linear (val argc // expected-error {{use of undeclared identifier 'val'}} expected-error {{expected ')'}} expected-note {{to match this '('}}
for (int k = 0; k < argc; ++k) ++k;
#pragma omp taskloop simd linear (val(argc, // expected-error {{expected expression}} expected-error 2 {{expected ')'}} expected-note 2 {{to match this '('}}
for (int k = 0; k < argc; ++k) ++k;
#pragma omp taskloop simd linear (argc > 0 ? argv[1] : argv[2]) // expected-error {{expected variable name}}
for (int k = 0; k < argc; ++k) ++k;
#pragma omp taskloop simd linear (argc : 5) allocate , allocate(, allocate(omp_default , allocate(omp_default_mem_alloc, allocate(omp_default_mem_alloc:, allocate(omp_default_mem_alloc: argc, allocate(omp_default_mem_alloc: argv), allocate(argv) // expected-error {{expected '(' after 'allocate'}} expected-error 2 {{expected expression}} expected-error 2 {{expected ')'}} expected-error {{use of undeclared identifier 'omp_default'}} expected-note 2 {{to match this '('}}
for (int k = 0; k < argc; ++k) ++k;
#pragma omp taskloop simd linear (S1) // expected-error {{'S1' does not refer to a value}}
for (int k = 0; k < argc; ++k) ++k;
// expected-error@+2 {{linear variable with incomplete type 'S1'}}
// expected-error@+1 {{argument of a linear clause should be of integral or pointer type, not 'S2'}}
#pragma omp taskloop simd linear (val(a, b):B::ib)
for (int k = 0; k < argc; ++k) ++k;
#pragma omp taskloop simd linear (argv[1]) // expected-error {{expected variable name}}
for (int k = 0; k < argc; ++k) ++k;
#pragma omp taskloop simd linear(ref(e, g)) // expected-error 2 {{variable of non-reference type 'int' can be used only with 'val' modifier, but used with 'ref'}}
for (int k = 0; k < argc; ++k) ++k;
#pragma omp taskloop simd linear(h, z) // expected-error {{threadprivate or thread local variable cannot be linear}}
for (int k = 0; k < argc; ++k) ++k;
#pragma omp taskloop simd linear(uval(i)) // expected-error {{variable of non-reference type 'int' can be used only with 'val' modifier, but used with 'uval'}}
for (int k = 0; k < argc; ++k) ++k;
#pragma omp parallel
{
int v = 0;
int i;
#pragma omp taskloop simd allocate(omp_thread_mem_alloc: v) linear(v:i) // expected-warning {{allocator with the 'thread' trait access has unspecified behavior on 'taskloop simd' directive}}
for (int k = 0; k < argc; ++k) { i = k; v += i; }
}
#pragma omp taskloop simd linear(ref(j))
for (int k = 0; k < argc; ++k) ++k;
#pragma omp taskloop simd linear(uval(j))
for (int k = 0; k < argc; ++k) ++k;
int v = 0;
#pragma omp taskloop simd linear(v:j)
for (int k = 0; k < argc; ++k) { ++k; v += j; }
#pragma omp taskloop simd linear(i)
for (int k = 0; k < argc; ++k) ++k;
return 0;
}
namespace A {
double x;
#pragma omp threadprivate(x) // expected-note {{defined as threadprivate or thread local}}
}
namespace C {
using A::x;
}
void linear_modifiers(int argc) {
int &f = argc;
#pragma omp taskloop simd linear(f)
for (int k = 0; k < argc; ++k) ++k;
#pragma omp taskloop simd linear(val(f))
for (int k = 0; k < argc; ++k) ++k;
#pragma omp taskloop simd linear(uval(f))
for (int k = 0; k < argc; ++k) ++k;
#pragma omp taskloop simd linear(ref(f))
for (int k = 0; k < argc; ++k) ++k;
#pragma omp taskloop simd linear(foo(f)) // expected-error {{expected one of 'ref', val' or 'uval' modifiers}}
for (int k = 0; k < argc; ++k) ++k;
}
int f;
int main(int argc, char **argv) {
double darr[100];
// expected-note@+1 {{in instantiation of function template specialization 'test_template<-4, double, int>' requested here}}
test_template<-4>(darr, 4);
// expected-note@+1 {{in instantiation of function template specialization 'test_warn<0>' requested here}}
test_warn<0>();
S4 e(4); // expected-note {{'e' defined here}}
S5 g(5); // expected-note {{'g' defined here}}
int i, z;
int &j = i;
#pragma omp taskloop simd linear(f) linear(f) // expected-error {{linear variable cannot be linear}} expected-note {{defined as linear}}
for (int k = 0; k < argc; ++k) ++k;
#pragma omp taskloop simd linear // expected-error {{expected '(' after 'linear'}}
for (int k = 0; k < argc; ++k) ++k;
#pragma omp taskloop simd linear ( // expected-error {{expected expression}} expected-error {{expected ')'}} expected-note {{to match this '('}}
for (int k = 0; k < argc; ++k) ++k;
#pragma omp taskloop simd linear () // expected-error {{expected expression}}
for (int k = 0; k < argc; ++k) ++k;
#pragma omp taskloop simd linear (val // expected-error {{use of undeclared identifier 'val'}} expected-error {{expected ')'}} expected-note {{to match this '('}}
for (int k = 0; k < argc; ++k) ++k;
#pragma omp taskloop simd linear (ref()) // expected-error {{expected expression}}
for (int k = 0; k < argc; ++k) ++k;
#pragma omp taskloop simd linear (foo()) // expected-error {{expected expression}}
for (int k = 0; k < argc; ++k) ++k;
#pragma omp taskloop simd linear (argc // expected-error {{expected ')'}} expected-note {{to match this '('}}
for (int k = 0; k < argc; ++k) ++k;
#pragma omp taskloop simd linear (argc, // expected-error {{expected expression}} expected-error {{expected ')'}} expected-note {{to match this '('}}
for (int k = 0; k < argc; ++k) ++k;
#pragma omp taskloop simd linear (argc > 0 ? argv[1] : argv[2]) // expected-error {{expected variable name}}
for (int k = 0; k < argc; ++k) ++k;
#pragma omp taskloop simd linear (argc, z)
for (int k = 0; k < argc; ++k) ++k;
#pragma omp taskloop simd linear (S1) // expected-error {{'S1' does not refer to a value}}
for (int k = 0; k < argc; ++k) ++k;
// expected-error@+2 {{linear variable with incomplete type 'S1'}}
// expected-error@+1 {{argument of a linear clause should be of integral or pointer type, not 'S2'}}
#pragma omp taskloop simd linear(a, b)
for (int k = 0; k < argc; ++k) ++k;
#pragma omp taskloop simd linear (argv[1]) // expected-error {{expected variable name}}
for (int k = 0; k < argc; ++k) ++k;
// expected-error@+2 {{argument of a linear clause should be of integral or pointer type, not 'S4'}}
// expected-error@+1 {{argument of a linear clause should be of integral or pointer type, not 'S5'}}
#pragma omp taskloop simd linear(val(e, g))
for (int k = 0; k < argc; ++k) ++k;
#pragma omp taskloop simd linear(h, C::x) // expected-error 2 {{threadprivate or thread local variable cannot be linear}}
for (int k = 0; k < argc; ++k) ++k;
#pragma omp parallel
{
int i;
#pragma omp taskloop simd linear(val(i))
for (int k = 0; k < argc; ++k) ++k;
#pragma omp taskloop simd linear(uval(i) : 4) // expected-error {{variable of non-reference type 'int' can be used only with 'val' modifier, but used with 'uval'}}
for (int k = 0; k < argc; ++k) { ++k; i += 4; }
}
#pragma omp taskloop simd linear(ref(j))
for (int k = 0; k < argc; ++k) ++k;
#pragma omp taskloop simd linear(i)
for (int k = 0; k < argc; ++k) ++k;
foomain<int,char>(argc,argv); // expected-note {{in instantiation of function template specialization 'foomain<int, char>' requested here}}
return 0;
}
| bsd-2-clause |
gregory-diaz/MatterControl | Community.CsharpSqlite/src/random_c.cs | 6835 | using System;
using System.Diagnostics;
using i64 = System.Int64;
using u8 = System.Byte;
using u32 = System.UInt32;
using u64 = System.UInt64;
namespace Community.CsharpSqlite
{
public partial class Sqlite3
{
/*
** 2001 September 15
**
** The author disclaims copyright to this source code. In place of
** a legal notice, here is a blessing:
**
** May you do good and not evil.
** May you find forgiveness for yourself and forgive others.
** May you share freely, never taking more than you give.
**
*************************************************************************
** This file contains code to implement a pseudo-random number
** generator (PRNG) for SQLite.
**
** Random numbers are used by some of the database backends in order
** to generate random integer keys for tables or random filenames.
*************************************************************************
** Included in SQLite3 port to C#-SQLite; 2008 Noah B Hart
** C#-SQLite is an independent reimplementation of the SQLite software library
**
** SQLITE_SOURCE_ID: 2010-08-23 18:52:01 42537b60566f288167f1b5864a5435986838e3a3
**
*************************************************************************
*/
//#include "sqliteInt.h"
/* All threads share a single random number generator.
** This structure is the current state of the generator.
*/
public class sqlite3PrngType
{
public bool isInit; /* True if initialized */
public int i;
public int j; /* State variables */
public u8[] s = new u8[256]; /* State variables */
public sqlite3PrngType Copy()
{
sqlite3PrngType cp = (sqlite3PrngType)MemberwiseClone();
cp.s = new u8[s.Length];
Array.Copy( s, cp.s, s.Length );
return cp;
}
}
public static sqlite3PrngType sqlite3Prng = new sqlite3PrngType();
/*
** Get a single 8-bit random value from the RC4 PRNG. The Mutex
** must be held while executing this routine.
**
** Why not just use a library random generator like lrand48() for this?
** Because the OP_NewRowid opcode in the VDBE depends on having a very
** good source of random numbers. The lrand48() library function may
** well be good enough. But maybe not. Or maybe lrand48() has some
** subtle problems on some systems that could cause problems. It is hard
** to know. To minimize the risk of problems due to bad lrand48()
** implementations, SQLite uses this random number generator based
** on RC4, which we know works very well.
**
** (Later): Actually, OP_NewRowid does not depend on a good source of
** randomness any more. But we will leave this code in all the same.
*/
static u8 randomu8()
{
u8 t;
/* The "wsdPrng" macro will resolve to the pseudo-random number generator
** state vector. If writable static data is unsupported on the target,
** we have to locate the state vector at run-time. In the more common
** case where writable static data is supported, wsdPrng can refer directly
** to the "sqlite3Prng" state vector declared above.
*/
#if SQLITE_OMIT_WSD
struct sqlite3PrngType *p = &GLOBAL(struct sqlite3PrngType, sqlite3Prng);
//# define wsdPrng p[0]
#else
//# define wsdPrng sqlite3Prng
sqlite3PrngType wsdPrng = sqlite3Prng;
#endif
/* Initialize the state of the random number generator once,
** the first time this routine is called. The seed value does
** not need to contain a lot of randomness since we are not
** trying to do secure encryption or anything like that...
**
** Nothing in this file or anywhere else in SQLite does any kind of
** encryption. The RC4 algorithm is being used as a PRNG (pseudo-random
** number generator) not as an encryption device.
*/
if ( !wsdPrng.isInit )
{
int i;
u8[] k = new u8[256];
wsdPrng.j = 0;
wsdPrng.i = 0;
sqlite3OsRandomness( sqlite3_vfs_find( "" ), 256, k );
for ( i = 0; i < 255; i++ )
{
wsdPrng.s[i] = (u8)i;
}
for ( i = 0; i < 255; i++ )
{
wsdPrng.j = (u8)( wsdPrng.j + wsdPrng.s[i] + k[i] );
t = wsdPrng.s[wsdPrng.j];
wsdPrng.s[wsdPrng.j] = wsdPrng.s[i];
wsdPrng.s[i] = t;
}
wsdPrng.isInit = true;
}
/* Generate and return single random u8
*/
wsdPrng.i++;
t = wsdPrng.s[(u8)wsdPrng.i];
wsdPrng.j = (u8)( wsdPrng.j + t );
wsdPrng.s[(u8)wsdPrng.i] = wsdPrng.s[wsdPrng.j];
wsdPrng.s[wsdPrng.j] = t;
t += wsdPrng.s[(u8)wsdPrng.i];
return wsdPrng.s[t];
}
/*
** Return N random u8s.
*/
static void sqlite3_randomness( int N, ref i64 pBuf )
{
//u8[] zBuf = new u8[N];
pBuf = 0;
#if SQLITE_THREADSAFE
sqlite3_mutex mutex = sqlite3MutexAlloc( SQLITE_MUTEX_STATIC_PRNG );
#endif
sqlite3_mutex_enter( mutex );
while ( N-- > 0 )
{
pBuf = (u32)( ( pBuf << 8 ) + randomu8() );// zBuf[N] = randomu8();
}
sqlite3_mutex_leave( mutex );
}
static void sqlite3_randomness( byte[] pBuf, int Offset, int N )
{
i64 iBuf = System.DateTime.Now.Ticks;
#if SQLITE_THREADSAFE
sqlite3_mutex mutex = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_PRNG);
#endif
sqlite3_mutex_enter( mutex );
while ( N-- > 0 )
{
iBuf = (u32)( ( iBuf << 8 ) + randomu8() );// zBuf[N] = randomu8();
pBuf[Offset++] = (byte)iBuf;
}
sqlite3_mutex_leave( mutex );
}
#if !SQLITE_OMIT_BUILTIN_TEST
/*
** For testing purposes, we sometimes want to preserve the state of
** PRNG and restore the PRNG to its saved state at a later time, or
** to reset the PRNG to its initial state. These routines accomplish
** those tasks.
**
** The sqlite3_test_control() interface calls these routines to
** control the PRNG.
*/
static sqlite3PrngType sqlite3SavedPrng = null;
static void sqlite3PrngSaveState()
{
sqlite3SavedPrng = sqlite3Prng.Copy();
// memcpy(
// &GLOBAL(struct sqlite3PrngType, sqlite3SavedPrng),
// &GLOBAL(struct sqlite3PrngType, sqlite3Prng),
// sizeof(sqlite3Prng)
//);
}
static void sqlite3PrngRestoreState()
{
sqlite3Prng = sqlite3SavedPrng.Copy();
//memcpy(
// &GLOBAL(struct sqlite3PrngType, sqlite3Prng),
// &GLOBAL(struct sqlite3PrngType, sqlite3SavedPrng),
// sizeof(sqlite3Prng)
//);
}
static void sqlite3PrngResetState()
{
sqlite3Prng.isInit = false;// GLOBAL(struct sqlite3PrngType, sqlite3Prng).isInit = 0;
}
#endif //* SQLITE_OMIT_BUILTIN_TEST */
}
}
| bsd-2-clause |
ablyler/homebrew-php | Formula/php53-libsodium.rb | 1027 | require File.expand_path("../../Abstract/abstract-php-extension", __FILE__)
class Php53Libsodium < AbstractPhp53Extension
init
desc "Modern and easy-to-use crypto library"
homepage "https://github.com/jedisct1/libsodium-php"
url "https://github.com/jedisct1/libsodium-php/archive/1.0.6.tar.gz"
sha256 "537944529e7c591e4bd6c73f37e926e538e8ff1f6384747c301436fb78269b9c"
head "https://github.com/jedisct1/libsodium-php.git"
bottle do
cellar :any
sha256 "6b7b1476b12c808fa6bb9503d4103a561db38babc49474ad71ea197352f64fac" => :el_capitan
sha256 "29ba8d57b6e1acd68bd52804962f6d04a7c6ce039cbeb76dcac738e179b9b9f1" => :yosemite
sha256 "e07e15ca9d8e7dfea339d211d74a3c1c43bc9dd6c7d9bcab2836267978097dc4" => :mavericks
end
depends_on "libsodium"
def install
ENV.universal_binary if build.universal?
safe_phpize
system "./configure", "--prefix=#{prefix}", phpconfig
system "make"
prefix.install "modules/libsodium.so"
write_config_file if build.with? "config-file"
end
end
| bsd-2-clause |
ltilve/ChromiumGStreamerBackend | components/dom_distiller/content/browser/distillable_page_utils.cc | 4003 | // Copyright 2015 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "components/dom_distiller/content/browser/distillable_page_utils.h"
#include "base/bind.h"
#include "base/location.h"
#include "base/single_thread_task_runner.h"
#include "base/strings/utf_string_conversions.h"
#include "base/thread_task_runner_handle.h"
#include "base/values.h"
#include "components/dom_distiller/content/browser/distiller_javascript_utils.h"
#include "components/dom_distiller/core/distillable_page_detector.h"
#include "components/dom_distiller/core/experiments.h"
#include "components/dom_distiller/core/page_features.h"
#include "content/public/browser/render_frame_host.h"
#include "grit/components_resources.h"
#include "ui/base/resource/resource_bundle.h"
namespace dom_distiller {
namespace {
void OnOGArticleJsResult(base::Callback<void(bool)> callback,
const base::Value* result) {
bool success = false;
if (result) {
result->GetAsBoolean(&success);
}
callback.Run(success);
}
void OnExtractFeaturesJsResult(const DistillablePageDetector* detector,
base::Callback<void(bool)> callback,
const base::Value* result) {
callback.Run(detector->Classify(CalculateDerivedFeaturesFromJSON(result)));
}
} // namespace
void IsOpenGraphArticle(content::WebContents* web_contents,
base::Callback<void(bool)> callback) {
content::RenderFrameHost* main_frame = web_contents->GetMainFrame();
if (!main_frame) {
base::ThreadTaskRunnerHandle::Get()->PostTask(FROM_HERE,
base::Bind(callback, false));
return;
}
std::string og_article_js = ResourceBundle::GetSharedInstance()
.GetRawDataResource(IDR_IS_DISTILLABLE_JS)
.as_string();
RunIsolatedJavaScript(main_frame, og_article_js,
base::Bind(OnOGArticleJsResult, callback));
}
void IsDistillablePage(content::WebContents* web_contents,
bool is_mobile_optimized,
base::Callback<void(bool)> callback) {
switch (GetDistillerHeuristicsType()) {
case DistillerHeuristicsType::ALWAYS_TRUE:
base::ThreadTaskRunnerHandle::Get()->PostTask(FROM_HERE,
base::Bind(callback, true));
return;
case DistillerHeuristicsType::OG_ARTICLE:
IsOpenGraphArticle(web_contents, callback);
return;
case DistillerHeuristicsType::ADABOOST_MODEL:
// The adaboost model is only applied to non-mobile pages.
if (is_mobile_optimized) {
base::ThreadTaskRunnerHandle::Get()->PostTask(
FROM_HERE, base::Bind(callback, false));
return;
}
IsDistillablePageForDetector(
web_contents, DistillablePageDetector::GetDefault(), callback);
return;
case DistillerHeuristicsType::NONE:
default:
base::ThreadTaskRunnerHandle::Get()->PostTask(
FROM_HERE, base::Bind(callback, false));
return;
}
}
void IsDistillablePageForDetector(content::WebContents* web_contents,
const DistillablePageDetector* detector,
base::Callback<void(bool)> callback) {
content::RenderFrameHost* main_frame = web_contents->GetMainFrame();
if (!main_frame) {
base::ThreadTaskRunnerHandle::Get()->PostTask(FROM_HERE,
base::Bind(callback, false));
return;
}
std::string extract_features_js =
ResourceBundle::GetSharedInstance()
.GetRawDataResource(IDR_EXTRACT_PAGE_FEATURES_JS)
.as_string();
RunIsolatedJavaScript(
main_frame, extract_features_js,
base::Bind(OnExtractFeaturesJsResult, detector, callback));
}
} // namespace dom_distiller
| bsd-3-clause |
danbeam/catapult | dashboard/dashboard/list_monitored_tests.py | 1227 | # Copyright 2015 The Chromium Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
"""Provides the web interface for listing monitored tests."""
import json
from google.appengine.ext import ndb
from dashboard import request_handler
from dashboard.models import graph_data
class ListMonitoredTestsHandler(request_handler.RequestHandler):
"""An endpoint to list the tests monitored by a given sheriff."""
def get(self):
"""Returns a JSON list of tests for a sheriff.
Request parameters:
get-sheriffed-by: A sheriff name.
"""
sheriff = self.request.get('get-sheriffed-by')
if not sheriff:
self.ReportError('No value for get-sheriffed-by.', status=400)
return
self.response.out.write(json.dumps(_ListMonitoredTests(sheriff)))
def _ListMonitoredTests(sheriff_name):
"""Outputs a sorted list of test paths for Tests sheriffed by a user."""
sheriff = ndb.Key('Sheriff', sheriff_name)
sheriffed_query = graph_data.Test.query(
graph_data.Test.sheriff == sheriff,
graph_data.Test.has_rows == True)
sheriffed = sorted(t.test_path for t in sheriffed_query.fetch())
return sheriffed
| bsd-3-clause |
chromium/chromium | chrome/browser/new_tab_page/promos/promo_data.cc | 845 | // Copyright 2018 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "chrome/browser/new_tab_page/promos/promo_data.h"
PromoData::PromoData() = default;
PromoData::PromoData(const PromoData&) = default;
PromoData::PromoData(PromoData&&) = default;
PromoData::~PromoData() = default;
PromoData& PromoData::operator=(const PromoData&) = default;
PromoData& PromoData::operator=(PromoData&&) = default;
bool operator==(const PromoData& lhs, const PromoData& rhs) {
return lhs.promo_html == rhs.promo_html &&
lhs.middle_slot_json == rhs.middle_slot_json &&
lhs.promo_log_url == rhs.promo_log_url && lhs.promo_id == rhs.promo_id;
}
bool operator!=(const PromoData& lhs, const PromoData& rhs) {
return !(lhs == rhs);
}
| bsd-3-clause |
google/skia | docs/examples/Pixmap_colorType.cpp | 688 | // Copyright 2019 Google LLC.
// Use of this source code is governed by a BSD-style license that can be found in the LICENSE file.
#include "tools/fiddle/examples.h"
// HASH=0ab5c7af272685f2ce177cc79e6b9457
REG_FIDDLE(Pixmap_colorType, 256, 256, true, 0) {
void draw(SkCanvas* canvas) {
const char* colors[] = {"Unknown", "Alpha_8", "RGB_565", "ARGB_4444", "RGBA_8888", "RGB_888x",
"BGRA_8888", "RGBA_1010102", "RGB_101010x", "Gray_8", "RGBA_F16Norm",
"RGBA_F16"};
SkPixmap pixmap(SkImageInfo::MakeA8(16, 32), nullptr, 64);
SkDebugf("color type: k" "%s" "_SkColorType\n", colors[pixmap.colorType()]);
}
} // END FIDDLE
| bsd-3-clause |
yetanotherindie/jMonkey-Engine | jme3-examples/src/main/java/jme3test/renderer/TestInconsistentCompareDetection.java | 4648 | /*
* Copyright (c) 2009-2014 jMonkeyEngine
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are
* met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* * Neither the name of 'jMonkeyEngine' nor the names of its contributors
* may be used to endorse or promote products derived from this software
* without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
* TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
* PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
* CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
* EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
* PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
* PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
* LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
* NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package jme3test.renderer;
import com.jme3.app.SimpleApplication;
import com.jme3.material.Material;
import com.jme3.math.ColorRGBA;
import com.jme3.math.FastMath;
import com.jme3.math.Quaternion;
import com.jme3.math.Vector3f;
import com.jme3.scene.Geometry;
import com.jme3.scene.Node;
import com.jme3.scene.Spatial;
import com.jme3.scene.shape.Box;
import com.jme3.texture.Texture;
/**
* Changes a material's texture from another thread while it is rendered.
* This should trigger the sorting function's inconsistent compare detection.
*
* @author Kirill Vainer
*/
public class TestInconsistentCompareDetection extends SimpleApplication {
private static Texture t1, t2;
public static void main(String[] args){
TestInconsistentCompareDetection app = new TestInconsistentCompareDetection();
app.start();
}
@Override
public void simpleInitApp() {
cam.setLocation(new Vector3f(-11.674385f, 7.892636f, 33.133106f));
cam.setRotation(new Quaternion(0.06426433f, 0.90940624f, -0.15329266f, 0.38125014f));
Material m = new Material(assetManager, "Common/MatDefs/Misc/ColoredTextured.j3md");
m.setColor("Color", ColorRGBA.White);
t1 = assetManager.loadTexture("Textures/Terrain/BrickWall/BrickWall.jpg");
t2 = assetManager.loadTexture("Textures/Terrain/Pond/Pond.jpg");
Box b = new Box(1, 1, 1);
for (int x = 0; x < 12; x++) {
for (int y = 0; y < 12; y++) {
Geometry g = new Geometry("g_" + x + "_" + y, b);
Node monkey = new Node("n_" + x + "_" + y);
monkey.attachChild(g);
monkey.move(x * 2, 0, y * 2);
Material newMat = m.clone();
g.setMaterial(newMat);
if (FastMath.rand.nextBoolean()) {
newMat.setTexture("ColorMap", t1);
} else {
newMat.setTexture("ColorMap", t2);
}
rootNode.attachChild(monkey);
}
}
Thread evilThread = new Thread(new Runnable() {
public void run() {
try {
Thread.sleep(1000);
} catch (InterruptedException ex) {
}
// begin randomly changing textures after 1 sec.
while (true) {
for (Spatial child : rootNode.getChildren()) {
Geometry g = (Geometry) (((Node)child).getChild(0));
Material m = g.getMaterial();
Texture curTex = m.getTextureParam("ColorMap").getTextureValue();
if (curTex == t1) {
m.setTexture("ColorMap", t2);
} else {
m.setTexture("ColorMap", t1);
}
}
}
}
});
evilThread.setDaemon(true);
evilThread.start();
}
}
| bsd-3-clause |
upmc-enterprises/elasticsearch-operator | vendor/golang.org/x/tools/cmd/tip/cert.go | 1555 | // Copyright 2017 The Go Authors. All rights reserved.
// Use of this source code is governed by the Apache 2.0
// license that can be found in the LICENSE file.
// +build autocert
// This file contains autocert and cloud.google.com/go/storage
// dependencies we want to hide by default from the Go build system,
// which currently doesn't know how to fetch non-golang.org/x/*
// dependencies. The Dockerfile builds the production binary
// with this code using --tags=autocert.
package main
import (
"context"
"crypto/tls"
"log"
"net/http"
"cloud.google.com/go/storage"
"golang.org/x/build/autocertcache"
"golang.org/x/crypto/acme/autocert"
)
func init() {
runHTTPS = runHTTPSAutocert
certInit = certInitAutocert
wrapHTTPMux = wrapHTTPMuxAutocert
}
var autocertManager *autocert.Manager
func certInitAutocert() {
var cache autocert.Cache
if b := *autoCertCacheBucket; b != "" {
sc, err := storage.NewClient(context.Background())
if err != nil {
log.Fatalf("storage.NewClient: %v", err)
}
cache = autocertcache.NewGoogleCloudStorageCache(sc, b)
}
autocertManager = &autocert.Manager{
Prompt: autocert.AcceptTOS,
HostPolicy: autocert.HostWhitelist(*autoCertDomain),
Cache: cache,
}
}
func runHTTPSAutocert(h http.Handler) error {
s := &http.Server{
Addr: ":https",
Handler: h,
TLSConfig: &tls.Config{
GetCertificate: autocertManager.GetCertificate,
},
}
return s.ListenAndServeTLS("", "")
}
func wrapHTTPMuxAutocert(h http.Handler) http.Handler {
return autocertManager.HTTPHandler(h)
}
| bsd-3-clause |
chromium/chromium | media/midi/task_service_unittest.cc | 9352 | // Copyright 2017 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "media/midi/task_service.h"
#include <memory>
#include "base/bind.h"
#include "base/callback.h"
#include "base/callback_helpers.h"
#include "base/memory/raw_ptr.h"
#include "base/memory/ref_counted.h"
#include "base/run_loop.h"
#include "base/synchronization/lock.h"
#include "base/test/test_simple_task_runner.h"
#include "base/threading/thread_task_runner_handle.h"
#include "base/time/time.h"
#include "testing/gtest/include/gtest/gtest.h"
namespace midi {
namespace {
enum {
kDefaultRunner = TaskService::kDefaultRunnerId,
kFirstRunner,
kSecondRunner
};
base::WaitableEvent* GetEvent() {
static base::WaitableEvent* event =
new base::WaitableEvent(base::WaitableEvent::ResetPolicy::MANUAL,
base::WaitableEvent::InitialState::NOT_SIGNALED);
return event;
}
void SignalEvent() {
GetEvent()->Signal();
}
void WaitEvent() {
GetEvent()->Wait();
}
void ResetEvent() {
GetEvent()->Reset();
}
class TaskServiceClient {
public:
TaskServiceClient(TaskService* task_service)
: task_service_(task_service),
wait_task_event_(std::make_unique<base::WaitableEvent>(
base::WaitableEvent::ResetPolicy::MANUAL,
base::WaitableEvent::InitialState::NOT_SIGNALED)),
count_(0u) {
DCHECK(task_service);
}
TaskServiceClient(const TaskServiceClient&) = delete;
TaskServiceClient& operator=(const TaskServiceClient&) = delete;
bool Bind() { return task_service()->BindInstance(); }
bool Unbind() { return task_service()->UnbindInstance(); }
void PostBoundTask(TaskService::RunnerId runner_id) {
task_service()->PostBoundTask(
runner_id, base::BindOnce(&TaskServiceClient::IncrementCount,
base::Unretained(this)));
}
void PostBoundSignalTask(TaskService::RunnerId runner_id) {
task_service()->PostBoundTask(
runner_id, base::BindOnce(&TaskServiceClient::SignalEvent,
base::Unretained(this)));
}
void PostBoundWaitTask(TaskService::RunnerId runner_id) {
wait_task_event_->Reset();
task_service()->PostBoundTask(
runner_id,
base::BindOnce(&TaskServiceClient::WaitEvent, base::Unretained(this)));
}
void PostBoundDelayedSignalTask(TaskService::RunnerId runner_id) {
task_service()->PostBoundDelayedTask(
runner_id,
base::BindOnce(&TaskServiceClient::SignalEvent, base::Unretained(this)),
base::Milliseconds(100));
}
void WaitTask() { wait_task_event_->Wait(); }
size_t count() {
base::AutoLock lock(lock_);
return count_;
}
private:
TaskService* task_service() { return task_service_; }
void IncrementCount() {
base::AutoLock lock(lock_);
count_++;
}
void SignalEvent() {
IncrementCount();
midi::SignalEvent();
}
void WaitEvent() {
IncrementCount();
wait_task_event_->Signal();
midi::WaitEvent();
}
base::Lock lock_;
raw_ptr<TaskService> task_service_;
std::unique_ptr<base::WaitableEvent> wait_task_event_;
size_t count_;
};
class MidiTaskServiceTest : public ::testing::Test {
public:
MidiTaskServiceTest() = default;
MidiTaskServiceTest(const MidiTaskServiceTest&) = delete;
MidiTaskServiceTest& operator=(const MidiTaskServiceTest&) = delete;
protected:
TaskService* task_service() { return &task_service_; }
void RunUntilIdle() { task_runner_->RunUntilIdle(); }
private:
void SetUp() override {
ResetEvent();
task_runner_ = new base::TestSimpleTaskRunner();
thread_task_runner_handle_ =
std::make_unique<base::ThreadTaskRunnerHandle>(task_runner_);
}
void TearDown() override {
thread_task_runner_handle_.reset();
task_runner_.reset();
}
scoped_refptr<base::TestSimpleTaskRunner> task_runner_;
std::unique_ptr<base::ThreadTaskRunnerHandle> thread_task_runner_handle_;
TaskService task_service_;
};
// Tests if posted tasks without calling BindInstance() are ignored.
TEST_F(MidiTaskServiceTest, RunUnauthorizedBoundTask) {
std::unique_ptr<TaskServiceClient> client =
std::make_unique<TaskServiceClient>(task_service());
client->PostBoundTask(kFirstRunner);
// Destruct |client| immediately, then see if the posted task is just ignored.
// If it isn't, another thread will touch the destructed instance and will
// cause a crash due to a use-after-free.
client = nullptr;
}
// Tests if invalid BindInstance() calls are correctly rejected, and it does not
// make the service insanity.
TEST_F(MidiTaskServiceTest, BindTwice) {
std::unique_ptr<TaskServiceClient> client =
std::make_unique<TaskServiceClient>(task_service());
EXPECT_TRUE(client->Bind());
// Should not be able to call BindInstance() twice before unbinding current
// bound instance.
EXPECT_FALSE(client->Bind());
// Should be able to unbind only the first instance.
EXPECT_TRUE(client->Unbind());
EXPECT_FALSE(client->Unbind());
}
// Tests if posted static tasks can be processed correctly.
TEST_F(MidiTaskServiceTest, RunStaticTask) {
std::unique_ptr<TaskServiceClient> client =
std::make_unique<TaskServiceClient>(task_service());
EXPECT_TRUE(client->Bind());
// Should be able to post a static task while an instance is bound.
task_service()->PostStaticTask(kFirstRunner, base::BindOnce(&SignalEvent));
WaitEvent();
EXPECT_TRUE(client->Unbind());
ResetEvent();
EXPECT_TRUE(client->Bind());
task_service()->PostStaticTask(kFirstRunner, base::BindOnce(&SignalEvent));
// Should be able to unbind the instance to process a static task.
EXPECT_TRUE(client->Unbind());
WaitEvent();
ResetEvent();
// Should be able to post a static task without a bound instance.
task_service()->PostStaticTask(kFirstRunner, base::BindOnce(&SignalEvent));
WaitEvent();
}
// Tests functionalities to run bound tasks.
TEST_F(MidiTaskServiceTest, RunBoundTasks) {
std::unique_ptr<TaskServiceClient> client =
std::make_unique<TaskServiceClient>(task_service());
EXPECT_TRUE(client->Bind());
// Tests if a post task run.
EXPECT_EQ(0u, client->count());
client->PostBoundSignalTask(kFirstRunner);
WaitEvent();
EXPECT_EQ(1u, client->count());
// Tests if another posted task is handled correctly even if the instance is
// unbound immediately. The posted task should run safely if it starts before
// UnboundInstance() is call. Otherwise, it should be ignored. It completely
// depends on timing.
client->PostBoundTask(kFirstRunner);
EXPECT_TRUE(client->Unbind());
client = std::make_unique<TaskServiceClient>(task_service());
// Tests if an immediate call of another BindInstance() works correctly.
EXPECT_TRUE(client->Bind());
// Runs two tasks in two runners.
ResetEvent();
client->PostBoundSignalTask(kFirstRunner);
client->PostBoundTask(kSecondRunner);
// Waits only the first runner completion to see if the second runner handles
// the task correctly even if the bound instance is destructed.
WaitEvent();
EXPECT_TRUE(client->Unbind());
client = nullptr;
}
// Tests if a blocking task does not block other task runners.
TEST_F(MidiTaskServiceTest, RunBlockingTask) {
std::unique_ptr<TaskServiceClient> client =
std::make_unique<TaskServiceClient>(task_service());
EXPECT_TRUE(client->Bind());
// Posts a task that waits until the event is signaled.
client->PostBoundWaitTask(kFirstRunner);
// Confirms if the posted task starts. Now, the task should block in the task
// until the second task is invoked.
client->WaitTask();
// Posts another task to the second runner. The task should be able to run
// even though another posted task is blocking inside a critical section that
// protects running tasks from an instance unbinding.
client->PostBoundSignalTask(kSecondRunner);
// Wait until the second task runs.
WaitEvent();
// UnbindInstance() should wait until any running task finishes so that the
// instance can be destructed safely.
EXPECT_TRUE(client->Unbind());
EXPECT_EQ(2u, client->count());
client = nullptr;
}
// Tests if a bound delayed task runs correctly.
TEST_F(MidiTaskServiceTest, RunBoundDelayedTask) {
std::unique_ptr<TaskServiceClient> client =
std::make_unique<TaskServiceClient>(task_service());
EXPECT_TRUE(client->Bind());
// Posts a delayed task that signals after 100msec.
client->PostBoundDelayedSignalTask(kFirstRunner);
// Wait until the delayed task runs.
WaitEvent();
EXPECT_TRUE(client->Unbind());
EXPECT_EQ(1u, client->count());
client = nullptr;
}
// Tests if a bound task runs on the thread that bound the instance.
TEST_F(MidiTaskServiceTest, RunBoundTaskOnDefaultRunner) {
std::unique_ptr<TaskServiceClient> client =
std::make_unique<TaskServiceClient>(task_service());
EXPECT_TRUE(client->Bind());
// Posts a task that increments the count on the caller thread.
client->PostBoundTask(kDefaultRunner);
// The posted task should not run until the current message loop is processed.
EXPECT_EQ(0u, client->count());
RunUntilIdle();
EXPECT_EQ(1u, client->count());
EXPECT_TRUE(client->Unbind());
}
} // namespace
} // namespace midi
| bsd-3-clause |
chromium/chromium | chrome/browser/safe_browsing/test_safe_browsing_service.cc | 7478 | // Copyright (c) 2016 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "chrome/browser/safe_browsing/test_safe_browsing_service.h"
#include "base/strings/string_util.h"
#include "chrome/browser/safe_browsing/chrome_safe_browsing_blocking_page_factory.h"
#include "chrome/browser/safe_browsing/chrome_ui_manager_delegate.h"
#include "chrome/browser/safe_browsing/download_protection/download_protection_service.h"
#include "chrome/browser/safe_browsing/incident_reporting/incident_reporting_service.h"
#include "chrome/browser/safe_browsing/services_delegate.h"
#include "chrome/common/url_constants.h"
#include "components/safe_browsing/buildflags.h"
#include "components/safe_browsing/content/browser/ui_manager.h"
#include "components/safe_browsing/core/browser/db/database_manager.h"
#include "components/safe_browsing/core/browser/db/test_database_manager.h"
#include "content/public/browser/browser_task_traits.h"
#include "content/public/browser/browser_thread.h"
namespace safe_browsing {
// TestSafeBrowsingService functions:
TestSafeBrowsingService::TestSafeBrowsingService()
: test_shared_loader_factory_(
base::MakeRefCounted<network::WeakWrapperSharedURLLoaderFactory>(
&test_url_loader_factory_)) {
#if BUILDFLAG(FULL_SAFE_BROWSING)
services_delegate_ = ServicesDelegate::CreateForTest(this, this);
#endif // BUILDFLAG(FULL_SAFE_BROWSING)
}
TestSafeBrowsingService::~TestSafeBrowsingService() {}
V4ProtocolConfig TestSafeBrowsingService::GetV4ProtocolConfig() const {
if (v4_protocol_config_)
return *v4_protocol_config_;
return SafeBrowsingService::GetV4ProtocolConfig();
}
void TestSafeBrowsingService::UseV4LocalDatabaseManager() {
use_v4_local_db_manager_ = true;
}
void TestSafeBrowsingService::SetUseTestUrlLoaderFactory(
bool use_test_url_loader_factory) {
use_test_url_loader_factory_ = use_test_url_loader_factory;
}
network::TestURLLoaderFactory*
TestSafeBrowsingService::GetTestUrlLoaderFactory() {
DCHECK(use_test_url_loader_factory_);
return &test_url_loader_factory_;
}
base::CallbackListSubscription TestSafeBrowsingService::RegisterStateCallback(
const base::RepeatingClosure& callback) {
// This override is required since TestSafeBrowsingService can be destroyed
// before CertificateReportingService, which causes a crash due to the
// leftover callback at destruction time.
return {};
}
std::string TestSafeBrowsingService::serilized_download_report() {
return serialized_download_report_;
}
void TestSafeBrowsingService::ClearDownloadReport() {
serialized_download_report_.clear();
}
void TestSafeBrowsingService::SetDatabaseManager(
TestSafeBrowsingDatabaseManager* database_manager) {
SetDatabaseManagerForTest(database_manager);
}
void TestSafeBrowsingService::SetUIManager(
TestSafeBrowsingUIManager* ui_manager) {
ui_manager_ = ui_manager;
}
SafeBrowsingUIManager* TestSafeBrowsingService::CreateUIManager() {
if (ui_manager_)
return ui_manager_.get();
return SafeBrowsingService::CreateUIManager();
}
void TestSafeBrowsingService::SendSerializedDownloadReport(
Profile* profile,
const std::string& report) {
serialized_download_report_ = report;
}
const scoped_refptr<SafeBrowsingDatabaseManager>&
TestSafeBrowsingService::database_manager() const {
if (test_database_manager_)
return test_database_manager_;
return SafeBrowsingService::database_manager();
}
void TestSafeBrowsingService::SetV4ProtocolConfig(
V4ProtocolConfig* v4_protocol_config) {
v4_protocol_config_.reset(v4_protocol_config);
}
// ServicesDelegate::ServicesCreator:
bool TestSafeBrowsingService::CanCreateDatabaseManager() {
return !use_v4_local_db_manager_;
}
#if BUILDFLAG(FULL_SAFE_BROWSING)
bool TestSafeBrowsingService::CanCreateDownloadProtectionService() {
return false;
}
#endif
bool TestSafeBrowsingService::CanCreateIncidentReportingService() {
return true;
}
SafeBrowsingDatabaseManager* TestSafeBrowsingService::CreateDatabaseManager() {
DCHECK(!use_v4_local_db_manager_);
#if BUILDFLAG(FULL_SAFE_BROWSING)
return new TestSafeBrowsingDatabaseManager(
content::GetUIThreadTaskRunner({}), content::GetIOThreadTaskRunner({}));
#else
NOTIMPLEMENTED();
return nullptr;
#endif // BUILDFLAG(FULL_SAFE_BROWSING)
}
#if BUILDFLAG(FULL_SAFE_BROWSING)
DownloadProtectionService*
TestSafeBrowsingService::CreateDownloadProtectionService() {
NOTIMPLEMENTED();
return nullptr;
}
#endif
IncidentReportingService*
TestSafeBrowsingService::CreateIncidentReportingService() {
#if BUILDFLAG(FULL_SAFE_BROWSING)
return new IncidentReportingService(nullptr);
#else
NOTIMPLEMENTED();
return nullptr;
#endif // BUILDFLAG(FULL_SAFE_BROWSING)
}
scoped_refptr<network::SharedURLLoaderFactory>
TestSafeBrowsingService::GetURLLoaderFactory(
content::BrowserContext* browser_context) {
if (use_test_url_loader_factory_)
return test_shared_loader_factory_;
return SafeBrowsingService::GetURLLoaderFactory(browser_context);
}
// TestSafeBrowsingServiceFactory functions:
TestSafeBrowsingServiceFactory::TestSafeBrowsingServiceFactory()
: test_safe_browsing_service_(nullptr), use_v4_local_db_manager_(false) {}
TestSafeBrowsingServiceFactory::~TestSafeBrowsingServiceFactory() {}
SafeBrowsingService*
TestSafeBrowsingServiceFactory::CreateSafeBrowsingService() {
// Instantiate TestSafeBrowsingService.
test_safe_browsing_service_ = new TestSafeBrowsingService();
// Plug-in test member clases accordingly.
if (use_v4_local_db_manager_)
test_safe_browsing_service_->UseV4LocalDatabaseManager();
if (test_ui_manager_)
test_safe_browsing_service_->SetUIManager(test_ui_manager_.get());
if (test_database_manager_) {
test_safe_browsing_service_->SetDatabaseManager(
test_database_manager_.get());
}
return test_safe_browsing_service_;
}
TestSafeBrowsingService*
TestSafeBrowsingServiceFactory::test_safe_browsing_service() {
return test_safe_browsing_service_;
}
void TestSafeBrowsingServiceFactory::SetTestUIManager(
TestSafeBrowsingUIManager* ui_manager) {
test_ui_manager_ = ui_manager;
}
void TestSafeBrowsingServiceFactory::SetTestDatabaseManager(
TestSafeBrowsingDatabaseManager* database_manager) {
test_database_manager_ = database_manager;
}
void TestSafeBrowsingServiceFactory::UseV4LocalDatabaseManager() {
use_v4_local_db_manager_ = true;
}
// TestSafeBrowsingUIManager functions:
TestSafeBrowsingUIManager::TestSafeBrowsingUIManager()
: SafeBrowsingUIManager(
std::make_unique<ChromeSafeBrowsingUIManagerDelegate>(),
std::make_unique<ChromeSafeBrowsingBlockingPageFactory>(),
GURL(chrome::kChromeUINewTabURL)) {}
TestSafeBrowsingUIManager::TestSafeBrowsingUIManager(
std::unique_ptr<SafeBrowsingBlockingPageFactory> blocking_page_factory)
: SafeBrowsingUIManager(
std::make_unique<ChromeSafeBrowsingUIManagerDelegate>(),
std::move(blocking_page_factory),
GURL(chrome::kChromeUINewTabURL)) {}
void TestSafeBrowsingUIManager::SendSerializedThreatDetails(
content::BrowserContext* browser_context,
const std::string& serialized) {
details_.push_back(serialized);
}
std::list<std::string>* TestSafeBrowsingUIManager::GetThreatDetails() {
return &details_;
}
TestSafeBrowsingUIManager::~TestSafeBrowsingUIManager() {}
} // namespace safe_browsing
| bsd-3-clause |
endlessm/chromium-browser | buildtools/third_party/libc++/trunk/test/std/diagnostics/syserr/syserr.syserr/syserr.syserr.members/ctor_int_error_category_const_char_pointer.pass.cpp | 1080 | //===----------------------------------------------------------------------===//
//
// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
// See https://llvm.org/LICENSE.txt for license information.
// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
//
//===----------------------------------------------------------------------===//
// <system_error>
// class system_error
// system_error(int ev, const error_category& ecat, const char* what_arg);
// Test is slightly non-portable
#include <system_error>
#include <string>
#include <cassert>
#include "test_macros.h"
int main(int, char**)
{
std::string what_arg("test message");
std::system_error se(static_cast<int>(std::errc::not_a_directory),
std::generic_category(), what_arg.c_str());
assert(se.code() == std::make_error_code(std::errc::not_a_directory));
std::string what_message(se.what());
assert(what_message.find(what_arg) != std::string::npos);
assert(what_message.find("Not a directory") != std::string::npos);
return 0;
}
| bsd-3-clause |
gurkerl83/millipede-xtreemfs | java/servers/src/org/xtreemfs/common/clients/internal/RAID0ObjectMapper.java | 2686 | /*
* Copyright (c) 2009 by Bjoern Kolbeck,
* Zuse Institute Berlin
*
* Licensed under the BSD License, see LICENSE file for details.
*
*/
package org.xtreemfs.common.clients.internal;
import java.util.LinkedList;
import java.util.List;
import org.xtreemfs.common.xloc.Replica;
import org.xtreemfs.foundation.buffer.ReusableBuffer;
import org.xtreemfs.foundation.logging.Logging;
import org.xtreemfs.pbrpc.generatedinterfaces.GlobalTypes.StripingPolicy;
/**
*
* @author bjko
*/
public class RAID0ObjectMapper extends ObjectMapper {
private final int stripeSize;
protected RAID0ObjectMapper(StripingPolicy fileSP) {
super(fileSP);
stripeSize = fileSP.getStripeSize()*1024;
}
@Override
public List<ObjectRequest> readRequest(int length, long fileOffset, Replica replica) {
List<ObjectRequest> reqs = new LinkedList();
final long firstObj = fileOffset / stripeSize;
final long lastObj = (fileOffset+length-1) / stripeSize;
final int firstOffset = (int)fileOffset%stripeSize;
if (firstObj == lastObj) {
ObjectRequest rq = new ObjectRequest(firstObj, firstOffset, length,
getOSDForObject(replica, firstObj), null);
reqs.add(rq);
return reqs;
}
//first obj
ObjectRequest rq = new ObjectRequest(firstObj, firstOffset, stripeSize-firstOffset,
getOSDForObject(replica, firstObj),null);
reqs.add(rq);
for (long o = firstObj+1; o < lastObj; o++) {
rq = new ObjectRequest(o, 0, stripeSize,
getOSDForObject(replica, o), null);
reqs.add(rq);
}
//last obj
final int lastSize = ((length+fileOffset)%stripeSize == 0) ? stripeSize : (int) (length+fileOffset)%stripeSize;
if (lastSize > 0) {
rq = new ObjectRequest(lastObj, 0, lastSize, getOSDForObject(replica, lastObj),
null);
reqs.add(rq);
}
return reqs;
}
@Override
public List<ObjectRequest> writeRequest(ReusableBuffer data, long fileOffset, Replica replica) {
List<ObjectRequest> reqs = readRequest(data.remaining(), fileOffset, replica);
int pCnt = 0;
for (ObjectRequest rq : reqs) {
ReusableBuffer viewBuf = data.createViewBuffer();
viewBuf.range(pCnt, rq.getLength());
pCnt += rq.getLength();
rq.setData(viewBuf);
}
return reqs;
}
protected String getOSDForObject(Replica replica, long objNo) {
return replica.getOSDForObject(objNo).toString();
}
}
| bsd-3-clause |
endlessm/chromium-browser | third_party/angle/third_party/VK-GL-CTS/src/external/openglcts/modules/glesext/texture_buffer/esextcTextureBufferPrecision.hpp | 5223 | #ifndef _ESEXTCTEXTUREBUFFERPRECISION_HPP
#define _ESEXTCTEXTUREBUFFERPRECISION_HPP
/*-------------------------------------------------------------------------
* OpenGL Conformance Test Suite
* -----------------------------
*
* Copyright (c) 2014-2016 The Khronos Group Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/ /*!
* \file
* \brief
*/ /*-------------------------------------------------------------------*/
/*!
* \file esextcTextureBufferPrecision.hpp
* \brief Texture Buffer Precision Qualifier (Test 10)
*/ /*-------------------------------------------------------------------*/
#include "../esextcTestCaseBase.hpp"
#include "glcTestCase.hpp"
#include "gluShaderUtil.hpp"
#include "tcuDefs.hpp"
#include <map>
namespace glcts
{
/** Implementation of (Test 10) from CTS_EXT_texture_buffer. Description follows:
*
* Test whether shaders that don't include a precision qualifier for each of the
* *samplerBuffer and *imageBuffer uniform declarations fail to compile.
*
* Category: API.
*
* Write a compute shader that defines
*
* layout (r32f) uniform imageBuffer image_buffer;
*
* buffer ComputeSSBO
* {
* float value;
* } computeSSBO;
*
* In the compute shader execute:
*
* computeSSBO.value = imageLoad( image_buffer, 0 ).r;
*
* Try to compile the shader. The shader should fail to compile.
*
* Include a precision qualifier for the uniform declaration:
*
* layout (r32f) uniform highp imageBuffer image_buffer;
*
* This time the shader should compile without error.
*
* Instead of including a precision qualifier for the uniform
* declaration specify the default precision qualifier:
*
* precision highp imageBuffer;
*
* This time the shader should also compile without error.
*
* Repeat the above tests with the iimageBuffer and uimageBuffer types
* (instead of imageBuffer).
*
* ---------------------------------------------------------------------------
*
* Write a fragment shader that defines:
*
* uniform samplerBuffer sampler_buffer;
*
* layout(location = 0) out vec4 color;
*
* In the fragment shader execute:
*
* color = texelFetch( sampler_buffer, 0 );
*
* Try to compile the shader. The shader should fail to compile.
*
* Include a precision qualifier for the uniform declaration:
*
* uniform highp samplerBuffer sampler_buffer;
*
* This time the shader should compile without error.
*
* Instead of including a precision qualifier for the uniform
* declaration specify the default precision qualifier:
*
* precision highp samplerBuffer;
*
* This time the shader should also compile without error.
*
* Repeat the above tests with the isamplerBuffer and usamplerBuffer types
* (instead of samplerBuffer).
*/
class TextureBufferPrecision : public TestCaseBase
{
public:
/* Public methods */
TextureBufferPrecision(Context& context, const ExtParameters& extParams, const char* name, const char* description);
virtual ~TextureBufferPrecision()
{
}
virtual void deinit(void);
virtual IterateResult iterate(void);
private:
/* Private methods */
glw::GLboolean verifyShaderCompilationStatus(glw::GLenum shader_type, const char** sh_code_parts,
const glw::GLuint parts_count, const glw::GLint expected_status);
/* Private variables */
glw::GLuint m_po_id; /* Program object */
glw::GLuint m_sh_id; /* Shader object */
static const char* const m_cs_code_head; /* Head of the compute shader. */
static const char* const m_cs_code_declaration_without_precision
[3]; /* Variables declarations for the compute shader without usage of the precision qualifier. */
static const char* const m_cs_code_declaration_with_precision
[3]; /* Variables declarations for the compute shader with usage of the precision qualifier. */
static const char* const
m_cs_code_global_precision[3]; /* The default precision qualifier declarations for the compute shader. */
static const char* const m_cs_code_body; /* The compute shader body. */
static const char* const m_fs_code_head; /* Head of the fragment shader. */
static const char* const m_fs_code_declaration_without_precision
[3]; /* Variables declarations for the fragment shader without usage of the precision qualifier. */
static const char* const m_fs_code_declaration_with_precision
[3]; /* Variables declarations for the fragment shader with usage of the precision qualifier. */
static const char* const
m_fs_code_global_precision[3]; /* The default precision qualifier declarations for the fragment shader. */
static const char* const m_fs_code_body; /* The fragment shader body. */
};
} // namespace glcts
#endif // _ESEXTCTEXTUREBUFFERPRECISION_HPP
| bsd-3-clause |
ApexWire/yupe | themes/default/views/geo/geo_profile.php | 1690 | <?php
$city_id = Yii::app()->getRequest()->getParam("GeoProfile[geo_city_id]") ? : ($model->geo_city_id ? : null);
if (!$city_id) {
$guessed_city = Yii::app()->getModule("geo")->guessCity();
}
if ($city_id && ($city = GeoCity::model()->with('country')->findByPk($city_id))) {
$city = $city->combinedName;
} else {
$city = "";
}
?>
<div class="list">
<div class="name"><?php echo Yii::t('default', 'City:'); ?></div>
<div class="form">
<?php
$form->widget(
'zii.widgets.jui.CJuiAutoComplete',
[
'name' => 'GeoProfile[geo_city]',
'value' => $city,
'sourceUrl' => $this->createUrl('/geo/geo/cityAjax'),
'htmlOptions' => ['class' => 'span5'],
'options' => [
'showAnim' => 'fold',
'select' => 'js: function (event, ui) {
$("#GeoProfile_geo_city_id").val(ui.item.id);
}',
]
]
);
echo CHtml::hiddenField('GeoProfile[geo_city_id]', $city_id);
if (!$city_id && $guessed_city) {
echo "<br /><small>" . Yii::t(
'default',
'We think, you are from'
) . " <a href='#' onClick='$(\"#GeoProfile_geo_city_id\").val(" . $guessed_city->id . ");$(\"#GeoProfile_geo_city\").val($(this).text());return false;'>" . $guessed_city->combinedName . "</a><br />. " . Yii::t(
'default',
'Click on link to choose the city.'
) . "</small>";
}
?>
</div>
<div class="accession"></div>
</div>
| bsd-3-clause |
Mirocow/funshop | vendor/funson86/yii2-auth/messages/en/auth.php | 615 | <?php
/**
* Created by PhpStorm.
* User: funson
* Date: 2014/10/25
* Time: 10:33
*/
return [
'Parent ID' => 'Parent',
'Name' => 'Name',
'Description' => 'Description',
'Operation List' => 'Operation List',
'basic' => 'Basic',
'user' => 'User',
'role' => 'Role',
'backendLogin' => 'Backend Login',
'viewUser' => 'View User',
'createUser' => 'Create User',
'updateUser' => 'Update User',
'deleteUser' => 'Delete User',
'viewRole' => 'View Role',
'createRole' => 'Create Role',
'updateRole' => 'Update Role',
'deleteRole' => 'Delete Role',
]; | bsd-3-clause |
yang1fan2/nematus | mosesdecoder-master/moses/TranslationModel/CYKPlusParser/CompletedRuleCollection.cpp | 4515 | /***********************************************************************
Moses - factored phrase-based language decoder
Copyright (C) 2014 University of Edinburgh
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either
version 2.1 of the License, or (at your option) any later version.
This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public
License along with this library; if not, write to the Free Software
Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
***********************************************************************/
#include <iostream>
#include "CompletedRuleCollection.h"
#include "moses/StaticData.h"
using namespace std;
namespace Moses
{
CompletedRuleCollection::CompletedRuleCollection(size_t rule_limit)
: m_ruleLimit(rule_limit)
{
m_scoreThreshold = numeric_limits<float>::infinity();
}
CompletedRuleCollection::~CompletedRuleCollection()
{
Clear();
}
// copies some functionality (pruning) from ChartTranslationOptionList::Add
void CompletedRuleCollection::Add(const TargetPhraseCollection &tpc,
const StackVec &stackVec,
const ChartParserCallback &outColl)
{
if (tpc.IsEmpty()) {
return;
}
const TargetPhrase &targetPhrase = **(tpc.begin());
float score = targetPhrase.GetFutureScore();
for (StackVec::const_iterator p = stackVec.begin(); p != stackVec.end(); ++p) {
float stackScore = (*p)->GetBestScore(&outColl);
score += stackScore;
}
// If the rule limit has already been reached then don't add the option
// unless it is better than at least one existing option.
if (m_ruleLimit && m_collection.size() > m_ruleLimit && score < m_scoreThreshold) {
return;
}
CompletedRule *completedRule = new CompletedRule(tpc, stackVec, score);
m_collection.push_back(completedRule);
// If the rule limit hasn't been exceeded then update the threshold.
if (!m_ruleLimit || m_collection.size() <= m_ruleLimit) {
m_scoreThreshold = (score < m_scoreThreshold) ? score : m_scoreThreshold;
}
// Prune if bursting
if (m_ruleLimit && m_collection.size() == m_ruleLimit * 2) {
NTH_ELEMENT4(m_collection.begin(),
m_collection.begin() + m_ruleLimit - 1,
m_collection.end(),
CompletedRuleOrdered());
m_scoreThreshold = m_collection[m_ruleLimit-1]->GetScoreEstimate();
for (size_t i = 0 + m_ruleLimit; i < m_collection.size(); i++) {
delete m_collection[i];
}
m_collection.resize(m_ruleLimit);
}
}
// copies some functionality (pruning) from ChartTranslationOptionList::Add
void CompletedRuleCollection::Add(const TargetPhraseCollection &tpc,
const StackVec &stackVec,
const std::vector<float> &stackScores,
const ChartParserCallback &outColl)
{
if (tpc.IsEmpty()) {
return;
}
const TargetPhrase &targetPhrase = **(tpc.begin());
float score = std::accumulate(stackScores.begin(), stackScores.end(), targetPhrase.GetFutureScore());
// If the rule limit has already been reached then don't add the option
// unless it is better than at least one existing option.
if (m_collection.size() > m_ruleLimit && score < m_scoreThreshold) {
return;
}
CompletedRule *completedRule = new CompletedRule(tpc, stackVec, score);
m_collection.push_back(completedRule);
// If the rule limit hasn't been exceeded then update the threshold.
if (m_collection.size() <= m_ruleLimit) {
m_scoreThreshold = (score < m_scoreThreshold) ? score : m_scoreThreshold;
}
// Prune if bursting
if (m_collection.size() == m_ruleLimit * 2) {
NTH_ELEMENT4(m_collection.begin(),
m_collection.begin() + m_ruleLimit - 1,
m_collection.end(),
CompletedRuleOrdered());
m_scoreThreshold = m_collection[m_ruleLimit-1]->GetScoreEstimate();
for (size_t i = 0 + m_ruleLimit; i < m_collection.size(); i++) {
delete m_collection[i];
}
m_collection.resize(m_ruleLimit);
}
}
}
| bsd-3-clause |
dammeheli75/blx | vendor/telerik/kendoui/Kendo/UI/GridScrollable.php | 445 | <?php
namespace Kendo\UI;
class GridScrollable extends \Kendo\SerializableObject {
//>> Properties
/**
* If set to true the grid will always display a single page of data. Scrolling would just change the data which is currently displayed.
* @param boolean $value
* @return \Kendo\UI\GridScrollable
*/
public function virtual($value) {
return $this->setProperty('virtual', $value);
}
//<< Properties
}
?>
| bsd-3-clause |
ml9951/rstm | bench/ListBench.cpp | 2658 | /**
* Copyright (C) 2011
* University of Rochester Department of Computer Science
* and
* Lehigh University Department of Computer Science and Engineering
*
* License: Modified BSD
* Please see the file LICENSE.RSTM for licensing information
*/
#include <stm/config.h>
#if defined(STM_CPU_SPARC)
#include <sys/types.h>
#endif
/**
* Step 1:
* Include the configuration code for the harness, and the API code.
*/
#include <iostream>
#include <api/api.hpp>
#include "bmconfig.hpp"
/**
* We provide the option to build the entire benchmark in a single
* source. The bmconfig.hpp include defines all of the important functions
* that are implemented in this file, and bmharness.cpp defines the
* execution infrastructure.
*/
#ifdef SINGLE_SOURCE_BUILD
#include "bmharness.cpp"
#endif
/**
* Step 2:
* Declare the data type that will be stress tested via this benchmark.
* Also provide any functions that will be needed to manipulate the data
* type. Take care to avoid unnecessary indirection.
*/
#include "List.hpp"
/**
* Step 3:
* Declare an instance of the data type, and provide init, test, and verify
* functions
*/
/*** the list we will manipulate in the experiment */
List* SET;
/*** Initialize the counter */
void bench_init()
{
SET = new List();
// warm up the datastructure
//
// NB: if we switch to CGL, we can initialize without transactions
TM_BEGIN_FAST_INITIALIZATION();
for (uint32_t w = 0; w < CFG.elements; w+=2)
SET->insert(w TM_PARAM);
TM_END_FAST_INITIALIZATION();
}
/*** Run a bunch of increment transactions */
void bench_test(uintptr_t, uint32_t* seed)
{
uint32_t val = rand_r(seed) % CFG.elements;
uint32_t act = rand_r(seed) % 100;
if (act < CFG.lookpct) {
TM_BEGIN(atomic) {
SET->lookup(val TM_PARAM);
} TM_END;
}
else if (act < CFG.inspct) {
TM_BEGIN(atomic) {
SET->insert(val TM_PARAM);
} TM_END;
}
else {
TM_BEGIN(atomic) {
SET->remove(val TM_PARAM);
} TM_END;
}
}
/*** Ensure the final state of the benchmark satisfies all invariants */
bool bench_verify() { return SET->isSane(); }
/**
* Step 4:
* Include the code that has the main() function, and the code for creating
* threads and calling the three above-named functions. Don't forget to
* provide an arg reparser.
*/
/*** Deal with special names that map to different M values */
void bench_reparse()
{
if (CFG.bmname == "") CFG.bmname = "List";
else if (CFG.bmname == "List") CFG.elements = 256;
}
| bsd-3-clause |
gpfreitas/bokeh | bokeh/server/protocol/tests/test_receiver.py | 758 | from __future__ import absolute_import
from bokeh.server.protocol import receiver, Protocol
from bokeh.util.string import decode_utf8
_proto = Protocol("1.0")
def test_creation():
receiver.Receiver(None)
def test_validation_success():
msg = _proto.create('ACK')
r = receiver.Receiver(_proto)
partial = r.consume(decode_utf8(msg.header_json)).result()
assert partial is None
partial = r.consume(decode_utf8(msg.metadata_json)).result()
assert partial is None
partial = r.consume(decode_utf8(msg.content_json)).result()
assert partial is not None
assert partial.msgtype == msg.msgtype
assert partial.header == msg.header
assert partial.content == msg.content
assert partial.metadata == msg.metadata
| bsd-3-clause |
atifaziz/RserveCLI2 | R/R-2.15.3/library/Rserve/client/java-new/REngineEvalException.java | 1256 | package org.rosuda.REngine ;
/**
* Exception thrown when an error occurs during eval.
*
* <p>
* This class is a placeholder and should be extended when more information
* can be extracted from R (call stack, etc ... )
* </p>
*/
public class REngineEvalException extends REngineException {
/**
* Value returned by the rniEval native method when the input passed to eval
* is invalid
*/
public static final int INVALID_INPUT = -1 ;
/**
* Value returned by the rniEval native method when an error occured during
* eval (stop, ...)
*/
public static final int ERROR = -2 ;
/**
* Type of eval error
*/
protected int type ;
/**
* Constructor
*
* @param eng associated REngine
* @param message error message
* @param type type of error (ERROR or INVALID_INPUT)
*/
public REngineEvalException( REngine eng, String message, int type ){
super( eng, message );
this.type = type ;
}
/**
* Constructor using ERROR type
*
* @param eng associated REngine
* @param message error message
*/
public REngineEvalException( REngine eng, String message){
this( eng, message, ERROR );
}
/**
* @return the type of error (ERROR or INVALID_INPUT)
*/
public int getType(){
return type ;
}
}
| bsd-3-clause |
chromium/chromium | chrome/browser/extensions/api/page_capture/page_capture_apitest.cc | 5860 | // Copyright (c) 2012 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include <atomic>
#include "base/base_switches.h"
#include "base/command_line.h"
#include "base/threading/thread_restrictions.h"
#include "build/build_config.h"
#include "build/chromeos_buildflags.h"
#include "chrome/browser/extensions/active_tab_permission_granter.h"
#include "chrome/browser/extensions/api/page_capture/page_capture_api.h"
#include "chrome/browser/extensions/extension_action_runner.h"
#include "chrome/browser/extensions/extension_apitest.h"
#include "chrome/browser/extensions/extension_util.h"
#include "chrome/browser/extensions/tab_helper.h"
#include "chrome/common/chrome_switches.h"
#include "chrome/test/base/ui_test_utils.h"
#include "chromeos/login/login_state/scoped_test_public_session_login_state.h"
#include "content/public/browser/browser_thread.h"
#include "content/public/common/content_switches.h"
#include "content/public/test/browser_test.h"
#include "content/public/test/test_utils.h"
#include "extensions/browser/extension_dialog_auto_confirm.h"
#include "extensions/common/permissions/permission_set.h"
#include "extensions/common/permissions/permissions_data.h"
#include "extensions/common/url_pattern_set.h"
#include "extensions/test/extension_test_message_listener.h"
#include "extensions/test/result_catcher.h"
#include "net/dns/mock_host_resolver.h"
#include "third_party/blink/public/common/switches.h"
#if BUILDFLAG(IS_CHROMEOS_ASH)
#include "chromeos/login/login_state/login_state.h"
#endif // BUILDFLAG(IS_CHROMEOS_ASH)
namespace extensions {
using ContextType = ExtensionApiTest::ContextType;
class PageCaptureSaveAsMHTMLDelegate
: public PageCaptureSaveAsMHTMLFunction::TestDelegate {
public:
PageCaptureSaveAsMHTMLDelegate() {
PageCaptureSaveAsMHTMLFunction::SetTestDelegate(this);
}
virtual ~PageCaptureSaveAsMHTMLDelegate() {
PageCaptureSaveAsMHTMLFunction::SetTestDelegate(NULL);
}
void OnTemporaryFileCreated(
scoped_refptr<storage::ShareableFileReference> file) override {
file->AddFinalReleaseCallback(
base::BindOnce(&PageCaptureSaveAsMHTMLDelegate::OnReleaseCallback,
base::Unretained(this)));
++temp_file_count_;
}
void WaitForFinalRelease() {
if (temp_file_count_ > 0)
run_loop_.Run();
}
int temp_file_count() const { return temp_file_count_; }
private:
void OnReleaseCallback(const base::FilePath& path) {
if (--temp_file_count_ == 0)
release_closure_.Run();
}
base::RunLoop run_loop_;
base::RepeatingClosure release_closure_ = run_loop_.QuitClosure();
std::atomic<int> temp_file_count_{0};
};
class ExtensionPageCaptureApiTest
: public ExtensionApiTest,
public testing::WithParamInterface<ContextType> {
protected:
void SetUpCommandLine(base::CommandLine* command_line) override {
ExtensionApiTest::SetUpCommandLine(command_line);
command_line->AppendSwitchASCII(blink::switches::kJavaScriptFlags,
"--expose-gc");
}
void SetUpOnMainThread() override {
ExtensionApiTest::SetUpOnMainThread();
host_resolver()->AddRule("*", "127.0.0.1");
}
bool RunTest(const char* extension_name,
const char* custom_arg = nullptr,
bool allow_file_access = false) {
return RunExtensionTest(extension_name, {.custom_arg = custom_arg},
{.allow_file_access = allow_file_access});
}
void WaitForFileCleanup(PageCaptureSaveAsMHTMLDelegate* delegate) {
// Garbage collection in SW-based extensions doesn't clean up the temp
// file.
if (GetParam() != ContextType::kServiceWorker)
delegate->WaitForFinalRelease();
}
};
INSTANTIATE_TEST_SUITE_P(PersistentBackground,
ExtensionPageCaptureApiTest,
::testing::Values(ContextType::kPersistentBackground));
INSTANTIATE_TEST_SUITE_P(ServiceWorker,
ExtensionPageCaptureApiTest,
::testing::Values(ContextType::kServiceWorker));
IN_PROC_BROWSER_TEST_P(ExtensionPageCaptureApiTest,
SaveAsMHTMLWithoutFileAccess) {
ASSERT_TRUE(StartEmbeddedTestServer());
PageCaptureSaveAsMHTMLDelegate delegate;
ASSERT_TRUE(RunTest("page_capture", "ONLY_PAGE_CAPTURE_PERMISSION"))
<< message_;
WaitForFileCleanup(&delegate);
}
IN_PROC_BROWSER_TEST_P(ExtensionPageCaptureApiTest, SaveAsMHTMLWithFileAccess) {
ASSERT_TRUE(StartEmbeddedTestServer());
PageCaptureSaveAsMHTMLDelegate delegate;
ASSERT_TRUE(RunTest("page_capture", /*custom_arg=*/nullptr,
/*allow_file_access=*/true))
<< message_;
WaitForFileCleanup(&delegate);
}
#if BUILDFLAG(IS_CHROMEOS_ASH)
IN_PROC_BROWSER_TEST_P(ExtensionPageCaptureApiTest,
PublicSessionRequestAllowed) {
ASSERT_TRUE(StartEmbeddedTestServer());
PageCaptureSaveAsMHTMLDelegate delegate;
chromeos::ScopedTestPublicSessionLoginState login_state;
// Resolve Permission dialog with Allow.
ScopedTestDialogAutoConfirm auto_confirm(ScopedTestDialogAutoConfirm::ACCEPT);
ASSERT_TRUE(RunTest("page_capture")) << message_;
WaitForFileCleanup(&delegate);
}
IN_PROC_BROWSER_TEST_P(ExtensionPageCaptureApiTest,
PublicSessionRequestDenied) {
ASSERT_TRUE(StartEmbeddedTestServer());
PageCaptureSaveAsMHTMLDelegate delegate;
chromeos::ScopedTestPublicSessionLoginState login_state;
// Resolve Permission dialog with Deny.
ScopedTestDialogAutoConfirm auto_confirm(ScopedTestDialogAutoConfirm::CANCEL);
ASSERT_TRUE(RunTest("page_capture", "REQUEST_DENIED")) << message_;
EXPECT_EQ(0, delegate.temp_file_count());
}
#endif // BUILDFLAG(IS_CHROMEOS_ASH)
} // namespace extensions
| bsd-3-clause |
leonwolfus/masterbrick | demo/utils.py | 2334 | from datetime import datetime, time, timedelta
import hashlib
def export_event(event, format='ical'):
# Only ical format supported at the moment
if format != 'ical':
return
# Begin event
# VEVENT format: http://www.kanzaki.com/docs/ical/vevent.html
ical_components = [
'BEGIN:VCALENDAR',
'VERSION:2.0',
'PRODID:-//Torchbox//wagtail//EN',
]
# Work out number of days the event lasts
if event.date_to is not None:
days = (event.date_to - event.date_from).days + 1
else:
days = 1
for day in range(days):
# Get date
date = event.date_from + timedelta(days=day)
# Get times
if event.time_from is not None:
start_time = event.time_from
else:
start_time = time.min
if event.time_to is not None:
end_time = event.time_to
else:
end_time = time.max
# Combine dates and times
start_datetime = datetime.combine(
date,
start_time
)
end_datetime = datetime.combine(date, end_time)
def add_slashes(string):
string.replace('"', '\\"')
string.replace('\\', '\\\\')
string.replace(',', '\\,')
string.replace(':', '\\:')
string.replace(';', '\\;')
string.replace('\n', '\\n')
return string
# Make a uid
event_string = event.url + str(start_datetime)
uid = hashlib.sha1(event_string.encode('utf-8')).hexdigest() + '@wagtaildemo'
# Make event
ical_components.extend([
'BEGIN:VEVENT',
'UID:' + add_slashes(uid),
'URL:' + add_slashes(event.url),
'DTSTAMP:' + start_time.strftime('%Y%m%dT%H%M%S'),
'SUMMARY:' + add_slashes(event.title),
'DESCRIPTION:' + add_slashes(event.search_description),
'LOCATION:' + add_slashes(event.location),
'DTSTART;TZID=Europe/London:' + start_datetime.strftime('%Y%m%dT%H%M%S'),
'DTEND;TZID=Europe/London:' + end_datetime.strftime('%Y%m%dT%H%M%S'),
'END:VEVENT',
])
# Finish event
ical_components.extend([
'END:VCALENDAR',
])
# Join components
return '\r'.join(ical_components)
| bsd-3-clause |
yubo/program | ds/demo/projects/xj/main/src/edu/usfca/xj/appkit/gview/shape/SLink.java | 6505 | /*
[The "BSD licence"]
Copyright (c) 2005 Jean Bovet
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions
are met:
1. Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.
3. The name of the author may not be used to endorse or promote products
derived from this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package edu.usfca.xj.appkit.gview.shape;
import edu.usfca.xj.appkit.gview.base.Anchor2D;
import edu.usfca.xj.appkit.gview.base.Rect;
import edu.usfca.xj.appkit.gview.base.Vector2D;
import edu.usfca.xj.foundation.XJXMLSerializable;
import java.awt.*;
public abstract class SLink implements XJXMLSerializable {
protected Vector2D start;
protected Vector2D end;
protected Vector2D startDirection;
protected Vector2D endDirection;
protected Vector2D startOffset;
protected Vector2D endOffset;
protected double startTangentOffset;
protected double endTangentOffset;
protected Vector2D direction;
protected double flateness;
protected SArrow arrow = new SArrow();
protected SLabel label = new SLabel();
protected boolean selfLoop = false;
protected boolean arrowVisible = true;
protected Color color = Color.black;
// Temporary
protected transient Vector2D startWithOffset = null;
protected transient Vector2D endWithOffset = null;
public SLink() {
}
public void setStartAnchor(Anchor2D anchor) {
setStart(anchor.position);
setStartDirection(anchor.direction);
}
public void setEndAnchor(Anchor2D anchor) {
setEnd(anchor.position);
setEndDirection(anchor.direction);
}
public void setStart(Vector2D start) {
this.start = start.copy();
computeOffsets();
}
public void setStart(double x, double y) {
setStart(new Vector2D(x, y));
}
public Vector2D getStart() {
return start;
}
public void setEnd(Vector2D end) {
this.end = end.copy();
computeOffsets();
}
public void setEnd(double x, double y) {
setEnd(new Vector2D(x, y));
}
public void setEnd(Point p) {
end = Vector2D.vector(p);
}
public Vector2D getEnd() {
return end;
}
public void setDirection(Vector2D direction) {
this.direction = direction;
}
public Vector2D getDirection() {
return direction;
}
public void setFlateness(double flatness) {
this.flateness = flatness;
}
public double getFlateness() {
return flateness;
}
public void setStartDirection(Vector2D direction) {
this.startDirection = direction;
}
public Vector2D getStartDirection() {
return startDirection;
}
public void setEndDirection(Vector2D direction) {
this.endDirection = direction;
}
public Vector2D getEndDirection() {
return endDirection;
}
public void setStartTangentOffset(double offset) {
this.startTangentOffset = offset;
}
public double getStartTangentOffset() {
return startTangentOffset;
}
public void setEndTangentOffset(double offset) {
this.endTangentOffset = offset;
}
public double getEndTangentOffset() {
return endTangentOffset;
}
public void setStartOffset(Vector2D offset) {
this.startOffset = offset;
computeOffsets();
}
public Vector2D getStartOffset() {
return startOffset;
}
public void setEndOffset(Vector2D offset) {
this.endOffset = offset;
computeOffsets();
}
public Vector2D getEndOffset() {
return endOffset;
}
public void computeOffsets() {
startWithOffset = start;
endWithOffset = end;
if(start != null && startOffset != null)
startWithOffset = start.add(startOffset);
if(end != null && endOffset != null)
endWithOffset = end.add(endOffset);
}
public Vector2D getStartWithOffset() {
return startWithOffset;
}
public Vector2D getEndWithOffset() {
return endWithOffset;
}
public void setArrow(SArrow arrow) {
this.arrow = arrow;
}
public SArrow getArrow() {
return arrow;
}
public void setArrowVisible(boolean flag) {
this.arrowVisible = flag;
}
public void setLabel(String label) {
this.label.setTitle(label);
}
public void setLabel(SLabel label) {
this.label = label;
}
public SLabel getLabel() {
return label;
}
public void setSelfLoop(boolean selfLoop) {
this.selfLoop = selfLoop;
}
public boolean isSelfLoop() {
return selfLoop;
}
public void setColor(Color color) {
this.color = color;
}
public Color getColor() {
return color;
}
public void setLabelColor(Color color) {
label.setColor(color);
}
public void setLabelVisible(boolean flag) {
label.setVisible(flag);
}
public boolean isLabelVisible() {
return label.isVisible();
}
public Rect getFrame() {
return new Rect(start, end);
}
public void setMousePosition(Vector2D position) {
}
public abstract boolean contains(double x, double y);
public abstract void update();
public abstract void draw(Graphics2D g);
public abstract void drawShape(Graphics2D g);
}
| bsd-3-clause |
joelmahoney/discoverbps | .gems/gems/actionpack-3.2.22/lib/action_dispatch/testing/assertions/response.rb | 3868 | require 'active_support/core_ext/object/inclusion'
module ActionDispatch
module Assertions
# A small suite of assertions that test responses from \Rails applications.
module ResponseAssertions
extend ActiveSupport::Concern
# Asserts that the response is one of the following types:
#
# * <tt>:success</tt> - Status code was 200
# * <tt>:redirect</tt> - Status code was in the 300-399 range
# * <tt>:missing</tt> - Status code was 404
# * <tt>:error</tt> - Status code was in the 500-599 range
#
# You can also pass an explicit status number like <tt>assert_response(501)</tt>
# or its symbolic equivalent <tt>assert_response(:not_implemented)</tt>.
# See Rack::Utils::SYMBOL_TO_STATUS_CODE for a full list.
#
# ==== Examples
#
# # assert that the response was a redirection
# assert_response :redirect
#
# # assert that the response code was status code 401 (unauthorized)
# assert_response 401
#
def assert_response(type, message = nil)
validate_request!
if type.in?([:success, :missing, :redirect, :error]) && @response.send("#{type}?")
assert_block("") { true } # to count the assertion
elsif type.is_a?(Fixnum) && @response.response_code == type
assert_block("") { true } # to count the assertion
elsif type.is_a?(Symbol) && @response.response_code == Rack::Utils::SYMBOL_TO_STATUS_CODE[type]
assert_block("") { true } # to count the assertion
else
flunk(build_message(message, "Expected response to be a <?>, but was <?>", type, @response.response_code))
end
end
# Assert that the redirection options passed in match those of the redirect called in the latest action.
# This match can be partial, such that <tt>assert_redirected_to(:controller => "weblog")</tt> will also
# match the redirection of <tt>redirect_to(:controller => "weblog", :action => "show")</tt> and so on.
#
# ==== Examples
#
# # assert that the redirection was to the "index" action on the WeblogController
# assert_redirected_to :controller => "weblog", :action => "index"
#
# # assert that the redirection was to the named route login_url
# assert_redirected_to login_url
#
# # assert that the redirection was to the url for @customer
# assert_redirected_to @customer
#
def assert_redirected_to(options = {}, message=nil)
assert_response(:redirect, message)
return true if options == @response.location
redirect_is = normalize_argument_to_redirection(@response.location)
redirect_expected = normalize_argument_to_redirection(options)
if redirect_is != redirect_expected
flunk(build_message(message, "Expected response to be a redirect to <?> but was a redirect to <?>", redirect_expected, redirect_is))
end
end
private
# Proxy to to_param if the object will respond to it.
def parameterize(value)
value.respond_to?(:to_param) ? value.to_param : value
end
def normalize_argument_to_redirection(fragment)
case fragment
when %r{^\w[A-Za-z\d+.-]*:.*}
fragment
when String
@request.protocol + @request.host_with_port + fragment
when :back
raise RedirectBackError unless refer = @request.headers["Referer"]
refer
else
@controller.url_for(fragment)
end.gsub(/[\0\r\n]/, '')
end
def validate_request!
unless @request.is_a?(ActionDispatch::Request)
raise ArgumentError, "@request must be an ActionDispatch::Request"
end
end
end
end
end
| mit |
wKoza/angular | packages/common/locales/global/en-VI.js | 2242 | /**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.io/license
*/
// THIS CODE IS GENERATED - DO NOT MODIFY
// See angular/tools/gulp-tasks/cldr/extract.js
(function(global) {
global.ng = global.ng || {};
global.ng.common = global.ng.common || {};
global.ng.common.locales = global.ng.common.locales || {};
const u = undefined;
function plural(n) {
let i = Math.floor(Math.abs(n)), v = n.toString().replace(/^[^.]*\.?/, '').length;
if (i === 1 && v === 0) return 1;
return 5;
}
global.ng.common.locales['en-vi'] = [
'en-VI',
[['a', 'p'], ['AM', 'PM'], u],
[['AM', 'PM'], u, u],
[
['S', 'M', 'T', 'W', 'T', 'F', 'S'], ['Sun', 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat'],
['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday'],
['Su', 'Mo', 'Tu', 'We', 'Th', 'Fr', 'Sa']
],
u,
[
['J', 'F', 'M', 'A', 'M', 'J', 'J', 'A', 'S', 'O', 'N', 'D'],
['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'],
[
'January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September',
'October', 'November', 'December'
]
],
u,
[['B', 'A'], ['BC', 'AD'], ['Before Christ', 'Anno Domini']],
0,
[6, 0],
['M/d/yy', 'MMM d, y', 'MMMM d, y', 'EEEE, MMMM d, y'],
['h:mm a', 'h:mm:ss a', 'h:mm:ss a z', 'h:mm:ss a zzzz'],
['{1}, {0}', u, '{1} \'at\' {0}', u],
['.', ',', ';', '%', '+', '-', 'E', '×', '‰', '∞', 'NaN', ':'],
['#,##0.###', '#,##0%', '¤#,##0.00', '#E0'],
'USD',
'$',
'US Dollar',
{},
'ltr',
plural,
[
[
['mi', 'n', 'in the morning', 'in the afternoon', 'in the evening', 'at night'],
['midnight', 'noon', 'in the morning', 'in the afternoon', 'in the evening', 'at night'], u
],
[['midnight', 'noon', 'morning', 'afternoon', 'evening', 'night'], u, u],
[
'00:00', '12:00', ['06:00', '12:00'], ['12:00', '18:00'], ['18:00', '21:00'],
['21:00', '06:00']
]
]
];
})(typeof globalThis !== 'undefined' && globalThis || typeof global !== 'undefined' && global ||
typeof window !== 'undefined' && window);
| mit |
auroraocciduusadmin/allReady | AllReadyApp/Web-App/AllReady/Areas/Admin/Features/Tasks/DeleteTaskCommandAsync.cs | 175 | using MediatR;
namespace AllReady.Areas.Admin.Features.Tasks
{
public class DeleteTaskCommandAsync : IAsyncRequest
{
public int TaskId {get; set;}
}
}
| mit |
mayaman26/p5js-website | assets/examples/es/21_Input/04_Mouse1D.js | 522 | /*
* @name Mouse 1D
* @description Move the mouse left and right to
* shift the balance. The "mouseX" variable is used
* to control both the size and color of the rectangles.
*/
function setup() {
createCanvas(720, 400);
noStroke();
rectMode(CENTER);
}
function draw() {
background(230);
let r1 = map(mouseX, 0, width, 0, height);
let r2 = height - r1;
fill(237, 34, 93, r1);
rect(width / 2 + r1 / 2, height / 2, r1, r1);
fill(237, 34, 93, r2);
rect(width / 2 - r2 / 2, height / 2, r2, r2);
}
| mit |
sufuf3/cdnjs | ajax/libs/PickMeUp/2.6.3/js/jquery.pickmeup.js | 32604 | /**
* @package PickMeUp - jQuery datepicker plugin
* @author Nazar Mokrynskyi <nazar@mokrynskyi.com>
* @author Stefan Petre <www.eyecon.ro>
* @copyright Copyright (c) 2013-2015, Nazar Mokrynskyi
* @copyright Copyright (c) 2008-2009, Stefan Petre
* @license MIT License, see license.txt
*/
(function (d) {
function getMaxDays () {
var tmpDate = new Date(this.toString()),
d = 28,
m = tmpDate.getMonth();
while (tmpDate.getMonth() == m) {
++d;
tmpDate.setDate(d);
}
return d - 1;
}
d.addDays = function (n) {
this.setDate(this.getDate() + n);
};
d.addMonths = function (n) {
var day = this.getDate();
this.setDate(1);
this.setMonth(this.getMonth() + n);
this.setDate(Math.min(day, getMaxDays.apply(this)));
};
d.addYears = function (n) {
var day = this.getDate();
this.setDate(1);
this.setFullYear(this.getFullYear() + n);
this.setDate(Math.min(day, getMaxDays.apply(this)));
};
d.getDayOfYear = function() {
var now = new Date(this.getFullYear(), this.getMonth(), this.getDate(), 0, 0, 0);
var then = new Date(this.getFullYear(), 0, 0, 0, 0, 0);
var time = now - then;
return Math.floor(time / 24*60*60*1000);
};
})(Date.prototype);
(function ($) {
var instances_count = 0;
$.pickmeup = $.extend($.pickmeup || {}, {
date : new Date,
default_date : new Date,
flat : false,
first_day : 1,
prev : '◀',
next : '▶',
mode : 'single',
select_year : true,
select_month : true,
select_day : true,
view : 'days',
calendars : 1,
format : 'd-m-Y',
position : 'bottom',
trigger_event : 'click touchstart',
class_name : '',
separator : ' - ',
hide_on_select : false,
min : null,
max : null,
render : function () {},
change : function () {return true;},
before_show : function () {return true;},
show : function () {return true;},
hide : function () {return true;},
fill : function () {return true;},
locale : {
days : ['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday', 'Sunday'],
daysShort : ['Sun', 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun'],
daysMin : ['Su', 'Mo', 'Tu', 'We', 'Th', 'Fr', 'Sa', 'Su'],
months : ['January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December'],
monthsShort : ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec']
}
});
var views = {
years : 'pmu-view-years',
months : 'pmu-view-months',
days : 'pmu-view-days'
},
tpl = {
wrapper : '<div class="pickmeup" />',
head : function (d) {
var result = '';
for (var i = 0; i < 7; ++i) {
result += '<div>' + d.day[i] + '</div>'
}
return '<div class="pmu-instance">' +
'<nav>' +
'<div class="pmu-prev pmu-button">' + d.prev + '</div>' +
'<div class="pmu-month pmu-button" />' +
'<div class="pmu-next pmu-button">' + d.next + '</div>' +
'</nav>' +
'<nav class="pmu-day-of-week">' + result + '</nav>' +
'</div>';
},
body : function (elements, container_class_name) {
var result = '';
for (var i = 0; i < elements.length; ++i) {
result += '<div class="' + elements[i].class_name + ' pmu-button">' + elements[i].text + '</div>'
}
return '<div class="' + container_class_name + '">' + result + '</div>';
}
};
function fill () {
var options = $(this).data('pickmeup-options'),
pickmeup = this.pickmeup,
current_cal = Math.floor(options.calendars / 2),
actual_date = options.date,
current_date = options.current,
min_date = options.min ? new Date(options.min) : null,
max_date = options.max ? new Date(options.max) : null,
local_date,
header,
html,
instance,
today = (new Date).setHours(0,0,0,0).valueOf(),
shown_date_from,
shown_date_to,
tmp_date;
if (min_date) {
min_date.setDate(1);
min_date.addMonths(1);
min_date.addDays(-1);
}
if (max_date) {
max_date.setDate(1);
max_date.addMonths(1);
max_date.addDays(-1);
}
/**
* Remove old content except header navigation
*/
pickmeup.find('.pmu-instance > :not(nav)').remove();
/**
* If several calendars should be shown
*/
for (var i = 0; i < options.calendars; i++) {
local_date = new Date(current_date);
instance = pickmeup.find('.pmu-instance').eq(i);
if (pickmeup.hasClass('pmu-view-years')) {
local_date.addYears((i - current_cal) * 12);
header = (local_date.getFullYear() - 6) + ' - ' + (local_date.getFullYear()+5);
} else if (pickmeup.hasClass('pmu-view-months')) {
local_date.addYears(i - current_cal);
header = local_date.getFullYear();
} else if (pickmeup.hasClass('pmu-view-days')) {
local_date.addMonths(i - current_cal);
header = formatDate(local_date, 'B, Y', options.locale);
}
if (!shown_date_to) {
if (max_date) {
// If all dates in this month (months in year or years in years block) are after max option - set next month as current
// in order not to show calendar with all disabled dates
tmp_date = new Date(local_date);
if (options.select_day) {
tmp_date.addMonths(options.calendars - 1);
} else if (options.select_month) {
tmp_date.addYears(options.calendars - 1);
} else {
tmp_date.addYears((options.calendars - 1) * 12);
}
if (tmp_date > max_date) {
--i;
current_date.addMonths(-1);
shown_date_to = undefined;
continue;
}
}
}
shown_date_to = new Date(local_date);
if (!shown_date_from) {
shown_date_from = new Date(local_date);
// If all dates in this month are before min option - set next month as current in order not to show calendar with all disabled dates
shown_date_from.setDate(1);
shown_date_from.addMonths(1);
shown_date_from.addDays(-1);
if (min_date && min_date > shown_date_from) {
--i;
current_date.addMonths(1);
shown_date_from = undefined;
continue;
}
}
instance
.find('.pmu-month')
.text(header);
html = '';
var is_year_selected = function (year) {
return (
options.mode == 'range' &&
year >= new Date(actual_date[0]).getFullYear() &&
year <= new Date(actual_date[1]).getFullYear()
) ||
(
options.mode == 'multiple' &&
actual_date.reduce(function (prev, current) {
prev.push(new Date(current).getFullYear());
return prev;
}, []).indexOf(year) !== -1
) ||
new Date(actual_date).getFullYear() == year;
};
var is_months_selected = function (year, month) {
var first_year = new Date(actual_date[0]).getFullYear(),
lastyear = new Date(actual_date[1]).getFullYear(),
first_month = new Date(actual_date[0]).getMonth(),
last_month = new Date(actual_date[1]).getMonth();
return (
options.mode == 'range' &&
year > first_year &&
year < lastyear
) ||
(
options.mode == 'range' &&
year == first_year &&
year < lastyear &&
month >= first_month
) ||
(
options.mode == 'range' &&
year > first_year &&
year == lastyear &&
month <= last_month
) ||
(
options.mode == 'range' &&
year == first_year &&
year == lastyear &&
month >= first_month &&
month <= last_month
) ||
(
options.mode == 'multiple' &&
actual_date.reduce(function (prev, current) {
current = new Date(current);
prev.push(current.getFullYear() + '-' + current.getMonth());
return prev;
}, []).indexOf(year + '-' + month) !== -1
) ||
(
new Date(actual_date).getFullYear() == year &&
new Date(actual_date).getMonth() == month
)
};
(function () {
var years = [],
start_from_year = local_date.getFullYear() - 6,
min_year = new Date(options.min).getFullYear(),
max_year = new Date(options.max).getFullYear(),
year;
for (var j = 0; j < 12; ++j) {
year = {
text : start_from_year + j,
class_name : []
};
if (
(
options.min && year.text < min_year
) ||
(
options.max && year.text > max_year
)
) {
year.class_name.push('pmu-disabled');
} else if (is_year_selected(year.text)) {
year.class_name.push('pmu-selected');
}
year.class_name = year.class_name.join(' ');
years.push(year);
}
html += tpl.body(years, 'pmu-years');
})();
(function () {
var months = [],
current_year = local_date.getFullYear(),
min_year = new Date(options.min).getFullYear(),
min_month = new Date(options.min).getMonth(),
max_year = new Date(options.max).getFullYear(),
max_month = new Date(options.max).getMonth(),
month;
for (var j = 0; j < 12; ++j) {
month = {
text : options.locale.monthsShort[j],
class_name : []
};
if (
(
options.min &&
(
current_year < min_year ||
(
j < min_month && current_year == min_year
)
)
) ||
(
options.max &&
(
current_year > max_year ||
(
j > max_month && current_year >= max_year
)
)
)
) {
month.class_name.push('pmu-disabled');
} else if (is_months_selected(current_year, j)) {
month.class_name.push('pmu-selected');
}
month.class_name = month.class_name.join(' ');
months.push(month);
}
html += tpl.body(months, 'pmu-months');
})();
(function () {
var days = [],
current_month = local_date.getMonth(),
day;
// Correct first day in calendar taking into account first day of week (Sunday or Monday)
(function () {
local_date.setDate(1);
var day = (local_date.getDay() - options.first_day) % 7;
local_date.addDays(-(day + (day < 0 ? 7 : 0)));
})();
for (var j = 0; j < 42; ++j) {
day = {
text : local_date.getDate(),
class_name : []
};
if (current_month != local_date.getMonth()) {
day.class_name.push('pmu-not-in-month');
}
if (local_date.getDay() == 0) {
day.class_name.push('pmu-sunday');
} else if (local_date.getDay() == 6) {
day.class_name.push('pmu-saturday');
}
var from_user = options.render(new Date(local_date)) || {},
val = local_date.valueOf(),
disabled = (options.min && options.min > local_date) || (options.max && options.max < local_date);
if (from_user.disabled || disabled) {
day.class_name.push('pmu-disabled');
} else if (
from_user.selected ||
options.date == val ||
$.inArray(val, options.date) !== -1 ||
(
options.mode == 'range' && val >= options.date[0] && val <= options.date[1]
)
) {
day.class_name.push('pmu-selected');
}
if (val == today) {
day.class_name.push('pmu-today');
}
if (from_user.class_name) {
day.class_name.push(from_user.class_name);
}
day.class_name = day.class_name.join(' ');
days.push(day);
// Move to next day
local_date.addDays(1);
}
html += tpl.body(days, 'pmu-days');
})();
instance.append(html);
}
shown_date_from.setDate(1);
shown_date_to.setDate(1);
shown_date_to.addMonths(1);
shown_date_to.addDays(-1);
pickmeup.find('.pmu-prev').css(
'visibility',
options.min && options.min >= shown_date_from ? 'hidden' : 'visible'
);
pickmeup.find('.pmu-next').css(
'visibility',
options.max && options.max <= shown_date_to ? 'hidden' : 'visible'
);
options.fill.apply(this);
}
function parseDate (date, format, separator, locale) {
if (date.constructor == Date) {
return date;
} else if (!date) {
return new Date;
}
var splitted_date = date.split(separator);
if (splitted_date.length > 1) {
splitted_date.forEach(function (element, index, array) {
array[index] = parseDate($.trim(element), format, separator, locale);
});
return splitted_date;
}
var months_text = locale.monthsShort.join(')(') + ')(' + locale.months.join(')('),
separator = new RegExp('[^0-9a-zA-Z(' + months_text + ')]+'),
parts = date.split(separator),
against = format.split(separator),
d,
m,
y,
h,
min,
now = new Date();
for (var i = 0; i < parts.length; i++) {
switch (against[i]) {
case 'b':
m = locale.monthsShort.indexOf(parts[i]);
break;
case 'B':
m = locale.months.indexOf(parts[i]);
break;
case 'd':
case 'e':
d = parseInt(parts[i],10);
break;
case 'm':
m = parseInt(parts[i], 10)-1;
break;
case 'Y':
case 'y':
y = parseInt(parts[i], 10);
y += y > 100 ? 0 : (y < 29 ? 2000 : 1900);
break;
case 'H':
case 'I':
case 'k':
case 'l':
h = parseInt(parts[i], 10);
break;
case 'P':
case 'p':
if (/pm/i.test(parts[i]) && h < 12) {
h += 12;
} else if (/am/i.test(parts[i]) && h >= 12) {
h -= 12;
}
break;
case 'M':
min = parseInt(parts[i], 10);
break;
}
}
var parsed_date = new Date(
y === undefined ? now.getFullYear() : y,
m === undefined ? now.getMonth() : m,
d === undefined ? now.getDate() : d,
h === undefined ? now.getHours() : h,
min === undefined ? now.getMinutes() : min,
0
);
if (isNaN(parsed_date * 1)) {
parsed_date = new Date;
}
return parsed_date;
}
function formatDate (date, format, locale) {
var m = date.getMonth();
var d = date.getDate();
var y = date.getFullYear();
var w = date.getDay();
var s = {};
var hr = date.getHours();
var pm = (hr >= 12);
var ir = (pm) ? (hr - 12) : hr;
var dy = date.getDayOfYear();
if (ir == 0) {
ir = 12;
}
var min = date.getMinutes();
var sec = date.getSeconds();
var parts = format.split(''), part;
for (var i = 0; i < parts.length; i++) {
part = parts[i];
switch (part) {
case 'a':
part = locale.daysShort[w];
break;
case 'A':
part = locale.days[w];
break;
case 'b':
part = locale.monthsShort[m];
break;
case 'B':
part = locale.months[m];
break;
case 'C':
part = 1 + Math.floor(y / 100);
break;
case 'd':
part = (d < 10) ? ("0" + d) : d;
break;
case 'e':
part = d;
break;
case 'H':
part = (hr < 10) ? ("0" + hr) : hr;
break;
case 'I':
part = (ir < 10) ? ("0" + ir) : ir;
break;
case 'j':
part = (dy < 100) ? ((dy < 10) ? ("00" + dy) : ("0" + dy)) : dy;
break;
case 'k':
part = hr;
break;
case 'l':
part = ir;
break;
case 'm':
part = (m < 9) ? ("0" + (1+m)) : (1+m);
break;
case 'M':
part = (min < 10) ? ("0" + min) : min;
break;
case 'p':
case 'P':
part = pm ? "PM" : "AM";
break;
case 's':
part = Math.floor(date.getTime() / 1000);
break;
case 'S':
part = (sec < 10) ? ("0" + sec) : sec;
break;
case 'u':
part = w + 1;
break;
case 'w':
part = w;
break;
case 'y':
part = ('' + y).substr(2, 2);
break;
case 'Y':
part = y;
break;
}
parts[i] = part;
}
return parts.join('');
}
function update_date () {
var $this = $(this),
options = $this.data('pickmeup-options'),
current_date = options.current,
new_value;
switch (options.mode) {
case 'multiple':
new_value = current_date.setHours(0,0,0,0).valueOf();
if ($.inArray(new_value, options.date) !== -1) {
$.each(options.date, function (index, value){
if (value == new_value) {
options.date.splice(index,1);
return false;
}
return true;
});
} else {
options.date.push(new_value);
}
break;
case 'range':
if (!options.lastSel) {
options.date[0] = current_date.setHours(0,0,0,0).valueOf();
}
new_value = current_date.setHours(0,0,0,0).valueOf();
if (new_value <= options.date[0]) {
options.date[1] = options.date[0];
options.date[0] = new_value;
} else {
options.date[1] = new_value;
}
options.lastSel = !options.lastSel;
break;
default:
options.date = current_date.valueOf();
break;
}
var prepared_date = prepareDate(options);
if ($this.is('input')) {
$this.val(options.mode == 'single' ? prepared_date[0] : prepared_date[0].join(options.separator));
}
options.change.apply(this, prepared_date);
if (
!options.flat &&
options.hide_on_select &&
(
options.mode != 'range' ||
!options.lastSel
)
) {
options.binded.hide();
return false;
}
}
function click (e) {
var el = $(e.target);
if (!el.hasClass('pmu-button')) {
el = el.closest('.pmu-button');
}
if (el.length) {
if (el.hasClass('pmu-disabled')) {
return false;
}
var $this = $(this),
options = $this.data('pickmeup-options'),
instance = el.parents('.pmu-instance').eq(0),
root = instance.parent(),
instance_index = $('.pmu-instance', root).index(instance);
if (el.parent().is('nav')) {
if (el.hasClass('pmu-month')) {
options.current.addMonths(instance_index - Math.floor(options.calendars / 2));
if (root.hasClass('pmu-view-years')) {
// Shift back to current date, otherwise with min value specified may jump on few (tens) years forward
if (options.mode != 'single') {
options.current = new Date(options.date[options.date.length - 1]);
} else {
options.current = new Date(options.date);
}
if (options.select_day) {
root.removeClass('pmu-view-years').addClass('pmu-view-days');
} else if (options.select_month) {
root.removeClass('pmu-view-years').addClass('pmu-view-months');
}
} else if (root.hasClass('pmu-view-months')) {
if (options.select_year) {
root.removeClass('pmu-view-months').addClass('pmu-view-years');
} else if (options.select_day) {
root.removeClass('pmu-view-months').addClass('pmu-view-days');
}
} else if (root.hasClass('pmu-view-days')) {
if (options.select_month) {
root.removeClass('pmu-view-days').addClass('pmu-view-months');
} else if (options.select_year) {
root.removeClass('pmu-view-days').addClass('pmu-view-years');
}
}
} else {
if (el.hasClass('pmu-prev')) {
options.binded.prev(false);
} else {
options.binded.next(false);
}
}
} else if (!el.hasClass('pmu-disabled')) {
if (root.hasClass('pmu-view-years')) {
options.current.setFullYear(parseInt(el.text(), 10));
if (options.select_month) {
root.removeClass('pmu-view-years').addClass('pmu-view-months');
} else if (options.select_day) {
root.removeClass('pmu-view-years').addClass('pmu-view-days');
} else {
options.binded.update_date();
}
} else if (root.hasClass('pmu-view-months')) {
options.current.setMonth(instance.find('.pmu-months .pmu-button').index(el));
options.current.setFullYear(parseInt(instance.find('.pmu-month').text(), 10));
if (options.select_day) {
root.removeClass('pmu-view-months').addClass('pmu-view-days');
} else {
options.binded.update_date();
}
// Move current month to the first place
options.current.addMonths(Math.floor(options.calendars / 2) - instance_index);
} else {
var val = parseInt(el.text(), 10);
options.current.addMonths(instance_index - Math.floor(options.calendars / 2));
if (el.hasClass('pmu-not-in-month')) {
options.current.addMonths(val > 15 ? -1 : 1);
}
options.current.setDate(val);
options.binded.update_date();
}
}
options.binded.fill();
}
return false;
}
function prepareDate (options) {
var result;
if (options.mode == 'single') {
result = new Date(options.date);
return [formatDate(result, options.format, options.locale), result];
} else {
result = [[],[]];
$.each(options.date, function(nr, val){
var date = new Date(val);
result[0].push(formatDate(date, options.format, options.locale));
result[1].push(date);
});
return result;
}
}
function show (force) {
var pickmeup = this.pickmeup;
if (force || !pickmeup.is(':visible')) {
var $this = $(this),
options = $this.data('pickmeup-options'),
pos = $this.offset(),
viewport = {
l : document.documentElement.scrollLeft,
t : document.documentElement.scrollTop,
w : document.documentElement.clientWidth,
h : document.documentElement.clientHeight
},
top = pos.top,
left = pos.left;
options.binded.fill();
if ($this.is('input')) {
$this
.pickmeup('set_date', parseDate(($this.val()) ? $this.val() : options.default_date, options.format, options.separator, options.locale))
.keydown(function (e) {
if (e.which == 9) {
$this.pickmeup('hide');
}
});
}
options.before_show();
if (options.show() == false) {
return;
}
if (!options.flat) {
switch (options.position){
case 'top':
top -= pickmeup.outerHeight();
break;
case 'left':
left -= pickmeup.outerWidth();
break;
case 'right':
left += this.offsetWidth;
break;
case 'bottom':
top += this.offsetHeight;
break;
}
if (top + pickmeup.offsetHeight > viewport.t + viewport.h) {
top = pos.top - pickmeup.offsetHeight;
}
if (top < viewport.t) {
top = pos.top + this.offsetHeight + pickmeup.offsetHeight;
}
if (left + pickmeup.offsetWidth > viewport.l + viewport.w) {
left = pos.left - pickmeup.offsetWidth;
}
if (left < viewport.l) {
left = pos.left + this.offsetWidth
}
pickmeup.css({
display : 'inline-block',
top : top + 'px',
left : left + 'px'
});
$(document)
.on(
'mousedown' + options.events_namespace,
options.binded.hide
)
.on(
'resize' + options.events_namespace,
[
true
],
options.binded.forced_show
);
}
}
}
function forced_show () {
show.call(this, true);
}
function hide (e) {
if (
!e ||
!e.target || //Called directly
(
e.target != this && //Clicked not on element itself
!(this.pickmeup.get(0).compareDocumentPosition(e.target) & 16) //And not o its children
)
) {
var pickmeup = this.pickmeup,
options = $(this).data('pickmeup-options');
if (options.hide() != false) {
pickmeup.hide();
$(document)
.off('mousedown', options.binded.hide)
.off('resize', options.binded.forced_show);
options.lastSel = false;
}
}
}
function update () {
var options = $(this).data('pickmeup-options');
$(document)
.off('mousedown', options.binded.hide)
.off('resize', options.binded.forced_show);
options.binded.forced_show();
}
function clear () {
var options = $(this).data('pickmeup-options');
if (options.mode != 'single') {
options.date = [];
options.lastSel = false;
options.binded.fill();
}
}
function prev (fill) {
if (typeof fill == 'undefined') {
fill = true;
}
var root = this.pickmeup;
var options = $(this).data('pickmeup-options');
if (root.hasClass('pmu-view-years')) {
options.current.addYears(-12);
} else if (root.hasClass('pmu-view-months')) {
options.current.addYears(-1);
} else if (root.hasClass('pmu-view-days')) {
options.current.addMonths(-1);
}
if (fill) {
options.binded.fill();
}
}
function next (fill) {
if (typeof fill == 'undefined') {
fill = true;
}
var root = this.pickmeup;
var options = $(this).data('pickmeup-options');
if (root.hasClass('pmu-view-years')) {
options.current.addYears(12);
} else if (root.hasClass('pmu-view-months')) {
options.current.addYears(1);
} else if (root.hasClass('pmu-view-days')) {
options.current.addMonths(1);
}
if (fill) {
options.binded.fill();
}
}
function get_date (formatted) {
var options = $(this).data('pickmeup-options'),
prepared_date = prepareDate(options);
if (typeof formatted === 'string') {
var date = prepared_date[1];
if (date.constructor == Date) {
return formatDate(date, formatted, options.locale)
} else {
return date.map(function (value) {
return formatDate(value, formatted, options.locale);
});
}
} else {
return prepared_date[formatted ? 0 : 1];
}
}
function set_date (date) {
var options = $(this).data('pickmeup-options');
options.date = date;
if (typeof options.date === 'string') {
options.date = parseDate(options.date, options.format, options.separator, options.locale).setHours(0,0,0,0);
} else if (options.date.constructor == Date) {
options.date.setHours(0,0,0,0);
}
if (!options.date) {
options.date = new Date;
options.date.setHours(0,0,0,0);
}
if (options.mode != 'single') {
if (options.date.constructor != Array) {
options.date = [options.date.valueOf()];
if (options.mode == 'range') {
options.date.push(((new Date(options.date[0])).setHours(0,0,0,0)).valueOf());
}
} else {
for (var i = 0; i < options.date.length; i++) {
options.date[i] = (parseDate(options.date[i], options.format, options.separator, options.locale).setHours(0,0,0,0)).valueOf();
}
if (options.mode == 'range') {
options.date[1] = ((new Date(options.date[1])).setHours(0,0,0,0)).valueOf();
}
}
} else {
options.date = options.date.constructor == Array ? options.date[0].valueOf() : options.date.valueOf();
}
options.current = new Date (options.mode != 'single' ? options.date[0] : options.date);
options.binded.fill();
}
function destroy () {
var $this = $(this),
options = $this.data('pickmeup-options');
$this.removeData('pickmeup-options');
$this.off(options.events_namespace);
$(document).off(options.events_namespace);
$(this.pickmeup).remove();
}
$.fn.pickmeup = function (initial_options) {
if (typeof initial_options === 'string') {
var data,
parameters = Array.prototype.slice.call(arguments, 1);
switch (initial_options) {
case 'hide':
case 'show':
case 'clear':
case 'update':
case 'prev':
case 'next':
case 'destroy':
this.each(function () {
data = $(this).data('pickmeup-options');
if (data) {
data.binded[initial_options]();
}
});
break;
case 'get_date':
data = this.data('pickmeup-options');
if (data) {
return data.binded.get_date(parameters[0]);
} else {
return null;
}
break;
case 'set_date':
this.each(function () {
data = $(this).data('pickmeup-options');
if (data) {
data.binded[initial_options].apply(this, parameters);
}
});
}
return this;
}
return this.each(function () {
var $this = $(this);
if ($this.data('pickmeup-options')) {
return;
}
var i,
option,
options = $.extend({}, $.pickmeup, initial_options || {});
for (i in options) {
option = $this.data('pmu-' + i);
if (typeof option !== 'undefined') {
options[i] = option;
}
}
// 4 conditional statements in order to account all cases
if (options.view == 'days' && !options.select_day) {
options.view = 'months';
}
if (options.view == 'months' && !options.select_month) {
options.view = 'years';
}
if (options.view == 'years' && !options.select_year) {
options.view = 'days';
}
if (options.view == 'days' && !options.select_day) {
options.view = 'months';
}
options.calendars = Math.max(1, parseInt(options.calendars, 10) || 1);
options.mode = /single|multiple|range/.test(options.mode) ? options.mode : 'single';
if (typeof options.min === 'string') {
options.min = parseDate(options.min, options.format, options.separator, options.locale).setHours(0,0,0,0);
} else if (options.min && options.min.constructor == Date) {
options.min.setHours(0,0,0,0);
}
if (typeof options.max === 'string') {
options.max = parseDate(options.max, options.format, options.separator, options.locale).setHours(0,0,0,0);
} else if (options.max && options.max.constructor == Date) {
options.max.setHours(0,0,0,0);
}
if (!options.select_day) {
if (options.min) {
options.min = new Date(options.min);
options.min.setDate(1);
options.min = options.min.valueOf();
}
if (options.max) {
options.max = new Date(options.max);
options.max.setDate(1);
options.max = options.max.valueOf();
}
}
if (typeof options.date === 'string') {
options.date = parseDate(options.date, options.format, options.separator, options.locale).setHours(0,0,0,0);
} else if (options.date.constructor == Date) {
options.date.setHours(0,0,0,0);
}
if (!options.date) {
options.date = new Date;
options.date.setHours(0,0,0,0);
}
if (options.mode != 'single') {
if (options.date.constructor != Array) {
options.date = [options.date.valueOf()];
if (options.mode == 'range') {
options.date.push(((new Date(options.date[0])).setHours(0,0,0,0)).valueOf());
}
} else {
for (i = 0; i < options.date.length; i++) {
options.date[i] = (parseDate(options.date[i], options.format, options.separator, options.locale).setHours(0,0,0,0)).valueOf();
}
if (options.mode == 'range') {
options.date[1] = ((new Date(options.date[1])).setHours(0,0,0,0)).valueOf();
}
}
options.current = new Date(options.date[0]);
// Set days to 1 in order to handle them consistently
if (!options.select_day) {
for (i = 0; i < options.date.length; ++i) {
options.date[i] = new Date(options.date[i]);
options.date[i].setDate(1);
options.date[i] = options.date[i].valueOf();
// Remove duplicates
if (
options.mode != 'range' &&
options.date.indexOf(options.date[i]) !== i
) {
delete options.date.splice(i, 1);
--i;
}
}
}
} else {
options.date = options.date.valueOf();
options.current = new Date(options.date);
if (!options.select_day) {
options.date = new Date(options.date);
options.date.setDate(1);
options.date = options.date.valueOf();
}
}
options.current.setDate(1);
options.current.setHours(0,0,0,0);
var cnt,
pickmeup = $(tpl.wrapper);
this.pickmeup = pickmeup;
if (options.class_name) {
pickmeup.addClass(options.class_name);
}
var html = '';
for (i = 0; i < options.calendars; i++) {
cnt = options.first_day;
html += tpl.head({
prev : options.prev,
next : options.next,
day : [
options.locale.daysMin[(cnt++) % 7],
options.locale.daysMin[(cnt++) % 7],
options.locale.daysMin[(cnt++) % 7],
options.locale.daysMin[(cnt++) % 7],
options.locale.daysMin[(cnt++) % 7],
options.locale.daysMin[(cnt++) % 7],
options.locale.daysMin[(cnt++) % 7]
]
});
}
$this.data('pickmeup-options', options);
for (i in options) {
if (['render', 'change', 'before_show', 'show', 'hide'].indexOf(i) != -1) {
options[i] = options[i].bind(this);
}
}
options.binded = {
fill : fill.bind(this),
update_date : update_date.bind(this),
click : click.bind(this),
show : show.bind(this),
forced_show : forced_show.bind(this),
hide : hide.bind(this),
update : update.bind(this),
clear : clear.bind(this),
prev : prev.bind(this),
next : next.bind(this),
get_date : get_date.bind(this),
set_date : set_date.bind(this),
destroy : destroy.bind(this)
};
options.events_namespace = '.pickmeup-' + (++instances_count);
pickmeup
.on('click touchstart', options.binded.click)
.addClass(views[options.view])
.append(html)
.on(
$.support.selectstart ? 'selectstart' : 'mousedown',
function(e){
e.preventDefault();
}
);
options.binded.fill();
if (options.flat) {
pickmeup.appendTo(this).css({
position : 'relative',
display : 'inline-block'
});
} else {
pickmeup.appendTo(document.body);
// Multiple events support
var trigger_event = options.trigger_event.split(' ');
for (i = 0; i < trigger_event.length; ++i) {
trigger_event[i] += options.events_namespace;
}
trigger_event = trigger_event.join(' ');
$this.on(trigger_event, options.binded.show);
}
});
};
})(jQuery);
| mit |
mxrrow/zaicoin | src/deps/boost/libs/intrusive/test/splay_multiset_test.cpp | 5911 | /////////////////////////////////////////////////////////////////////////////
//
// (C) Copyright Olaf Krzikalla 2004-2006.
// (C) Copyright Ion Gaztanaga 2006-2012.
//
// Distributed under the Boost Software License, Version 1.0.
// (See accompanying file LICENSE_1_0.txt or copy at
// http://www.boost.org/LICENSE_1_0.txt)
//
// See http://www.boost.org/libs/intrusive for documentation.
//
/////////////////////////////////////////////////////////////////////////////
#include <boost/intrusive/detail/config_begin.hpp>
#include <boost/intrusive/splay_set.hpp>
#include <boost/intrusive/pointer_traits.hpp>
#include "itestvalue.hpp"
#include "smart_ptr.hpp"
#include "generic_multiset_test.hpp"
namespace boost { namespace intrusive { namespace test {
#if !defined (BOOST_INTRUSIVE_VARIADIC_TEMPLATES)
template<class T, class O1, class O2, class O3, class O4>
#else
template<class T, class ...Options>
#endif
struct has_const_overloads<boost::intrusive::splay_multiset<
#if !defined (BOOST_INTRUSIVE_VARIADIC_TEMPLATES)
T, O1, O2, O3, O4
#else
T, Options...
#endif
>
>
{
static const bool value = false;
};
#if !defined (BOOST_INTRUSIVE_VARIADIC_TEMPLATES)
template<class T, class O1, class O2, class O3, class O4>
#else
template<class T, class ...Options>
#endif
struct has_splay<boost::intrusive::splay_multiset<T,
#if !defined (BOOST_INTRUSIVE_VARIADIC_TEMPLATES)
O1, O2, O3, O4
#else
Options...
#endif
> >
{
static const bool value = true;
};
#if !defined (BOOST_INTRUSIVE_VARIADIC_TEMPLATES)
template<class T, class O1, class O2, class O3, class O4>
#else
template<class T, class ...Options>
#endif
struct has_rebalance<boost::intrusive::splay_multiset<T,
#if !defined (BOOST_INTRUSIVE_VARIADIC_TEMPLATES)
O1, O2, O3, O4
#else
Options...
#endif
> >
{
static const bool value = true;
};
#if !defined (BOOST_INTRUSIVE_VARIADIC_TEMPLATES)
template<class T, class O1, class O2, class O3, class O4>
#else
template<class T, class ...Options>
#endif
struct has_const_searches<boost::intrusive::splay_multiset<T,
#if !defined (BOOST_INTRUSIVE_VARIADIC_TEMPLATES)
O1, O2, O3, O4
#else
Options...
#endif
> >
{
static const bool value = false;
};
}}}
using namespace boost::intrusive;
struct my_tag;
template<class VoidPointer>
struct hooks
{
typedef splay_set_base_hook<void_pointer<VoidPointer> > base_hook_type;
typedef splay_set_base_hook
< link_mode<auto_unlink>
, void_pointer<VoidPointer>
, tag<my_tag> > auto_base_hook_type;
typedef splay_set_member_hook<void_pointer<VoidPointer> > member_hook_type;
typedef splay_set_member_hook
< link_mode<auto_unlink>
, void_pointer<VoidPointer> > auto_member_hook_type;
};
template< class ValueType
, class Option1 = boost::intrusive::none
, class Option2 = boost::intrusive::none
, class Option3 = boost::intrusive::none
>
struct GetContainer
{
typedef boost::intrusive::splay_multiset
< ValueType
, Option1
, Option2
, Option3
> type;
};
template<class VoidPointer, bool constant_time_size>
class test_main_template
{
public:
int operator()()
{
using namespace boost::intrusive;
typedef testvalue<hooks<VoidPointer> , constant_time_size> value_type;
test::test_generic_multiset < typename detail::get_base_value_traits
< value_type
, typename hooks<VoidPointer>::base_hook_type
>::type
, GetContainer
>::test_all();
test::test_generic_multiset < typename detail::get_member_value_traits
< value_type
, member_hook< value_type
, typename hooks<VoidPointer>::member_hook_type
, &value_type::node_
>
>::type
, GetContainer
>::test_all();
return 0;
}
};
template<class VoidPointer>
class test_main_template<VoidPointer, false>
{
public:
int operator()()
{
using namespace boost::intrusive;
typedef testvalue<hooks<VoidPointer> , false> value_type;
test::test_generic_multiset < typename detail::get_base_value_traits
< value_type
, typename hooks<VoidPointer>::base_hook_type
>::type
, GetContainer
>::test_all();
test::test_generic_multiset < typename detail::get_member_value_traits
< value_type
, member_hook< value_type
, typename hooks<VoidPointer>::member_hook_type
, &value_type::node_
>
>::type
, GetContainer
>::test_all();
test::test_generic_multiset < typename detail::get_base_value_traits
< value_type
, typename hooks<VoidPointer>::auto_base_hook_type
>::type
, GetContainer
>::test_all();
test::test_generic_multiset < typename detail::get_member_value_traits
< value_type
, member_hook< value_type
, typename hooks<VoidPointer>::auto_member_hook_type
, &value_type::auto_node_
>
>::type
, GetContainer
>::test_all();
return 0;
}
};
int main( int, char* [] )
{
test_main_template<void*, false>()();
test_main_template<boost::intrusive::smart_ptr<void>, false>()();
test_main_template<void*, true>()();
test_main_template<boost::intrusive::smart_ptr<void>, true>()();
return boost::report_errors();
}
| mit |
savichris/spongycastle | core/src/main/java/org/spongycastle/crypto/prng/EntropySourceProvider.java | 129 | package org.spongycastle.crypto.prng;
public interface EntropySourceProvider
{
EntropySource get(final int bitsRequired);
}
| mit |
DavidRogers/kato | src/FirstFloor.ModernUI/Windows/Navigation/NavigationFailedEventArgs.cs | 909 | using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using FirstFloor.ModernUI.Windows.Controls;
namespace FirstFloor.ModernUI.Windows.Navigation
{
/// <summary>
/// Provides data for the <see cref="ModernFrame.NavigationFailed"/> event.
/// </summary>
public class NavigationFailedEventArgs
: NavigationBaseEventArgs
{
/// <summary>
/// Gets the error from the failed navigation.
/// </summary>
public Exception Error { get; internal set; }
/// <summary>
/// Gets or sets a value that indicates whether the failure event has been handled.
/// </summary>
/// <remarks>
/// When not handled, the error is displayed in the ModernFrame raising the NavigationFailed event.
/// </remarks>
public bool Handled { get; set; }
}
}
| mit |
NikRimington/Umbraco-CMS | src/Umbraco.Core/UdiGetterExtensions.cs | 13870 | using System;
using Umbraco.Core.Models;
using Umbraco.Core.Models.Entities;
namespace Umbraco.Core
{
/// <summary>
/// Provides extension methods that return udis for Umbraco entities.
/// </summary>
public static class UdiGetterExtensions
{
/// <summary>
/// Gets the entity identifier of the entity.
/// </summary>
/// <param name="entity">The entity.</param>
/// <returns>The entity identifier of the entity.</returns>
public static GuidUdi GetUdi(this ITemplate entity)
{
if (entity == null) throw new ArgumentNullException("entity");
return new GuidUdi(Constants.UdiEntityType.Template, entity.Key).EnsureClosed();
}
/// <summary>
/// Gets the entity identifier of the entity.
/// </summary>
/// <param name="entity">The entity.</param>
/// <returns>The entity identifier of the entity.</returns>
public static GuidUdi GetUdi(this IContentType entity)
{
if (entity == null) throw new ArgumentNullException("entity");
return new GuidUdi(Constants.UdiEntityType.DocumentType, entity.Key).EnsureClosed();
}
/// <summary>
/// Gets the entity identifier of the entity.
/// </summary>
/// <param name="entity">The entity.</param>
/// <returns>The entity identifier of the entity.</returns>
public static GuidUdi GetUdi(this IMediaType entity)
{
if (entity == null) throw new ArgumentNullException("entity");
return new GuidUdi(Constants.UdiEntityType.MediaType, entity.Key).EnsureClosed();
}
/// <summary>
/// Gets the entity identifier of the entity.
/// </summary>
/// <param name="entity">The entity.</param>
/// <returns>The entity identifier of the entity.</returns>
public static GuidUdi GetUdi(this IMemberType entity)
{
if (entity == null) throw new ArgumentNullException("entity");
return new GuidUdi(Constants.UdiEntityType.MemberType, entity.Key).EnsureClosed();
}
/// <summary>
/// Gets the entity identifier of the entity.
/// </summary>
/// <param name="entity">The entity.</param>
/// <returns>The entity identifier of the entity.</returns>
public static GuidUdi GetUdi(this IMemberGroup entity)
{
if (entity == null) throw new ArgumentNullException("entity");
return new GuidUdi(Constants.UdiEntityType.MemberGroup, entity.Key).EnsureClosed();
}
/// <summary>
/// Gets the entity identifier of the entity.
/// </summary>
/// <param name="entity">The entity.</param>
/// <returns>The entity identifier of the entity.</returns>
public static GuidUdi GetUdi(this IContentTypeComposition entity)
{
if (entity == null) throw new ArgumentNullException("entity");
string type;
if (entity is IContentType) type = Constants.UdiEntityType.DocumentType;
else if (entity is IMediaType) type = Constants.UdiEntityType.MediaType;
else if (entity is IMemberType) type = Constants.UdiEntityType.MemberType;
else throw new NotSupportedException(string.Format("Composition type {0} is not supported.", entity.GetType().FullName));
return new GuidUdi(type, entity.Key).EnsureClosed();
}
/// <summary>
/// Gets the entity identifier of the entity.
/// </summary>
/// <param name="entity">The entity.</param>
/// <returns>The entity identifier of the entity.</returns>
public static GuidUdi GetUdi(this IDataType entity)
{
if (entity == null) throw new ArgumentNullException("entity");
return new GuidUdi(Constants.UdiEntityType.DataType, entity.Key).EnsureClosed();
}
/// <summary>
/// Gets the entity identifier of the entity.
/// </summary>
/// <param name="entity">The entity.</param>
/// <returns>The entity identifier of the entity.</returns>
public static GuidUdi GetUdi(this EntityContainer entity)
{
if (entity == null) throw new ArgumentNullException("entity");
string entityType;
if (entity.ContainedObjectType == Constants.ObjectTypes.DataType)
entityType = Constants.UdiEntityType.DataTypeContainer;
else if (entity.ContainedObjectType == Constants.ObjectTypes.DocumentType)
entityType = Constants.UdiEntityType.DocumentTypeContainer;
else if (entity.ContainedObjectType == Constants.ObjectTypes.MediaType)
entityType = Constants.UdiEntityType.MediaTypeContainer;
else
throw new NotSupportedException(string.Format("Contained object type {0} is not supported.", entity.ContainedObjectType));
return new GuidUdi(entityType, entity.Key).EnsureClosed();
}
/// <summary>
/// Gets the entity identifier of the entity.
/// </summary>
/// <param name="entity">The entity.</param>
/// <returns>The entity identifier of the entity.</returns>
public static GuidUdi GetUdi(this IMedia entity)
{
if (entity == null) throw new ArgumentNullException("entity");
return new GuidUdi(Constants.UdiEntityType.Media, entity.Key).EnsureClosed();
}
/// <summary>
/// Gets the entity identifier of the entity.
/// </summary>
/// <param name="entity">The entity.</param>
/// <returns>The entity identifier of the entity.</returns>
public static GuidUdi GetUdi(this IContent entity)
{
if (entity == null) throw new ArgumentNullException("entity");
return new GuidUdi(entity.Blueprint ? Constants.UdiEntityType.DocumentBlueprint : Constants.UdiEntityType.Document, entity.Key).EnsureClosed();
}
/// <summary>
/// Gets the entity identifier of the entity.
/// </summary>
/// <param name="entity">The entity.</param>
/// <returns>The entity identifier of the entity.</returns>
public static GuidUdi GetUdi(this IMember entity)
{
if (entity == null) throw new ArgumentNullException("entity");
return new GuidUdi(Constants.UdiEntityType.Member, entity.Key).EnsureClosed();
}
/// <summary>
/// Gets the entity identifier of the entity.
/// </summary>
/// <param name="entity">The entity.</param>
/// <returns>The entity identifier of the entity.</returns>
public static StringUdi GetUdi(this Stylesheet entity)
{
if (entity == null) throw new ArgumentNullException("entity");
return new StringUdi(Constants.UdiEntityType.Stylesheet, entity.Path.TrimStart('/')).EnsureClosed();
}
/// <summary>
/// Gets the entity identifier of the entity.
/// </summary>
/// <param name="entity">The entity.</param>
/// <returns>The entity identifier of the entity.</returns>
public static StringUdi GetUdi(this Script entity)
{
if (entity == null) throw new ArgumentNullException("entity");
return new StringUdi(Constants.UdiEntityType.Script, entity.Path.TrimStart('/')).EnsureClosed();
}
/// <summary>
/// Gets the entity identifier of the entity.
/// </summary>
/// <param name="entity">The entity.</param>
/// <returns>The entity identifier of the entity.</returns>
public static GuidUdi GetUdi(this IDictionaryItem entity)
{
if (entity == null) throw new ArgumentNullException("entity");
return new GuidUdi(Constants.UdiEntityType.DictionaryItem, entity.Key).EnsureClosed();
}
/// <summary>
/// Gets the entity identifier of the entity.
/// </summary>
/// <param name="entity">The entity.</param>
/// <returns>The entity identifier of the entity.</returns>
public static GuidUdi GetUdi(this IMacro entity)
{
if (entity == null) throw new ArgumentNullException("entity");
return new GuidUdi(Constants.UdiEntityType.Macro, entity.Key).EnsureClosed();
}
/// <summary>
/// Gets the entity identifier of the entity.
/// </summary>
/// <param name="entity">The entity.</param>
/// <returns>The entity identifier of the entity.</returns>
public static StringUdi GetUdi(this IPartialView entity)
{
if (entity == null) throw new ArgumentNullException("entity");
// we should throw on Unknown but for the time being, assume it means PartialView
var entityType = entity.ViewType == PartialViewType.PartialViewMacro
? Constants.UdiEntityType.PartialViewMacro
: Constants.UdiEntityType.PartialView;
return new StringUdi(entityType, entity.Path.TrimStart('/')).EnsureClosed();
}
/// <summary>
/// Gets the entity identifier of the entity.
/// </summary>
/// <param name="entity">The entity.</param>
/// <returns>The entity identifier of the entity.</returns>
public static GuidUdi GetUdi(this IContentBase entity)
{
if (entity == null) throw new ArgumentNullException("entity");
string type;
if (entity is IContent) type = Constants.UdiEntityType.Document;
else if (entity is IMedia) type = Constants.UdiEntityType.Media;
else if (entity is IMember) type = Constants.UdiEntityType.Member;
else throw new NotSupportedException(string.Format("ContentBase type {0} is not supported.", entity.GetType().FullName));
return new GuidUdi(type, entity.Key).EnsureClosed();
}
/// <summary>
/// Gets the entity identifier of the entity.
/// </summary>
/// <param name="entity">The entity.</param>
/// <returns>The entity identifier of the entity.</returns>
public static GuidUdi GetUdi(this IRelationType entity)
{
if (entity == null) throw new ArgumentNullException("entity");
return new GuidUdi(Constants.UdiEntityType.RelationType, entity.Key).EnsureClosed();
}
/// <summary>
/// Gets the entity identifier of the entity.
/// </summary>
/// <param name="entity">The entity.</param>
/// <returns>The entity identifier of the entity.</returns>
public static StringUdi GetUdi(this ILanguage entity)
{
if (entity == null) throw new ArgumentNullException("entity");
return new StringUdi(Constants.UdiEntityType.Language, entity.IsoCode).EnsureClosed();
}
/// <summary>
/// Gets the entity identifier of the entity.
/// </summary>
/// <param name="entity">The entity.</param>
/// <returns>The entity identifier of the entity.</returns>
public static Udi GetUdi(this IEntity entity)
{
if (entity == null) throw new ArgumentNullException("entity");
// entity could eg be anything implementing IThing
// so we have to go through casts here
var template = entity as ITemplate;
if (template != null) return template.GetUdi();
var contentType = entity as IContentType;
if (contentType != null) return contentType.GetUdi();
var mediaType = entity as IMediaType;
if (mediaType != null) return mediaType.GetUdi();
var memberType = entity as IMemberType;
if (memberType != null) return memberType.GetUdi();
var memberGroup = entity as IMemberGroup;
if (memberGroup != null) return memberGroup.GetUdi();
var contentTypeComposition = entity as IContentTypeComposition;
if (contentTypeComposition != null) return contentTypeComposition.GetUdi();
var dataTypeComposition = entity as IDataType;
if (dataTypeComposition != null) return dataTypeComposition.GetUdi();
var container = entity as EntityContainer;
if (container != null) return container.GetUdi();
var media = entity as IMedia;
if (media != null) return media.GetUdi();
var content = entity as IContent;
if (content != null) return content.GetUdi();
var member = entity as IMember;
if (member != null) return member.GetUdi();
var stylesheet = entity as Stylesheet;
if (stylesheet != null) return stylesheet.GetUdi();
var script = entity as Script;
if (script != null) return script.GetUdi();
var dictionaryItem = entity as IDictionaryItem;
if (dictionaryItem != null) return dictionaryItem.GetUdi();
var macro = entity as IMacro;
if (macro != null) return macro.GetUdi();
var partialView = entity as IPartialView;
if (partialView != null) return partialView.GetUdi();
var contentBase = entity as IContentBase;
if (contentBase != null) return contentBase.GetUdi();
var relationType = entity as IRelationType;
if (relationType != null) return relationType.GetUdi();
var language = entity as ILanguage;
if (language != null) return language.GetUdi();
throw new NotSupportedException(string.Format("Entity type {0} is not supported.", entity.GetType().FullName));
}
}
}
| mit |
nicolas-grekas/symfony | src/Symfony/Component/Validator/Tests/Fixtures/PropertyConstraint.php | 487 | <?php
/*
* This file is part of the Symfony package.
*
* (c) Fabien Potencier <fabien@symfony.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Symfony\Component\Validator\Tests\Fixtures;
use Symfony\Component\Validator\Constraint;
class PropertyConstraint extends Constraint
{
public function getTargets(): string|array
{
return self::PROPERTY_CONSTRAINT;
}
}
| mit |
morozd/videogular | app/scripts/com/2fdevs/videogular/plugins/overlay-play.js | 1420 | "use strict";
angular.module("com.2fdevs.videogular.plugins.overlayplay", [])
.directive(
"vgOverlayPlay",
["$rootScope", "VG_EVENTS", "VG_STATES", function($rootScope, VG_EVENTS, VG_STATES){
return {
restrict: "E",
require: "^videogular",
scope: {
vgPlayIcon: "="
},
controller: function ($scope){
$scope.playIcon = $.parseHTML($scope.vgPlayIcon)[0].data;
$scope.currentIcon = $scope.playIcon;
},
templateUrl: "views/videogular/plugins/overlay-play/overlay-play.html",
link: function($scope, $elem, $attr, $API) {
function onComplete(target, params) {
$scope.currentIcon = $scope.playIcon;
}
function onClickOverlayPlay($event) {
$API.playPause();
}
function onPlay(target, params) {
$scope.currentIcon = "";
}
function onChangeState(target, params) {
switch (params[0]) {
case VG_STATES.PLAY:
$scope.currentIcon = "";
break;
case VG_STATES.PAUSE:
$scope.currentIcon = $scope.playIcon;
break;
case VG_STATES.STOP:
$scope.currentIcon = $scope.playIcon;
break;
}
$scope.$apply();
}
$elem.bind("click", onClickOverlayPlay);
$rootScope.$on(VG_EVENTS.ON_PLAY, onPlay);
$rootScope.$on(VG_EVENTS.ON_SET_STATE, onChangeState);
$rootScope.$on(VG_EVENTS.ON_COMPLETE, onComplete);
}
}
}
]);
| mit |
thomsbg/ractive | src/Ractive/config/custom/css/transform.js | 2055 | var selectorsPattern = /(?:^|\})?\s*([^\{\}]+)\s*\{/g,
commentsPattern = /\/\*.*?\*\//g,
selectorUnitPattern = /((?:(?:\[[^\]+]\])|(?:[^\s\+\>\~:]))+)((?::[^\s\+\>\~\(]+(?:\([^\)]+\))?)?\s*[\s\+\>\~]?)\s*/g,
mediaQueryPattern = /^@media/,
dataRvcGuidPattern = /\[data-ractive-css~="\{[a-z0-9-]+\}"]/g;
export default function transformCss( css, id ) {
var transformed, dataAttr, addGuid;
dataAttr = `[data-ractive-css~="{${id}}"]`;
addGuid = function ( selector ) {
var selectorUnits, match, unit, base, prepended, appended, i, transformed = [];
selectorUnits = [];
while ( match = selectorUnitPattern.exec( selector ) ) {
selectorUnits.push({
str: match[0],
base: match[1],
modifiers: match[2]
});
}
// For each simple selector within the selector, we need to create a version
// that a) combines with the id, and b) is inside the id
base = selectorUnits.map( extractString );
i = selectorUnits.length;
while ( i-- ) {
appended = base.slice();
// Pseudo-selectors should go after the attribute selector
unit = selectorUnits[i];
appended[i] = unit.base + dataAttr + unit.modifiers || '';
prepended = base.slice();
prepended[i] = dataAttr + ' ' + prepended[i];
transformed.push( appended.join( ' ' ), prepended.join( ' ' ) );
}
return transformed.join( ', ' );
};
if ( dataRvcGuidPattern.test( css ) ) {
transformed = css.replace( dataRvcGuidPattern, dataAttr );
} else {
transformed = css
.replace( commentsPattern, '' )
.replace( selectorsPattern, function ( match, $1 ) {
var selectors, transformed;
// don't transform media queries!
if ( mediaQueryPattern.test( $1 ) ) return match;
selectors = $1.split( ',' ).map( trim );
transformed = selectors.map( addGuid ).join( ', ' ) + ' ';
return match.replace( $1, transformed );
});
}
return transformed;
}
function trim ( str ) {
if ( str.trim ) {
return str.trim();
}
return str.replace( /^\s+/, '' ).replace( /\s+$/, '' );
}
function extractString ( unit ) {
return unit.str;
}
| mit |
wenjoy/homePage | node_modules/node-captcha/node_modules/canvas/node_modules/should/node_modules/vinyl-source-stream2/node_modules/vinyl-map/node_modules/gulp/node_modules/gulp-jshint/node_modules/gulp-util/node_modules/replace-ext/node_modules/mocha/mocha.js | 23040 | ;(function(){
// CommonJS require()
function require(p){
var path = require.resolve(p)
, mod = require.modules[path];
if (!mod) throw new Error('failed to require "' + p + '"');
if (!mod.exports) {
mod.exports = {};
mod.call(mod.exports, mod, mod.exports, require.relative(path));
}
return mod.exports;
}
require.modules = {};
require.resolve = function (path){
var orig = path
, reg = path + '.js'
, index = path + '/index.js';
return require.modules[reg] && reg
|| require.modules[index] && index
|| orig;
};
require.register = function (path, fn){
require.modules[path] = fn;
};
require.relative = function (parent) {
return function(p){
if ('.' != p.charAt(0)) return require(p);
var path = parent.split('/')
, segs = p.split('/');
path.pop();
for (var i = 0; i < segs.length; i++) {
var seg = segs[i];
if ('..' == seg) path.pop();
else if ('.' != seg) path.push(seg);
}
return require(path.join('/'));
};
};
require.register("browser/debug.js", function(module, exports, require){
module.exports = function(type){
return function(){
}
};
}); // module: browser/debug.js
require.register("browser/diff.js", function(module, exports, require){
/* See LICENSE file for terms of use */
/*
* Text diff implementation.
*
* This library supports the following APIS:
* JsDiff.diffChars: Character by character diff
* JsDiff.diffWords: Word (as defined by \b regex) diff which ignores whitespace
* JsDiff.diffLines: Line based diff
*
* JsDiff.diffCss: Diff targeted at CSS content
*
* These methods are based on the implementation proposed in
* "An O(ND) Difference Algorithm and its Variations" (Myers, 1986).
* http://citeseerx.ist.psu.edu/viewdoc/summary?doi=10.1.1.4.6927
*/
var JsDiff = (function() {
/*jshint maxparams: 5*/
function clonePath(path) {
return { newPos: path.newPos, components: path.components.slice(0) };
}
function removeEmpty(array) {
var ret = [];
for (var i = 0; i < array.length; i++) {
if (array[i]) {
ret.push(array[i]);
}
}
return ret;
}
function escapeHTML(s) {
var n = s;
n = n.replace(/&/g, '&');
n = n.replace(/</g, '<');
n = n.replace(/>/g, '>');
n = n.replace(/"/g, '"');
return n;
}
var Diff = function(ignoreWhitespace) {
this.ignoreWhitespace = ignoreWhitespace;
};
Diff.prototype = {
diff: function(oldString, newString) {
// Handle the identity case (this is due to unrolling editLength == 0
if (newString === oldString) {
return [{ value: newString }];
}
if (!newString) {
return [{ value: oldString, removed: true }];
}
if (!oldString) {
return [{ value: newString, added: true }];
}
newString = this.tokenize(newString);
oldString = this.tokenize(oldString);
var newLen = newString.length, oldLen = oldString.length;
var maxEditLength = newLen + oldLen;
var bestPath = [{ newPos: -1, components: [] }];
// Seed editLength = 0
var oldPos = this.extractCommon(bestPath[0], newString, oldString, 0);
if (bestPath[0].newPos+1 >= newLen && oldPos+1 >= oldLen) {
return bestPath[0].components;
}
for (var editLength = 1; editLength <= maxEditLength; editLength++) {
for (var diagonalPath = -1*editLength; diagonalPath <= editLength; diagonalPath+=2) {
var basePath;
var addPath = bestPath[diagonalPath-1],
removePath = bestPath[diagonalPath+1];
oldPos = (removePath ? removePath.newPos : 0) - diagonalPath;
if (addPath) {
// No one else is going to attempt to use this value, clear it
bestPath[diagonalPath-1] = undefined;
}
var canAdd = addPath && addPath.newPos+1 < newLen;
var canRemove = removePath && 0 <= oldPos && oldPos < oldLen;
if (!canAdd && !canRemove) {
bestPath[diagonalPath] = undefined;
continue;
}
// Select the diagonal that we want to branch from. We select the prior
// path whose position in the new string is the farthest from the origin
// and does not pass the bounds of the diff graph
if (!canAdd || (canRemove && addPath.newPos < removePath.newPos)) {
basePath = clonePath(removePath);
this.pushComponent(basePath.components, oldString[oldPos], undefined, true);
} else {
basePath = clonePath(addPath);
basePath.newPos++;
this.pushComponent(basePath.components, newString[basePath.newPos], true, undefined);
}
var oldPos = this.extractCommon(basePath, newString, oldString, diagonalPath);
if (basePath.newPos+1 >= newLen && oldPos+1 >= oldLen) {
return basePath.components;
} else {
bestPath[diagonalPath] = basePath;
}
}
}
},
pushComponent: function(components, value, added, removed) {
var last = components[components.length-1];
if (last && last.added === added && last.removed === removed) {
// We need to clone here as the component clone operation is just
// as shallow array clone
components[components.length-1] =
{value: this.join(last.value, value), added: added, removed: removed };
} else {
components.push({value: value, added: added, removed: removed });
}
},
extractCommon: function(basePath, newString, oldString, diagonalPath) {
var newLen = newString.length,
oldLen = oldString.length,
newPos = basePath.newPos,
oldPos = newPos - diagonalPath;
while (newPos+1 < newLen && oldPos+1 < oldLen && this.equals(newString[newPos+1], oldString[oldPos+1])) {
newPos++;
oldPos++;
this.pushComponent(basePath.components, newString[newPos], undefined, undefined);
}
basePath.newPos = newPos;
return oldPos;
},
equals: function(left, right) {
var reWhitespace = /\S/;
if (this.ignoreWhitespace && !reWhitespace.test(left) && !reWhitespace.test(right)) {
return true;
} else {
return left === right;
}
},
join: function(left, right) {
return left + right;
},
tokenize: function(value) {
return value;
}
};
var CharDiff = new Diff();
var WordDiff = new Diff(true);
var WordWithSpaceDiff = new Diff();
WordDiff.tokenize = WordWithSpaceDiff.tokenize = function(value) {
return removeEmpty(value.split(/(\s+|\b)/));
};
var CssDiff = new Diff(true);
CssDiff.tokenize = function(value) {
return removeEmpty(value.split(/([{}:;,]|\s+)/));
};
var LineDiff = new Diff();
LineDiff.tokenize = function(value) {
return value.split(/^/m);
};
return {
Diff: Diff,
diffChars: function(oldStr, newStr) { return CharDiff.diff(oldStr, newStr); },
diffWords: function(oldStr, newStr) { return WordDiff.diff(oldStr, newStr); },
diffWordsWithSpace: function(oldStr, newStr) { return WordWithSpaceDiff.diff(oldStr, newStr); },
diffLines: function(oldStr, newStr) { return LineDiff.diff(oldStr, newStr); },
diffCss: function(oldStr, newStr) { return CssDiff.diff(oldStr, newStr); },
createPatch: function(fileName, oldStr, newStr, oldHeader, newHeader) {
var ret = [];
ret.push('Index: ' + fileName);
ret.push('===================================================================');
ret.push('--- ' + fileName + (typeof oldHeader === 'undefined' ? '' : '\t' + oldHeader));
ret.push('+++ ' + fileName + (typeof newHeader === 'undefined' ? '' : '\t' + newHeader));
var diff = LineDiff.diff(oldStr, newStr);
if (!diff[diff.length-1].value) {
diff.pop(); // Remove trailing newline add
}
diff.push({value: '', lines: []}); // Append an empty value to make cleanup easier
function contextLines(lines) {
return lines.map(function(entry) { return ' ' + entry; });
}
function eofNL(curRange, i, current) {
var last = diff[diff.length-2],
isLast = i === diff.length-2,
isLastOfType = i === diff.length-3 && (current.added !== last.added || current.removed !== last.removed);
// Figure out if this is the last line for the given file and missing NL
if (!/\n$/.test(current.value) && (isLast || isLastOfType)) {
curRange.push('\\ No newline at end of file');
}
}
var oldRangeStart = 0, newRangeStart = 0, curRange = [],
oldLine = 1, newLine = 1;
for (var i = 0; i < diff.length; i++) {
var current = diff[i],
lines = current.lines || current.value.replace(/\n$/, '').split('\n');
current.lines = lines;
if (current.added || current.removed) {
if (!oldRangeStart) {
var prev = diff[i-1];
oldRangeStart = oldLine;
newRangeStart = newLine;
if (prev) {
curRange = contextLines(prev.lines.slice(-4));
oldRangeStart -= curRange.length;
newRangeStart -= curRange.length;
}
}
curRange.push.apply(curRange, lines.map(function(entry) { return (current.added?'+':'-') + entry; }));
eofNL(curRange, i, current);
if (current.added) {
newLine += lines.length;
} else {
oldLine += lines.length;
}
} else {
if (oldRangeStart) {
// Close out any changes that have been output (or join overlapping)
if (lines.length <= 8 && i < diff.length-2) {
// Overlapping
curRange.push.apply(curRange, contextLines(lines));
} else {
// end the range and output
var contextSize = Math.min(lines.length, 4);
ret.push(
'@@ -' + oldRangeStart + ',' + (oldLine-oldRangeStart+contextSize)
+ ' +' + newRangeStart + ',' + (newLine-newRangeStart+contextSize)
+ ' @@');
ret.push.apply(ret, curRange);
ret.push.apply(ret, contextLines(lines.slice(0, contextSize)));
if (lines.length <= 4) {
eofNL(ret, i, current);
}
oldRangeStart = 0; newRangeStart = 0; curRange = [];
}
}
oldLine += lines.length;
newLine += lines.length;
}
}
return ret.join('\n') + '\n';
},
applyPatch: function(oldStr, uniDiff) {
var diffstr = uniDiff.split('\n');
var diff = [];
var remEOFNL = false,
addEOFNL = false;
for (var i = (diffstr[0][0]==='I'?4:0); i < diffstr.length; i++) {
if(diffstr[i][0] === '@') {
var meh = diffstr[i].split(/@@ -(\d+),(\d+) \+(\d+),(\d+) @@/);
diff.unshift({
start:meh[3],
oldlength:meh[2],
oldlines:[],
newlength:meh[4],
newlines:[]
});
} else if(diffstr[i][0] === '+') {
diff[0].newlines.push(diffstr[i].substr(1));
} else if(diffstr[i][0] === '-') {
diff[0].oldlines.push(diffstr[i].substr(1));
} else if(diffstr[i][0] === ' ') {
diff[0].newlines.push(diffstr[i].substr(1));
diff[0].oldlines.push(diffstr[i].substr(1));
} else if(diffstr[i][0] === '\\') {
if (diffstr[i-1][0] === '+') {
remEOFNL = true;
} else if(diffstr[i-1][0] === '-') {
addEOFNL = true;
}
}
}
var str = oldStr.split('\n');
for (var i = diff.length - 1; i >= 0; i--) {
var d = diff[i];
for (var j = 0; j < d.oldlength; j++) {
if(str[d.start-1+j] !== d.oldlines[j]) {
return false;
}
}
Array.prototype.splice.apply(str,[d.start-1,+d.oldlength].concat(d.newlines));
}
if (remEOFNL) {
while (!str[str.length-1]) {
str.pop();
}
} else if (addEOFNL) {
str.push('');
}
return str.join('\n');
},
convertChangesToXML: function(changes){
var ret = [];
for ( var i = 0; i < changes.length; i++) {
var change = changes[i];
if (change.added) {
ret.push('<ins>');
} else if (change.removed) {
ret.push('<del>');
}
ret.push(escapeHTML(change.value));
if (change.added) {
ret.push('</ins>');
} else if (change.removed) {
ret.push('</del>');
}
}
return ret.join('');
},
// See: http://code.google.com/p/google-diff-match-patch/wiki/API
convertChangesToDMP: function(changes){
var ret = [], change;
for ( var i = 0; i < changes.length; i++) {
change = changes[i];
ret.push([(change.added ? 1 : change.removed ? -1 : 0), change.value]);
}
return ret;
}
};
})();
if (typeof module !== 'undefined') {
module.exports = JsDiff;
}
}); // module: browser/diff.js
require.register("browser/events.js", function(module, exports, require){
/**
* Module exports.
*/
exports.EventEmitter = EventEmitter;
/**
* Check if `obj` is an array.
*/
function isArray(obj) {
return '[object Array]' == {}.toString.call(obj);
}
/**
* Event emitter constructor.
*
* @api public
*/
function EventEmitter(){};
/**
* Adds a listener.
*
* @api public
*/
EventEmitter.prototype.on = function (name, fn) {
if (!this.$events) {
this.$events = {};
}
if (!this.$events[name]) {
this.$events[name] = fn;
} else if (isArray(this.$events[name])) {
this.$events[name].push(fn);
} else {
this.$events[name] = [this.$events[name], fn];
}
return this;
};
EventEmitter.prototype.addListener = EventEmitter.prototype.on;
/**
* Adds a volatile listener.
*
* @api public
*/
EventEmitter.prototype.once = function (name, fn) {
var self = this;
function on () {
self.removeListener(name, on);
fn.apply(this, arguments);
};
on.listener = fn;
this.on(name, on);
return this;
};
/**
* Removes a listener.
*
* @api public
*/
EventEmitter.prototype.removeListener = function (name, fn) {
if (this.$events && this.$events[name]) {
var list = this.$events[name];
if (isArray(list)) {
var pos = -1;
for (var i = 0, l = list.length; i < l; i++) {
if (list[i] === fn || (list[i].listener && list[i].listener === fn)) {
pos = i;
break;
}
}
if (pos < 0) {
return this;
}
list.splice(pos, 1);
if (!list.length) {
delete this.$events[name];
}
} else if (list === fn || (list.listener && list.listener === fn)) {
delete this.$events[name];
}
}
return this;
};
/**
* Removes all listeners for an event.
*
* @api public
*/
EventEmitter.prototype.removeAllListeners = function (name) {
if (name === undefined) {
this.$events = {};
return this;
}
if (this.$events && this.$events[name]) {
this.$events[name] = null;
}
return this;
};
/**
* Gets all listeners for a certain event.
*
* @api public
*/
EventEmitter.prototype.listeners = function (name) {
if (!this.$events) {
this.$events = {};
}
if (!this.$events[name]) {
this.$events[name] = [];
}
if (!isArray(this.$events[name])) {
this.$events[name] = [this.$events[name]];
}
return this.$events[name];
};
/**
* Emits an event.
*
* @api public
*/
EventEmitter.prototype.emit = function (name) {
if (!this.$events) {
return false;
}
var handler = this.$events[name];
if (!handler) {
return false;
}
var args = [].slice.call(arguments, 1);
if ('function' == typeof handler) {
handler.apply(this, args);
} else if (isArray(handler)) {
var listeners = handler.slice();
for (var i = 0, l = listeners.length; i < l; i++) {
listeners[i].apply(this, args);
}
} else {
return false;
}
return true;
};
}); // module: browser/events.js
require.register("browser/fs.js", function(module, exports, require){
}); // module: browser/fs.js
require.register("browser/path.js", function(module, exports, require){
}); // module: browser/path.js
require.register("browser/progress.js", function(module, exports, require){
/**
* Expose `Progress`.
*/
module.exports = Progress;
/**
* Initialize a new `Progress` indicator.
*/
function Progress() {
this.percent = 0;
this.size(0);
this.fontSize(11);
this.font('helvetica, arial, sans-serif');
}
/**
* Set progress size to `n`.
*
* @param {Number} n
* @return {Progress} for chaining
* @api public
*/
Progress.prototype.size = function(n){
this._size = n;
return this;
};
/**
* Set text to `str`.
*
* @param {String} str
* @return {Progress} for chaining
* @api public
*/
Progress.prototype.text = function(str){
this._text = str;
return this;
};
/**
* Set font size to `n`.
*
* @param {Number} n
* @return {Progress} for chaining
* @api public
*/
Progress.prototype.fontSize = function(n){
this._fontSize = n;
return this;
};
/**
* Set font `family`.
*
* @param {String} family
* @return {Progress} for chaining
*/
Progress.prototype.font = function(family){
this._font = family;
return this;
};
/**
* Update percentage to `n`.
*
* @param {Number} n
* @return {Progress} for chaining
*/
Progress.prototype.update = function(n){
this.percent = n;
return this;
};
/**
* Draw on `ctx`.
*
* @param {CanvasRenderingContext2d} ctx
* @return {Progress} for chaining
*/
Progress.prototype.draw = function(ctx){
try {
var percent = Math.min(this.percent, 100)
, size = this._size
, half = size / 2
, x = half
, y = half
, rad = half - 1
, fontSize = this._fontSize;
ctx.font = fontSize + 'px ' + this._font;
var angle = Math.PI * 2 * (percent / 100);
ctx.clearRect(0, 0, size, size);
// outer circle
ctx.strokeStyle = '#9f9f9f';
ctx.beginPath();
ctx.arc(x, y, rad, 0, angle, false);
ctx.stroke();
// inner circle
ctx.strokeStyle = '#eee';
ctx.beginPath();
ctx.arc(x, y, rad - 1, 0, angle, true);
ctx.stroke();
// text
var text = this._text || (percent | 0) + '%'
, w = ctx.measureText(text).width;
ctx.fillText(
text
, x - w / 2 + 1
, y + fontSize / 2 - 1);
} catch (ex) {} //don't fail if we can't render progress
return this;
};
}); // module: browser/progress.js
require.register("browser/tty.js", function(module, exports, require){
exports.isatty = function(){
return true;
};
exports.getWindowSize = function(){
if ('innerHeight' in global) {
return [global.innerHeight, global.innerWidth];
} else {
// In a Web Worker, the DOM Window is not available.
return [640, 480];
}
};
}); // module: browser/tty.js
require.register("context.js", function(module, exports, require){
/**
* Expose `Context`.
*/
module.exports = Context;
/**
* Initialize a new `Context`.
*
* @api private
*/
function Context(){}
/**
* Set or get the context `Runnable` to `runnable`.
*
* @param {Runnable} runnable
* @return {Context}
* @api private
*/
Context.prototype.runnable = function(runnable){
if (0 == arguments.length) return this._runnable;
this.test = this._runnable = runnable;
return this;
};
/**
* Set test timeout `ms`.
*
* @param {Number} ms
* @return {Context} self
* @api private
*/
Context.prototype.timeout = function(ms){
this.runnable().timeout(ms);
return this;
};
/**
* Set test slowness threshold `ms`.
*
* @param {Number} ms
* @return {Context} self
* @api private
*/
Context.prototype.slow = function(ms){
this.runnable().slow(ms);
return this;
};
/**
* Inspect the context void of `._runnable`.
*
* @return {String}
* @api private
*/
Context.prototype.inspect = function(){
return JSON.stringify(this, function(key, val){
if ('_runnable' == key) return;
if ('test' == key) return;
return val;
}, 2);
};
}); // module: context.js
require.register("hook.js", function(module, exports, require){
/**
* Module dependencies.
*/
var Runnable = require('./runnable');
/**
* Expose `Hook`.
*/
module.exports = Hook;
/**
* Initialize a new `Hook` with the given `title` and callback `fn`.
*
* @param {String} title
* @param {Function} fn
* @api private
*/
function Hook(title, fn) {
Runnable.call(this, title, fn);
this.type = 'hook';
}
/**
* Inherit from `Runnable.prototype`.
*/
function F(){};
F.prototype = Runnable.prototype;
Hook.prototype = new F;
Hook.prototype.constructor = Hook;
/**
* Get or set the test `err`.
*
* @param {Error} err
* @return {Error}
* @api public
*/
Hook.prototype.error = function(err){
if (0 == arguments.length) {
var err = this._error;
this._error = null;
return err;
}
this._error = err;
};
}); // module: hook.js
require.register("interfaces/bdd.js", function(module, exports, require){
/**
* Module dependencies.
*/
var Suite = require('../suite')
, Test = require('../test')
, utils = require('../utils');
/**
* BDD-style interface:
*
* describe('Array', function(){
* describe('#indexOf()', function(){
* it('should return -1 when not present', function(){
*
* });
*
* it('should return the index when present', function(){
*
* });
* });
* });
*
*/
module.exports = function(suite){
var suites = [suite];
suite.on('pre-require', function(context, file, mocha){
/**
* Execute before running tests.
*/
context.before = function(fn){
suites[0].beforeAll(fn);
};
/**
* Execute after running tests.
*/
context.after = function(fn){
suites[0].afterAll(fn);
};
/**
* Execute before each test case.
*/
context.beforeEach = function(fn){
suites[0].beforeEach(fn);
};
/**
* Execute after each test case.
*/
context.afterEach = function(fn){
suites[0].afterEach(fn);
};
/**
* Describe a "suite" with the given `title`
* and callback `fn` containing nested suites
* and/or tests.
*/
context.describe = context.context = function(title, fn){
var suite = Suite.create(suites[0], title);
suites.unshift(suite);
fn.call(suite);
suites.shift();
return suite;
};
/**
* Pending describe.
*/
context.xdescribe =
context. | mit |
immerrr/jedi | test/test_evaluate/test_representation.py | 610 | from jedi import Script
def test_function_execution():
"""
We've been having an issue of a mutable list that was changed inside the
function execution. Test if an execution always returns the same result.
"""
s = """
def x():
return str()
x"""
d = Script(s).goto_definitions()[0]
# Now just use the internals of the result (easiest way to get a fully
# usable function).
func, evaluator = d._definition, d._evaluator
# Should return the same result both times.
assert len(evaluator.execute(func)) == 1
assert len(evaluator.execute(func)) == 1
| mit |
mrsimpson/Rocket.Chat | packages/rocketchat-lib/server/functions/Notifications.js | 4023 | RocketChat.Notifications = new class {
constructor() {
this.debug = false;
this.streamAll = new Meteor.Streamer('notify-all');
this.streamLogged = new Meteor.Streamer('notify-logged');
this.streamRoom = new Meteor.Streamer('notify-room');
this.streamRoomUsers = new Meteor.Streamer('notify-room-users');
this.streamUser = new Meteor.Streamer('notify-user');
this.streamAll.allowWrite('none');
this.streamLogged.allowWrite('none');
this.streamRoom.allowWrite('none');
this.streamRoomUsers.allowWrite(function(eventName, ...args) {
const [roomId, e] = eventName.split('/');
// const user = Meteor.users.findOne(this.userId, {
// fields: {
// username: 1
// }
// });
if (RocketChat.models.Subscriptions.findOneByRoomIdAndUserId(roomId, this.userId) != null) {
const subscriptions = RocketChat.models.Subscriptions.findByRoomIdAndNotUserId(roomId, this.userId).fetch();
subscriptions.forEach(subscription => RocketChat.Notifications.notifyUser(subscription.u._id, e, ...args));
}
return false;
});
this.streamUser.allowWrite('logged');
this.streamAll.allowRead('all');
this.streamLogged.allowRead('logged');
this.streamRoom.allowRead(function(eventName) {
if (this.userId == null) {
return false;
}
const [roomId] = eventName.split('/');
const user = Meteor.users.findOne(this.userId, {
fields: {
username: 1
}
});
const room = RocketChat.models.Rooms.findOneById(roomId);
if (room.t === 'l' && room.v._id === user._id) {
return true;
}
return room.usernames.indexOf(user.username) > -1;
});
this.streamRoomUsers.allowRead('none');
this.streamUser.allowRead(function(eventName) {
const [userId] = eventName.split('/');
return (this.userId != null) && this.userId === userId;
});
}
notifyAll(eventName, ...args) {
if (this.debug === true) {
console.log('notifyAll', arguments);
}
args.unshift(eventName);
return this.streamAll.emit.apply(this.streamAll, args);
}
notifyLogged(eventName, ...args) {
if (this.debug === true) {
console.log('notifyLogged', arguments);
}
args.unshift(eventName);
return this.streamLogged.emit.apply(this.streamLogged, args);
}
notifyRoom(room, eventName, ...args) {
if (this.debug === true) {
console.log('notifyRoom', arguments);
}
args.unshift(`${ room }/${ eventName }`);
return this.streamRoom.emit.apply(this.streamRoom, args);
}
notifyUser(userId, eventName, ...args) {
if (this.debug === true) {
console.log('notifyUser', arguments);
}
args.unshift(`${ userId }/${ eventName }`);
return this.streamUser.emit.apply(this.streamUser, args);
}
notifyAllInThisInstance(eventName, ...args) {
if (this.debug === true) {
console.log('notifyAll', arguments);
}
args.unshift(eventName);
return this.streamAll.emitWithoutBroadcast.apply(this.streamAll, args);
}
notifyLoggedInThisInstance(eventName, ...args) {
if (this.debug === true) {
console.log('notifyLogged', arguments);
}
args.unshift(eventName);
return this.streamLogged.emitWithoutBroadcast.apply(this.streamLogged, args);
}
notifyRoomInThisInstance(room, eventName, ...args) {
if (this.debug === true) {
console.log('notifyRoomAndBroadcast', arguments);
}
args.unshift(`${ room }/${ eventName }`);
return this.streamRoom.emitWithoutBroadcast.apply(this.streamRoom, args);
}
notifyUserInThisInstance(userId, eventName, ...args) {
if (this.debug === true) {
console.log('notifyUserAndBroadcast', arguments);
}
args.unshift(`${ userId }/${ eventName }`);
return this.streamUser.emitWithoutBroadcast.apply(this.streamUser, args);
}
};
RocketChat.Notifications.streamRoom.allowWrite(function(eventName, username) {
const [, e] = eventName.split('/');
if (e === 'webrtc') {
return true;
}
if (e === 'typing') {
const user = Meteor.users.findOne(this.userId, {
fields: {
username: 1
}
});
if (user != null && user.username === username) {
return true;
}
}
return false;
});
| mit |
terrafrost/phpseclib | phpseclib/File/ASN1/Maps/Attribute.php | 852 | <?php
/**
* Attribute
*
* PHP version 5
*
* @category File
* @package ASN1
* @author Jim Wigginton <terrafrost@php.net>
* @copyright 2016 Jim Wigginton
* @license http://www.opensource.org/licenses/mit-license.html MIT License
* @link http://phpseclib.sourceforge.net
*/
namespace phpseclib3\File\ASN1\Maps;
use phpseclib3\File\ASN1;
/**
* Attribute
*
* @package ASN1
* @author Jim Wigginton <terrafrost@php.net>
* @access public
*/
abstract class Attribute
{
const MAP = [
'type' => ASN1::TYPE_SEQUENCE,
'children' => [
'type' => AttributeType::MAP,
'value'=> [
'type' => ASN1::TYPE_SET,
'min' => 1,
'max' => -1,
'children' => AttributeValue::MAP
]
]
];
}
| mit |
fahmyard/jadwal-ruangan | vendor/google/apiclient-services/src/Google/Service/DeploymentManager.php | 14102 | <?php
/*
* Copyright 2016 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations under
* the License.
*/
/**
* Service definition for DeploymentManager (v2).
*
* <p>
* Declares, configures, and deploys complex solutions on Google Cloud Platform.</p>
*
* <p>
* For more information about this service, see the API
* <a href="https://cloud.google.com/deployment-manager/" target="_blank">Documentation</a>
* </p>
*
* @author Google, Inc.
*/
class Google_Service_DeploymentManager extends Google_Service
{
/** View and manage your data across Google Cloud Platform services. */
const CLOUD_PLATFORM =
"https://www.googleapis.com/auth/cloud-platform";
/** View your data across Google Cloud Platform services. */
const CLOUD_PLATFORM_READ_ONLY =
"https://www.googleapis.com/auth/cloud-platform.read-only";
/** View and manage your Google Cloud Platform management resources and deployment status information. */
const NDEV_CLOUDMAN =
"https://www.googleapis.com/auth/ndev.cloudman";
/** View your Google Cloud Platform management resources and deployment status information. */
const NDEV_CLOUDMAN_READONLY =
"https://www.googleapis.com/auth/ndev.cloudman.readonly";
public $deployments;
public $manifests;
public $operations;
public $resources;
public $types;
/**
* Constructs the internal representation of the DeploymentManager service.
*
* @param Google_Client $client
*/
public function __construct(Google_Client $client)
{
parent::__construct($client);
$this->rootUrl = 'https://www.googleapis.com/';
$this->servicePath = 'deploymentmanager/v2/projects/';
$this->version = 'v2';
$this->serviceName = 'deploymentmanager';
$this->deployments = new Google_Service_DeploymentManager_Resource_Deployments(
$this,
$this->serviceName,
'deployments',
array(
'methods' => array(
'cancelPreview' => array(
'path' => '{project}/global/deployments/{deployment}/cancelPreview',
'httpMethod' => 'POST',
'parameters' => array(
'project' => array(
'location' => 'path',
'type' => 'string',
'required' => true,
),
'deployment' => array(
'location' => 'path',
'type' => 'string',
'required' => true,
),
),
),'delete' => array(
'path' => '{project}/global/deployments/{deployment}',
'httpMethod' => 'DELETE',
'parameters' => array(
'project' => array(
'location' => 'path',
'type' => 'string',
'required' => true,
),
'deployment' => array(
'location' => 'path',
'type' => 'string',
'required' => true,
),
),
),'get' => array(
'path' => '{project}/global/deployments/{deployment}',
'httpMethod' => 'GET',
'parameters' => array(
'project' => array(
'location' => 'path',
'type' => 'string',
'required' => true,
),
'deployment' => array(
'location' => 'path',
'type' => 'string',
'required' => true,
),
),
),'insert' => array(
'path' => '{project}/global/deployments',
'httpMethod' => 'POST',
'parameters' => array(
'project' => array(
'location' => 'path',
'type' => 'string',
'required' => true,
),
'preview' => array(
'location' => 'query',
'type' => 'boolean',
),
),
),'list' => array(
'path' => '{project}/global/deployments',
'httpMethod' => 'GET',
'parameters' => array(
'project' => array(
'location' => 'path',
'type' => 'string',
'required' => true,
),
'filter' => array(
'location' => 'query',
'type' => 'string',
),
'maxResults' => array(
'location' => 'query',
'type' => 'integer',
),
'pageToken' => array(
'location' => 'query',
'type' => 'string',
),
),
),'patch' => array(
'path' => '{project}/global/deployments/{deployment}',
'httpMethod' => 'PATCH',
'parameters' => array(
'project' => array(
'location' => 'path',
'type' => 'string',
'required' => true,
),
'deployment' => array(
'location' => 'path',
'type' => 'string',
'required' => true,
),
'createPolicy' => array(
'location' => 'query',
'type' => 'string',
),
'deletePolicy' => array(
'location' => 'query',
'type' => 'string',
),
'preview' => array(
'location' => 'query',
'type' => 'boolean',
),
),
),'stop' => array(
'path' => '{project}/global/deployments/{deployment}/stop',
'httpMethod' => 'POST',
'parameters' => array(
'project' => array(
'location' => 'path',
'type' => 'string',
'required' => true,
),
'deployment' => array(
'location' => 'path',
'type' => 'string',
'required' => true,
),
),
),'update' => array(
'path' => '{project}/global/deployments/{deployment}',
'httpMethod' => 'PUT',
'parameters' => array(
'project' => array(
'location' => 'path',
'type' => 'string',
'required' => true,
),
'deployment' => array(
'location' => 'path',
'type' => 'string',
'required' => true,
),
'createPolicy' => array(
'location' => 'query',
'type' => 'string',
),
'deletePolicy' => array(
'location' => 'query',
'type' => 'string',
),
'preview' => array(
'location' => 'query',
'type' => 'boolean',
),
),
),
)
)
);
$this->manifests = new Google_Service_DeploymentManager_Resource_Manifests(
$this,
$this->serviceName,
'manifests',
array(
'methods' => array(
'get' => array(
'path' => '{project}/global/deployments/{deployment}/manifests/{manifest}',
'httpMethod' => 'GET',
'parameters' => array(
'project' => array(
'location' => 'path',
'type' => 'string',
'required' => true,
),
'deployment' => array(
'location' => 'path',
'type' => 'string',
'required' => true,
),
'manifest' => array(
'location' => 'path',
'type' => 'string',
'required' => true,
),
),
),'list' => array(
'path' => '{project}/global/deployments/{deployment}/manifests',
'httpMethod' => 'GET',
'parameters' => array(
'project' => array(
'location' => 'path',
'type' => 'string',
'required' => true,
),
'deployment' => array(
'location' => 'path',
'type' => 'string',
'required' => true,
),
'filter' => array(
'location' => 'query',
'type' => 'string',
),
'maxResults' => array(
'location' => 'query',
'type' => 'integer',
),
'pageToken' => array(
'location' => 'query',
'type' => 'string',
),
),
),
)
)
);
$this->operations = new Google_Service_DeploymentManager_Resource_Operations(
$this,
$this->serviceName,
'operations',
array(
'methods' => array(
'get' => array(
'path' => '{project}/global/operations/{operation}',
'httpMethod' => 'GET',
'parameters' => array(
'project' => array(
'location' => 'path',
'type' => 'string',
'required' => true,
),
'operation' => array(
'location' => 'path',
'type' => 'string',
'required' => true,
),
),
),'list' => array(
'path' => '{project}/global/operations',
'httpMethod' => 'GET',
'parameters' => array(
'project' => array(
'location' => 'path',
'type' => 'string',
'required' => true,
),
'filter' => array(
'location' => 'query',
'type' => 'string',
),
'maxResults' => array(
'location' => 'query',
'type' => 'integer',
),
'pageToken' => array(
'location' => 'query',
'type' => 'string',
),
),
),
)
)
);
$this->resources = new Google_Service_DeploymentManager_Resource_Resources(
$this,
$this->serviceName,
'resources',
array(
'methods' => array(
'get' => array(
'path' => '{project}/global/deployments/{deployment}/resources/{resource}',
'httpMethod' => 'GET',
'parameters' => array(
'project' => array(
'location' => 'path',
'type' => 'string',
'required' => true,
),
'deployment' => array(
'location' => 'path',
'type' => 'string',
'required' => true,
),
'resource' => array(
'location' => 'path',
'type' => 'string',
'required' => true,
),
),
),'list' => array(
'path' => '{project}/global/deployments/{deployment}/resources',
'httpMethod' => 'GET',
'parameters' => array(
'project' => array(
'location' => 'path',
'type' => 'string',
'required' => true,
),
'deployment' => array(
'location' => 'path',
'type' => 'string',
'required' => true,
),
'filter' => array(
'location' => 'query',
'type' => 'string',
),
'maxResults' => array(
'location' => 'query',
'type' => 'integer',
),
'pageToken' => array(
'location' => 'query',
'type' => 'string',
),
),
),
)
)
);
$this->types = new Google_Service_DeploymentManager_Resource_Types(
$this,
$this->serviceName,
'types',
array(
'methods' => array(
'list' => array(
'path' => '{project}/global/types',
'httpMethod' => 'GET',
'parameters' => array(
'project' => array(
'location' => 'path',
'type' => 'string',
'required' => true,
),
'filter' => array(
'location' => 'query',
'type' => 'string',
),
'maxResults' => array(
'location' => 'query',
'type' => 'integer',
),
'pageToken' => array(
'location' => 'query',
'type' => 'string',
),
),
),
)
)
);
}
}
| mit |
zj831007/some-mmorpg | common/gddata/attribute.lua | 485 | local health_max = {
warrior = {
[1] = 100,
[2] = 300,
[3] = 500,
},
mage = {
[1] = 80,
[2] = 160,
[3] = 240,
},
}
local strength = {
human = {
[1] = 22,
[2] = 24,
[3] = 26,
},
orc = {
[1] = 24,
[2] = 27,
[3] = 30,
},
}
local stamina = {
human = {
[1] = 21,
[2] = 23,
[3] = 25,
},
orc = {
[1] = 23,
[2] = 26,
[3] = 29,
},
}
local attribute = {
health_max = health_max,
strength = strength,
stamina = stamina,
}
return attribute
| mit |
capstone-rust/capstone-rs | capstone-sys/capstone/suite/MC/ARM/thumb.s.cs | 453 | # CS_ARCH_ARM, CS_MODE_THUMB, None
0x91,0x42 = cmp r1, r2
0x16,0xbc = pop {r1, r2, r4}
0xfe,0xde = trap
0xc8,0x47 = blx r9
0xd0,0x47 = blx r10
0x1a,0xba = rev r2, r3
0x63,0xba = rev16 r3, r4
0xf5,0xba = revsh r5, r6
0x5a,0xb2 = sxtb r2, r3
0x1a,0xb2 = sxth r2, r3
0x2c,0x42 = tst r4, r5
0xf3,0xb2 = uxtb r3, r6
0xb3,0xb2 = uxth r3, r6
0x8b,0x58 = ldr r3, [r1, r2]
0x02,0xbe = bkpt #2
0xc0,0x46 = mov r8, r8
0x67,0xb6 = cpsie aif
0x78,0x46 = mov r0, pc
| mit |
ManZzup/phpjs | functions/strings/quoted_printable_encode.js | 1915 | function quoted_printable_encode(str) {
// discuss at: http://phpjs.org/functions/quoted_printable_encode/
// original by: Theriault
// improved by: Brett Zamir (http://brett-zamir.me)
// improved by: Theriault
// example 1: quoted_printable_encode('a=b=c');
// returns 1: 'a=3Db=3Dc'
// example 2: quoted_printable_encode('abc \r\n123 \r\n');
// returns 2: 'abc =20\r\n123 =20\r\n'
// example 3: quoted_printable_encode('0123456789012345678901234567890123456789012345678901234567890123456789012345');
// returns 3: '012345678901234567890123456789012345678901234567890123456789012345678901234=\r\n5'
var hexChars = ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F'],
RFC2045Encode1IN = / \r\n|\r\n|[^!-<>-~ ]/gm,
RFC2045Encode1OUT = function(sMatch) {
// Encode space before CRLF sequence to prevent spaces from being stripped
// Keep hard line breaks intact; CRLF sequences
if (sMatch.length > 1) {
return sMatch.replace(' ', '=20');
}
// Encode matching character
var chr = sMatch.charCodeAt(0);
return '=' + hexChars[((chr >>> 4) & 15)] + hexChars[(chr & 15)];
};
// Split lines to 75 characters; the reason it's 75 and not 76 is because softline breaks are preceeded by an equal sign; which would be the 76th character.
// However, if the last line/string was exactly 76 characters, then a softline would not be needed. PHP currently softbreaks anyway; so this function replicates PHP.
RFC2045Encode2IN = /.{1,72}(?!\r\n)[^=]{0,3}/g,
RFC2045Encode2OUT = function(sMatch) {
if (sMatch.substr(sMatch.length - 2) === '\r\n') {
return sMatch;
}
return sMatch + '=\r\n';
};
str = str.replace(RFC2045Encode1IN, RFC2045Encode1OUT)
.replace(RFC2045Encode2IN, RFC2045Encode2OUT);
// Strip last softline break
return str.substr(0, str.length - 3);
} | mit |
begoldsm/azure-sdk-for-net | src/Batch/Client/Src/Azure.Batch/GeneratedProtocol/Models/PoolEvaluateAutoScaleHeaders.cs | 4874 | // Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License. See License.txt in the project root for
// license information.
//
// Code generated by Microsoft (R) AutoRest Code Generator.
// Changes may cause incorrect behavior and will be lost if the code is
// regenerated.
namespace Microsoft.Azure.Batch.Protocol.Models
{
using System.Linq;
/// <summary>
/// Defines headers for EvaluateAutoScale operation.
/// </summary>
public partial class PoolEvaluateAutoScaleHeaders
{
/// <summary>
/// Initializes a new instance of the PoolEvaluateAutoScaleHeaders
/// class.
/// </summary>
public PoolEvaluateAutoScaleHeaders() { }
/// <summary>
/// Initializes a new instance of the PoolEvaluateAutoScaleHeaders
/// class.
/// </summary>
/// <param name="clientRequestId">The client-request-id provided by the
/// client during the request. This will be returned only if the
/// return-client-request-id parameter was set to true.</param>
/// <param name="requestId">A unique identifier for the request that
/// was made to the Batch service. If a request is consistently failing
/// and you have verified that the request is properly formulated, you
/// may use this value to report the error to Microsoft. In your
/// report, include the value of this request ID, the approximate time
/// that the request was made, the Batch account against which the
/// request was made, and the region that account resides in.</param>
/// <param name="eTag">The ETag HTTP response header. This is an opaque
/// string. You can use it to detect whether the resource has changed
/// between requests. In particular, you can pass the ETag to one of
/// the If-Modified-Since, If-Unmodified-Since, If-Match or
/// If-None-Match headers.</param>
/// <param name="lastModified">The time at which the resource was last
/// modified.</param>
/// <param name="dataServiceId">The OData ID of the resource to which
/// the request applied.</param>
public PoolEvaluateAutoScaleHeaders(System.Guid? clientRequestId = default(System.Guid?), System.Guid? requestId = default(System.Guid?), string eTag = default(string), System.DateTime? lastModified = default(System.DateTime?), string dataServiceId = default(string))
{
ClientRequestId = clientRequestId;
RequestId = requestId;
ETag = eTag;
LastModified = lastModified;
DataServiceId = dataServiceId;
}
/// <summary>
/// Gets or sets the client-request-id provided by the client during
/// the request. This will be returned only if the
/// return-client-request-id parameter was set to true.
/// </summary>
[Newtonsoft.Json.JsonProperty(PropertyName = "client-request-id")]
public System.Guid? ClientRequestId { get; set; }
/// <summary>
/// Gets or sets a unique identifier for the request that was made to
/// the Batch service. If a request is consistently failing and you
/// have verified that the request is properly formulated, you may use
/// this value to report the error to Microsoft. In your report,
/// include the value of this request ID, the approximate time that the
/// request was made, the Batch account against which the request was
/// made, and the region that account resides in.
/// </summary>
[Newtonsoft.Json.JsonProperty(PropertyName = "request-id")]
public System.Guid? RequestId { get; set; }
/// <summary>
/// Gets or sets the ETag HTTP response header. This is an opaque
/// string. You can use it to detect whether the resource has changed
/// between requests. In particular, you can pass the ETag to one of
/// the If-Modified-Since, If-Unmodified-Since, If-Match or
/// If-None-Match headers.
/// </summary>
[Newtonsoft.Json.JsonProperty(PropertyName = "ETag")]
public string ETag { get; set; }
/// <summary>
/// Gets or sets the time at which the resource was last modified.
/// </summary>
[Newtonsoft.Json.JsonConverter(typeof(Microsoft.Rest.Serialization.DateTimeRfc1123JsonConverter))]
[Newtonsoft.Json.JsonProperty(PropertyName = "Last-Modified")]
public System.DateTime? LastModified { get; set; }
/// <summary>
/// Gets or sets the OData ID of the resource to which the request
/// applied.
/// </summary>
[Newtonsoft.Json.JsonProperty(PropertyName = "DataServiceId")]
public string DataServiceId { get; set; }
}
}
| mit |
seogi1004/cdnjs | ajax/libs/d3-color/1.1.0/d3-color.js | 15253 | // https://d3js.org/d3-color/ Version 1.1.0. Copyright 2018 Mike Bostock.
(function (global, factory) {
typeof exports === 'object' && typeof module !== 'undefined' ? factory(exports) :
typeof define === 'function' && define.amd ? define(['exports'], factory) :
(factory((global.d3 = global.d3 || {})));
}(this, (function (exports) { 'use strict';
var define = function(constructor, factory, prototype) {
constructor.prototype = factory.prototype = prototype;
prototype.constructor = constructor;
};
function extend(parent, definition) {
var prototype = Object.create(parent.prototype);
for (var key in definition) prototype[key] = definition[key];
return prototype;
}
function Color() {}
var darker = 0.7;
var brighter = 1 / darker;
var reI = "\\s*([+-]?\\d+)\\s*";
var reN = "\\s*([+-]?\\d*\\.?\\d+(?:[eE][+-]?\\d+)?)\\s*";
var reP = "\\s*([+-]?\\d*\\.?\\d+(?:[eE][+-]?\\d+)?)%\\s*";
var reHex3 = /^#([0-9a-f]{3})$/;
var reHex6 = /^#([0-9a-f]{6})$/;
var reRgbInteger = new RegExp("^rgb\\(" + [reI, reI, reI] + "\\)$");
var reRgbPercent = new RegExp("^rgb\\(" + [reP, reP, reP] + "\\)$");
var reRgbaInteger = new RegExp("^rgba\\(" + [reI, reI, reI, reN] + "\\)$");
var reRgbaPercent = new RegExp("^rgba\\(" + [reP, reP, reP, reN] + "\\)$");
var reHslPercent = new RegExp("^hsl\\(" + [reN, reP, reP] + "\\)$");
var reHslaPercent = new RegExp("^hsla\\(" + [reN, reP, reP, reN] + "\\)$");
var named = {
aliceblue: 0xf0f8ff,
antiquewhite: 0xfaebd7,
aqua: 0x00ffff,
aquamarine: 0x7fffd4,
azure: 0xf0ffff,
beige: 0xf5f5dc,
bisque: 0xffe4c4,
black: 0x000000,
blanchedalmond: 0xffebcd,
blue: 0x0000ff,
blueviolet: 0x8a2be2,
brown: 0xa52a2a,
burlywood: 0xdeb887,
cadetblue: 0x5f9ea0,
chartreuse: 0x7fff00,
chocolate: 0xd2691e,
coral: 0xff7f50,
cornflowerblue: 0x6495ed,
cornsilk: 0xfff8dc,
crimson: 0xdc143c,
cyan: 0x00ffff,
darkblue: 0x00008b,
darkcyan: 0x008b8b,
darkgoldenrod: 0xb8860b,
darkgray: 0xa9a9a9,
darkgreen: 0x006400,
darkgrey: 0xa9a9a9,
darkkhaki: 0xbdb76b,
darkmagenta: 0x8b008b,
darkolivegreen: 0x556b2f,
darkorange: 0xff8c00,
darkorchid: 0x9932cc,
darkred: 0x8b0000,
darksalmon: 0xe9967a,
darkseagreen: 0x8fbc8f,
darkslateblue: 0x483d8b,
darkslategray: 0x2f4f4f,
darkslategrey: 0x2f4f4f,
darkturquoise: 0x00ced1,
darkviolet: 0x9400d3,
deeppink: 0xff1493,
deepskyblue: 0x00bfff,
dimgray: 0x696969,
dimgrey: 0x696969,
dodgerblue: 0x1e90ff,
firebrick: 0xb22222,
floralwhite: 0xfffaf0,
forestgreen: 0x228b22,
fuchsia: 0xff00ff,
gainsboro: 0xdcdcdc,
ghostwhite: 0xf8f8ff,
gold: 0xffd700,
goldenrod: 0xdaa520,
gray: 0x808080,
green: 0x008000,
greenyellow: 0xadff2f,
grey: 0x808080,
honeydew: 0xf0fff0,
hotpink: 0xff69b4,
indianred: 0xcd5c5c,
indigo: 0x4b0082,
ivory: 0xfffff0,
khaki: 0xf0e68c,
lavender: 0xe6e6fa,
lavenderblush: 0xfff0f5,
lawngreen: 0x7cfc00,
lemonchiffon: 0xfffacd,
lightblue: 0xadd8e6,
lightcoral: 0xf08080,
lightcyan: 0xe0ffff,
lightgoldenrodyellow: 0xfafad2,
lightgray: 0xd3d3d3,
lightgreen: 0x90ee90,
lightgrey: 0xd3d3d3,
lightpink: 0xffb6c1,
lightsalmon: 0xffa07a,
lightseagreen: 0x20b2aa,
lightskyblue: 0x87cefa,
lightslategray: 0x778899,
lightslategrey: 0x778899,
lightsteelblue: 0xb0c4de,
lightyellow: 0xffffe0,
lime: 0x00ff00,
limegreen: 0x32cd32,
linen: 0xfaf0e6,
magenta: 0xff00ff,
maroon: 0x800000,
mediumaquamarine: 0x66cdaa,
mediumblue: 0x0000cd,
mediumorchid: 0xba55d3,
mediumpurple: 0x9370db,
mediumseagreen: 0x3cb371,
mediumslateblue: 0x7b68ee,
mediumspringgreen: 0x00fa9a,
mediumturquoise: 0x48d1cc,
mediumvioletred: 0xc71585,
midnightblue: 0x191970,
mintcream: 0xf5fffa,
mistyrose: 0xffe4e1,
moccasin: 0xffe4b5,
navajowhite: 0xffdead,
navy: 0x000080,
oldlace: 0xfdf5e6,
olive: 0x808000,
olivedrab: 0x6b8e23,
orange: 0xffa500,
orangered: 0xff4500,
orchid: 0xda70d6,
palegoldenrod: 0xeee8aa,
palegreen: 0x98fb98,
paleturquoise: 0xafeeee,
palevioletred: 0xdb7093,
papayawhip: 0xffefd5,
peachpuff: 0xffdab9,
peru: 0xcd853f,
pink: 0xffc0cb,
plum: 0xdda0dd,
powderblue: 0xb0e0e6,
purple: 0x800080,
rebeccapurple: 0x663399,
red: 0xff0000,
rosybrown: 0xbc8f8f,
royalblue: 0x4169e1,
saddlebrown: 0x8b4513,
salmon: 0xfa8072,
sandybrown: 0xf4a460,
seagreen: 0x2e8b57,
seashell: 0xfff5ee,
sienna: 0xa0522d,
silver: 0xc0c0c0,
skyblue: 0x87ceeb,
slateblue: 0x6a5acd,
slategray: 0x708090,
slategrey: 0x708090,
snow: 0xfffafa,
springgreen: 0x00ff7f,
steelblue: 0x4682b4,
tan: 0xd2b48c,
teal: 0x008080,
thistle: 0xd8bfd8,
tomato: 0xff6347,
turquoise: 0x40e0d0,
violet: 0xee82ee,
wheat: 0xf5deb3,
white: 0xffffff,
whitesmoke: 0xf5f5f5,
yellow: 0xffff00,
yellowgreen: 0x9acd32
};
define(Color, color, {
displayable: function() {
return this.rgb().displayable();
},
toString: function() {
return this.rgb() + "";
}
});
function color(format) {
var m;
format = (format + "").trim().toLowerCase();
return (m = reHex3.exec(format)) ? (m = parseInt(m[1], 16), new Rgb((m >> 8 & 0xf) | (m >> 4 & 0x0f0), (m >> 4 & 0xf) | (m & 0xf0), ((m & 0xf) << 4) | (m & 0xf), 1)) // #f00
: (m = reHex6.exec(format)) ? rgbn(parseInt(m[1], 16)) // #ff0000
: (m = reRgbInteger.exec(format)) ? new Rgb(m[1], m[2], m[3], 1) // rgb(255, 0, 0)
: (m = reRgbPercent.exec(format)) ? new Rgb(m[1] * 255 / 100, m[2] * 255 / 100, m[3] * 255 / 100, 1) // rgb(100%, 0%, 0%)
: (m = reRgbaInteger.exec(format)) ? rgba(m[1], m[2], m[3], m[4]) // rgba(255, 0, 0, 1)
: (m = reRgbaPercent.exec(format)) ? rgba(m[1] * 255 / 100, m[2] * 255 / 100, m[3] * 255 / 100, m[4]) // rgb(100%, 0%, 0%, 1)
: (m = reHslPercent.exec(format)) ? hsla(m[1], m[2] / 100, m[3] / 100, 1) // hsl(120, 50%, 50%)
: (m = reHslaPercent.exec(format)) ? hsla(m[1], m[2] / 100, m[3] / 100, m[4]) // hsla(120, 50%, 50%, 1)
: named.hasOwnProperty(format) ? rgbn(named[format])
: format === "transparent" ? new Rgb(NaN, NaN, NaN, 0)
: null;
}
function rgbn(n) {
return new Rgb(n >> 16 & 0xff, n >> 8 & 0xff, n & 0xff, 1);
}
function rgba(r, g, b, a) {
if (a <= 0) r = g = b = NaN;
return new Rgb(r, g, b, a);
}
function rgbConvert(o) {
if (!(o instanceof Color)) o = color(o);
if (!o) return new Rgb;
o = o.rgb();
return new Rgb(o.r, o.g, o.b, o.opacity);
}
function rgb(r, g, b, opacity) {
return arguments.length === 1 ? rgbConvert(r) : new Rgb(r, g, b, opacity == null ? 1 : opacity);
}
function Rgb(r, g, b, opacity) {
this.r = +r;
this.g = +g;
this.b = +b;
this.opacity = +opacity;
}
define(Rgb, rgb, extend(Color, {
brighter: function(k) {
k = k == null ? brighter : Math.pow(brighter, k);
return new Rgb(this.r * k, this.g * k, this.b * k, this.opacity);
},
darker: function(k) {
k = k == null ? darker : Math.pow(darker, k);
return new Rgb(this.r * k, this.g * k, this.b * k, this.opacity);
},
rgb: function() {
return this;
},
displayable: function() {
return (0 <= this.r && this.r <= 255)
&& (0 <= this.g && this.g <= 255)
&& (0 <= this.b && this.b <= 255)
&& (0 <= this.opacity && this.opacity <= 1);
},
toString: function() {
var a = this.opacity; a = isNaN(a) ? 1 : Math.max(0, Math.min(1, a));
return (a === 1 ? "rgb(" : "rgba(")
+ Math.max(0, Math.min(255, Math.round(this.r) || 0)) + ", "
+ Math.max(0, Math.min(255, Math.round(this.g) || 0)) + ", "
+ Math.max(0, Math.min(255, Math.round(this.b) || 0))
+ (a === 1 ? ")" : ", " + a + ")");
}
}));
function hsla(h, s, l, a) {
if (a <= 0) h = s = l = NaN;
else if (l <= 0 || l >= 1) h = s = NaN;
else if (s <= 0) h = NaN;
return new Hsl(h, s, l, a);
}
function hslConvert(o) {
if (o instanceof Hsl) return new Hsl(o.h, o.s, o.l, o.opacity);
if (!(o instanceof Color)) o = color(o);
if (!o) return new Hsl;
if (o instanceof Hsl) return o;
o = o.rgb();
var r = o.r / 255,
g = o.g / 255,
b = o.b / 255,
min = Math.min(r, g, b),
max = Math.max(r, g, b),
h = NaN,
s = max - min,
l = (max + min) / 2;
if (s) {
if (r === max) h = (g - b) / s + (g < b) * 6;
else if (g === max) h = (b - r) / s + 2;
else h = (r - g) / s + 4;
s /= l < 0.5 ? max + min : 2 - max - min;
h *= 60;
} else {
s = l > 0 && l < 1 ? 0 : h;
}
return new Hsl(h, s, l, o.opacity);
}
function hsl(h, s, l, opacity) {
return arguments.length === 1 ? hslConvert(h) : new Hsl(h, s, l, opacity == null ? 1 : opacity);
}
function Hsl(h, s, l, opacity) {
this.h = +h;
this.s = +s;
this.l = +l;
this.opacity = +opacity;
}
define(Hsl, hsl, extend(Color, {
brighter: function(k) {
k = k == null ? brighter : Math.pow(brighter, k);
return new Hsl(this.h, this.s, this.l * k, this.opacity);
},
darker: function(k) {
k = k == null ? darker : Math.pow(darker, k);
return new Hsl(this.h, this.s, this.l * k, this.opacity);
},
rgb: function() {
var h = this.h % 360 + (this.h < 0) * 360,
s = isNaN(h) || isNaN(this.s) ? 0 : this.s,
l = this.l,
m2 = l + (l < 0.5 ? l : 1 - l) * s,
m1 = 2 * l - m2;
return new Rgb(
hsl2rgb(h >= 240 ? h - 240 : h + 120, m1, m2),
hsl2rgb(h, m1, m2),
hsl2rgb(h < 120 ? h + 240 : h - 120, m1, m2),
this.opacity
);
},
displayable: function() {
return (0 <= this.s && this.s <= 1 || isNaN(this.s))
&& (0 <= this.l && this.l <= 1)
&& (0 <= this.opacity && this.opacity <= 1);
}
}));
/* From FvD 13.37, CSS Color Module Level 3 */
function hsl2rgb(h, m1, m2) {
return (h < 60 ? m1 + (m2 - m1) * h / 60
: h < 180 ? m2
: h < 240 ? m1 + (m2 - m1) * (240 - h) / 60
: m1) * 255;
}
var deg2rad = Math.PI / 180;
var rad2deg = 180 / Math.PI;
// https://beta.observablehq.com/@mbostock/lab-and-rgb
var K = 18;
var Xn = 0.96422;
var Yn = 1;
var Zn = 0.82521;
var t0 = 4 / 29;
var t1 = 6 / 29;
var t2 = 3 * t1 * t1;
var t3 = t1 * t1 * t1;
function labConvert(o) {
if (o instanceof Lab) return new Lab(o.l, o.a, o.b, o.opacity);
if (o instanceof Hcl) {
if (isNaN(o.h)) return new Lab(o.l, 0, 0, o.opacity);
var h = o.h * deg2rad;
return new Lab(o.l, Math.cos(h) * o.c, Math.sin(h) * o.c, o.opacity);
}
if (!(o instanceof Rgb)) o = rgbConvert(o);
var r = rgb2lrgb(o.r),
g = rgb2lrgb(o.g),
b = rgb2lrgb(o.b),
y = xyz2lab((0.2225045 * r + 0.7168786 * g + 0.0606169 * b) / Yn), x, z;
if (r === g && g === b) x = z = y; else {
x = xyz2lab((0.4360747 * r + 0.3850649 * g + 0.1430804 * b) / Xn);
z = xyz2lab((0.0139322 * r + 0.0971045 * g + 0.7141733 * b) / Zn);
}
return new Lab(116 * y - 16, 500 * (x - y), 200 * (y - z), o.opacity);
}
function gray(l, opacity) {
return new Lab(l, 0, 0, opacity == null ? 1 : opacity);
}
function lab(l, a, b, opacity) {
return arguments.length === 1 ? labConvert(l) : new Lab(l, a, b, opacity == null ? 1 : opacity);
}
function Lab(l, a, b, opacity) {
this.l = +l;
this.a = +a;
this.b = +b;
this.opacity = +opacity;
}
define(Lab, lab, extend(Color, {
brighter: function(k) {
return new Lab(this.l + K * (k == null ? 1 : k), this.a, this.b, this.opacity);
},
darker: function(k) {
return new Lab(this.l - K * (k == null ? 1 : k), this.a, this.b, this.opacity);
},
rgb: function() {
var y = (this.l + 16) / 116,
x = isNaN(this.a) ? y : y + this.a / 500,
z = isNaN(this.b) ? y : y - this.b / 200;
x = Xn * lab2xyz(x);
y = Yn * lab2xyz(y);
z = Zn * lab2xyz(z);
return new Rgb(
lrgb2rgb( 3.1338561 * x - 1.6168667 * y - 0.4906146 * z),
lrgb2rgb(-0.9787684 * x + 1.9161415 * y + 0.0334540 * z),
lrgb2rgb( 0.0719453 * x - 0.2289914 * y + 1.4052427 * z),
this.opacity
);
}
}));
function xyz2lab(t) {
return t > t3 ? Math.pow(t, 1 / 3) : t / t2 + t0;
}
function lab2xyz(t) {
return t > t1 ? t * t * t : t2 * (t - t0);
}
function lrgb2rgb(x) {
return 255 * (x <= 0.0031308 ? 12.92 * x : 1.055 * Math.pow(x, 1 / 2.4) - 0.055);
}
function rgb2lrgb(x) {
return (x /= 255) <= 0.04045 ? x / 12.92 : Math.pow((x + 0.055) / 1.055, 2.4);
}
function hclConvert(o) {
if (o instanceof Hcl) return new Hcl(o.h, o.c, o.l, o.opacity);
if (!(o instanceof Lab)) o = labConvert(o);
if (o.a === 0 && o.b === 0) return new Hcl(NaN, 0, o.l, o.opacity);
var h = Math.atan2(o.b, o.a) * rad2deg;
return new Hcl(h < 0 ? h + 360 : h, Math.sqrt(o.a * o.a + o.b * o.b), o.l, o.opacity);
}
function lch(l, c, h, opacity) {
return arguments.length === 1 ? hclConvert(l) : new Hcl(h, c, l, opacity == null ? 1 : opacity);
}
function hcl(h, c, l, opacity) {
return arguments.length === 1 ? hclConvert(h) : new Hcl(h, c, l, opacity == null ? 1 : opacity);
}
function Hcl(h, c, l, opacity) {
this.h = +h;
this.c = +c;
this.l = +l;
this.opacity = +opacity;
}
define(Hcl, hcl, extend(Color, {
brighter: function(k) {
return new Hcl(this.h, this.c, this.l + K * (k == null ? 1 : k), this.opacity);
},
darker: function(k) {
return new Hcl(this.h, this.c, this.l - K * (k == null ? 1 : k), this.opacity);
},
rgb: function() {
return labConvert(this).rgb();
}
}));
var A = -0.14861;
var B = +1.78277;
var C = -0.29227;
var D = -0.90649;
var E = +1.97294;
var ED = E * D;
var EB = E * B;
var BC_DA = B * C - D * A;
function cubehelixConvert(o) {
if (o instanceof Cubehelix) return new Cubehelix(o.h, o.s, o.l, o.opacity);
if (!(o instanceof Rgb)) o = rgbConvert(o);
var r = o.r / 255,
g = o.g / 255,
b = o.b / 255,
l = (BC_DA * b + ED * r - EB * g) / (BC_DA + ED - EB),
bl = b - l,
k = (E * (g - l) - C * bl) / D,
s = Math.sqrt(k * k + bl * bl) / (E * l * (1 - l)), // NaN if l=0 or l=1
h = s ? Math.atan2(k, bl) * rad2deg - 120 : NaN;
return new Cubehelix(h < 0 ? h + 360 : h, s, l, o.opacity);
}
function cubehelix(h, s, l, opacity) {
return arguments.length === 1 ? cubehelixConvert(h) : new Cubehelix(h, s, l, opacity == null ? 1 : opacity);
}
function Cubehelix(h, s, l, opacity) {
this.h = +h;
this.s = +s;
this.l = +l;
this.opacity = +opacity;
}
define(Cubehelix, cubehelix, extend(Color, {
brighter: function(k) {
k = k == null ? brighter : Math.pow(brighter, k);
return new Cubehelix(this.h, this.s, this.l * k, this.opacity);
},
darker: function(k) {
k = k == null ? darker : Math.pow(darker, k);
return new Cubehelix(this.h, this.s, this.l * k, this.opacity);
},
rgb: function() {
var h = isNaN(this.h) ? 0 : (this.h + 120) * deg2rad,
l = +this.l,
a = isNaN(this.s) ? 0 : this.s * l * (1 - l),
cosh = Math.cos(h),
sinh = Math.sin(h);
return new Rgb(
255 * (l + a * (A * cosh + B * sinh)),
255 * (l + a * (C * cosh + D * sinh)),
255 * (l + a * (E * cosh)),
this.opacity
);
}
}));
exports.color = color;
exports.rgb = rgb;
exports.hsl = hsl;
exports.lab = lab;
exports.hcl = hcl;
exports.lch = lch;
exports.gray = gray;
exports.cubehelix = cubehelix;
Object.defineProperty(exports, '__esModule', { value: true });
})));
| mit |
cdnjs/cdnjs | ajax/libs/material-ui/5.0.0-beta.2/node/ImageListItem/index.js | 2185 | "use strict";
var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault");
Object.defineProperty(exports, "__esModule", {
value: true
});
var _exportNames = {
imageListItemClasses: true
};
Object.defineProperty(exports, "default", {
enumerable: true,
get: function () {
return _ImageListItem.default;
}
});
Object.defineProperty(exports, "imageListItemClasses", {
enumerable: true,
get: function () {
return _imageListItemClasses.default;
}
});
var _ImageListItem = _interopRequireDefault(require("./ImageListItem"));
var _imageListItemClasses = _interopRequireWildcard(require("./imageListItemClasses"));
Object.keys(_imageListItemClasses).forEach(function (key) {
if (key === "default" || key === "__esModule") return;
if (Object.prototype.hasOwnProperty.call(_exportNames, key)) return;
if (key in exports && exports[key] === _imageListItemClasses[key]) return;
Object.defineProperty(exports, key, {
enumerable: true,
get: function () {
return _imageListItemClasses[key];
}
});
});
function _getRequireWildcardCache(nodeInterop) { if (typeof WeakMap !== "function") return null; var cacheBabelInterop = new WeakMap(); var cacheNodeInterop = new WeakMap(); return (_getRequireWildcardCache = function (nodeInterop) { return nodeInterop ? cacheNodeInterop : cacheBabelInterop; })(nodeInterop); }
function _interopRequireWildcard(obj, nodeInterop) { if (!nodeInterop && obj && obj.__esModule) { return obj; } if (obj === null || typeof obj !== "object" && typeof obj !== "function") { return { default: obj }; } var cache = _getRequireWildcardCache(nodeInterop); if (cache && cache.has(obj)) { return cache.get(obj); } var newObj = {}; var hasPropertyDescriptor = Object.defineProperty && Object.getOwnPropertyDescriptor; for (var key in obj) { if (key !== "default" && Object.prototype.hasOwnProperty.call(obj, key)) { var desc = hasPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : null; if (desc && (desc.get || desc.set)) { Object.defineProperty(newObj, key, desc); } else { newObj[key] = obj[key]; } } } newObj.default = obj; if (cache) { cache.set(obj, newObj); } return newObj; } | mit |
skyqinsc/CppPrime | ch13/ex13_42_TextQuery.cpp | 1381 | #include "ex13_42_TextQuery.h"
#include <sstream>
#include <algorithm>
using std::string;
TextQuery::TextQuery(std::ifstream &ifs) : input(new StrVec)
{
size_t lineNo = 0;
for (string line; std::getline(ifs, line); ++lineNo) {
input->push_back(line);
std::istringstream line_stream(line);
for (string text, word; line_stream >> text; word.clear()) {
// avoid read a word followed by punctuation(such as: word, )
std::remove_copy_if(text.begin(), text.end(), std::back_inserter(word), ispunct);
// use reference avoid count of shared_ptr add.
auto &nos = result[word];
if (!nos) nos.reset(new std::set<size_t>);
nos->insert(lineNo);
}
}
}
QueryResult TextQuery::query(const string& str) const
{
// use static just allocate once.
static std::shared_ptr<std::set<size_t>> nodate(new std::set<size_t>);
auto found = result.find(str);
if (found == result.end()) return QueryResult(str, nodate, input);
else return QueryResult(str, found->second, input);
}
std::ostream& print(std::ostream &out, const QueryResult& qr)
{
out << qr.word << " occurs " << qr.nos->size() << (qr.nos->size() > 1 ? " times" : " time") << std::endl;
for (auto i : *qr.nos)
out << "\t(line " << i+1 << ") " << qr.input->at(i) << std::endl;
return out;
}
| cc0-1.0 |
aryantaheri/monitoring-controller | opendaylight/md-sal/sal-distributed-datastore/src/main/java/org/opendaylight/controller/cluster/datastore/messages/DataChangedReply.java | 1009 | /*
* Copyright (c) 2014 Cisco Systems, Inc. and others. All rights reserved.
*
* This program and the accompanying materials are made available under the
* terms of the Eclipse Public License v1.0 which accompanies this distribution,
* and is available at http://www.eclipse.org/legal/epl-v10.html
*/
package org.opendaylight.controller.cluster.datastore.messages;
import org.opendaylight.controller.protobuff.messages.datachange.notification.DataChangeListenerMessages;
public class DataChangedReply implements SerializableMessage {
public static final Class<DataChangeListenerMessages.DataChangedReply> SERIALIZABLE_CLASS =
DataChangeListenerMessages.DataChangedReply.class;
private static final Object SERIALIZED_INSTANCE =
DataChangeListenerMessages.DataChangedReply.newBuilder().build();
public static final DataChangedReply INSTANCE = new DataChangedReply();
@Override
public Object toSerializable() {
return SERIALIZED_INSTANCE;
}
}
| epl-1.0 |
macnlos/runuo_rpi | Scripts/Engines/Craft/Core/QueryMakersMarkGump.cs | 1586 | using System;
using Server;
using Server.Gumps;
using Server.Items;
namespace Server.Engines.Craft
{
public class QueryMakersMarkGump : Gump
{
private int m_Quality;
private Mobile m_From;
private CraftItem m_CraftItem;
private CraftSystem m_CraftSystem;
private Type m_TypeRes;
private BaseTool m_Tool;
public QueryMakersMarkGump( int quality, Mobile from, CraftItem craftItem, CraftSystem craftSystem, Type typeRes, BaseTool tool ) : base( 100, 200 )
{
from.CloseGump( typeof( QueryMakersMarkGump ) );
m_Quality = quality;
m_From = from;
m_CraftItem = craftItem;
m_CraftSystem = craftSystem;
m_TypeRes = typeRes;
m_Tool = tool;
AddPage( 0 );
AddBackground( 0, 0, 220, 170, 5054 );
AddBackground( 10, 10, 200, 150, 3000 );
AddHtmlLocalized( 20, 20, 180, 80, 1018317, false, false ); // Do you wish to place your maker's mark on this item?
AddHtmlLocalized( 55, 100, 140, 25, 1011011, false, false ); // CONTINUE
AddButton( 20, 100, 4005, 4007, 1, GumpButtonType.Reply, 0 );
AddHtmlLocalized( 55, 125, 140, 25, 1011012, false, false ); // CANCEL
AddButton( 20, 125, 4005, 4007, 0, GumpButtonType.Reply, 0 );
}
public override void OnResponse( Server.Network.NetState sender, RelayInfo info )
{
bool makersMark = ( info.ButtonID == 1 );
if ( makersMark )
m_From.SendLocalizedMessage( 501808 ); // You mark the item.
else
m_From.SendLocalizedMessage( 501809 ); // Cancelled mark.
m_CraftItem.CompleteCraft( m_Quality, makersMark, m_From, m_CraftSystem, m_TypeRes, m_Tool, null );
}
}
} | gpl-2.0 |
md-5/jdk10 | test/hotspot/jtreg/vmTestbase/nsk/monitoring/LoggingMXBean/getLoggerNames/getloggernames003/TestDescription.java | 1886 | /*
* Copyright (c) 2017, 2018, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
/*
* @test
*
* @summary converted from VM Testbase nsk/monitoring/LoggingMXBean/getLoggerNames/getloggernames003.
* VM Testbase keywords: [quick, monitoring]
* VM Testbase readme:
* DESCRIPTION
* Interface: java.util.logging.LoggingMXBean
* Method: getLoggerNames()
* Returns the list of currently registered loggers
* Access to metrics is provided in following way: custom MBeanServer.
* The test checks that
* 1. This method calls LogManager.getLoggerNames() and returns a
* list of the logger names.
* COMMENT
*
* @library /vmTestbase
* /test/lib
* @run driver jdk.test.lib.FileInstaller . .
* @run main/othervm
* nsk.monitoring.LoggingMXBean.getLoggerNames.getloggernames001
* -testMode=server
* -MBeanServer=custom
*/
| gpl-2.0 |
krichter722/gcc | libstdc++-v3/testsuite/tr1/2_general_utilities/shared_ptr/cons/default.cc | 1114 | // Copyright (C) 2005-2017 Free Software Foundation, Inc.
//
// This file is part of the GNU ISO C++ Library. This library is free
// software; you can redistribute it and/or modify it under the
// terms of the GNU General Public License as published by the
// Free Software Foundation; either version 3, or (at your option)
// any later version.
// This library is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
// You should have received a copy of the GNU General Public License along
// with this library; see the file COPYING3. If not see
// <http://www.gnu.org/licenses/>.
// TR1 2.2.2 Template class shared_ptr [tr.util.smartptr.shared]
#include <tr1/memory>
#include <testsuite_hooks.h>
struct A { };
// 2.2.3.1 shared_ptr constructors [tr.util.smartptr.shared.const]
// Default construction
int
test01()
{
std::tr1::shared_ptr<A> a;
VERIFY( a.get() == 0 );
return 0;
}
int
main()
{
test01();
return 0;
}
| gpl-2.0 |
krichter722/gcc | libstdc++-v3/testsuite/27_io/basic_filebuf/imbue/wchar_t/1.cc | 1231 | // 981208 bkoz test functionality of basic_stringbuf for char_type == char
// Copyright (C) 1997-2017 Free Software Foundation, Inc.
//
// This file is part of the GNU ISO C++ Library. This library is free
// software; you can redistribute it and/or modify it under the
// terms of the GNU General Public License as published by the
// Free Software Foundation; either version 3, or (at your option)
// any later version.
// This library is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
// You should have received a copy of the GNU General Public License along
// with this library; see the file COPYING3. If not see
// <http://www.gnu.org/licenses/>.
#include <fstream>
#include <testsuite_hooks.h>
std::wfilebuf fbuf;
// test the filebuf locale settings
void test02()
{
std::locale loc_c = std::locale::classic();
loc_c = fbuf.getloc();
fbuf.pubimbue(loc_c); //This should initialize _M_init to true
std::locale loc_tmp = fbuf.getloc();
VERIFY( loc_tmp == loc_c );
}
int main()
{
test02();
return 0;
}
// more candy!!!
| gpl-2.0 |
pulibrary/recap | core/tests/Drupal/KernelTests/Core/Plugin/ContextHandlerTest.php | 2228 | <?php
namespace Drupal\KernelTests\Core\Plugin;
use Drupal\Core\Plugin\Context\ContextHandler;
use Drupal\Core\Plugin\Context\EntityContext;
use Drupal\Core\Plugin\Context\EntityContextDefinition;
use Drupal\Core\Plugin\ContextAwarePluginInterface;
use Drupal\Core\Plugin\ContextAwarePluginTrait;
use Drupal\Core\Plugin\PluginBase;
use Drupal\entity_test\Entity\EntityTest;
use Drupal\KernelTests\KernelTestBase;
/**
* @coversDefaultClass \Drupal\Core\Plugin\Context\ContextHandler
*
* @group Plugin
*/
class ContextHandlerTest extends KernelTestBase {
/**
* {@inheritdoc}
*/
protected static $modules = [
'entity_test',
'user',
];
/**
* @covers ::applyContextMapping
*/
public function testApplyContextMapping() {
$entity = EntityTest::create([]);
$context_definition = EntityContextDefinition::fromEntity($entity);
$context = EntityContext::fromEntity($entity);
$definition = ['context_definitions' => ['a_context_id' => $context_definition]];
$plugin = new TestContextAwarePlugin([], 'test_plugin_id', $definition);
(new ContextHandler())->applyContextMapping($plugin, ['a_context_id' => $context]);
$result = $plugin->getContext('a_context_id');
$this->assertInstanceOf(EntityContext::class, $result);
$this->assertSame($context, $result);
}
/**
* @covers ::applyContextMapping
*/
public function testApplyContextMappingAlreadyApplied() {
$entity = EntityTest::create([]);
$context_definition = EntityContextDefinition::fromEntity($entity);
$context = EntityContext::fromEntity($entity);
$definition = ['context_definitions' => ['a_context_id' => $context_definition]];
$plugin = new TestContextAwarePlugin([], 'test_plugin_id', $definition);
$plugin->setContext('a_context_id', $context);
(new ContextHandler())->applyContextMapping($plugin, []);
$result = $plugin->getContext('a_context_id');
$this->assertInstanceOf(EntityContext::class, $result);
$this->assertSame($context, $result);
}
}
/**
* Provides a test implementation of a context-aware plugin.
*/
class TestContextAwarePlugin extends PluginBase implements ContextAwarePluginInterface {
use ContextAwarePluginTrait;
}
| gpl-2.0 |
isabisa/nccdi | wp-content/plugins/wp-smushit/core/external/free-dashboard/admin.js | 3139 | jQuery(function() {
var el_notice = jQuery( ".frash-notice" ),
type = el_notice.find( "input[name=type]" ).val(),
plugin_id = el_notice.find( "input[name=plugin_id]" ).val(),
url_wp = el_notice.find( "input[name=url_wp]" ).val(),
inp_email = el_notice.find( "input[name=EMAIL]" ),
btn_act = el_notice.find( ".frash-notice-act" ),
btn_dismiss = el_notice.find( ".frash-notice-dismiss" ),
ajax_data = {};
ajax_data.plugin_id = plugin_id;
ajax_data.type = type;
function init_email() {
if ( ! inp_email.length ) { return; }
// Adjust the size of the email field to its contents.
function adjust_email_size() {
var width, tmp = jQuery( "<span></span>" );
tmp.addClass( "input-field" ).text( inp_email.val() );
tmp.appendTo( "body" );
width = parseInt( tmp.width() );
tmp.remove();
inp_email.width( width + 34 );
}
function email_keycheck( ev ) {
if ( 13 === ev.keyCode ) {
btn_act.click();
} else {
adjust_email_size();
}
}
inp_email.keyup( email_keycheck ).focus().select();
adjust_email_size();
}
// Display the notice after the page was loaded.
function initialize() {
el_notice.fadeIn( 500 );
init_email();
}
// Hide the notice after a CTA button was clicked
function remove_notice() {
el_notice.fadeTo( 100 , 0, function() {
el_notice.slideUp( 100, function() {
el_notice.remove();
});
});
}
// Open a tab to rate the plugin.
function act_rate() {
var url = url_wp.replace( /\/plugins\//, "/support/plugin/" ) + "/reviews/?rate=5#new-post",
link = jQuery( '<a href="' + url + '" target="_blank">Rate</a>' );
link.appendTo( "body" );
link[0].click();
link.remove();
}
// Submit the user to our email list.
function act_email() {
var form = inp_email.parent('form');
//Submit email to mailing list
jQuery.ajax({
type: form.attr('method'),
url: form.attr('action'),
data: form.serialize(),
cache: false,
dataType: 'json',
contentType: 'application/json; charset=utf-8',
success: function (data) {
console.log(data.msg);
}
});
}
// Notify WordPress about the users choice and close the message.
function notify_wordpress( action, message ) {
el_notice.attr( "data-message", message );
el_notice.addClass( "loading" );
ajax_data.action = action;
jQuery.post(
window.ajaxurl,
ajax_data,
remove_notice
);
}
// Handle click on the primary CTA button.
// Either open the wp.org page or submit the email address.
btn_act.click(function( ev ) {
ev.preventDefault();
//Do not submit form if the value is not set
var email_inpt = btn_act.parent().find('input[type="email"]');
if( ( !email_inpt.length || !email_inpt.val() ) && type === 'email' ) {
return;
}
switch ( type ) {
case 'rate': act_rate(); break;
case 'email': act_email(); break;
}
notify_wordpress( "frash_act", btn_act.data( "msg" ) );
});
// Dismiss the notice without any action.
btn_dismiss.click(function( ev ) {
ev.preventDefault();
notify_wordpress( "frash_dismiss", btn_dismiss.data( "msg" ) );
});
window.setTimeout( initialize, 500 );
}); | gpl-2.0 |
frioux/sysdig | userspace/sysdig/chisels/v_errors.lua | 1879 | --[[
Copyright (C) 2013-2015 Draios inc.
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License version 2 as
published by the Free Software Foundation.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
--]]
view_info =
{
id = "errors",
name = "Errors",
description = "This view shows the top system call errors, sorted by number of occurrences. Errors are shows as errno codes. Do a 'man errno' to find the meaning of the most important codes.",
tips = {
"This view can be applied not only to the whole machine, but also to single processes, containers, threads and so on. Use it after a drill down for more fine grained investigation.",
"Drill down on an error by clicking enter to see which processes are generating it."
},
tags = {"Default"},
view_type = "table",
applies_to = {"", "container.id", "proc.pid", "proc.name", "thread.tid", "fd.sport", "fd.directory"},
filter = "evt.res != SUCCESS",
use_defaults = true,
drilldown_target = "procs_errors",
columns =
{
{
name = "NA",
field = "evt.res",
is_key = true
},
{
name = "COUNT",
field = "evt.count",
description = "The number of times the error happened during the sample interval. On trace files, this is the total for the whole file.",
colsize = 12,
aggregation = "SUM",
is_sorting = true,
},
{
name = "ERROR",
description = "The error 'errno' code. Do a 'man errno' to find the meaning of the most important codes.",
field = "evt.res",
colsize = 0
}
}
}
| gpl-2.0 |
destdev/ygopro-scripts | c52035300.lua | 1858 | --不死武士
function c52035300.initial_effect(c)
--release limit
local e1=Effect.CreateEffect(c)
e1:SetType(EFFECT_TYPE_SINGLE)
e1:SetCode(EFFECT_UNRELEASABLE_SUM)
e1:SetProperty(EFFECT_FLAG_SINGLE_RANGE)
e1:SetRange(LOCATION_MZONE)
e1:SetValue(c52035300.recon)
c:RegisterEffect(e1)
local e2=Effect.CreateEffect(c)
e2:SetType(EFFECT_TYPE_SINGLE)
e2:SetCode(EFFECT_UNRELEASABLE_NONSUM)
e2:SetProperty(EFFECT_FLAG_SINGLE_RANGE)
e2:SetRange(LOCATION_MZONE)
e2:SetValue(1)
c:RegisterEffect(e2)
--Special Summon
local e3=Effect.CreateEffect(c)
e3:SetDescription(aux.Stringid(52035300,0))
e3:SetType(EFFECT_TYPE_TRIGGER_O+EFFECT_TYPE_FIELD)
e3:SetCategory(CATEGORY_SPECIAL_SUMMON)
e3:SetCode(EVENT_PHASE+PHASE_STANDBY)
e3:SetRange(LOCATION_GRAVE)
e3:SetCountLimit(1)
e3:SetCondition(c52035300.condition)
e3:SetTarget(c52035300.target)
e3:SetOperation(c52035300.operation)
c:RegisterEffect(e3)
end
function c52035300.recon(e,c)
return not c:IsRace(RACE_WARRIOR)
end
function c52035300.filter(c)
return c:IsType(TYPE_MONSTER) and not c:IsRace(RACE_WARRIOR)
end
function c52035300.condition(e,tp,eg,ep,ev,re,r,rp)
return tp==Duel.GetTurnPlayer() and Duel.GetFieldGroupCount(tp,LOCATION_MZONE,0)==0
and not Duel.IsExistingMatchingCard(c52035300.filter,tp,LOCATION_GRAVE,0,1,nil)
end
function c52035300.target(e,tp,eg,ep,ev,re,r,rp,chk)
if chk==0 then return Duel.GetLocationCount(tp,LOCATION_MZONE)>0
and e:GetHandler():IsCanBeSpecialSummoned(e,0,tp,false,false) end
Duel.SetOperationInfo(0,CATEGORY_SPECIAL_SUMMON,e:GetHandler(),1,0,0)
end
function c52035300.operation(e,tp,eg,ep,ev,re,r,rp)
if Duel.GetLocationCount(tp,LOCATION_MZONE)<=0 or Duel.GetFieldGroupCount(tp,LOCATION_MZONE,0)>0 then return end
if e:GetHandler():IsRelateToEffect(e) then
Duel.SpecialSummon(e:GetHandler(),0,tp,tp,false,false,POS_FACEUP)
end
end
| gpl-2.0 |
unofficial-opensource-apple/gcc_40 | gcc/testsuite/g++.apple/asm-block-50.C | 1736 | /* APPLE LOCAL file CW asm blocks */
/* { dg-do assemble { target i?86*-*-darwin* } } */
/* APPLE LOCAL x86_64 */
/* { dg-require-effective-target ilp32 } */
/* { dg-options { -fasm-blocks -msse3 } } */
/* Radar 4505741 */
static int c[5];
void foo(int pa[5], int j) {
unsigned int *ptr = (unsigned int *)0x12345678;
static int b[5];
int i;
int a[5];
_asm {
mov esi, [ptr][0]
mov esi, [ptr]
mov esi, [esi][eax]
mov esi, [esi+eax]
mov esi, [esi+eax+4]
mov esi, [esi][eax][4]
mov esi, [a][4]
mov esi, [pa]
mov esi, [j]
mov esi, [i]
mov esi, i
mov esi, [b][4] /* { dg-warning "non-pic addressing form not suitible for pic code" } */
mov esi, [c][4] /* { dg-warning "non-pic addressing form not suitible for pic code" } */
mov esi, [b] /* { dg-warning "non-pic addressing form not suitible for pic code" } */
mov esi, [c] /* { dg-warning "non-pic addressing form not suitible for pic code" } */
mov esi, [ptr][4] /* { dg-warning "will consume extra register" } */
mov esi, [ptr+4] /* { dg-warning "will consume extra register" } */
mov esi, [ptr][eax] /* { dg-warning "will consume extra register" } */
mov esi, [ptr+eax] /* { dg-warning "will consume extra register" } */
mov esi, [-4][pa+esi] /* { dg-warning "will consume extra register" } */
mov esi, [-4][j+esi] /* { dg-warning "will consume extra register" } */
mov esi, [pa-4+esi] /* { dg-warning "will consume extra register" } */
mov esi, [a][3] /* { dg-warning "will consume extra register" } */
jmp [a+4*ebx] /* { dg-warning "will consume extra register" } */
}
}
| gpl-2.0 |
gildaslemoal/elpi | applications/product/src/org/ofbiz/shipment/packing/PackingServices.java | 16924 | /*******************************************************************************
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*******************************************************************************/
package org.ofbiz.shipment.packing;
import java.math.BigDecimal;
import java.util.Locale;
import java.util.Map;
import org.ofbiz.base.util.Debug;
import org.ofbiz.base.util.GeneralException;
import org.ofbiz.base.util.UtilGenerics;
import org.ofbiz.base.util.UtilMisc;
import org.ofbiz.base.util.UtilProperties;
import org.ofbiz.base.util.UtilValidate;
import org.ofbiz.service.DispatchContext;
import org.ofbiz.service.ServiceUtil;
public class PackingServices {
public static final String module = PackingServices.class.getName();
public static final String resource = "ProductUiLabels";
public static Map<String, Object> addPackLine(DispatchContext dctx, Map<String, ? extends Object> context) {
PackingSession session = (PackingSession) context.get("packingSession");
String shipGroupSeqId = (String) context.get("shipGroupSeqId");
String orderId = (String) context.get("orderId");
String productId = (String) context.get("productId");
BigDecimal quantity = (BigDecimal) context.get("quantity");
BigDecimal weight = (BigDecimal) context.get("weight");
Integer packageSeq = (Integer) context.get("packageSeq");
// set the instructions -- will clear out previous if now null
String instructions = (String) context.get("handlingInstructions");
session.setHandlingInstructions(instructions);
// set the picker party id -- will clear out previous if now null
String pickerPartyId = (String) context.get("pickerPartyId");
session.setPickerPartyId(pickerPartyId);
if (quantity == null) {
quantity = BigDecimal.ONE;
}
Debug.logInfo("OrderId [" + orderId + "] ship group [" + shipGroupSeqId + "] Pack input [" + productId + "] @ [" + quantity + "] packageSeq [" + packageSeq + "] weight [" + weight +"]", module);
if (weight == null) {
Debug.logWarning("OrderId [" + orderId + "] ship group [" + shipGroupSeqId + "] product [" + productId + "] being packed without a weight, assuming 0", module);
weight = BigDecimal.ZERO;
}
try {
session.addOrIncreaseLine(orderId, null, shipGroupSeqId, productId, quantity, packageSeq.intValue(), weight, false);
} catch (GeneralException e) {
Debug.logError(e, module);
return ServiceUtil.returnError(e.getMessage());
}
return ServiceUtil.returnSuccess();
}
/**
* <p>Create or update package lines.</p>
* <p>Context parameters:
* <ul>
* <li>selInfo - selected rows</li>
* <li>iteInfo - orderItemIds</li>
* <li>prdInfo - productIds</li>
* <li>pkgInfo - package numbers</li>
* <li>wgtInfo - weights to pack</li>
* <li>numPackagesInfo - number of packages to pack per line (>= 1, default: 1)<br/>
* Packs the same items n times in consecutive packages, starting from the package number retrieved from pkgInfo.</li>
* </ul>
* </p>
* @param dctx the dispatch context
* @param context the context
* @return returns the result of the service execution
*/
public static Map<String, Object> packBulk(DispatchContext dctx, Map<String, ? extends Object> context) {
PackingSession session = (PackingSession) context.get("packingSession");
String orderId = (String) context.get("orderId");
String shipGroupSeqId = (String) context.get("shipGroupSeqId");
Boolean updateQuantity = (Boolean) context.get("updateQuantity");
Locale locale = (Locale) context.get("locale");
if (updateQuantity == null) {
updateQuantity = Boolean.FALSE;
}
// set the instructions -- will clear out previous if now null
String instructions = (String) context.get("handlingInstructions");
session.setHandlingInstructions(instructions);
// set the picker party id -- will clear out previous if now null
String pickerPartyId = (String) context.get("pickerPartyId");
session.setPickerPartyId(pickerPartyId);
Map<String, ?> selInfo = UtilGenerics.checkMap(context.get("selInfo"));
Map<String, String> iteInfo = UtilGenerics.checkMap(context.get("iteInfo"));
Map<String, String> prdInfo = UtilGenerics.checkMap(context.get("prdInfo"));
Map<String, String> qtyInfo = UtilGenerics.checkMap(context.get("qtyInfo"));
Map<String, String> pkgInfo = UtilGenerics.checkMap(context.get("pkgInfo"));
Map<String, String> wgtInfo = UtilGenerics.checkMap(context.get("wgtInfo"));
Map<String, String> numPackagesInfo = UtilGenerics.checkMap(context.get("numPackagesInfo"));
if (selInfo != null) {
for (String rowKey: selInfo.keySet()) {
String orderItemSeqId = iteInfo.get(rowKey);
String prdStr = prdInfo.get(rowKey);
if (UtilValidate.isEmpty(prdStr)) {
// set the productId to null if empty
prdStr = null;
}
// base package/quantity/weight strings
String pkgStr = pkgInfo.get(rowKey);
String qtyStr = qtyInfo.get(rowKey);
String wgtStr = wgtInfo.get(rowKey);
Debug.logInfo("Item: " + orderItemSeqId + " / Product: " + prdStr + " / Quantity: " + qtyStr + " / Package: " + pkgStr + " / Weight: " + wgtStr, module);
// array place holders
String[] quantities;
String[] packages;
String[] weights;
// process the package array
if (pkgStr.indexOf(",") != -1) {
// this is a multi-box update
packages = pkgStr.split(",");
} else {
packages = new String[] { pkgStr };
}
// check to make sure there is at least one package
if (packages == null || packages.length == 0) {
return ServiceUtil.returnError(UtilProperties.getMessage(resource,
"ProductPackBulkNoPackagesDefined", locale));
}
// process the quantity array
if (qtyStr == null) {
quantities = new String[packages.length];
for (int p = 0; p < packages.length; p++) {
quantities[p] = qtyInfo.get(rowKey + ":" + packages[p]);
}
if (quantities.length != packages.length) {
return ServiceUtil.returnError(UtilProperties.getMessage(resource,
"ProductPackBulkPackagesAndQuantitiesDoNotMatch", locale));
}
} else {
quantities = new String[] { qtyStr };
}
// process the weight array
if (UtilValidate.isEmpty(wgtStr)) wgtStr = "0";
weights = new String[] { wgtStr };
for (int p = 0; p < packages.length; p++) {
BigDecimal quantity;
int packageSeq;
BigDecimal weightSeq;
try {
quantity = new BigDecimal(quantities[p]);
packageSeq = Integer.parseInt(packages[p]);
weightSeq = new BigDecimal(weights[p]);
} catch (Exception e) {
return ServiceUtil.returnError(e.getMessage());
}
try {
String numPackagesStr = numPackagesInfo.get(rowKey);
int numPackages = 1;
if (numPackagesStr != null) {
try {
numPackages = Integer.parseInt(numPackagesStr);
if (numPackages < 1) {
numPackages = 1;
}
} catch (NumberFormatException nex) {
}
}
for (int numPackage=0; numPackage<numPackages; numPackage++) {
session.addOrIncreaseLine(orderId, orderItemSeqId, shipGroupSeqId, prdStr, quantity, packageSeq+numPackage, weightSeq, updateQuantity.booleanValue());
}
} catch (GeneralException e) {
Debug.logError(e, module);
return ServiceUtil.returnError(e.getMessage());
}
}
}
}
return ServiceUtil.returnSuccess();
}
public static Map<String, Object> incrementPackageSeq(DispatchContext dctx, Map<String, ? extends Object> context) {
PackingSession session = (PackingSession) context.get("packingSession");
int nextSeq = session.nextPackageSeq();
Map<String, Object> result = ServiceUtil.returnSuccess();
result.put("nextPackageSeq", Integer.valueOf(nextSeq));
return result;
}
public static Map<String, Object> clearLastPackage(DispatchContext dctx, Map<String, ? extends Object> context) {
PackingSession session = (PackingSession) context.get("packingSession");
int nextSeq = session.clearLastPackage();
Map<String, Object> result = ServiceUtil.returnSuccess();
result.put("nextPackageSeq", Integer.valueOf(nextSeq));
return result;
}
public static Map<String, Object> clearPackLine(DispatchContext dctx, Map<String, ? extends Object> context) {
PackingSession session = (PackingSession) context.get("packingSession");
String orderId = (String) context.get("orderId");
String orderItemSeqId = (String) context.get("orderItemSeqId");
String shipGroupSeqId = (String) context.get("shipGroupSeqId");
String inventoryItemId = (String) context.get("inventoryItemId");
String productId = (String) context.get("productId");
Integer packageSeqId = (Integer) context.get("packageSeqId");
Locale locale = (Locale) context.get("locale");
PackingSessionLine line = session.findLine(orderId, orderItemSeqId, shipGroupSeqId,
productId, inventoryItemId, packageSeqId.intValue());
// remove the line
if (line != null) {
session.clearLine(line);
} else {
return ServiceUtil.returnError(UtilProperties.getMessage(resource,
"ProductPackLineNotFound", locale));
}
return ServiceUtil.returnSuccess();
}
public static Map<String, Object> clearPackAll(DispatchContext dctx, Map<String, ? extends Object> context) {
PackingSession session = (PackingSession) context.get("packingSession");
session.clearAllLines();
return ServiceUtil.returnSuccess();
}
public static Map<String, Object> calcPackSessionAdditionalShippingCharge(DispatchContext dctx, Map<String, ? extends Object> context) {
PackingSession session = (PackingSession) context.get("packingSession");
Map<String, String> packageWeights = UtilGenerics.checkMap(context.get("packageWeights"));
String weightUomId = (String) context.get("weightUomId");
String shippingContactMechId = (String) context.get("shippingContactMechId");
String shipmentMethodTypeId = (String) context.get("shipmentMethodTypeId");
String carrierPartyId = (String) context.get("carrierPartyId");
String carrierRoleTypeId = (String) context.get("carrierRoleTypeId");
String productStoreId = (String) context.get("productStoreId");
BigDecimal shippableWeight = setSessionPackageWeights(session, packageWeights);
BigDecimal estimatedShipCost = session.getShipmentCostEstimate(shippingContactMechId, shipmentMethodTypeId, carrierPartyId, carrierRoleTypeId, productStoreId, null, null, shippableWeight, null);
session.setAdditionalShippingCharge(estimatedShipCost);
session.setWeightUomId(weightUomId);
Map<String, Object> result = ServiceUtil.returnSuccess();
result.put("additionalShippingCharge", estimatedShipCost);
return result;
}
public static Map<String, Object> completePack(DispatchContext dctx, Map<String, ? extends Object> context) {
PackingSession session = (PackingSession) context.get("packingSession");
Locale locale = (Locale) context.get("locale");
// set the instructions -- will clear out previous if now null
String instructions = (String) context.get("handlingInstructions");
String pickerPartyId = (String) context.get("pickerPartyId");
BigDecimal additionalShippingCharge = (BigDecimal) context.get("additionalShippingCharge");
Map<String, String> packageWeights = UtilGenerics.checkMap(context.get("packageWeights"));
Map<String, String> boxTypes = UtilGenerics.checkMap(context.get("boxTypes"));
String weightUomId = (String) context.get("weightUomId");
session.setHandlingInstructions(instructions);
session.setPickerPartyId(pickerPartyId);
session.setAdditionalShippingCharge(additionalShippingCharge);
session.setWeightUomId(weightUomId);
setSessionPackageWeights(session, packageWeights);
setSessionShipmentBoxTypes(session, boxTypes);
Boolean force = (Boolean) context.get("forceComplete");
if (force == null) {
force = Boolean.FALSE;
}
String shipmentId = null;
try {
shipmentId = session.complete(force);
} catch (GeneralException e) {
Debug.logError(e, module);
return ServiceUtil.returnError(e.getMessage(), e.getMessageList());
}
Map<String, Object> resp;
if ("EMPTY".equals(shipmentId)) {
resp = ServiceUtil.returnError(UtilProperties.getMessage(resource,
"ProductPackCompleteNoItems", locale));
} else {
resp = ServiceUtil.returnSuccess(UtilProperties.getMessage(resource,
"ProductPackComplete", UtilMisc.toMap("shipmentId", shipmentId), locale));
}
resp.put("shipmentId", shipmentId);
return resp;
}
public static BigDecimal setSessionPackageWeights(PackingSession session, Map<String, String> packageWeights) {
BigDecimal shippableWeight = BigDecimal.ZERO;
if (! UtilValidate.isEmpty(packageWeights)) {
for (Map.Entry<String, String> entry: packageWeights.entrySet()) {
String packageSeqId = entry.getKey();
String packageWeightStr = entry.getValue();
if (UtilValidate.isNotEmpty(packageWeightStr)) {
BigDecimal packageWeight = new BigDecimal(packageWeights.get(packageSeqId));
session.setPackageWeight(Integer.parseInt(packageSeqId), packageWeight);
shippableWeight = shippableWeight.add(packageWeight);
} else {
session.setPackageWeight(Integer.parseInt(packageSeqId), null);
}
}
}
return shippableWeight;
}
public static void setSessionShipmentBoxTypes(PackingSession session, Map<String, String> boxTypes) {
if (UtilValidate.isNotEmpty(boxTypes)) {
for (Map.Entry<String, String> entry: boxTypes.entrySet()) {
String packageSeqId = entry.getKey();
String boxTypeStr = entry.getValue();
if (UtilValidate.isNotEmpty(boxTypeStr)) {
session.setShipmentBoxType(Integer.parseInt(packageSeqId), boxTypeStr);
} else {
session.setShipmentBoxType(Integer.parseInt(packageSeqId), null);
}
}
}
}
}
| gpl-2.0 |
berkeley-amsa/amsa | administrator/components/com_phocadownload/views/phocadownloadlayout/tmpl/edit.php | 3634 | <?php
/*
* @package Joomla.Framework
* @copyright Copyright (C) 2005 - 2010 Open Source Matters, Inc. All rights reserved.
* @license GNU General Public License version 2 or later; see LICENSE.txt
*
* @component Phoca Component
* @copyright Copyright (C) Jan Pavelka www.phoca.cz
* @license http://www.gnu.org/copyleft/gpl.html GNU General Public License version 2 or later;
*/
defined('_JEXEC') or die;
JHtml::_('behavior.tooltip');
JHtml::_('behavior.formvalidation');
?>
<script type="text/javascript">
Joomla.submitbutton = function(task)
{
if (task == 'phocadownloadlayout.cancel' || document.formvalidator.isValid(document.id('phocadownloadlayout-form'))) {
Joomla.submitform(task, document.getElementById('phocadownloadlayout-form'));
}
else {
alert('<?php echo $this->escape(JText::_('JGLOBAL_VALIDATION_FORM_FAILED'));?>');
}
}
</script>
<form action="<?php JRoute::_('index.php?option=com_phocadownload'); ?>" method="post" name="adminForm" id="phocadownloadlayout-form" class="form-validate">
<div class="width-60 fltlft">
<fieldset class="adminform">
<legend><?php
echo JText::_('COM_PHOCADOWNLOAD_LAYOUT'); ?></legend>
<?php /*
<ul class="adminformlist">
<?php
$formArray = array ('title', 'alias', 'link_ext', 'link_cat', 'ordering');
foreach ($formArray as $value) {
echo '<li>'.$this->form->getLabel($value) . $this->form->getInput($value).'</li>' . "\n";
} ?>
</ul> */ ?>
<?php echo $this->form->getLabel('categories'); ?>
<div class="clr"></div>
<?php echo $this->form->getInput('categories'); ?>
<?php echo $this->form->getLabel('category'); ?>
<div class="clr"></div>
<?php echo $this->form->getInput('category'); ?>
<?php echo $this->form->getLabel('file'); ?>
<div class="clr"></div>
<?php echo $this->form->getInput('file'); ?>
</fieldset>
</div>
<div class="width-40 fltrt"><?php
echo '<div class="warning">' . JText::_('COM_PHOCADOWNLOAD_LAYOUT_WARNING').'</div>';
echo '<div class="pdview"><h4>' . JText::_('COM_PHOCADOWNLOAD_CATEGORIES_VIEW').'</h4>';
$lP = PhocaDownloadHelper::getLayoutParams('categories');
echo '<div><h3>' . JText::_('COM_PHOCADOWNLOAD_PARAMETERS').'</h3></div>';
if (isset($lP['search'])) {
foreach ($lP['search'] as $k => $v) {
echo $v . ' ';
}
}
echo '<div><h3>' . JText::_('COM_PHOCADOWNLOAD_STYLES').'</h3></div>';
if (isset($lP['style'])) {
foreach ($lP['style'] as $k => $v) {
echo $v . ' ';
}
}
echo '</div>';
echo '<div class="pdview"><h4>' . JText::_('COM_PHOCADOWNLOAD_CATEGORY_VIEW').'</h4>';
$lP = PhocaDownloadHelper::getLayoutParams('category');
echo '<div><h3>' . JText::_('COM_PHOCADOWNLOAD_PARAMETERS').'</h3></div>';
if (isset($lP['search'])) {
foreach ($lP['search'] as $k => $v) {
echo $v . ' ';
}
}
echo '<div><h3>' . JText::_('COM_PHOCADOWNLOAD_STYLES').'</h3></div>';
if (isset($lP['style'])) {
foreach ($lP['style'] as $k => $v) {
echo $v . ' ';
}
}
echo '</div>';
echo '<div class="pdview"><h4>' . JText::_('COM_PHOCADOWNLOAD_FILE_VIEW').'</h4>';
$lP = PhocaDownloadHelper::getLayoutParams('file');
echo '<div><h3>' . JText::_('COM_PHOCADOWNLOAD_PARAMETERS').'</h3></div>';
if (isset($lP['search'])) {
foreach ($lP['search'] as $k => $v) {
echo $v . ' ';
}
}
echo '<div><h3>' . JText::_('COM_PHOCADOWNLOAD_STYLES').'</h3></div>';
if (isset($lP['style'])) {
foreach ($lP['style'] as $k => $v) {
echo $v . ' ';
}
}
echo '</div>';
?>
</div>
<div class="clr"></div>
<input type="hidden" name="task" value="" />
<?php echo JHtml::_('form.token'); ?>
</form>
</div>
| gpl-2.0 |
janusnic/Portfolio | hostweb/kernel/plugins/anandpatel/wysiwygeditors/formwidgets/editor/assets/froala/js/langs/hr.js | 3096 | /*!
* froala_editor v1.2.6 (http://editor.froala.com)
* License http://editor.froala.com/license
* Copyright 2014-2015 Froala Labs
*/
/**
* Croatian.
*/
$.Editable.LANGS['hr'] = {
translation: {
"Bold": "Podebljaj",
"Italic": "Kurziv",
"Underline": "Crta ispod",
"Strikethrough": "Crta kroz sredinu",
"Font Size": "Veli\u010dina fonta",
"Color": "Boja",
"Background": "Pozadine",
"Text": "Teksta",
"Format Block": "Format bloka",
"Normal": "Normalno",
"Paragraph": "Paragraf",
"Code": "Izvorni kod",
"Quote": "Citat",
"Heading 1": "Zaglavlje 1",
"Heading 2": "Zaglavlje 2",
"Heading 3": "Zaglavlje 3",
"Heading 4": "Zaglavlje 4",
"Heading 5": "Zaglavlje 5",
"Heading 6": "Zaglavlje 6",
"Block Style": "Blokiranje stil",
"Alignment": "Poravnanje",
"Align Left": "Poravnaj lijevo",
"Align Center": "Poravnaj po sredini",
"Align Right": "Poravnaj desno",
"Justify": "Obostrano poravnanje",
"Numbered List": "Numerirana lista",
"Bulleted List": "Lista bez reda",
"Indent Less": "Uvuci paragraf",
"Indent More": "Izvuci paragraf",
"Select All": "Sa\u010duvaj sve",
"Insert Link": "Umetni link",
"Insert Image": "Umetni sliku",
"Insert Video": "Umetni video",
"Undo": "Korak natrag",
"Redo": "Korak naprijed",
"Show HTML": "Prika\u017ei HTML kod",
"Float Left": "Prebaci lijevo",
"Float None": "Bez prebacivanja",
"Float Right": "Prebaci desno",
"Replace Image": "Zamijeni sliku",
"Remove Image": "Ukloni sliku",
"Title": "Naslov",
"Drop image": "Izbaci sliku",
"or click": "ili odaberi",
"or": "ili",
"Enter URL": "Enter URL",
"Please wait!": "Molim pri\u010dekaj!",
"Are you sure? Image will be deleted.": "Da li ste sigurni da \u017eelite obrisati ovu sliku?",
"UNLINK": "Ukloni link",
"Open in new tab": "Otvori u novom prozoru",
"Type something": "Ukucaj ne\u0161to",
"Cancel": "Otka\u017ei",
"OK": "U redu",
"Manage images": "Upravljanje slike",
"Delete": "Obri\u0161i",
"Font Family": "Odaberi font",
"Insert Horizontal Line": "Umetni liniju",
"Table": "Tablica",
"Insert table": "Umetni tablicu",
"Cell": "Polje",
"Row": "Red",
"Column": "Stupac",
"Delete table": "Obri\u0161i tablicu",
"Insert cell before": "Umetni polje prije",
"Insert cell after": "Umetni polje poslije",
"Delete cell": "Obri\u0161i polje",
"Merge cells": "Spoji polja",
"Horizontal split": "Horizontalno razdvajanje polja",
"Vertical split": "Vertikalno razdvajanje polja",
"Insert row above": "Umetni red iznad",
"Insert row below": "Umetni red ispod",
"Delete row": "Obri\u0161i red",
"Insert column before": "Umetni stupac prije",
"Insert column after": "Umetni stupac poslije",
"Delete column": "Obri\u0161i stupac",
"Uploading image": "Prijenos slike",
"Upload File": "Prijenos datoteke",
"Drop File": "Izbaci datoteke",
"Clear formatting": "Ukloniti oblikovanje"
},
direction: "ltr"
};
| gpl-2.0 |
vanfanel/scummvm | audio/decoders/wave.cpp | 7248 | /* ScummVM - Graphic Adventure Engine
*
* ScummVM is the legal property of its developers, whose names
* are too numerous to list here. Please refer to the COPYRIGHT
* file distributed with this source distribution.
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* as published by the Free Software Foundation; either version 2
* of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*
*/
#include "common/debug.h"
#include "common/textconsole.h"
#include "common/stream.h"
#include "common/substream.h"
#include "audio/audiostream.h"
#include "audio/decoders/wave_types.h"
#include "audio/decoders/wave.h"
#include "audio/decoders/adpcm.h"
#include "audio/decoders/mp3.h"
#include "audio/decoders/raw.h"
#include "audio/decoders/g711.h"
namespace Audio {
bool loadWAVFromStream(Common::SeekableReadStream &stream, int &size, int &rate, byte &flags, uint16 *wavType, int *blockAlign_) {
const int32 initialPos = stream.pos();
byte buf[4+1];
buf[4] = 0;
stream.read(buf, 4);
if (memcmp(buf, "RIFF", 4) != 0) {
warning("getWavInfo: No 'RIFF' header");
return false;
}
int32 wavLength = stream.readUint32LE();
stream.read(buf, 4);
if (memcmp(buf, "WAVE", 4) != 0) {
warning("getWavInfo: No 'WAVE' header");
return false;
}
stream.read(buf, 4);
if (memcmp(buf, "fact", 4) == 0) {
// Initial fact chunk, so skip over it
uint32 factLen = stream.readUint32LE();
stream.skip(factLen);
stream.read(buf, 4);
}
if (memcmp(buf, "fmt ", 4) != 0) {
warning("getWavInfo: No 'fmt' header");
return false;
}
uint32 fmtLength = stream.readUint32LE();
if (fmtLength < 16) {
// A valid fmt chunk always contains at least 16 bytes
warning("getWavInfo: 'fmt' header is too short");
return false;
}
// Next comes the "type" field of the fmt header. Some typical
// values for it:
// 1 -> uncompressed PCM
// 17 -> IMA ADPCM compressed WAVE
// See <http://www-mmsp.ece.mcgill.ca/Documents/AudioFormats/WAVE/WAVE.html>
// for a more complete list of common WAVE compression formats...
uint16 type = stream.readUint16LE(); // == 1 for PCM data
uint16 numChannels = stream.readUint16LE(); // 1 for mono, 2 for stereo
uint32 samplesPerSec = stream.readUint32LE(); // in Hz
uint32 avgBytesPerSec = stream.readUint32LE(); // == SampleRate * NumChannels * BitsPerSample/8
uint16 blockAlign = stream.readUint16LE(); // == NumChannels * BitsPerSample/8
uint16 bitsPerSample = stream.readUint16LE(); // 8, 16 ...
// 8 bit data is unsigned, 16 bit data signed
if (wavType != 0)
*wavType = type;
if (blockAlign_ != 0)
*blockAlign_ = blockAlign;
#if 0
debug("WAVE information:");
debug(" total size: %d", wavLength);
debug(" fmt size: %d", fmtLength);
debug(" type: %d", type);
debug(" numChannels: %d", numChannels);
debug(" samplesPerSec: %d", samplesPerSec);
debug(" avgBytesPerSec: %d", avgBytesPerSec);
debug(" blockAlign: %d", blockAlign);
debug(" bitsPerSample: %d", bitsPerSample);
#endif
switch (type) {
case kWaveFormatPCM:
case kWaveFormatMSADPCM:
case kWaveFormatALawPCM:
case kWaveFormatMuLawPCM:
case kWaveFormatMSIMAADPCM:
#ifdef USE_MAD
case kWaveFormatMP3:
#endif
break;
default:
warning("getWavInfo: unsupported format (type %d)", type);
return false;
}
if (type == kWaveFormatMP3) {
bitsPerSample = 8;
} else if (type != kWaveFormatMSADPCM) {
if (blockAlign != numChannels * bitsPerSample / 8) {
debug(0, "getWavInfo: blockAlign is invalid");
}
if (avgBytesPerSec != samplesPerSec * blockAlign) {
debug(0, "getWavInfo: avgBytesPerSec is invalid");
}
}
// Prepare the return values.
rate = samplesPerSec;
flags = 0;
if (bitsPerSample == 8) // 8 bit data is unsigned
flags |= Audio::FLAG_UNSIGNED;
else if (bitsPerSample == 16) // 16 bit data is signed little endian
flags |= (Audio::FLAG_16BITS | Audio::FLAG_LITTLE_ENDIAN);
else if (bitsPerSample == 24) // 24 bit data is signed little endian
flags |= (Audio::FLAG_24BITS | Audio::FLAG_LITTLE_ENDIAN);
else if (bitsPerSample == 4 && (type == kWaveFormatMSADPCM || type == kWaveFormatMSIMAADPCM))
flags |= Audio::FLAG_16BITS;
else {
warning("getWavInfo: unsupported bitsPerSample %d", bitsPerSample);
return false;
}
if (numChannels == 2)
flags |= Audio::FLAG_STEREO;
else if (numChannels != 1) {
warning("getWavInfo: unsupported number of channels %d", numChannels);
return false;
}
// It's almost certainly a WAV file, but we still need to find its
// 'data' chunk.
// Skip over the rest of the fmt chunk.
int offset = fmtLength - 16;
do {
stream.seek(offset, SEEK_CUR);
if (stream.pos() >= initialPos + wavLength + 8) {
warning("getWavInfo: Can't find 'data' chunk");
return false;
}
stream.read(buf, 4);
offset = stream.readUint32LE();
#if 0
debug(" found a '%s' tag of size %d", buf, offset);
#endif
} while (memcmp(buf, "data", 4) != 0);
// Stream now points at 'offset' bytes of sample data...
size = offset;
return true;
}
SeekableAudioStream *makeWAVStream(Common::SeekableReadStream *stream, DisposeAfterUse::Flag disposeAfterUse) {
int size, rate;
byte flags;
uint16 type;
int blockAlign;
if (!loadWAVFromStream(*stream, size, rate, flags, &type, &blockAlign)) {
if (disposeAfterUse == DisposeAfterUse::YES)
delete stream;
return 0;
}
int channels = (flags & Audio::FLAG_STEREO) ? 2 : 1;
int bytesPerSample = (flags & Audio::FLAG_24BITS) ? 3 : ((flags & Audio::FLAG_16BITS) ? 2 : 1);
// Raw PCM, make sure the last packet is complete
if (type == kWaveFormatPCM) {
uint sampleSize = bytesPerSample * channels;
if (size % sampleSize != 0) {
warning("makeWAVStream: Trying to play a WAVE file with an incomplete PCM packet");
size &= ~(sampleSize - 1);
}
}
Common::SeekableReadStream *dataStream = new Common::SeekableSubReadStream(stream, stream->pos(), stream->pos() + size, disposeAfterUse);
switch (type) {
case kWaveFormatMSIMAADPCM:
return makeADPCMStream(dataStream, DisposeAfterUse::YES, 0, Audio::kADPCMMSIma, rate, channels, blockAlign);
case kWaveFormatMSADPCM:
return makeADPCMStream(dataStream, DisposeAfterUse::YES, 0, Audio::kADPCMMS, rate, channels, blockAlign);
#ifdef USE_MAD
case kWaveFormatMP3:
return makeMP3Stream(dataStream, DisposeAfterUse::YES);
#endif
case kWaveFormatALawPCM:
return makeALawStream(dataStream, DisposeAfterUse::YES, rate, channels);
case kWaveFormatMuLawPCM:
return makeMuLawStream(dataStream, DisposeAfterUse::YES, rate, channels);
case kWaveFormatPCM:
return makeRawStream(dataStream, rate, flags);
}
// If the format is unsupported, we already returned earlier, but just in case
delete dataStream;
return 0;
}
} // End of namespace Audio
| gpl-2.0 |
CristianOspinaOspina/testlinkpruebas | lib/functions/database.class.php | 27394 | <?php
/**
* TestLink Open Source Project - http://testlink.sourceforge.net/
* This script is distributed under the GNU General Public License 2 or later.
*
* @filesource database.class.php
* @package TestLink
* @author Francisco Mancardi
* @author Mantis Team
* @copyright 2006-2011 TestLink community
* @copyright 2002-2004 Mantis Team - mantisbt-dev@lists.sourceforge.net
* (Parts of code has been adapted from Mantis BT)
* @link http://www.testlink.org
*
* @internal revisions
* @since 1.9.12
*/
/**
* IMPORTANT NOTICE
* As stated on ADODB documentation:
*
* ----------------------------------------------------------------------------------------------------------------------
* $ADODB_COUNTRECS
* If the database driver API does not support counting the number of records returned in a SELECT statement,
* the function RecordCount() is emulated when the global variable $ADODB_COUNTRECS is set to true, which is the default.
* We emulate this by buffering the records, WHICH CAN TAKE UP LARGE AMOUNTS OF MEMORY FOR BIG RECORDSETS.
* Set this variable to false for the best performance.
* THIS VARIABLE IS CHECKED EVERY TIME A QUERY IS EXECUTED, so you can selectively choose which recordsets to count.
* ----------------------------------------------------------------------------------------------------------------------
*
* this set will improve performance but have a side
* effect, for DBMS like POSTGRES method num_rows() will return ALWAYS -1, causing problems
*
*/
$ADODB_COUNTRECS = TRUE;
// To use a different version of ADODB that provided with TL, use a similar bunch of lines
// on custom_config.inc.php
if( !defined('TL_ADODB_RELATIVE_PATH') )
{
define('TL_ADODB_RELATIVE_PATH','/../../third_party/adodb/adodb.inc.php' );
}
require_once( dirname(__FILE__). TL_ADODB_RELATIVE_PATH );
require_once( dirname(__FILE__). '/logging.inc.php' );
/**
* TestLink wrapper for ADODB component
* @package TestLink
*/
class database
{
const CUMULATIVE=1;
const ONERROREXIT=1;
var $db;
var $queries_array = array();
var $is_connected=false;
var $nQuery = 0;
var $overallDuration = 0;
var $dbType;
private $logEnabled=0;
private $logQueries=0;
// timer analysis
function microtime_float()
{
list( $usec, $sec ) = explode( " ", microtime() );
return ( (float)$usec + (float)$sec );
}
function setLogEnabled($value)
{
$this->logEnabled=$value ? 1 : 0;
}
function getLogEnabled($value)
{
return $this->logEnabled;
}
function setLogQueries($value)
{
$this->logQueries = $value ? 1 : 0;
}
function getLogQueries($value)
{
return $this->logQueries;
}
// TICKET 4898: MSSQL - Add support for SQLSRV drivers needed for PHP on WINDOWS version 5.3 and higher
function database($db_type)
{
$this->dbType = $adodb_driver = $db_type;
$fetch_mode = ADODB_FETCH_ASSOC;
// added to reduce memory usage (before this setting we used ADODB_FETCH_BOTH)
if($this->dbType == 'mssql')
{
$fetch_mode = ADODB_FETCH_BOTH;
if(PHP_OS == 'WINNT')
{
// Faced this problem when testing XAMPP 1.7.7 on Windows 7 with MSSQL 2008 Express
// From PHP MANUAL - reganding mssql_* functions
// These functions allow you to access MS SQL Server database.
// This extension is not available anymore on Windows with PHP 5.3 or later.
// SQLSRV, an alternative driver for MS SQL is available from Microsoft:
// http://msdn.microsoft.com/en-us/sqlserver/ff657782.aspx.
//
// PHP_VERSION_ID is available as of PHP 5.2.7
if ( defined('PHP_VERSION_ID') && PHP_VERSION_ID >= 50300)
{
$adodb_driver = 'mssqlnative';
}
}
}
$this->db = NewADOConnection($adodb_driver);
$this->db->SetFetchMode($fetch_mode);
}
// access to the ADODB object
function get_dbmgr_object()
{
return($this->db);
}
/** Make a connection to the database */
# changed Connect() to NConnect() see ADODB Manuals
function connect( $p_dsn, $p_hostname = null, $p_username = null,
$p_password = null, $p_database_name = null )
{
$result = array('status' => 1, 'dbms_msg' => 'ok');
if( $p_dsn === false ) {
$t_result = $this->db->NConnect($p_hostname, $p_username, $p_password, $p_database_name );
} else {
$t_result = $this->db->IsConnected();
}
if ( $t_result ) {
$this->is_connected = true;
} else {
$result['status'] = 0;
$result['dbms_msg']=$this->error();
}
return ($result);
}
/**
* execute SQL query,
* requires connection to be opened
*
* @param string $p_query SQL request
* @param integer $p_limit (optional) number of rows
* @param integer $p_offset (optional) begining row number
*
* @return boolean result of request
**/
function exec_query( $p_query, $p_limit = -1, $p_offset = -1 )
{
$ec = 0;
$emsg = null;
$logLevel = 'DEBUG';
$message = '';
if($this->logQueries)
{
$this->nQuery++;
$t_start = $this->microtime_float();
}
if ( ( $p_limit != -1 ) || ( $p_offset != -1 ) ) {
$t_result = $this->db->SelectLimit( $p_query, $p_limit, $p_offset );
} else {
$t_result = $this->db->Execute( $p_query );
}
if($this->logQueries)
{
$t_elapsed = number_format( $this->microtime_float() - $t_start, 4);
$this->overallDuration += $t_elapsed;
$message = "SQL [". $this->nQuery . "] executed [took {$t_elapsed} secs]" .
"[all took {$this->overallDuration} secs]:\n\t\t";
}
$message .= $p_query;
if (!$t_result)
{
$ec = $this->error_num();
$emsg = $this->error_msg();
$message .= "\nQuery failed: errorcode[" . $ec . "]". "\n\terrormsg:".$emsg;
$logLevel = 'ERROR';
tLog("ERROR ON exec_query() - database.class.php <br />" . $this->error(htmlspecialchars($p_query)) .
"<br />THE MESSAGE : $message ", 'ERROR', "DATABASE");
echo "<pre> ============================================================================== </pre>";
echo "<pre> DB Access Error - debug_print_backtrace() OUTPUT START </pre>";
echo "<pre> ATTENTION: Enabling more debug info will produce path disclosure weakness (CWE-200) </pre>";
echo "<pre> Having this additional Information could be useful for reporting </pre>";
echo "<pre> issue to development TEAM. </pre>";
echo "<pre> ============================================================================== </pre>";
if(defined('DBUG_ON') && DBUG_ON == 1)
{
echo "<pre>"; debug_print_backtrace(); echo "</pre>";
}
//else
//{
// echo "<pre>"; debug_print_backtrace(DEBUG_BACKTRACE_IGNORE_ARGS); echo "</pre>";
//}
echo "<pre> ============================================================================== </pre>";
$t_result = false;
}
if($this->logEnabled)
{
tLog($message,$logLevel,"DATABASE");
}
if($this->logQueries)
{
array_push ($this->queries_array, array( $p_query, $t_elapsed, $ec, $emsg ) );
}
return $t_result;
}
// TICKET 4898: MSSQL - Add support for SQLSRV drivers needed for PHP on WINDOWS version 5.3 and higher
function fetch_array( &$p_result )
{
if ( $p_result->EOF ) {
return false;
}
// mysql obeys FETCH_MODE_BOTH, hence ->fields works, other drivers do not support this
switch ($this->db->databaseType)
{
case "mysql":
case "oci8po":
case "mssql":
case "mssqlnative":
$t_array = $p_result->fields;
break;
default:
$t_array = $p_result->GetRowAssoc(false);
break;
}
$p_result->MoveNext();
return $t_array;
}
// 20080315 - franciscom - Got new code from Mantis, that manages FETCH_MODE_ASSOC
function db_result( $p_result, $p_index1=0, $p_index2=0 ) {
if ( $p_result && ( $this->num_rows( $p_result ) > 0 ) )
{
$p_result->Move( $p_index1 );
$t_result = $p_result->GetArray();
if ( isset( $t_result[0][$p_index2] ) ) {
return $t_result[0][$p_index2];
}
// The numeric index doesn't exist. FETCH_MODE_ASSOC may have been used.
// Get 2nd dimension and make it numerically indexed
$t_result = array_values( $t_result[0] );
return $t_result[$p_index2];
}
return false;
}
/** @return integer the last inserted id */
function insert_id($p_table = null)
{
if ( isset($p_table) && ($this->db_is_pgsql() || $this->db_is_oracle()))
{
if ( $this->db_is_pgsql() )
{
$sql = "SELECT currval('".$p_table."_id_seq')";
}
elseif ($this->db_is_oracle())
{
$sql = "SELECT ".$p_table."_id_seq.currval from dual";
}
$result = $this->exec_query( $sql );
return $this->db_result($result);
}
return $this->db->Insert_ID( );
}
/** Check is the database is PostgreSQL */
function db_is_pgsql()
{
$status_ok = false;
switch( $this->dbType )
{
case 'postgres':
case 'postgres7':
case 'pgsql':
$status_ok = true;
break;
}
return $status_ok;
}
/**
* Check is the database is ORACLE
* @return boolean TRUE = Oracle type
**/
function db_is_oracle()
{
$status_ok = false;
switch( $this->dbType )
{
case 'oci8':
case 'oci8po':
$status_ok = true;
break;
}
return $status_ok;
}
function db_table_exists( $p_table_name ) {
return in_array ( $p_table_name , $this->db->MetaTables( "TABLE" ) ) ;
}
function db_field_exists( $p_field_name, $p_table_name ) {
return in_array ( $p_field_name , $this->db->MetaColumnNames( $p_table_name ) ) ;
}
/**
* Check if there is an index defined on the specified table/field and with
* the specified type.
* Warning: only works with MySQL
*
* @param string $p_table Name of table to check
* @param string $p_field Name of field to check
* @param string $p_key key type to check for (eg: PRI, MUL, ...etc)
*
* @return boolean
*/
function key_exists_on_field( $p_table, $p_field, $p_key ) {
$c_table = $this->db->prepare_string( $p_table );
$c_field = $this->db->prepare_string( $p_field );
$c_key = $this->db->prepare_string( $p_key );
$sql = "DESCRIBE $c_table";
$result = $this->exec_query( $sql );
$count = $this->num_rows( $result );
for ( $i=0 ; $i < $count ; $i++ ) {
$row = $this->db->fetch_array( $result );
if ( $row['Field'] == $c_field ) {
return ( $row['Key'] == $c_key );
}
}
return false;
}
# prepare a string before DB insertion
# 20051226 - fm
function prepare_string( $p_string )
{
if (is_null($p_string))
return '';
$t_escaped = $this->db->qstr( $p_string, false );
// from second char(1) to one before last(-1)
return(substr($t_escaped,1,-1));
}
# prepare an integer before DB insertion
function prepare_int( $p_int ) {
return (int)$p_int;
}
# prepare a boolean before DB insertion
function prepare_bool( $p_bool ) {
return (int)(bool)$p_bool;
}
# return current timestamp for DB
function db_now()
{
switch($this->db->databaseType)
{
/* @todo: maybe we should use this?
case 'odbc_mssql':
return "GETDATE()";
*/
default:
return $this->db->DBTimeStamp(time());
}
}
# generate a unixtimestamp of a date
# > SELECT UNIX_TIMESTAMP();
# -> 882226357
# > SELECT UNIX_TIMESTAMP('1997-10-04 22:23:00');
# -> 875996580
function db_timestamp( $p_date=null ) {
if ( null !== $p_date ) {
$p_timestamp = $this->db->UnixTimeStamp($p_date);
} else {
$p_timestamp = time();
}
return $this->db->DBTimeStamp($p_timestamp) ;
}
function db_unixtimestamp( $p_date=null ) {
if ( null !== $p_date ) {
$p_timestamp = $this->db->UnixTimeStamp($p_date);
} else {
$p_timestamp = time();
}
return $p_timestamp ;
}
/** @return integer count queries */
function count_queries () {
return count( $this->queries_array );
}
/** @return integer count unique queries */
function count_unique_queries () {
$t_unique_queries = 0;
$t_shown_queries = array();
foreach ($this->queries_array as $t_val_array) {
if ( ! in_array( $t_val_array[0], $t_shown_queries ) ) {
$t_unique_queries++;
array_push( $t_shown_queries, $t_val_array[0] );
}
}
return $t_unique_queries;
}
/** get total time for queries */
function time_queries () {
$t_count = count( $this->queries_array );
$t_total = 0;
for ( $i = 0; $i < $t_count; $i++ ) {
$t_total += $this->queries_array[$i][1];
}
return $t_total;
}
/**
* close the connection.
* Not really necessary most of the time since a connection is
* automatically closed when a page finishes loading.
*/
function close() {
$t_result = $this->db->Close();
}
function error_num() {
return $this->db->ErrorNo();
}
function error_msg() {
return $this->db->ErrorMsg();
}
/**
* returns a message string with: error num, error msg and query.
*
* @return string the message
*/
function error( $p_query=null ) {
$msg= $this->error_num() . " - " . $this->error_msg();
if ( null !== $p_query )
{
$msg .= " - " . $p_query ;
}
return $msg;
}
function num_rows( $p_result ) {
return $p_result->RecordCount( );
}
function affected_rows() {
return $this->db->Affected_Rows( );
}
/**
* Fetches the first column first row
*
* @param string $sql the query to be executed
* @param string $column the name of the column which shall be returned
*
* @return mixed the value of the column
**/
function fetchFirstRowSingleColumn($sql,$column)
{
$value = null;
$row = $this->fetchFirstRow($sql);
// BUGID 1318
if ($row && array_key_exists($column, $row))
{
$value = $row[$column];
}
return $value;
}
/**
* Fetches the first row (in a assoc-array)
*
* @param string $sql the query to be executed
* @return array the first row
**/
function fetchFirstRow($sql)
{
$result = $this->exec_query($sql);
$row = null;
if ($result)
{
$row = $this->fetch_array($result);
}
unset($result);
return $row;
}
/**
* Get one value (no array)
* for example: SELECT COUNT(*) FROM table
*
* @param string $sql the query to be executed
* @return string of one value || null
**/
public function fetchOneValue($sql)
{
$row = $this->fetchFirstRow($sql);
if ($row)
{
$fieldName = array_keys($row);
return $row[$fieldName[0]];
}
return null;
}
/**
* Fetches all values for a given column of all returned rows
*
* @param string $sql the query to be executed
* @param string $column the name of the column
* @param integer $limit (optional) number of rows
*
* @return array an enumerated array, which contains all the values
**/
function fetchColumnsIntoArray($sql,$column,$limit = -1)
{
$items = null;
$result = $this->exec_query($sql,$limit);
if ($result)
{
while($row = $this->fetch_array($result))
{
$items[] = $row[$column];
}
}
unset($result);
return $items;
}
/**
* Fetches all rows into a map whose keys are the values of columns
*
* @param string $sql the query to be executed
* @param string $column the name of the column
* @param booleam $cumulative default 0
* useful in situations with results set with multiple
* rows with same value on key column like this:
*
* col1 col2 col3 ...
* X A C
* X B Z
* Y B 0
*
* cumulative=0 -> return items= array('X' => array('A','C'), 'Y' => array('B','0') )
*
* cumulative=1 -> return items=
* array('X' => array( 0 => array('A','C'), 1 => array('B','Z')),
* 'Y' => array( 0 => array('B','0')I )
*
* @param integer $limit (optional) number of rows
*
* @return array an assoc array whose keys are the values from the columns
* of the rows
**/
function fetchRowsIntoMap($sql,$column,$cumulative = 0,$limit = -1,$col2implode='')
{
$items = null;
$result = $this->exec_query($sql,$limit);
if ($result)
{
// -----------------------------------------------
// Error management Code
$errorMsg=__CLASS__ . '/' . __FUNCTION__ . ' - ';
if( ($empty_column = (trim($column)=='') ) )
{
$errorMsg .= 'empty column - SQL:' . $sql;
trigger_error($errorMsg,E_USER_NOTICE);
return null;
}
while($row = $this->fetch_array($result))
{
// -----------------------------------------------
// Error management Code
if( !isset($row[$column]) )
{
$errorMsg .= 'missing column:' . $column;
$errorMsg .= ' - SQL:' . $sql;
trigger_error($errorMsg,E_USER_NOTICE);
return null;
}
// -----------------------------------------------
if ($cumulative)
{
$items[$row[$column]][] = $row;
}
else if($col2implode != '')
{
if(isset($items[$row[$column]]))
{
$items[$row[$column]][$col2implode] .= ',' . $row[$col2implode];
}
else
{
$items[$row[$column]] = $row;
}
}
else
{
$items[$row[$column]] = $row;
}
}
}
unset($result);
unset($row);
return $items;
}
/**
* Fetches the values of two columns from all rows into a map
*
* @param string $sql the query to be executed
* @param string $column1 the name of the column (keys for the map)
* @param string $column2 the name of the second column (values of the map)
* @param boolean $cumulative
* useful in situations with results set like
* col1 col2
* X A
* X B
* Y B
*
* cumulative=0 -> return items= array('X' => 'B', 'Y' => 'B')
*
* cumulative=1 -> return items= array('X' => array('A','B'), 'Y' => array('B') )
*
* @param integer $limit (optional) number of rows
*
* @return assoc array whose keys are the values of column1 and the values are:
*
* cumulative=0 => the values of column2
* cumulative=1 => array with the values of column2
*
**/
function fetchColumnsIntoMap($sql,$column1,$column2,$cumulative=0,$limit = -1)
{
$result = $this->exec_query($sql,$limit);
$items = null;
if ($result)
{
while ($myrow = $this->fetch_array($result))
{
if($cumulative)
{
$items[$myrow[$column1]][] = $myrow[$column2];
}
else
{
$items[$myrow[$column1]] = $myrow[$column2];
}
}
}
unset($result);
return $items;
}
/**
* database server information
* wrapper for adodb method ServerInfo
*
* @return assoc array members 'version' and 'description'
**/
function get_version_info()
{
$version = $this->db->ServerInfo();
return $version;
}
/**
**/
function get_recordset($sql,$fetch_mode = null,$limit = -1, $start = -1)
{
$output = null;
$result = $this->exec_query($sql,$limit,$start);
if ($result)
{
while($row = $this->fetch_array($result))
{
$output[] = $row;
}
}
unset($result);
return $output;
}
/**
* Fetches all rows into a map whose keys are the values of columns
*
* @param string $sql the query to be executed
* @param string $column the name of the column
* @param integer $limit (optional) number of rows
*
* @return array an assoc array whose keys are the values from the columns
* of the rows
**/
function fetchArrayRowsIntoMap($sql,$column,$limit = -1)
{
$items = null;
$result = $this->exec_query($sql,$limit);
if ($result)
{
while($row = $this->fetch_array($result))
{
$items[$row[$column]][] = $row;
}
}
unset($result);
return $items;
}
/**
* Fetches all rows into a map whose keys are the values of columns
*
* @param string $sql the query to be executed
* @param string $column_main_key the name of the column
* @param string $column_sec_key the name of the column
* @param boolean $cumulative
* @param integer $limit (optional) number of rows
*
* @return array $items[$row[$column_main_key]][$row[$column_sec_key]]
*
**/
function fetchMapRowsIntoMap($sql,$main_key,$sec_key,
$cumulative = 0,$limit = -1, $col2implode ='')
{
$items = null;
$result = $this->exec_query($sql,$limit);
if ($result)
{
while($row = $this->fetch_array($result))
{
if($cumulative)
{
$items[$row[$main_key]][$row[$sec_key]][] = $row;
}
else if($col2implode !='')
{
if(isset($items[$row[$main_key]][$row[$sec_key]]))
{
$items[$row[$main_key]][$row[$sec_key]][$col2implode] .=
',' . $row[$col2implode];
}
else
{
$items[$row[$main_key]][$row[$sec_key]] = $row;
}
}
else
{
$items[$row[$main_key]][$row[$sec_key]] = $row;
}
}
}
unset($result);
return $items;
}
/**
* TICKET 4898: MSSQL - Add support for SQLSRV drivers needed for PHP on WINDOWS version 5.3 and higher
**/
function build_sql_create_db($db_name)
{
$sql='';
switch($this->db->databaseType)
{
case 'postgres7':
$sql = 'CREATE DATABASE "' . $this->prepare_string($db_name) . '" ' . "WITH ENCODING='UNICODE' ";
break;
case 'mssql':
case 'mssqlnative':
$sql = 'CREATE DATABASE [' . $this->prepare_string($db_name) . '] ';
break;
case 'mysql':
default:
$sql = "CREATE DATABASE `" . $this->prepare_string($db_name) . "` CHARACTER SET utf8 ";
break;
}
return ($sql);
}
function db_null_timestamp()
{
$db_type = $this->db->databaseType;
$nullValue = NULL;
switch($db_type)
{
case 'mysql':
// is not an error i put single quote on value
$nullValue = " '0000-00-00 00:00:00' ";
break;
}
return $nullValue;
}
/**
* Fetches all rows into a map of 3 levels
*
* @param string $sql the query to be executed
* @param array $keyCols, columns to used as access key
* @param boolean $cumulative
* @param integer $limit (optional) number of rows
*
* @return array $items[$row[$column_main_key]][$row[$column_sec_key]]
*
**/
function fetchRowsIntoMap3l($sql,$keyCols,$cumulative = 0,$limit = -1)
{
$items = null;
$result = $this->exec_query($sql,$limit);
// new dBug($result);
if ($result)
{
while($row = $this->fetch_array($result))
{
if($cumulative)
{
$items[$row[$keyCols[0]]][$row[$keyCols[1]]][$row[$keyCols[2]]][] = $row;
}
else
{
$items[$row[$keyCols[0]]][$row[$keyCols[1]]][$row[$keyCols[2]]] = $row;
}
}
}
unset($result);
return $items;
}
/**
* Fetches all rows into a map of 3 levels
*
* @param string $sql the query to be executed
* @param array $keyCols, columns to used as access key
* @param boolean $cumulative
* @param integer $limit (optional) number of rows
*
* @return array $items[$row[$column_main_key]][$row[$column_sec_key]]
*
**/
function fetchRowsIntoMap4l($sql,$keyCols,$cumulative = 0,$limit = -1)
{
$items = null;
$result = $this->exec_query($sql,$limit);
// displayMemUsage(__FUNCTION__);
// new dBug($result);
if ($result)
{
while($row = $this->fetch_array($result))
{
if($cumulative)
{
$items[$row[$keyCols[0]]][$row[$keyCols[1]]][$row[$keyCols[2]]][$row[$keyCols[3]]][] = $row;
}
else
{
$items[$row[$keyCols[0]]][$row[$keyCols[1]]][$row[$keyCols[2]]][$row[$keyCols[3]]] = $row;
}
}
}
// displayMemUsage(__FUNCTION__);
unset($result);
// displayMemUsage(__FUNCTION__);
return $items;
}
/**
* Fetches all rows into a map whose keys are the values of columns
*
* @param string $sql the query to be executed
* @param string $column the name of the column
*
* @return array an assoc array
**/
function fetchRowsIntoMapAddRC($sql,$column,$limit = -1)
{
$items = null;
$result = $this->exec_query($sql,$limit);
if ($result)
{
$errorMsg=__CLASS__ . '/' . __FUNCTION__ . ' - ';
if( ($empty_column = (trim($column)=='') ) )
{
$errorMsg .= 'empty column - SQL:' . $sql;
trigger_error($errorMsg,E_USER_NOTICE);
return null;
}
while($row = $this->fetch_array($result))
{
if( !isset($row[$column]) )
{
$errorMsg .= 'missing column:' . $column;
$errorMsg .= ' - SQL:' . $sql;
trigger_error($errorMsg,E_USER_NOTICE);
return null;
}
if(!isset($items[$row[$column]]) )
{
$row['recordcount'] = 0;
}
else
{
$row['recordcount'] = $items[$row[$column]]['recordcount'];
}
$row['recordcount']++;
$items[$row[$column]] = $row;
}
}
unset($result);
unset($row);
return $items;
}
/**
* @used-by testplan.class.php
*/
function fetchMapRowsIntoMapStackOnCol($sql,$column_main_key,$column_sec_key,$stackOnCol)
{
$items = null;
$result = $this->exec_query($sql);
if ($result)
{
while($row = $this->fetch_array($result))
{
if( !isset($items[$row[$column_main_key]][$row[$column_sec_key]]) )
{
$items[$row[$column_main_key]][$row[$column_sec_key]] = $row;
$items[$row[$column_main_key]][$row[$column_sec_key]][$stackOnCol] = array();
}
$items[$row[$column_main_key]][$row[$column_sec_key]][$stackOnCol][]=$row[$stackOnCol];
}
}
unset($result);
return $items;
}
} // end of database class | gpl-2.0 |
kevday/MooEge-X | src/Mooege/Core/GS/Actors/ActorFactory.cs | 7603 | /*
* Copyright (C) 2011 - 2012 mooege project - http://www.mooege.org
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using Mooege.Common.MPQ;
using Mooege.Core.GS.Common.Types.SNO;
using Mooege.Core.GS.Map;
using Mooege.Core.GS.Common.Types.TagMap;
using Mooege.Core.GS.Actors.Implementations;
using Mooege.Common.Logging;
namespace Mooege.Core.GS.Actors
{
public static class ActorFactory
{
private static readonly Dictionary<int, Type> SNOHandlers = new Dictionary<int, Type>();
private static Logger Logger = new Logger("ActorFactory");
static ActorFactory()
{
LoadSNOHandlers();
}
public static Actor Create(World world, int snoId, TagMap tags)
{
if (!MPQStorage.Data.Assets[SNOGroup.Actor].ContainsKey(snoId))
return null;
var actorAsset = MPQStorage.Data.Assets[SNOGroup.Actor][snoId];
var actorData = actorAsset.Data as Mooege.Common.MPQ.FileFormats.Actor;
if (actorData == null) return null;
if (actorData.Type == ActorType.Invalid)
return null;
// see if we have an implementation for actor.
if (SNOHandlers.ContainsKey(snoId))
return (Actor)Activator.CreateInstance(SNOHandlers[snoId], new object[] { world, snoId, tags });
switch (actorData.Type)
{
case ActorType.Monster:
if (tags.ContainsKey(MarkerKeys.ConversationList))
return new InteractiveNPC(world, snoId, tags);
else
if (!MPQStorage.Data.Assets[SNOGroup.Monster].ContainsKey(actorData.MonsterSNO))
return null;
var monsterAsset = MPQStorage.Data.Assets[SNOGroup.Monster][actorData.MonsterSNO];
var monsterData = monsterAsset.Data as Mooege.Common.MPQ.FileFormats.Monster;
if (monsterData.Type == Mooege.Common.MPQ.FileFormats.Monster.MonsterType.Ally ||
monsterData.Type == Mooege.Common.MPQ.FileFormats.Monster.MonsterType.Helper)
return new NPC(world, snoId, tags);
else
return new Monster(world, snoId, tags);
case ActorType.Gizmo:
switch (actorData.TagMap[ActorKeys.GizmoGroup])
{
case GizmoGroup.LootContainer:
return new LootContainer(world, snoId, tags);
case GizmoGroup.Door:
return new Door(world, snoId, tags);
case GizmoGroup.DestructibleLootContainer:
case GizmoGroup.Barricade:
return new DesctructibleLootContainer(world, snoId, tags);
case GizmoGroup.Portal:
//Prevent Development Hell portal from showing
if (tags[MarkerKeys.DestinationWorld].Id != 222591)
return new Portal(world, snoId, tags);
else
return null;
case GizmoGroup.BossPortal:
Logger.Warn("Skipping loading of boss portals");
return null;
case GizmoGroup.CheckPoint:
return new Checkpoint(world, snoId, tags);
case GizmoGroup.Waypoint:
return new Waypoint(world, snoId, tags);
case GizmoGroup.Savepoint:
return new Savepoint(world, snoId, tags);
case GizmoGroup.ProximityTriggered:
return new ProximityTriggeredGizmo(world, snoId, tags);
case GizmoGroup.Shrine:
return new Shrine(world, snoId, tags);
case GizmoGroup.Healthwell:
return new Healthwell(world, snoId, tags);
case GizmoGroup.StartLocations:
return new StartingPoint(world, snoId, tags);
case GizmoGroup.ActChangeTempObject:
case GizmoGroup.Banner:
case GizmoGroup.CathedralIdol:
case GizmoGroup.Destructible:
case GizmoGroup.DungeonStonePortal:
case GizmoGroup.Headstone:
case GizmoGroup.HearthPortal:
//case GizmoGroup.NephalemAltar:
case GizmoGroup.Passive:
case GizmoGroup.PlayerSharedStash:
case GizmoGroup.QuestLoot:
case GizmoGroup.Readable:
case GizmoGroup.ServerProp:
case GizmoGroup.Sign:
case GizmoGroup.Spawner:
case GizmoGroup.TownPortal:
case GizmoGroup.Trigger:
case GizmoGroup.WeirdGroup57:
//Logger.Info("GizmoGroup {0} has no proper implementation, using default gizmo instead", actorData.TagMap[ActorKeys.GizmoGroup]);
return CreateGizmo(world, snoId, tags);
default:
Logger.Warn("Unknown gizmo group {0}", actorData.TagMap[ActorKeys.GizmoGroup]);
return CreateGizmo(world, snoId, tags);
}
case ActorType.ServerProp:
return new ServerProp(world, snoId, tags);
}
return null;
}
private static Actor CreateGizmo(World world, int snoId, TagMap tags)
{
if (tags.ContainsKey(MarkerKeys.DestinationWorld))
{
if (tags[MarkerKeys.DestinationWorld].Id != 222591)
return new Portal(world, snoId, tags);
}
return new Gizmo(world, snoId, tags);
}
public static void LoadSNOHandlers()
{
foreach (var type in Assembly.GetExecutingAssembly().GetTypes())
{
if (!type.IsSubclassOf(typeof(Actor))) continue;
var attributes = (HandledSNOAttribute[])type.GetCustomAttributes(typeof(HandledSNOAttribute), true);
if (attributes.Length == 0) continue;
foreach (var sno in attributes.First().SNOIds)
{
if (!SNOHandlers.ContainsKey(sno))
SNOHandlers.Add(sno, type);
}
}
}
}
}
| gpl-2.0 |
suesai/notepad-plus-plus | PowerEditor/src/ScitillaComponent/ScintillaEditView.cpp | 101322 | // This file is part of Notepad++ project
// Copyright (C)2003 Don HO <don.h@free.fr>
//
// This program is free software; you can redistribute it and/or
// modify it under the terms of the GNU General Public License
// as published by the Free Software Foundation; either
// version 2 of the License, or (at your option) any later version.
//
// Note that the GPL places important restrictions on "derived works", yet
// it does not provide a detailed definition of that term. To avoid
// misunderstandings, we consider an application to constitute a
// "derivative work" for the purpose of this license if it does any of the
// following:
// 1. Integrates source code from Notepad++.
// 2. Integrates/includes/aggregates Notepad++ into a proprietary executable
// installer, such as those produced by InstallShield.
// 3. Links to a library or executes a program that does any of the above.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program; if not, write to the Free Software
// Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
#include <shlwapi.h>
#include "ScintillaEditView.h"
#include "Parameters.h"
#include "Sorters.h"
#include "TCHAR.h"
#include <memory>
using namespace std;
// initialize the static variable
// get full ScinLexer.dll path to avoid hijack
TCHAR * getSciLexerFullPathName(TCHAR * moduleFileName, size_t len){
::GetModuleFileName(NULL, moduleFileName, len);
::PathRemoveFileSpec(moduleFileName);
::PathAppend(moduleFileName, TEXT("SciLexer.dll"));
return moduleFileName;
};
TCHAR moduleFileName[1024];
HINSTANCE ScintillaEditView::_hLib = ::LoadLibrary(getSciLexerFullPathName(moduleFileName, 1024));
int ScintillaEditView::_refCount = 0;
UserDefineDialog ScintillaEditView::_userDefineDlg;
const int ScintillaEditView::_SC_MARGE_LINENUMBER = 0;
const int ScintillaEditView::_SC_MARGE_SYBOLE = 1;
const int ScintillaEditView::_SC_MARGE_FOLDER = 2;
//const int ScintillaEditView::_SC_MARGE_MODIFMARKER = 3;
WNDPROC ScintillaEditView::_scintillaDefaultProc = NULL;
/*
SC_MARKNUM_* | Arrow Plus/minus Circle tree Box tree
-------------------------------------------------------------------------------------------------------------
FOLDEROPEN | SC_MARK_ARROWDOWN SC_MARK_MINUS SC_MARK_CIRCLEMINUS SC_MARK_BOXMINUS
FOLDER | SC_MARK_ARROW SC_MARK_PLUS SC_MARK_CIRCLEPLUS SC_MARK_BOXPLUS
FOLDERSUB | SC_MARK_EMPTY SC_MARK_EMPTY SC_MARK_VLINE SC_MARK_VLINE
FOLDERTAIL | SC_MARK_EMPTY SC_MARK_EMPTY SC_MARK_LCORNERCURVE SC_MARK_LCORNER
FOLDEREND | SC_MARK_EMPTY SC_MARK_EMPTY SC_MARK_CIRCLEPLUSCONNECTED SC_MARK_BOXPLUSCONNECTED
FOLDEROPENMID | SC_MARK_EMPTY SC_MARK_EMPTY SC_MARK_CIRCLEMINUSCONNECTED SC_MARK_BOXMINUSCONNECTED
FOLDERMIDTAIL | SC_MARK_EMPTY SC_MARK_EMPTY SC_MARK_TCORNERCURVE SC_MARK_TCORNER
*/
const int ScintillaEditView::_markersArray[][NB_FOLDER_STATE] = {
{SC_MARKNUM_FOLDEROPEN, SC_MARKNUM_FOLDER, SC_MARKNUM_FOLDERSUB, SC_MARKNUM_FOLDERTAIL, SC_MARKNUM_FOLDEREND, SC_MARKNUM_FOLDEROPENMID, SC_MARKNUM_FOLDERMIDTAIL},
{SC_MARK_MINUS, SC_MARK_PLUS, SC_MARK_EMPTY, SC_MARK_EMPTY, SC_MARK_EMPTY, SC_MARK_EMPTY, SC_MARK_EMPTY},
{SC_MARK_ARROWDOWN, SC_MARK_ARROW, SC_MARK_EMPTY, SC_MARK_EMPTY, SC_MARK_EMPTY, SC_MARK_EMPTY, SC_MARK_EMPTY},
{SC_MARK_CIRCLEMINUS, SC_MARK_CIRCLEPLUS,SC_MARK_VLINE, SC_MARK_LCORNERCURVE, SC_MARK_CIRCLEPLUSCONNECTED, SC_MARK_CIRCLEMINUSCONNECTED, SC_MARK_TCORNERCURVE},
{SC_MARK_BOXMINUS, SC_MARK_BOXPLUS, SC_MARK_VLINE, SC_MARK_LCORNER, SC_MARK_BOXPLUSCONNECTED, SC_MARK_BOXMINUSCONNECTED, SC_MARK_TCORNER}
};
// Array with all the names of all languages
// The order of lang type (enum LangType) must be respected
LanguageName ScintillaEditView::langNames[L_EXTERNAL+1] = {
{TEXT("normal"), TEXT("Normal text"), TEXT("Normal text file"), L_TEXT, SCLEX_NULL},
{TEXT("php"), TEXT("PHP"), TEXT("PHP Hypertext Preprocessor file"), L_PHP, SCLEX_HTML},
{TEXT("c"), TEXT("C"), TEXT("C source file"), L_C, SCLEX_CPP},
{TEXT("cpp"), TEXT("C++"), TEXT("C++ source file"), L_CPP, SCLEX_CPP},
{TEXT("cs"), TEXT("C#"), TEXT("C# source file"), L_CS, SCLEX_CPP},
{TEXT("objc"), TEXT("Objective-C"), TEXT("Objective-C source file"), L_OBJC, SCLEX_CPP},
{TEXT("java"), TEXT("Java"), TEXT("Java source file"), L_JAVA, SCLEX_CPP},
{TEXT("rc"), TEXT("RC"), TEXT("Windows Resource file"), L_RC, SCLEX_CPP},
{TEXT("html"), TEXT("HTML"), TEXT("Hyper Text Markup Language file"), L_HTML, SCLEX_HTML},
{TEXT("xml"), TEXT("XML"), TEXT("eXtensible Markup Language file"), L_XML, SCLEX_XML},
{TEXT("makefile"), TEXT("Makefile"), TEXT("Makefile"), L_MAKEFILE, SCLEX_MAKEFILE},
{TEXT("pascal"), TEXT("Pascal"), TEXT("Pascal source file"), L_PASCAL, SCLEX_PASCAL},
{TEXT("batch"), TEXT("Batch"), TEXT("Batch file"), L_BATCH, SCLEX_BATCH},
{TEXT("ini"), TEXT("ini"), TEXT("MS ini file"), L_INI, SCLEX_PROPERTIES},
{TEXT("nfo"), TEXT("NFO"), TEXT("MSDOS Style/ASCII Art"), L_ASCII, SCLEX_NULL},
{TEXT("udf"), TEXT("udf"), TEXT("User Define File"), L_USER, SCLEX_USER},
{TEXT("asp"), TEXT("ASP"), TEXT("Active Server Pages script file"), L_ASP, SCLEX_HTML},
{TEXT("sql"), TEXT("SQL"), TEXT("Structured Query Language file"), L_SQL, SCLEX_SQL},
{TEXT("vb"), TEXT("VB"), TEXT("Visual Basic file"), L_VB, SCLEX_VB},
{TEXT("javascript"), TEXT("JavaScript"), TEXT("JavaScript file"), L_JS, SCLEX_CPP},
{TEXT("css"), TEXT("CSS"), TEXT("Cascade Style Sheets File"), L_CSS, SCLEX_CSS},
{TEXT("perl"), TEXT("Perl"), TEXT("Perl source file"), L_PERL, SCLEX_PERL},
{TEXT("python"), TEXT("Python"), TEXT("Python file"), L_PYTHON, SCLEX_PYTHON},
{TEXT("lua"), TEXT("Lua"), TEXT("Lua source File"), L_LUA, SCLEX_LUA},
{TEXT("tex"), TEXT("TeX"), TEXT("TeX file"), L_TEX, SCLEX_TEX},
{TEXT("fortran"), TEXT("Fortran"), TEXT("Fortran source file"), L_FORTRAN, SCLEX_FORTRAN},
{TEXT("bash"), TEXT("Shell"), TEXT("Unix script file"), L_BASH, SCLEX_BASH},
{TEXT("actionscript"), TEXT("Flash Action"), TEXT("Flash Action script file"), L_FLASH, SCLEX_CPP},//WARNING, was "flash"
{TEXT("nsis"), TEXT("NSIS"), TEXT("Nullsoft Scriptable Install System script file"), L_NSIS, SCLEX_NSIS},
{TEXT("tcl"), TEXT("TCL"), TEXT("Tool Command Language file"), L_TCL, SCLEX_TCL},
{TEXT("lisp"), TEXT("Lisp"), TEXT("List Processing language file"), L_LISP, SCLEX_LISP},
{TEXT("scheme"), TEXT("Scheme"), TEXT("Scheme file"), L_SCHEME, SCLEX_LISP},
{TEXT("asm"), TEXT("Assembly"), TEXT("Assembly language source file"), L_ASM, SCLEX_ASM},
{TEXT("diff"), TEXT("Diff"), TEXT("Diff file"), L_DIFF, SCLEX_DIFF},
{TEXT("props"), TEXT("Properties file"), TEXT("Properties file"), L_PROPS, SCLEX_PROPERTIES},
{TEXT("postscript"), TEXT("Postscript"), TEXT("Postscript file"), L_PS, SCLEX_PS},
{TEXT("ruby"), TEXT("Ruby"), TEXT("Ruby file"), L_RUBY, SCLEX_RUBY},
{TEXT("smalltalk"), TEXT("Smalltalk"), TEXT("Smalltalk file"), L_SMALLTALK, SCLEX_SMALLTALK},
{TEXT("vhdl"), TEXT("VHDL"), TEXT("VHSIC Hardware Description Language file"), L_VHDL, SCLEX_VHDL},
{TEXT("kix"), TEXT("KiXtart"), TEXT("KiXtart file"), L_KIX, SCLEX_KIX},
{TEXT("autoit"), TEXT("AutoIt"), TEXT("AutoIt"), L_AU3, SCLEX_AU3},
{TEXT("caml"), TEXT("CAML"), TEXT("Categorical Abstract Machine Language"), L_CAML, SCLEX_CAML},
{TEXT("ada"), TEXT("Ada"), TEXT("Ada file"), L_ADA, SCLEX_ADA},
{TEXT("verilog"), TEXT("Verilog"), TEXT("Verilog file"), L_VERILOG, SCLEX_VERILOG},
{TEXT("matlab"), TEXT("MATLAB"), TEXT("MATrix LABoratory"), L_MATLAB, SCLEX_MATLAB},
{TEXT("haskell"), TEXT("Haskell"), TEXT("Haskell"), L_HASKELL, SCLEX_HASKELL},
{TEXT("inno"), TEXT("Inno"), TEXT("Inno Setup script"), L_INNO, SCLEX_INNOSETUP},
{TEXT("searchResult"), TEXT("Internal Search"), TEXT("Internal Search"), L_SEARCHRESULT, SCLEX_SEARCHRESULT},
{TEXT("cmake"), TEXT("CMAKEFILE"), TEXT("CMAKEFILE"), L_CMAKE, SCLEX_CMAKE},
{TEXT("yaml"), TEXT("YAML"), TEXT("YAML Ain't Markup Language"), L_YAML, SCLEX_YAML},
{TEXT("cobol"), TEXT("COBOL"), TEXT("COmmon Business Oriented Language"), L_COBOL, SCLEX_COBOL},
{TEXT("gui4cli"), TEXT("Gui4Cli"), TEXT("Gui4Cli file"), L_GUI4CLI, SCLEX_GUI4CLI},
{TEXT("d"), TEXT("D"), TEXT("D programming language"), L_D, SCLEX_D},
{TEXT("powershell"), TEXT("PowerShell"), TEXT("Windows PowerShell"), L_POWERSHELL, SCLEX_POWERSHELL},
{TEXT("r"), TEXT("R"), TEXT("R programming language"), L_R, SCLEX_R},
{TEXT("jsp"), TEXT("JSP"), TEXT("JavaServer Pages script file"), L_JSP, SCLEX_HTML},
{TEXT("coffeescript"), TEXT("CoffeeScript"), TEXT("CoffeeScript file"), L_COFFEESCRIPT, SCLEX_COFFEESCRIPT},
{ TEXT("json"), TEXT("json"), TEXT("JSON file"), L_JSON, SCLEX_CPP },
{TEXT("ext"), TEXT("External"), TEXT("External"), L_EXTERNAL, SCLEX_NULL}
};
//const int MASK_RED = 0xFF0000;
//const int MASK_GREEN = 0x00FF00;
//const int MASK_BLUE = 0x0000FF;
int getNbDigits(int aNum, int base)
{
int nbChiffre = 1;
int diviseur = base;
for (;;)
{
int result = aNum / diviseur;
if (!result)
break;
else
{
diviseur *= base;
++nbChiffre;
}
}
if ((base == 16) && (nbChiffre % 2 != 0))
nbChiffre += 1;
return nbChiffre;
}
void ScintillaEditView::init(HINSTANCE hInst, HWND hPere)
{
if (!_hLib)
{
throw std::exception("ScintillaEditView::init : SCINTILLA ERROR - Can not load the dynamic library");
}
Window::init(hInst, hPere);
_hSelf = ::CreateWindowEx(
WS_EX_CLIENTEDGE,\
TEXT("Scintilla"),\
TEXT("Notepad++"),\
WS_CHILD | WS_VSCROLL | WS_HSCROLL | WS_CLIPCHILDREN | WS_EX_RTLREADING,\
0, 0, 100, 100,\
_hParent,\
NULL,\
_hInst,\
NULL);
if (!_hSelf)
{
throw std::exception("ScintillaEditView::init : CreateWindowEx() function return null");
}
_pScintillaFunc = (SCINTILLA_FUNC)::SendMessage(_hSelf, SCI_GETDIRECTFUNCTION, 0, 0);
_pScintillaPtr = (SCINTILLA_PTR)::SendMessage(_hSelf, SCI_GETDIRECTPOINTER, 0, 0);
_userDefineDlg.init(_hInst, _hParent, this);
if (!_pScintillaFunc)
{
throw std::exception("ScintillaEditView::init : SCI_GETDIRECTFUNCTION message failed");
}
if (!_pScintillaPtr)
{
throw std::exception("ScintillaEditView::init : SCI_GETDIRECTPOINTER message failed");
}
execute(SCI_SETMARGINMASKN, _SC_MARGE_FOLDER, SC_MASK_FOLDERS);
showMargin(_SC_MARGE_FOLDER, true);
execute(SCI_SETMARGINMASKN, _SC_MARGE_SYBOLE, (1<<MARK_BOOKMARK) | (1<<MARK_HIDELINESBEGIN) | (1<<MARK_HIDELINESEND));
execute(SCI_MARKERSETALPHA, MARK_BOOKMARK, 70);
execute(SCI_MARKERDEFINEPIXMAP, MARK_BOOKMARK, (LPARAM)bookmark_xpm);
execute(SCI_MARKERDEFINEPIXMAP, MARK_HIDELINESBEGIN, (LPARAM)acTop_xpm);
execute(SCI_MARKERDEFINEPIXMAP, MARK_HIDELINESEND, (LPARAM)acBottom_xpm);
execute(SCI_SETMARGINSENSITIVEN, _SC_MARGE_FOLDER, true);
execute(SCI_SETMARGINSENSITIVEN, _SC_MARGE_SYBOLE, true);
execute(SCI_SETFOLDFLAGS, 16);
execute(SCI_SETSCROLLWIDTHTRACKING, true);
execute(SCI_SETSCROLLWIDTH, 1); //default empty document: override default width of 2000
// smart hilighting
execute(SCI_INDICSETSTYLE, SCE_UNIVERSAL_FOUND_STYLE_SMART, INDIC_ROUNDBOX);
execute(SCI_INDICSETSTYLE, SCE_UNIVERSAL_FOUND_STYLE, INDIC_ROUNDBOX);
execute(SCI_INDICSETSTYLE, SCE_UNIVERSAL_FOUND_STYLE_INC, INDIC_ROUNDBOX);
execute(SCI_INDICSETSTYLE, SCE_UNIVERSAL_TAGMATCH, INDIC_ROUNDBOX);
execute(SCI_INDICSETSTYLE, SCE_UNIVERSAL_TAGATTR, INDIC_ROUNDBOX);
execute(SCI_INDICSETSTYLE, SCE_UNIVERSAL_FOUND_STYLE_EXT1, INDIC_ROUNDBOX);
execute(SCI_INDICSETSTYLE, SCE_UNIVERSAL_FOUND_STYLE_EXT2, INDIC_ROUNDBOX);
execute(SCI_INDICSETSTYLE, SCE_UNIVERSAL_FOUND_STYLE_EXT3, INDIC_ROUNDBOX);
execute(SCI_INDICSETSTYLE, SCE_UNIVERSAL_FOUND_STYLE_EXT4, INDIC_ROUNDBOX);
execute(SCI_INDICSETSTYLE, SCE_UNIVERSAL_FOUND_STYLE_EXT5, INDIC_ROUNDBOX);
execute(SCI_INDICSETALPHA, SCE_UNIVERSAL_FOUND_STYLE_SMART, 100);
execute(SCI_INDICSETALPHA, SCE_UNIVERSAL_FOUND_STYLE, 100);
execute(SCI_INDICSETALPHA, SCE_UNIVERSAL_FOUND_STYLE_INC, 100);
execute(SCI_INDICSETALPHA, SCE_UNIVERSAL_TAGMATCH, 100);
execute(SCI_INDICSETALPHA, SCE_UNIVERSAL_TAGATTR, 100);
execute(SCI_INDICSETALPHA, SCE_UNIVERSAL_FOUND_STYLE_EXT1, 100);
execute(SCI_INDICSETALPHA, SCE_UNIVERSAL_FOUND_STYLE_EXT2, 100);
execute(SCI_INDICSETALPHA, SCE_UNIVERSAL_FOUND_STYLE_EXT3, 100);
execute(SCI_INDICSETALPHA, SCE_UNIVERSAL_FOUND_STYLE_EXT4, 100);
execute(SCI_INDICSETALPHA, SCE_UNIVERSAL_FOUND_STYLE_EXT5, 100);
execute(SCI_INDICSETUNDER, SCE_UNIVERSAL_FOUND_STYLE_SMART, true);
execute(SCI_INDICSETUNDER, SCE_UNIVERSAL_FOUND_STYLE, true);
execute(SCI_INDICSETUNDER, SCE_UNIVERSAL_FOUND_STYLE_INC, true);
execute(SCI_INDICSETUNDER, SCE_UNIVERSAL_TAGMATCH, true);
execute(SCI_INDICSETUNDER, SCE_UNIVERSAL_TAGATTR, true);
execute(SCI_INDICSETUNDER, SCE_UNIVERSAL_FOUND_STYLE_EXT1, true);
execute(SCI_INDICSETUNDER, SCE_UNIVERSAL_FOUND_STYLE_EXT2, true);
execute(SCI_INDICSETUNDER, SCE_UNIVERSAL_FOUND_STYLE_EXT3, true);
execute(SCI_INDICSETUNDER, SCE_UNIVERSAL_FOUND_STYLE_EXT4, true);
execute(SCI_INDICSETUNDER, SCE_UNIVERSAL_FOUND_STYLE_EXT5, true);
_pParameter = NppParameters::getInstance();
_codepage = ::GetACP();
::SetWindowLongPtr(_hSelf, GWLP_USERDATA, reinterpret_cast<LONG_PTR>(this));
_callWindowProc = CallWindowProc;
_scintillaDefaultProc = reinterpret_cast<WNDPROC>(::SetWindowLongPtr(_hSelf, GWLP_WNDPROC, reinterpret_cast<LONG_PTR>(scintillaStatic_Proc)));
//Get the startup document and make a buffer for it so it can be accessed like a file
attachDefaultDoc();
}
LRESULT CALLBACK ScintillaEditView::scintillaStatic_Proc(HWND hwnd, UINT Message, WPARAM wParam, LPARAM lParam)
{
ScintillaEditView *pScint = (ScintillaEditView *)(::GetWindowLongPtr(hwnd, GWLP_USERDATA));
if (Message == WM_MOUSEWHEEL || Message == WM_MOUSEHWHEEL)
{
POINT pt;
POINTS pts = MAKEPOINTS(lParam);
POINTSTOPOINT(pt, pts);
HWND hwndOnMouse = WindowFromPoint(pt);
//Hack for Synaptics TouchPad Driver
char synapticsHack[26];
GetClassNameA(hwndOnMouse, (LPSTR)&synapticsHack, 26);
bool isSynpnatic = std::string(synapticsHack) == "SynTrackCursorWindowClass";
bool makeTouchPadCompetible = ((NppParameters::getInstance())->getSVP())._disableAdvancedScrolling;
if (isSynpnatic || makeTouchPadCompetible)
return (pScint->scintillaNew_Proc(hwnd, Message, wParam, lParam));
ScintillaEditView *pScintillaOnMouse = (ScintillaEditView *)(::GetWindowLongPtr(hwndOnMouse, GWLP_USERDATA));
if (pScintillaOnMouse != pScint)
return ::SendMessage(hwndOnMouse, Message, wParam, lParam);
}
if (pScint)
return (pScint->scintillaNew_Proc(hwnd, Message, wParam, lParam));
else
return ::DefWindowProc(hwnd, Message, wParam, lParam);
}
LRESULT ScintillaEditView::scintillaNew_Proc(HWND hwnd, UINT Message, WPARAM wParam, LPARAM lParam)
{
switch (Message)
{
case WM_MOUSEHWHEEL :
{
::CallWindowProc(_scintillaDefaultProc, hwnd, WM_HSCROLL, ((short)HIWORD(wParam) > 0)?SB_LINERIGHT:SB_LINELEFT, NULL);
break;
}
case WM_MOUSEWHEEL :
{
if (LOWORD(wParam) & MK_RBUTTON)
{
::SendMessage(_hParent, Message, wParam, lParam);
return TRUE;
}
//Have to perform the scroll first, because the first/last line do not get updated untill after the scroll has been parsed
LRESULT scrollResult = ::CallWindowProc(_scintillaDefaultProc, hwnd, Message, wParam, lParam);
return scrollResult;
break;
}
case WM_IME_REQUEST:
{
if (wParam == IMR_RECONVERTSTRING)
{
int textLength;
int selectSize;
char smallTextBuffer[128];
char * selectedStr = smallTextBuffer;
RECONVERTSTRING * reconvert = (RECONVERTSTRING *)lParam;
// does nothing with a rectangular selection
if (execute(SCI_SELECTIONISRECTANGLE, 0, 0))
return 0;
// get the codepage of the text
unsigned int codepage = execute(SCI_GETCODEPAGE);
// get the current text selection
CharacterRange range = getSelection();
if (range.cpMax == range.cpMin)
{
// no selection: select the current word instead
expandWordSelection();
range = getSelection();
}
selectSize = range.cpMax - range.cpMin;
// does nothing if still no luck with the selection
if (selectSize == 0)
return 0;
if (selectSize + 1 > sizeof(smallTextBuffer))
selectedStr = new char[selectSize + 1];
getText(selectedStr, range.cpMin, range.cpMax);
if (reconvert == NULL)
{
// convert the selection to Unicode, and get the number
// of bytes required for the converted text
textLength = sizeof(WCHAR) * ::MultiByteToWideChar(codepage, 0, selectedStr, selectSize, NULL, 0);
}
else
{
// convert the selection to Unicode, and store it at the end of the structure.
// Beware: For a Unicode IME, dwStrLen , dwCompStrLen, and dwTargetStrLen
// are TCHAR values, that is, character counts. The members dwStrOffset,
// dwCompStrOffset, and dwTargetStrOffset specify byte counts.
textLength = ::MultiByteToWideChar( codepage, 0,
selectedStr, selectSize,
(LPWSTR)((LPSTR)reconvert + sizeof(RECONVERTSTRING)),
reconvert->dwSize - sizeof(RECONVERTSTRING));
// fill the structure
reconvert->dwVersion = 0;
reconvert->dwStrLen = textLength;
reconvert->dwStrOffset = sizeof(RECONVERTSTRING);
reconvert->dwCompStrLen = textLength;
reconvert->dwCompStrOffset = 0;
reconvert->dwTargetStrLen = reconvert->dwCompStrLen;
reconvert->dwTargetStrOffset = reconvert->dwCompStrOffset;
textLength *= sizeof(WCHAR);
}
if (selectedStr != smallTextBuffer)
delete [] selectedStr;
// return the total length of the structure
return sizeof(RECONVERTSTRING) + textLength;
}
break;
}
case WM_KEYUP :
{
if (wParam == VK_PRIOR || wParam == VK_NEXT)
{
// find hotspots
/*
NMHDR nmhdr;
nmhdr.code = SCN_PAINTED;
nmhdr.hwndFrom = _hSelf;
nmhdr.idFrom = ::GetDlgCtrlID(nmhdr.hwndFrom);
::SendMessage(_hParent, WM_NOTIFY, (WPARAM)LINKTRIGGERED, (LPARAM)&nmhdr);
*/
SCNotification notification = {};
notification.nmhdr.code = SCN_PAINTED;
notification.nmhdr.hwndFrom = _hSelf;
notification.nmhdr.idFrom = ::GetDlgCtrlID(_hSelf);
::SendMessage(_hParent, WM_NOTIFY, (WPARAM)LINKTRIGGERED, (LPARAM)¬ification);
}
break;
}
case WM_VSCROLL :
{
break;
}
}
return _callWindowProc(_scintillaDefaultProc, hwnd, Message, wParam, lParam);
}
#define DEFAULT_FONT_NAME "Courier New"
void ScintillaEditView::setSpecialStyle(const Style & styleToSet)
{
int styleID = styleToSet._styleID;
if ( styleToSet._colorStyle & COLORSTYLE_FOREGROUND )
execute(SCI_STYLESETFORE, styleID, styleToSet._fgColor);
if ( styleToSet._colorStyle & COLORSTYLE_BACKGROUND )
execute(SCI_STYLESETBACK, styleID, styleToSet._bgColor);
if (styleToSet._fontName && lstrcmp(styleToSet._fontName, TEXT("")) != 0)
{
WcharMbcsConvertor *wmc = WcharMbcsConvertor::getInstance();
if (not _pParameter->isInFontList(styleToSet._fontName))
{
execute(SCI_STYLESETFONT, (WPARAM)styleID, (LPARAM)DEFAULT_FONT_NAME);
}
else
{
const char * fontNameA = wmc->wchar2char(styleToSet._fontName, CP_UTF8);
execute(SCI_STYLESETFONT, (WPARAM)styleID, (LPARAM)fontNameA);
}
}
int fontStyle = styleToSet._fontStyle;
if (fontStyle != STYLE_NOT_USED)
{
execute(SCI_STYLESETBOLD, (WPARAM)styleID, fontStyle & FONTSTYLE_BOLD);
execute(SCI_STYLESETITALIC, (WPARAM)styleID, fontStyle & FONTSTYLE_ITALIC);
execute(SCI_STYLESETUNDERLINE, (WPARAM)styleID, fontStyle & FONTSTYLE_UNDERLINE);
}
if (styleToSet._fontSize > 0)
execute(SCI_STYLESETSIZE, styleID, styleToSet._fontSize);
}
void ScintillaEditView::setHotspotStyle(Style& styleToSet)
{
StyleMap* styleMap;
if( _hotspotStyles.find(_currentBuffer) == _hotspotStyles.end() )
{
_hotspotStyles[_currentBuffer] = new StyleMap;
}
styleMap = _hotspotStyles[_currentBuffer];
(*styleMap)[styleToSet._styleID] = styleToSet;
setStyle(styleToSet);
}
void ScintillaEditView::setStyle(Style styleToSet)
{
GlobalOverride & go = _pParameter->getGlobalOverrideStyle();
if (go.isEnable())
{
StyleArray & stylers = _pParameter->getMiscStylerArray();
int i = stylers.getStylerIndexByName(TEXT("Global override"));
if (i != -1)
{
Style & style = stylers.getStyler(i);
if (go.enableFg)
{
if (style._colorStyle & COLORSTYLE_FOREGROUND)
{
styleToSet._colorStyle |= COLORSTYLE_FOREGROUND;
styleToSet._fgColor = style._fgColor;
}
else
{
if (styleToSet._styleID == STYLE_DEFAULT) //if global is set to transparent, use default style color
styleToSet._colorStyle |= COLORSTYLE_FOREGROUND;
else
styleToSet._colorStyle &= ~COLORSTYLE_FOREGROUND;
}
}
if (go.enableBg)
{
if (style._colorStyle & COLORSTYLE_BACKGROUND)
{
styleToSet._colorStyle |= COLORSTYLE_BACKGROUND;
styleToSet._bgColor = style._bgColor;
}
else
{
if (styleToSet._styleID == STYLE_DEFAULT) //if global is set to transparent, use default style color
styleToSet._colorStyle |= COLORSTYLE_BACKGROUND;
else
styleToSet._colorStyle &= ~COLORSTYLE_BACKGROUND;
}
}
if (go.enableFont && style._fontName && style._fontName[0])
styleToSet._fontName = style._fontName;
if (go.enableFontSize && (style._fontSize > 0))
styleToSet._fontSize = style._fontSize;
if (style._fontStyle != STYLE_NOT_USED)
{
if (go.enableBold)
{
if (style._fontStyle & FONTSTYLE_BOLD)
styleToSet._fontStyle |= FONTSTYLE_BOLD;
else
styleToSet._fontStyle &= ~FONTSTYLE_BOLD;
}
if (go.enableItalic)
{
if (style._fontStyle & FONTSTYLE_ITALIC)
styleToSet._fontStyle |= FONTSTYLE_ITALIC;
else
styleToSet._fontStyle &= ~FONTSTYLE_ITALIC;
}
if (go.enableUnderLine)
{
if (style._fontStyle & FONTSTYLE_UNDERLINE)
styleToSet._fontStyle |= FONTSTYLE_UNDERLINE;
else
styleToSet._fontStyle &= ~FONTSTYLE_UNDERLINE;
}
}
}
}
setSpecialStyle(styleToSet);
}
void ScintillaEditView::setXmlLexer(LangType type)
{
if (type == L_XML)
{
execute(SCI_SETLEXER, SCLEX_XML);
for (int i = 0 ; i < 4 ; ++i)
execute(SCI_SETKEYWORDS, i, reinterpret_cast<LPARAM>(TEXT("")));
makeStyle(type);
}
else if ((type == L_HTML) || (type == L_PHP) || (type == L_ASP) || (type == L_JSP))
{
execute(SCI_SETLEXER, SCLEX_HTML);
const TCHAR *htmlKeyWords_generic =_pParameter->getWordList(L_HTML, LANG_INDEX_INSTR);
WcharMbcsConvertor *wmc = WcharMbcsConvertor::getInstance();
const char *htmlKeyWords = wmc->wchar2char(htmlKeyWords_generic, CP_ACP);
execute(SCI_SETKEYWORDS, 0, reinterpret_cast<LPARAM>(htmlKeyWords?htmlKeyWords:""));
makeStyle(L_HTML);
setEmbeddedJSLexer();
setEmbeddedPhpLexer();
setEmbeddedAspLexer();
}
execute(SCI_SETPROPERTY, reinterpret_cast<WPARAM>("fold"), reinterpret_cast<LPARAM>("1"));
execute(SCI_SETPROPERTY, reinterpret_cast<WPARAM>("fold.compact"), reinterpret_cast<LPARAM>("0"));
execute(SCI_SETPROPERTY, reinterpret_cast<WPARAM>("fold.html"), reinterpret_cast<LPARAM>("1"));
// This allow to fold comment strem in php/javascript code
execute(SCI_SETPROPERTY, reinterpret_cast<WPARAM>("fold.hypertext.comment"), reinterpret_cast<LPARAM>("1"));
}
void ScintillaEditView::setEmbeddedJSLexer()
{
const TCHAR *pKwArray[10] = {NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL};
makeStyle(L_JS, pKwArray);
basic_string<char> keywordList("");
if (pKwArray[LANG_INDEX_INSTR])
{
basic_string<wchar_t> kwlW = pKwArray[LANG_INDEX_INSTR];
keywordList = wstring2string(kwlW, CP_ACP);
}
execute(SCI_SETKEYWORDS, 1, (LPARAM)getCompleteKeywordList(keywordList, L_JS, LANG_INDEX_INSTR));
execute(SCI_STYLESETEOLFILLED, SCE_HJ_DEFAULT, true);
execute(SCI_STYLESETEOLFILLED, SCE_HJ_COMMENT, true);
execute(SCI_STYLESETEOLFILLED, SCE_HJ_COMMENTDOC, true);
}
void ScintillaEditView::setJsonLexer()
{
execute(SCI_SETLEXER, SCLEX_CPP);
const TCHAR *pKwArray[10] = { NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL };
makeStyle(L_JSON, pKwArray);
execute(SCI_SETPROPERTY, reinterpret_cast<WPARAM>("fold"), reinterpret_cast<LPARAM>("1"));
execute(SCI_SETPROPERTY, reinterpret_cast<WPARAM>("fold.compact"), reinterpret_cast<LPARAM>("0"));
execute(SCI_SETPROPERTY, reinterpret_cast<WPARAM>("fold.comment"), reinterpret_cast<LPARAM>("1"));
execute(SCI_SETPROPERTY, reinterpret_cast<WPARAM>("fold.preprocessor"), reinterpret_cast<LPARAM>("1"));
}
void ScintillaEditView::setEmbeddedPhpLexer()
{
const TCHAR *pKwArray[10] = {NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL};
makeStyle(L_PHP, pKwArray);
basic_string<char> keywordList("");
if (pKwArray[LANG_INDEX_INSTR])
{
basic_string<wchar_t> kwlW = pKwArray[LANG_INDEX_INSTR];
keywordList = wstring2string(kwlW, CP_ACP);
}
execute(SCI_SETKEYWORDS, 4, (LPARAM)getCompleteKeywordList(keywordList, L_PHP, LANG_INDEX_INSTR));
execute(SCI_STYLESETEOLFILLED, SCE_HPHP_DEFAULT, true);
execute(SCI_STYLESETEOLFILLED, SCE_HPHP_COMMENT, true);
}
void ScintillaEditView::setEmbeddedAspLexer()
{
const TCHAR *pKwArray[10] = {NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL};
makeStyle(L_ASP, pKwArray);
basic_string<char> keywordList("");
if (pKwArray[LANG_INDEX_INSTR])
{
basic_string<wchar_t> kwlW = pKwArray[LANG_INDEX_INSTR];
keywordList = wstring2string(kwlW, CP_ACP);
}
execute(SCI_SETKEYWORDS, 2, (LPARAM)getCompleteKeywordList(keywordList, L_VB, LANG_INDEX_INSTR));
execute(SCI_STYLESETEOLFILLED, SCE_HBA_DEFAULT, true);
}
void ScintillaEditView::setUserLexer(const TCHAR *userLangName)
{
int setKeywordsCounter = 0;
execute(SCI_SETLEXER, SCLEX_USER);
UserLangContainer * userLangContainer = userLangName?_pParameter->getULCFromName(userLangName):_userDefineDlg._pCurrentUserLang;
if (!userLangContainer)
return;
UINT codepage = CP_ACP;
UniMode unicodeMode = _currentBuffer->getUnicodeMode();
int encoding = _currentBuffer->getEncoding();
if (encoding == -1)
{
if (unicodeMode == uniUTF8 || unicodeMode == uniCookie)
codepage = CP_UTF8;
}
else
{
codepage = CP_OEMCP; // system OEM code page might not match user selection for character set,
// but this is the best match WideCharToMultiByte offers
}
execute(SCI_SETPROPERTY, reinterpret_cast<WPARAM>("fold"), reinterpret_cast<LPARAM>("1"));
execute(SCI_SETPROPERTY, (WPARAM)"userDefine.isCaseIgnored", (LPARAM)(userLangContainer->_isCaseIgnored ? "1":"0"));
execute(SCI_SETPROPERTY, (WPARAM)"userDefine.allowFoldOfComments", (LPARAM)(userLangContainer->_allowFoldOfComments ? "1":"0"));
execute(SCI_SETPROPERTY, (WPARAM)"userDefine.foldCompact", (LPARAM)(userLangContainer->_foldCompact ? "1":"0"));
char name[] = "userDefine.prefixKeywords0";
for (int i=0 ; i<SCE_USER_TOTAL_KEYWORD_GROUPS ; ++i)
{
itoa(i+1, (name+25), 10);
execute(SCI_SETPROPERTY, (WPARAM)name, (LPARAM)(userLangContainer->_isPrefix[i]?"1":"0"));
}
for (int i = 0 ; i < SCE_USER_KWLIST_TOTAL ; ++i)
{
WcharMbcsConvertor *wmc = WcharMbcsConvertor::getInstance();
const char * keyWords_char = wmc->wchar2char(userLangContainer->_keywordLists[i], codepage);
if (globalMappper().setLexerMapper.find(i) != globalMappper().setLexerMapper.end())
{
execute(SCI_SETPROPERTY, (WPARAM)globalMappper().setLexerMapper[i].c_str(), reinterpret_cast<LPARAM>(keyWords_char));
}
else // OPERATORS2, FOLDERS_IN_CODE2, FOLDERS_IN_COMMENT, KEYWORDS1-8
{
char temp[max_char];
bool inDoubleQuote = false;
bool inSingleQuote = false;
bool nonWSFound = false;
int index = 0;
for (size_t j=0, len = strlen(keyWords_char); j<len; ++j)
{
if (!inSingleQuote && keyWords_char[j] == '"')
{
inDoubleQuote = !inDoubleQuote;
continue;
}
if (!inDoubleQuote && keyWords_char[j] == '\'')
{
inSingleQuote = !inSingleQuote;
continue;
}
if (keyWords_char[j] == '\\' && (keyWords_char[j+1] == '"' || keyWords_char[j+1] == '\'' || keyWords_char[j+1] == '\\'))
{
++j;
temp[index++] = keyWords_char[j];
continue;
}
if (inDoubleQuote || inSingleQuote)
{
if (keyWords_char[j] > ' ') // copy non-whitespace unconditionally
{
temp[index++] = keyWords_char[j];
if (nonWSFound == false)
nonWSFound = true;
}
else if (nonWSFound == true && keyWords_char[j-1] != '"' && keyWords_char[j+1] != '"' && keyWords_char[j+1] > ' ')
{
temp[index++] = inDoubleQuote ? '\v' : '\b';
}
else
continue;
}
else
{
temp[index++] = keyWords_char[j];
}
}
temp[index++] = 0;
execute(SCI_SETKEYWORDS, setKeywordsCounter++, reinterpret_cast<LPARAM>(temp));
}
}
char intBuffer[15];
char nestingBuffer[] = "userDefine.nesting.00";
itoa(userLangContainer->_forcePureLC, intBuffer, 10);
execute(SCI_SETPROPERTY, (WPARAM)"userDefine.forcePureLC", reinterpret_cast<LPARAM>(intBuffer));
itoa(userLangContainer->_decimalSeparator, intBuffer, 10);
execute(SCI_SETPROPERTY, (WPARAM)"userDefine.decimalSeparator", reinterpret_cast<LPARAM>(intBuffer));
// at the end (position SCE_USER_KWLIST_TOTAL) send id values
itoa((int)userLangContainer->getName(), intBuffer, 10); // use numeric value of TCHAR pointer
execute(SCI_SETPROPERTY, (WPARAM)"userDefine.udlName", reinterpret_cast<LPARAM>(intBuffer));
itoa((int)_currentBufferID, intBuffer, 10); // use numeric value of BufferID pointer
execute(SCI_SETPROPERTY, (WPARAM)"userDefine.currentBufferID", reinterpret_cast<LPARAM>(intBuffer));
for (int i = 0 ; i < SCE_USER_STYLE_TOTAL_STYLES ; ++i)
{
Style & style = userLangContainer->_styleArray.getStyler(i);
if (style._styleID == STYLE_NOT_USED)
continue;
if (i < 10) itoa(i, (nestingBuffer+20), 10);
else itoa(i, (nestingBuffer+19), 10);
execute(SCI_SETPROPERTY, (WPARAM)nestingBuffer, (LPARAM)(itoa(style._nesting, intBuffer, 10)));
setStyle(style);
}
}
void ScintillaEditView::setExternalLexer(LangType typeDoc)
{
int id = typeDoc - L_EXTERNAL;
TCHAR * name = _pParameter->getELCFromIndex(id)._name;
WcharMbcsConvertor *wmc = WcharMbcsConvertor::getInstance();
const char *pName = wmc->wchar2char(name, CP_ACP);
execute(SCI_SETLEXERLANGUAGE, 0, (LPARAM)pName);
LexerStyler *pStyler = (_pParameter->getLStylerArray()).getLexerStylerByName(name);
if (pStyler)
{
for (int i = 0 ; i < pStyler->getNbStyler() ; ++i)
{
Style & style = pStyler->getStyler(i);
setStyle(style);
if (style._keywordClass >= 0 && style._keywordClass <= KEYWORDSET_MAX)
{
basic_string<char> keywordList("");
if (style._keywords)
{
keywordList = wstring2string(*(style._keywords), CP_ACP);
}
execute(SCI_SETKEYWORDS, style._keywordClass, (LPARAM)getCompleteKeywordList(keywordList, typeDoc, style._keywordClass));
}
}
}
}
void ScintillaEditView::setCppLexer(LangType langType)
{
const char *cppInstrs;
const char *cppTypes;
const TCHAR *doxygenKeyWords = _pParameter->getWordList(L_CPP, LANG_INDEX_TYPE2);
const TCHAR *lexerName = ScintillaEditView::langNames[langType].lexerName;
execute(SCI_SETLEXER, SCLEX_CPP);
if ((langType != L_RC) && (langType != L_JS))
{
if (doxygenKeyWords)
{
WcharMbcsConvertor *wmc = WcharMbcsConvertor::getInstance();
const char * doxygenKeyWords_char = wmc->wchar2char(doxygenKeyWords, CP_ACP);
execute(SCI_SETKEYWORDS, 2, (LPARAM)doxygenKeyWords_char);
}
}
if (langType == L_JS)
{
LexerStyler *pStyler = (_pParameter->getLStylerArray()).getLexerStylerByName(lexerName);
if (pStyler)
{
for (int i = 0, nb = pStyler->getNbStyler() ; i < nb ; ++i)
{
Style style = pStyler->getStyler(i); //not by reference, but copy
int cppID = style._styleID;
switch (style._styleID)
{
case SCE_HJ_DEFAULT : cppID = SCE_C_DEFAULT; break;
case SCE_HJ_WORD : cppID = SCE_C_IDENTIFIER; break;
case SCE_HJ_SYMBOLS : cppID = SCE_C_OPERATOR; break;
case SCE_HJ_COMMENT : cppID = SCE_C_COMMENT; break;
case SCE_HJ_COMMENTLINE : cppID = SCE_C_COMMENTLINE; break;
case SCE_HJ_COMMENTDOC : cppID = SCE_C_COMMENTDOC; break;
case SCE_HJ_NUMBER : cppID = SCE_C_NUMBER; break;
case SCE_HJ_KEYWORD : cppID = SCE_C_WORD; break;
case SCE_HJ_DOUBLESTRING : cppID = SCE_C_STRING; break;
case SCE_HJ_SINGLESTRING : cppID = SCE_C_CHARACTER; break;
case SCE_HJ_REGEX : cppID = SCE_C_REGEX; break;
}
style._styleID = cppID;
setStyle(style);
}
}
execute(SCI_STYLESETEOLFILLED, SCE_C_DEFAULT, true);
execute(SCI_STYLESETEOLFILLED, SCE_C_COMMENTLINE, true);
execute(SCI_STYLESETEOLFILLED, SCE_C_COMMENT, true);
execute(SCI_STYLESETEOLFILLED, SCE_C_COMMENTDOC, true);
}
const TCHAR *pKwArray[10] = {NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL};
makeStyle(langType, pKwArray);
basic_string<char> keywordListInstruction("");
basic_string<char> keywordListType("");
if (pKwArray[LANG_INDEX_INSTR])
{
basic_string<wchar_t> kwlW = pKwArray[LANG_INDEX_INSTR];
keywordListInstruction = wstring2string(kwlW, CP_ACP);
}
cppInstrs = getCompleteKeywordList(keywordListInstruction, langType, LANG_INDEX_INSTR);
if (pKwArray[LANG_INDEX_TYPE])
{
basic_string<wchar_t> kwlW = pKwArray[LANG_INDEX_TYPE];
keywordListType = wstring2string(kwlW, CP_ACP);
}
cppTypes = getCompleteKeywordList(keywordListType, langType, LANG_INDEX_TYPE);
execute(SCI_SETKEYWORDS, 0, (LPARAM)cppInstrs);
execute(SCI_SETKEYWORDS, 1, (LPARAM)cppTypes);
execute(SCI_SETPROPERTY, reinterpret_cast<WPARAM>("fold"), reinterpret_cast<LPARAM>("1"));
execute(SCI_SETPROPERTY, reinterpret_cast<WPARAM>("fold.compact"), reinterpret_cast<LPARAM>("0"));
execute(SCI_SETPROPERTY, reinterpret_cast<WPARAM>("fold.comment"), reinterpret_cast<LPARAM>("1"));
execute(SCI_SETPROPERTY, reinterpret_cast<WPARAM>("fold.preprocessor"), reinterpret_cast<LPARAM>("1"));
// Disable track preprocessor to avoid incorrect detection.
// In the most of cases, the symbols are defined outside of file.
execute(SCI_SETPROPERTY, reinterpret_cast<WPARAM>("lexer.cpp.track.preprocessor"), reinterpret_cast<LPARAM>("0"));
}
void ScintillaEditView::setTclLexer()
{
const char *tclInstrs;
const char *tclTypes;
execute(SCI_SETLEXER, SCLEX_TCL);
const TCHAR *pKwArray[10] = {NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL};
makeStyle(L_TCL, pKwArray);
basic_string<char> keywordListInstruction("");
basic_string<char> keywordListType("");
if (pKwArray[LANG_INDEX_INSTR])
{
basic_string<wchar_t> kwlW = pKwArray[LANG_INDEX_INSTR];
keywordListInstruction = wstring2string(kwlW, CP_ACP);
}
tclInstrs = getCompleteKeywordList(keywordListInstruction, L_TCL, LANG_INDEX_INSTR);
if (pKwArray[LANG_INDEX_TYPE])
{
basic_string<wchar_t> kwlW = pKwArray[LANG_INDEX_TYPE];
keywordListType = wstring2string(kwlW, CP_ACP);
}
tclTypes = getCompleteKeywordList(keywordListType, L_TCL, LANG_INDEX_TYPE);
execute(SCI_SETKEYWORDS, 0, (LPARAM)tclInstrs);
execute(SCI_SETKEYWORDS, 1, (LPARAM)tclTypes);
}
//used by Objective-C and Actionscript
void ScintillaEditView::setObjCLexer(LangType langType)
{
execute(SCI_SETLEXER, SCLEX_OBJC);
const TCHAR *pKwArray[10] = {NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL};
makeStyle(langType, pKwArray);
basic_string<char> objcInstr1Kwl("");
if (pKwArray[LANG_INDEX_INSTR])
{
objcInstr1Kwl = wstring2string(pKwArray[LANG_INDEX_INSTR], CP_ACP);
}
const char *objcInstrs = getCompleteKeywordList(objcInstr1Kwl, langType, LANG_INDEX_INSTR);
basic_string<char> objcInstr2Kwl("");
if (pKwArray[LANG_INDEX_INSTR2])
{
objcInstr2Kwl = wstring2string(pKwArray[LANG_INDEX_INSTR2], CP_ACP);
}
const char *objCDirective = getCompleteKeywordList(objcInstr2Kwl, langType, LANG_INDEX_INSTR2);
basic_string<char> objcTypeKwl("");
if (pKwArray[LANG_INDEX_TYPE])
{
objcTypeKwl = wstring2string(pKwArray[LANG_INDEX_TYPE], CP_ACP);
}
const char *objcTypes = getCompleteKeywordList(objcTypeKwl, langType, LANG_INDEX_TYPE);
basic_string<char> objcType2Kwl("");
if (pKwArray[LANG_INDEX_TYPE2])
{
objcType2Kwl = wstring2string(pKwArray[LANG_INDEX_TYPE2], CP_ACP);
}
const char *objCQualifier = getCompleteKeywordList(objcType2Kwl, langType, LANG_INDEX_TYPE2);
basic_string<char> doxygenKeyWordsString("");
const TCHAR *doxygenKeyWordsW = _pParameter->getWordList(L_CPP, LANG_INDEX_TYPE2);
if (doxygenKeyWordsW)
{
doxygenKeyWordsString = wstring2string(doxygenKeyWordsW, CP_ACP);
}
const char *doxygenKeyWords = doxygenKeyWordsString.c_str();
execute(SCI_SETKEYWORDS, 0, (LPARAM)objcInstrs);
execute(SCI_SETKEYWORDS, 1, (LPARAM)objcTypes);
execute(SCI_SETKEYWORDS, 2, (LPARAM)doxygenKeyWords);
execute(SCI_SETKEYWORDS, 3, (LPARAM)objCDirective);
execute(SCI_SETKEYWORDS, 4, (LPARAM)objCQualifier);
execute(SCI_SETPROPERTY, reinterpret_cast<WPARAM>("fold"), reinterpret_cast<LPARAM>("1"));
execute(SCI_SETPROPERTY, reinterpret_cast<WPARAM>("fold.compact"), reinterpret_cast<LPARAM>("0"));
execute(SCI_SETPROPERTY, reinterpret_cast<WPARAM>("fold.comment"), reinterpret_cast<LPARAM>("1"));
execute(SCI_SETPROPERTY, reinterpret_cast<WPARAM>("fold.preprocessor"), reinterpret_cast<LPARAM>("1"));
}
void ScintillaEditView::setKeywords(LangType langType, const char *keywords, int index)
{
std::basic_string<char> wordList;
wordList = (keywords)?keywords:"";
execute(SCI_SETKEYWORDS, index, (LPARAM)getCompleteKeywordList(wordList, langType, index));
}
void ScintillaEditView::setLexer(int lexerID, LangType langType, int whichList)
{
execute(SCI_SETLEXER, lexerID);
const TCHAR *pKwArray[10] = {NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL};
makeStyle(langType, pKwArray);
WcharMbcsConvertor *wmc = WcharMbcsConvertor::getInstance();
if (whichList & LIST_0)
{
const char * keyWords_char = wmc->wchar2char(pKwArray[LANG_INDEX_INSTR], CP_ACP);
setKeywords(langType, keyWords_char, LANG_INDEX_INSTR);
}
if (whichList & LIST_1)
{
const char * keyWords_char = wmc->wchar2char(pKwArray[LANG_INDEX_INSTR2], CP_ACP);
setKeywords(langType, keyWords_char, LANG_INDEX_INSTR2);
}
if (whichList & LIST_2)
{
const char * keyWords_char = wmc->wchar2char(pKwArray[LANG_INDEX_TYPE], CP_ACP);
setKeywords(langType, keyWords_char, LANG_INDEX_TYPE);
}
if (whichList & LIST_3)
{
const char * keyWords_char = wmc->wchar2char(pKwArray[LANG_INDEX_TYPE2], CP_ACP);
setKeywords(langType, keyWords_char, LANG_INDEX_TYPE2);
}
if (whichList & LIST_4)
{
const char * keyWords_char = wmc->wchar2char(pKwArray[LANG_INDEX_TYPE3], CP_ACP);
setKeywords(langType, keyWords_char, LANG_INDEX_TYPE3);
}
if (whichList & LIST_5)
{
const char * keyWords_char = wmc->wchar2char(pKwArray[LANG_INDEX_TYPE4], CP_ACP);
setKeywords(langType, keyWords_char, LANG_INDEX_TYPE4);
}
if (whichList & LIST_6)
{
const char * keyWords_char = wmc->wchar2char(pKwArray[LANG_INDEX_TYPE5], CP_ACP);
setKeywords(langType, keyWords_char, LANG_INDEX_TYPE5);
}
execute(SCI_SETPROPERTY, reinterpret_cast<WPARAM>("fold"), reinterpret_cast<LPARAM>("1"));
execute(SCI_SETPROPERTY, reinterpret_cast<WPARAM>("fold.compact"), reinterpret_cast<LPARAM>("0"));
execute(SCI_SETPROPERTY, reinterpret_cast<WPARAM>("fold.comment"), reinterpret_cast<LPARAM>("1"));
}
void ScintillaEditView::makeStyle(LangType language, const TCHAR **keywordArray)
{
const TCHAR * lexerName = ScintillaEditView::langNames[language].lexerName;
LexerStyler *pStyler = (_pParameter->getLStylerArray()).getLexerStylerByName(lexerName);
if (pStyler)
{
for (int i = 0, nb = pStyler->getNbStyler(); i < nb ; ++i)
{
Style & style = pStyler->getStyler(i);
setStyle(style);
if (keywordArray)
{
if ((style._keywordClass != STYLE_NOT_USED) && (style._keywords))
keywordArray[style._keywordClass] = style._keywords->c_str();
}
}
}
}
void ScintillaEditView::defineDocType(LangType typeDoc)
{
StyleArray & stylers = _pParameter->getMiscStylerArray();
int iStyleDefault = stylers.getStylerIndexByID(STYLE_DEFAULT);
if (iStyleDefault != -1)
{
Style & styleDefault = stylers.getStyler(iStyleDefault);
styleDefault._colorStyle = COLORSTYLE_ALL; //override transparency
setStyle(styleDefault);
}
execute(SCI_STYLECLEARALL);
Style *pStyle;
Style defaultIndicatorStyle;
defaultIndicatorStyle._styleID = SCE_UNIVERSAL_FOUND_STYLE;
defaultIndicatorStyle._bgColor = red;
pStyle = &defaultIndicatorStyle;
int iFind = stylers.getStylerIndexByID(SCE_UNIVERSAL_FOUND_STYLE);
if (iFind != -1)
{
pStyle = &(stylers.getStyler(iFind));
}
setSpecialIndicator(*pStyle);
defaultIndicatorStyle._styleID = SCE_UNIVERSAL_FOUND_STYLE_SMART;
defaultIndicatorStyle._bgColor = liteGreen;
pStyle = &defaultIndicatorStyle;
iFind = stylers.getStylerIndexByID(SCE_UNIVERSAL_FOUND_STYLE_SMART);
if (iFind != -1)
{
pStyle = &(stylers.getStyler(iFind));
}
setSpecialIndicator(*pStyle);
defaultIndicatorStyle._styleID = SCE_UNIVERSAL_FOUND_STYLE_INC;
defaultIndicatorStyle._bgColor = blue;
pStyle = &defaultIndicatorStyle;
iFind = stylers.getStylerIndexByID(SCE_UNIVERSAL_FOUND_STYLE_INC);
if (iFind != -1)
{
pStyle = &(stylers.getStyler(iFind));
}
setSpecialIndicator(*pStyle);
defaultIndicatorStyle._styleID = SCE_UNIVERSAL_TAGMATCH;
defaultIndicatorStyle._bgColor = RGB(0x80, 0x00, 0xFF);
pStyle = &defaultIndicatorStyle;
iFind = stylers.getStylerIndexByID(SCE_UNIVERSAL_TAGMATCH);
if (iFind != -1)
{
pStyle = &(stylers.getStyler(iFind));
}
setSpecialIndicator(*pStyle);
defaultIndicatorStyle._styleID = SCE_UNIVERSAL_TAGATTR;
defaultIndicatorStyle._bgColor = yellow;
pStyle = &defaultIndicatorStyle;
iFind = stylers.getStylerIndexByID(SCE_UNIVERSAL_TAGATTR);
if (iFind != -1)
{
pStyle = &(stylers.getStyler(iFind));
}
setSpecialIndicator(*pStyle);
defaultIndicatorStyle._styleID = SCE_UNIVERSAL_FOUND_STYLE_EXT1;
defaultIndicatorStyle._bgColor = cyan;
pStyle = &defaultIndicatorStyle;
iFind = stylers.getStylerIndexByID(SCE_UNIVERSAL_FOUND_STYLE_EXT1);
if (iFind != -1)
{
pStyle = &(stylers.getStyler(iFind));
}
setSpecialIndicator(*pStyle);
defaultIndicatorStyle._styleID = SCE_UNIVERSAL_FOUND_STYLE_EXT2;
defaultIndicatorStyle._bgColor = orange;
pStyle = &defaultIndicatorStyle;
iFind = stylers.getStylerIndexByID(SCE_UNIVERSAL_FOUND_STYLE_EXT2);
if (iFind != -1)
{
pStyle = &(stylers.getStyler(iFind));
}
setSpecialIndicator(*pStyle);
defaultIndicatorStyle._styleID = SCE_UNIVERSAL_FOUND_STYLE_EXT3;
defaultIndicatorStyle._bgColor = yellow;
pStyle = &defaultIndicatorStyle;
iFind = stylers.getStylerIndexByID(SCE_UNIVERSAL_FOUND_STYLE_EXT3);
if (iFind != -1)
{
pStyle = &(stylers.getStyler(iFind));
}
setSpecialIndicator(*pStyle);
defaultIndicatorStyle._styleID = SCE_UNIVERSAL_FOUND_STYLE_EXT4;
defaultIndicatorStyle._bgColor = purple;
pStyle = &defaultIndicatorStyle;
iFind = stylers.getStylerIndexByID(SCE_UNIVERSAL_FOUND_STYLE_EXT4);
if (iFind != -1)
{
pStyle = &(stylers.getStyler(iFind));
}
setSpecialIndicator(*pStyle);
defaultIndicatorStyle._styleID = SCE_UNIVERSAL_FOUND_STYLE_EXT5;
defaultIndicatorStyle._bgColor = darkGreen;
pStyle = &defaultIndicatorStyle;
iFind = stylers.getStylerIndexByID(SCE_UNIVERSAL_FOUND_STYLE_EXT5);
if (iFind != -1)
{
pStyle = &(stylers.getStyler(iFind));
}
setSpecialIndicator(*pStyle);
// Il faut surtout faire un test ici avant d'exécuter SCI_SETCODEPAGE
// Sinon y'aura un soucis de performance!
if (isCJK())
{
if (getCurrentBuffer()->getUnicodeMode() == uni8Bit)
{
if (typeDoc == L_CSS || typeDoc == L_CAML || typeDoc == L_ASM || typeDoc == L_MATLAB)
execute(SCI_SETCODEPAGE, CP_ACP);
else
execute(SCI_SETCODEPAGE, _codepage);
}
}
ScintillaViewParams & svp = (ScintillaViewParams &)_pParameter->getSVP();
if (svp._folderStyle != FOLDER_STYLE_NONE)
showMargin(_SC_MARGE_FOLDER, isNeededFolderMarge(typeDoc));
switch (typeDoc)
{
case L_C :
case L_CPP :
case L_JS:
case L_JAVA :
case L_RC :
case L_CS :
case L_FLASH :
setCppLexer(typeDoc); break;
case L_TCL :
setTclLexer(); break;
case L_OBJC :
setObjCLexer(typeDoc); break;
case L_PHP :
case L_ASP :
case L_JSP :
case L_HTML :
case L_XML :
setXmlLexer(typeDoc); break;
case L_JSON:
setJsonLexer(); break;
case L_CSS :
setCssLexer(); break;
case L_LUA :
setLuaLexer(); break;
case L_MAKEFILE :
setMakefileLexer(); break;
case L_INI :
setIniLexer(); break;
case L_USER : {
const TCHAR * langExt = _currentBuffer->getUserDefineLangName();
if (langExt[0])
setUserLexer(langExt);
else
setUserLexer();
break; }
case L_ASCII :
{
LexerStyler *pStyler = (_pParameter->getLStylerArray()).getLexerStylerByName(TEXT("nfo"));
Style nfoStyle;
nfoStyle._styleID = STYLE_DEFAULT;
nfoStyle._fontName = TEXT("Lucida Console");
nfoStyle._fontSize = 10;
if (pStyler)
{
int i = pStyler->getStylerIndexByName(TEXT("DEFAULT"));
if (i != -1)
{
Style & style = pStyler->getStyler(i);
nfoStyle._bgColor = style._bgColor;
nfoStyle._fgColor = style._fgColor;
nfoStyle._colorStyle = style._colorStyle;
}
}
setSpecialStyle(nfoStyle);
execute(SCI_STYLECLEARALL);
Buffer * buf = MainFileManager->getBufferByID(_currentBufferID);
if (buf->getEncoding() != NPP_CP_DOS_437)
{
buf->setEncoding(NPP_CP_DOS_437);
::SendMessage(_hParent, WM_COMMAND, IDM_FILE_RELOAD, 0);
}
}
break;
case L_SQL :
setSqlLexer(); break;
case L_VB :
setVBLexer(); break;
case L_PASCAL :
setPascalLexer(); break;
case L_PERL :
setPerlLexer(); break;
case L_PYTHON :
setPythonLexer(); break;
case L_BATCH :
setBatchLexer(); break;
case L_TEX :
setTeXLexer(); break;
case L_NSIS :
setNsisLexer(); break;
case L_BASH :
setBashLexer(); break;
case L_FORTRAN :
setFortranLexer(); break;
case L_LISP :
setLispLexer(); break;
case L_SCHEME :
setSchemeLexer(); break;
case L_ASM :
setAsmLexer(); break;
case L_DIFF :
setDiffLexer(); break;
case L_PROPS :
setPropsLexer(); break;
case L_PS :
setPostscriptLexer(); break;
case L_RUBY :
setRubyLexer(); break;
case L_SMALLTALK :
setSmalltalkLexer(); break;
case L_VHDL :
setVhdlLexer(); break;
case L_KIX :
setKixLexer(); break;
case L_CAML :
setCamlLexer(); break;
case L_ADA :
setAdaLexer(); break;
case L_VERILOG :
setVerilogLexer(); break;
case L_AU3 :
setAutoItLexer(); break;
case L_MATLAB :
setMatlabLexer(); break;
case L_HASKELL :
setHaskellLexer(); break;
case L_INNO :
setInnoLexer(); break;
case L_CMAKE :
setCmakeLexer(); break;
case L_YAML :
setYamlLexer(); break;
case L_COBOL :
setCobolLexer(); break;
case L_GUI4CLI :
setGui4CliLexer(); break;
case L_D :
setDLexer(); break;
case L_POWERSHELL :
setPowerShellLexer(); break;
case L_R :
setRLexer(); break;
case L_COFFEESCRIPT :
setCoffeeScriptLexer(); break;
case L_TEXT :
default :
if (typeDoc >= L_EXTERNAL && typeDoc < _pParameter->L_END)
setExternalLexer(typeDoc);
else
execute(SCI_SETLEXER, (_codepage == CP_CHINESE_TRADITIONAL)?SCLEX_MAKEFILE:SCLEX_NULL);
break;
}
//All the global styles should put here
int indexOfIndentGuide = stylers.getStylerIndexByID(STYLE_INDENTGUIDE);
if (indexOfIndentGuide != -1)
{
Style & styleIG = stylers.getStyler(indexOfIndentGuide);
setStyle(styleIG);
}
int indexOfBraceLight = stylers.getStylerIndexByID(STYLE_BRACELIGHT);
if (indexOfBraceLight != -1)
{
Style & styleBL = stylers.getStyler(indexOfBraceLight);
setStyle(styleBL);
}
//setStyle(STYLE_CONTROLCHAR, liteGrey);
int indexBadBrace = stylers.getStylerIndexByID(STYLE_BRACEBAD);
if (indexBadBrace != -1)
{
Style & styleBB = stylers.getStyler(indexBadBrace);
setStyle(styleBB);
}
int indexLineNumber = stylers.getStylerIndexByID(STYLE_LINENUMBER);
if (indexLineNumber != -1)
{
Style & styleLN = stylers.getStyler(indexLineNumber);
setSpecialStyle(styleLN);
}
setTabSettings(_pParameter->getLangFromID(typeDoc));
execute(SCI_SETSTYLEBITS, 8); // Always use 8 bit mask in Document class (Document::stylingBitsMask),
// in that way Editor::PositionIsHotspot will return correct hotspot styleID.
// This value has no effect on LexAccessor::mask.
}
BufferID ScintillaEditView::attachDefaultDoc()
{
// get the doc pointer attached (by default) on the view Scintilla
Document doc = execute(SCI_GETDOCPOINTER, 0, 0);
execute(SCI_ADDREFDOCUMENT, 0, doc);
BufferID id = MainFileManager->bufferFromDocument(doc, false, true);//true, true); //keep counter on 1
Buffer * buf = MainFileManager->getBufferByID(id);
MainFileManager->addBufferReference(id, this); //add a reference. Notepad only shows the buffer in tabbar
_currentBufferID = id;
_currentBuffer = buf;
bufferUpdated(buf, BufferChangeMask); //make sure everything is in sync with the buffer, since no reference exists
return id;
}
void ScintillaEditView::saveCurrentPos()
{
//Save data so, that the current topline becomes visible again after restoring.
int displayedLine = static_cast<int>(execute(SCI_GETFIRSTVISIBLELINE));
int docLine = execute(SCI_DOCLINEFROMVISIBLE, displayedLine); //linenumber of the line displayed in the top
//int offset = displayedLine - execute(SCI_VISIBLEFROMDOCLINE, docLine); //use this to calc offset of wrap. If no wrap this should be zero
Buffer * buf = MainFileManager->getBufferByID(_currentBufferID);
Position pos;
// the correct visible line number
pos._firstVisibleLine = docLine;
pos._startPos = static_cast<int>(execute(SCI_GETANCHOR));
pos._endPos = static_cast<int>(execute(SCI_GETCURRENTPOS));
pos._xOffset = static_cast<int>(execute(SCI_GETXOFFSET));
pos._selMode = execute(SCI_GETSELECTIONMODE);
pos._scrollWidth = execute(SCI_GETSCROLLWIDTH);
buf->setPosition(pos, this);
}
void ScintillaEditView::restoreCurrentPos()
{
Buffer * buf = MainFileManager->getBufferByID(_currentBufferID);
Position & pos = buf->getPosition(this);
execute(SCI_GOTOPOS, 0); //make sure first line visible by setting caret there, will scroll to top of document
execute(SCI_SETSELECTIONMODE, pos._selMode); //enable
execute(SCI_SETANCHOR, pos._startPos);
execute(SCI_SETCURRENTPOS, pos._endPos);
execute(SCI_CANCEL); //disable
if (!isWrap()) { //only offset if not wrapping, otherwise the offset isnt needed at all
execute(SCI_SETSCROLLWIDTH, pos._scrollWidth);
execute(SCI_SETXOFFSET, pos._xOffset);
}
execute(SCI_CHOOSECARETX); // choose current x position
int lineToShow = execute(SCI_VISIBLEFROMDOCLINE, pos._firstVisibleLine);
scroll(0, lineToShow);
}
void ScintillaEditView::restyleBuffer() {
execute(SCI_CLEARDOCUMENTSTYLE);
execute(SCI_COLOURISE, 0, -1);
_currentBuffer->setNeedsLexing(false);
}
void ScintillaEditView::styleChange() {
defineDocType(_currentBuffer->getLangType());
restyleBuffer();
}
void ScintillaEditView::activateBuffer(BufferID buffer)
{
if (buffer == BUFFER_INVALID)
return;
if (buffer == _currentBuffer)
return;
Buffer * newBuf = MainFileManager->getBufferByID(buffer);
// before activating another document, we get the current position
// from the Scintilla view then save it to the current document
saveCurrentPos();
// get foldStateInfo of current doc
std::vector<size_t> lineStateVector;
getCurrentFoldStates(lineStateVector);
// put the state into the future ex buffer
_currentBuffer->setHeaderLineState(lineStateVector, this);
_currentBufferID = buffer; //the magical switch happens here
_currentBuffer = newBuf;
// change the doc, this operation will decrease
// the ref count of old current doc and increase the one of the new doc. FileManager should manage the rest
// Note that the actual reference in the Buffer itself is NOT decreased, Notepad_plus does that if neccessary
execute(SCI_SETDOCPOINTER, 0, _currentBuffer->getDocument());
// Due to execute(SCI_CLEARDOCUMENTSTYLE); in defineDocType() function
// defineDocType() function should be called here, but not be after the fold info loop
defineDocType(_currentBuffer->getLangType());
setTabSettings(_currentBuffer->getCurrentLang());
if (_currentBuffer->getNeedsLexing()) {
restyleBuffer();
}
// restore the collapsed info
const std::vector<size_t> & lineStateVectorNew = newBuf->getHeaderLineState(this);
syncFoldStateWith(lineStateVectorNew);
restoreCurrentPos();
bufferUpdated(_currentBuffer, (BufferChangeMask & ~BufferChangeLanguage)); //everything should be updated, but the language (which undoes some operations done here like folding)
//setup line number margin
int numLines = execute(SCI_GETLINECOUNT);
char numLineStr[32];
itoa(numLines, numLineStr, 10);
runMarkers(true, 0, true, false);
return; //all done
}
void ScintillaEditView::getCurrentFoldStates(std::vector<size_t> & lineStateVector)
{
//-- FLS: xCodeOptimization1304: For active document get folding state from Scintilla.
//-- The code using SCI_CONTRACTEDFOLDNEXT is usually 10%-50% faster than checking each line of the document!!
int contractedFoldHeaderLine = 0;
do {
contractedFoldHeaderLine = execute(SCI_CONTRACTEDFOLDNEXT, contractedFoldHeaderLine);
if (contractedFoldHeaderLine != -1)
{
//-- Store contracted line
lineStateVector.push_back(contractedFoldHeaderLine);
//-- Start next search with next line
++contractedFoldHeaderLine;
}
} while (contractedFoldHeaderLine != -1);
}
void ScintillaEditView::syncFoldStateWith(const std::vector<size_t> & lineStateVectorNew)
{
int nbLineState = lineStateVectorNew.size();
for (int i = 0 ; i < nbLineState ; ++i)
{
int line = lineStateVectorNew.at(i);
fold(line, false);
}
}
void ScintillaEditView::bufferUpdated(Buffer * buffer, int mask)
{
//actually only care about language and lexing etc
if (buffer == _currentBuffer)
{
if (mask & BufferChangeLanguage)
{
defineDocType(buffer->getLangType());
foldAll(fold_uncollapse);
}
if (mask & BufferChangeLexing)
{
if (buffer->getNeedsLexing())
{
restyleBuffer(); //sets to false, this will apply to any other view aswell
} //else nothing, otherwise infinite loop
}
if (mask & BufferChangeFormat)
{
execute(SCI_SETEOLMODE, static_cast<int>(_currentBuffer->getFormat()));
}
if (mask & BufferChangeReadonly)
{
execute(SCI_SETREADONLY, _currentBuffer->isReadOnly());
}
if (mask & BufferChangeUnicode)
{
int enc = CP_ACP;
if (buffer->getUnicodeMode() == uni8Bit)
{ //either 0 or CJK codepage
LangType typeDoc = buffer->getLangType();
if (isCJK())
{
if (typeDoc == L_CSS || typeDoc == L_CAML || typeDoc == L_ASM || typeDoc == L_MATLAB)
enc = CP_ACP; //you may also want to set charsets here, not yet implemented
else
enc = _codepage;
}
else
enc = CP_ACP;
}
else //CP UTF8 for all unicode
enc = SC_CP_UTF8;
execute(SCI_SETCODEPAGE, enc);
}
}
}
void ScintillaEditView::collapse(int level2Collapse, bool mode)
{
execute(SCI_COLOURISE, 0, -1);
int maxLine = execute(SCI_GETLINECOUNT);
for (int line = 0; line < maxLine; ++line)
{
int level = execute(SCI_GETFOLDLEVEL, line);
if (level & SC_FOLDLEVELHEADERFLAG)
{
level -= SC_FOLDLEVELBASE;
if (level2Collapse == (level & SC_FOLDLEVELNUMBERMASK))
if (isFolded(line) != mode)
{
fold(line, mode);
}
}
}
runMarkers(true, 0, true, false);
}
void ScintillaEditView::foldCurrentPos(bool mode)
{
int currentLine = this->getCurrentLineNumber();
fold(currentLine, mode);
}
void ScintillaEditView::fold(int line, bool mode)
{
int endStyled = execute(SCI_GETENDSTYLED);
int len = execute(SCI_GETTEXTLENGTH);
if (endStyled < len)
execute(SCI_COLOURISE, 0, -1);
int headerLine;
int level = execute(SCI_GETFOLDLEVEL, line);
if (level & SC_FOLDLEVELHEADERFLAG)
headerLine = line;
else
{
headerLine = execute(SCI_GETFOLDPARENT, line);
if (headerLine == -1)
return;
}
if (isFolded(headerLine) != mode)
{
execute(SCI_TOGGLEFOLD, headerLine);
SCNotification scnN;
scnN.nmhdr.code = SCN_FOLDINGSTATECHANGED;
scnN.nmhdr.hwndFrom = _hSelf;
scnN.nmhdr.idFrom = 0;
scnN.line = headerLine;
scnN.foldLevelNow = isFolded(headerLine)?1:0; //folded:1, unfolded:0
::SendMessage(_hParent, WM_NOTIFY, 0, (LPARAM)&scnN);
}
}
void ScintillaEditView::foldAll(bool mode)
{
int maxLine = execute(SCI_GETLINECOUNT);
for (int line = 0; line < maxLine; ++line)
{
int level = execute(SCI_GETFOLDLEVEL, line);
if (level & SC_FOLDLEVELHEADERFLAG)
if (isFolded(line) != mode)
fold(line, mode);
}
}
void ScintillaEditView::getText(char *dest, int start, int end) const
{
TextRange tr;
tr.chrg.cpMin = start;
tr.chrg.cpMax = end;
tr.lpstrText = dest;
execute(SCI_GETTEXTRANGE, 0, reinterpret_cast<LPARAM>(&tr));
}
generic_string ScintillaEditView::getGenericTextAsString(int start, int end) const
{
assert(end > start);
const int bufSize = end - start + 1;
TCHAR *buf = new TCHAR[bufSize];
getGenericText(buf, bufSize, start, end);
generic_string text = buf;
delete[] buf;
return text;
}
void ScintillaEditView::getGenericText(TCHAR *dest, size_t destlen, int start, int end) const
{
WcharMbcsConvertor *wmc = WcharMbcsConvertor::getInstance();
char *destA = new char[end - start + 1];
getText(destA, start, end);
unsigned int cp = execute(SCI_GETCODEPAGE);
const TCHAR *destW = wmc->char2wchar(destA, cp);
_tcsncpy_s(dest, destlen, destW, _TRUNCATE);
delete [] destA;
}
// "mstart" and "mend" are pointers to indexes in the read string,
// which are converted to the corresponding indexes in the returned TCHAR string.
void ScintillaEditView::getGenericText(TCHAR *dest, size_t destlen, int start, int end, int *mstart, int *mend) const
{
WcharMbcsConvertor *wmc = WcharMbcsConvertor::getInstance();
char *destA = new char[end - start + 1];
getText(destA, start, end);
unsigned int cp = execute(SCI_GETCODEPAGE);
const TCHAR *destW = wmc->char2wchar(destA, cp, mstart, mend);
_tcsncpy_s(dest, destlen, destW, _TRUNCATE);
delete [] destA;
}
void ScintillaEditView::insertGenericTextFrom(int position, const TCHAR *text2insert) const
{
WcharMbcsConvertor *wmc = WcharMbcsConvertor::getInstance();
unsigned int cp = execute(SCI_GETCODEPAGE);
const char *text2insertA = wmc->wchar2char(text2insert, cp);
execute(SCI_INSERTTEXT, position, (WPARAM)text2insertA);
}
void ScintillaEditView::replaceSelWith(const char * replaceText)
{
execute(SCI_REPLACESEL, 0, (WPARAM)replaceText);
}
void ScintillaEditView::getVisibleStartAndEndPosition(int * startPos, int * endPos)
{
assert(startPos != NULL && endPos != NULL);
int firstVisibleLine = execute(SCI_GETFIRSTVISIBLELINE);
*startPos = execute(SCI_POSITIONFROMLINE, execute(SCI_DOCLINEFROMVISIBLE, firstVisibleLine));
int linesOnScreen = execute(SCI_LINESONSCREEN);
int lineCount = execute(SCI_GETLINECOUNT);
*endPos = execute(SCI_POSITIONFROMLINE, execute(SCI_DOCLINEFROMVISIBLE, firstVisibleLine + min(linesOnScreen, lineCount)));
if (*endPos == -1) *endPos = execute(SCI_GETLENGTH);
}
char * ScintillaEditView::getWordFromRange(char * txt, int size, int pos1, int pos2)
{
if (!size)
return NULL;
if (pos1 > pos2)
{
int tmp = pos1;
pos1 = pos2;
pos2 = tmp;
}
if (size < pos2-pos1)
return NULL;
getText(txt, pos1, pos2);
return txt;
}
char * ScintillaEditView::getWordOnCaretPos(char * txt, int size)
{
if (!size)
return NULL;
pair<int,int> range = getWordRange();
return getWordFromRange(txt, size, range.first, range.second);
}
TCHAR * ScintillaEditView::getGenericWordOnCaretPos(TCHAR * txt, int size)
{
WcharMbcsConvertor *wmc = WcharMbcsConvertor::getInstance();
unsigned int cp = execute(SCI_GETCODEPAGE);
char *txtA = new char[size + 1];
getWordOnCaretPos(txtA, size);
const TCHAR * txtW = wmc->char2wchar(txtA, cp);
lstrcpy(txt, txtW);
delete [] txtA;
return txt;
}
char * ScintillaEditView::getSelectedText(char * txt, int size, bool expand)
{
if (!size)
return NULL;
CharacterRange range = getSelection();
if (range.cpMax == range.cpMin && expand)
{
expandWordSelection();
range = getSelection();
}
if (!(size > (range.cpMax - range.cpMin))) //there must be atleast 1 byte left for zero terminator
{
range.cpMax = range.cpMin+size-1; //keep room for zero terminator
}
//getText(txt, range.cpMin, range.cpMax);
return getWordFromRange(txt, size, range.cpMin, range.cpMax);
}
TCHAR * ScintillaEditView::getGenericSelectedText(TCHAR * txt, int size, bool expand)
{
WcharMbcsConvertor *wmc = WcharMbcsConvertor::getInstance();
unsigned int cp = execute(SCI_GETCODEPAGE);
char *txtA = new char[size + 1];
getSelectedText(txtA, size, expand);
const TCHAR * txtW = wmc->char2wchar(txtA, cp);
lstrcpy(txt, txtW);
delete [] txtA;
return txt;
}
int ScintillaEditView::searchInTarget(const TCHAR * text2Find, int lenOfText2Find, int fromPos, int toPos) const
{
execute(SCI_SETTARGETSTART, fromPos);
execute(SCI_SETTARGETEND, toPos);
WcharMbcsConvertor *wmc = WcharMbcsConvertor::getInstance();
unsigned int cp = execute(SCI_GETCODEPAGE);
const char *text2FindA = wmc->wchar2char(text2Find, cp);
size_t text2FindALen = strlen(text2FindA);
int len = (lenOfText2Find > (int)text2FindALen)?lenOfText2Find:text2FindALen;
int targetFound = execute(SCI_SEARCHINTARGET, (WPARAM)len, (LPARAM)text2FindA);
return targetFound;
}
void ScintillaEditView::appandGenericText(const TCHAR * text2Append) const
{
WcharMbcsConvertor *wmc = WcharMbcsConvertor::getInstance();
unsigned int cp = execute(SCI_GETCODEPAGE);
const char *text2AppendA =wmc->wchar2char(text2Append, cp);
execute(SCI_APPENDTEXT, strlen(text2AppendA), (LPARAM)text2AppendA);
}
void ScintillaEditView::addGenericText(const TCHAR * text2Append) const
{
WcharMbcsConvertor *wmc = WcharMbcsConvertor::getInstance();
unsigned int cp = execute(SCI_GETCODEPAGE);
const char *text2AppendA =wmc->wchar2char(text2Append, cp);
execute(SCI_ADDTEXT, strlen(text2AppendA), (LPARAM)text2AppendA);
}
void ScintillaEditView::addGenericText(const TCHAR * text2Append, long *mstart, long *mend) const
{
WcharMbcsConvertor *wmc = WcharMbcsConvertor::getInstance();
unsigned int cp = execute(SCI_GETCODEPAGE);
const char *text2AppendA =wmc->wchar2char(text2Append, cp, mstart, mend);
execute(SCI_ADDTEXT, strlen(text2AppendA), (LPARAM)text2AppendA);
}
int ScintillaEditView::replaceTarget(const TCHAR * str2replace, int fromTargetPos, int toTargetPos) const
{
if (fromTargetPos != -1 || toTargetPos != -1)
{
execute(SCI_SETTARGETSTART, fromTargetPos);
execute(SCI_SETTARGETEND, toTargetPos);
}
WcharMbcsConvertor *wmc = WcharMbcsConvertor::getInstance();
unsigned int cp = execute(SCI_GETCODEPAGE);
const char *str2replaceA = wmc->wchar2char(str2replace, cp);
return execute(SCI_REPLACETARGET, (WPARAM)-1, (LPARAM)str2replaceA);
}
int ScintillaEditView::replaceTargetRegExMode(const TCHAR * re, int fromTargetPos, int toTargetPos) const
{
if (fromTargetPos != -1 || toTargetPos != -1)
{
execute(SCI_SETTARGETSTART, fromTargetPos);
execute(SCI_SETTARGETEND, toTargetPos);
}
WcharMbcsConvertor *wmc = WcharMbcsConvertor::getInstance();
unsigned int cp = execute(SCI_GETCODEPAGE);
const char *reA = wmc->wchar2char(re, cp);
return execute(SCI_REPLACETARGETRE, (WPARAM)-1, (LPARAM)reA);
}
void ScintillaEditView::showAutoComletion(int lenEntered, const TCHAR* list)
{
WcharMbcsConvertor *wmc = WcharMbcsConvertor::getInstance();
unsigned int cp = execute(SCI_GETCODEPAGE);
const char *listA = wmc->wchar2char(list, cp);
execute(SCI_AUTOCSHOW, lenEntered, WPARAM(listA));
}
void ScintillaEditView::showCallTip(int startPos, const TCHAR * def)
{
WcharMbcsConvertor *wmc = WcharMbcsConvertor::getInstance();
unsigned int cp = execute(SCI_GETCODEPAGE);
const char *defA = wmc->wchar2char(def, cp);
execute(SCI_CALLTIPSHOW, startPos, LPARAM(defA));
}
generic_string ScintillaEditView::getLine(int lineNumber)
{
int lineLen = execute(SCI_LINELENGTH, lineNumber);
const int bufSize = lineLen + 1;
std::unique_ptr<TCHAR[]> buf = std::make_unique<TCHAR[]>(bufSize);
getLine(lineNumber, buf.get(), bufSize);
return buf.get();
}
void ScintillaEditView::getLine(int lineNumber, TCHAR * line, int lineBufferLen)
{
WcharMbcsConvertor *wmc = WcharMbcsConvertor::getInstance();
unsigned int cp = execute(SCI_GETCODEPAGE);
char *lineA = new char[lineBufferLen];
// From Scintilla documentation for SCI_GETLINE: "The buffer is not terminated by a 0 character."
memset(lineA, 0x0, sizeof(char) * lineBufferLen);
execute(SCI_GETLINE, lineNumber, (LPARAM)lineA);
const TCHAR *lineW = wmc->char2wchar(lineA, cp);
lstrcpyn(line, lineW, lineBufferLen);
delete [] lineA;
}
void ScintillaEditView::addText(int length, const char *buf)
{
execute(SCI_ADDTEXT, length, (LPARAM)buf);
}
void ScintillaEditView::beginOrEndSelect()
{
if(_beginSelectPosition == -1)
{
_beginSelectPosition = execute(SCI_GETCURRENTPOS);
}
else
{
execute(SCI_SETANCHOR, (WPARAM)_beginSelectPosition);
_beginSelectPosition = -1;
}
}
void ScintillaEditView::updateBeginEndSelectPosition(const bool is_insert, const int position, const int length)
{
if(_beginSelectPosition != -1 && position < _beginSelectPosition - 1)
{
if(is_insert)
_beginSelectPosition += length;
else
_beginSelectPosition -= length;
assert(_beginSelectPosition >= 0);
}
}
void ScintillaEditView::marginClick(int position, int modifiers)
{
int lineClick = int(execute(SCI_LINEFROMPOSITION, position, 0));
int levelClick = int(execute(SCI_GETFOLDLEVEL, lineClick, 0));
if (levelClick & SC_FOLDLEVELHEADERFLAG)
{
if (modifiers & SCMOD_SHIFT)
{
// Ensure all children visible
execute(SCI_SETFOLDEXPANDED, lineClick, 1);
expand(lineClick, true, true, 100, levelClick);
}
else if (modifiers & SCMOD_CTRL)
{
if (isFolded(lineClick))
{
// Contract this line and all children
execute(SCI_SETFOLDEXPANDED, lineClick, 0);
expand(lineClick, false, true, 0, levelClick);
}
else
{
// Expand this line and all children
execute(SCI_SETFOLDEXPANDED, lineClick, 1);
expand(lineClick, true, true, 100, levelClick);
}
}
else
{
// Toggle this line
bool mode = isFolded(lineClick);
fold(lineClick, !mode);
runMarkers(true, lineClick, true, false);
}
}
}
void ScintillaEditView::expand(int &line, bool doExpand, bool force, int visLevels, int level)
{
int lineMaxSubord = int(execute(SCI_GETLASTCHILD, line, level & SC_FOLDLEVELNUMBERMASK));
++line;
while (line <= lineMaxSubord)
{
if (force)
{
execute(((visLevels > 0) ? SCI_SHOWLINES : SCI_HIDELINES), line, line);
}
else
{
if (doExpand)
execute(SCI_SHOWLINES, line, line);
}
int levelLine = level;
if (levelLine == -1)
levelLine = int(execute(SCI_GETFOLDLEVEL, line, 0));
if (levelLine & SC_FOLDLEVELHEADERFLAG)
{
if (force)
{
if (visLevels > 1)
execute(SCI_SETFOLDEXPANDED, line, 1);
else
execute(SCI_SETFOLDEXPANDED, line, 0);
expand(line, doExpand, force, visLevels - 1);
}
else
{
if (doExpand)
{
if (!isFolded(line))
execute(SCI_SETFOLDEXPANDED, line, 1);
expand(line, true, force, visLevels - 1);
}
else
expand(line, false, force, visLevels - 1);
}
}
else
++line;
}
runMarkers(true, 0, true, false);
}
void ScintillaEditView::performGlobalStyles()
{
StyleArray & stylers = _pParameter->getMiscStylerArray();
int i = stylers.getStylerIndexByName(TEXT("Current line background colour"));
if (i != -1)
{
Style & style = stylers.getStyler(i);
execute(SCI_SETCARETLINEBACK, style._bgColor);
}
COLORREF selectColorBack = grey;
i = stylers.getStylerIndexByName(TEXT("Selected text colour"));
if (i != -1)
{
Style & style = stylers.getStyler(i);
selectColorBack = style._bgColor;
}
execute(SCI_SETSELBACK, 1, selectColorBack);
COLORREF caretColor = black;
i = stylers.getStylerIndexByID(SCI_SETCARETFORE);
if (i != -1)
{
Style & style = stylers.getStyler(i);
caretColor = style._fgColor;
}
execute(SCI_SETCARETFORE, caretColor);
COLORREF edgeColor = liteGrey;
i = stylers.getStylerIndexByName(TEXT("Edge colour"));
if (i != -1)
{
Style & style = stylers.getStyler(i);
edgeColor = style._fgColor;
}
execute(SCI_SETEDGECOLOUR, edgeColor);
COLORREF foldMarginColor = grey;
COLORREF foldMarginHiColor = white;
i = stylers.getStylerIndexByName(TEXT("Fold margin"));
if (i != -1)
{
Style & style = stylers.getStyler(i);
foldMarginHiColor = style._fgColor;
foldMarginColor = style._bgColor;
}
execute(SCI_SETFOLDMARGINCOLOUR, true, foldMarginColor);
execute(SCI_SETFOLDMARGINHICOLOUR, true, foldMarginHiColor);
COLORREF foldfgColor = white;
COLORREF foldbgColor = grey;
i = stylers.getStylerIndexByName(TEXT("Fold"));
if (i != -1)
{
Style & style = stylers.getStyler(i);
foldfgColor = style._bgColor;
foldbgColor = style._fgColor;
}
COLORREF activeFoldFgColor = red;
i = stylers.getStylerIndexByName(TEXT("Fold active"));
if (i != -1)
{
Style & style = stylers.getStyler(i);
activeFoldFgColor = style._fgColor;
}
ScintillaViewParams & svp = (ScintillaViewParams &)_pParameter->getSVP();
for (int j = 0 ; j < NB_FOLDER_STATE ; ++j)
defineMarker(_markersArray[FOLDER_TYPE][j], _markersArray[svp._folderStyle][j], foldfgColor, foldbgColor, activeFoldFgColor);
execute(SCI_MARKERENABLEHIGHLIGHT, true);
COLORREF wsSymbolFgColor = black;
i = stylers.getStylerIndexByName(TEXT("White space symbol"));
if (i != -1)
{
Style & style = stylers.getStyler(i);
wsSymbolFgColor = style._fgColor;
}
execute(SCI_SETWHITESPACEFORE, true, wsSymbolFgColor);
}
void ScintillaEditView::setLineIndent(int line, int indent) const {
if (indent < 0)
return;
CharacterRange crange = getSelection();
int posBefore = execute(SCI_GETLINEINDENTPOSITION, line);
execute(SCI_SETLINEINDENTATION, line, indent);
int posAfter = execute(SCI_GETLINEINDENTPOSITION, line);
int posDifference = posAfter - posBefore;
if (posAfter > posBefore) {
// Move selection on
if (crange.cpMin >= posBefore) {
crange.cpMin += posDifference;
}
if (crange.cpMax >= posBefore) {
crange.cpMax += posDifference;
}
} else if (posAfter < posBefore) {
// Move selection back
if (crange.cpMin >= posAfter) {
if (crange.cpMin >= posBefore)
crange.cpMin += posDifference;
else
crange.cpMin = posAfter;
}
if (crange.cpMax >= posAfter) {
if (crange.cpMax >= posBefore)
crange.cpMax += posDifference;
else
crange.cpMax = posAfter;
}
}
execute(SCI_SETSEL, crange.cpMin, crange.cpMax);
}
void ScintillaEditView::updateLineNumberWidth()
{
if (_lineNumbersShown)
{
int linesVisible = (int) execute(SCI_LINESONSCREEN);
if (linesVisible)
{
int firstVisibleLineVis = (int) execute(SCI_GETFIRSTVISIBLELINE);
int lastVisibleLineVis = linesVisible + firstVisibleLineVis + 1;
if (execute(SCI_GETWRAPMODE) != SC_WRAP_NONE)
{
int numLinesDoc = (int) execute(SCI_GETLINECOUNT);
int prevLineDoc = (int) execute(SCI_DOCLINEFROMVISIBLE, firstVisibleLineVis);
for (int i = firstVisibleLineVis + 1; i <= lastVisibleLineVis; ++i)
{
int lineDoc = (int) execute(SCI_DOCLINEFROMVISIBLE, i);
if (lineDoc == numLinesDoc)
break;
if (lineDoc == prevLineDoc)
lastVisibleLineVis++;
prevLineDoc = lineDoc;
}
}
int lastVisibleLineDoc = (int) execute(SCI_DOCLINEFROMVISIBLE, lastVisibleLineVis);
int i = 0;
while (lastVisibleLineDoc)
{
lastVisibleLineDoc /= 10;
++i;
}
i = max(i, 3);
int pixelWidth = int(8 + i * execute(SCI_TEXTWIDTH, STYLE_LINENUMBER, (LPARAM)"8"));
execute(SCI_SETMARGINWIDTHN, _SC_MARGE_LINENUMBER, pixelWidth);
}
}
}
const char * ScintillaEditView::getCompleteKeywordList(std::basic_string<char> & kwl, LangType langType, int keywordIndex)
{
kwl += " ";
const TCHAR *defKwl_generic = _pParameter->getWordList(langType, keywordIndex);
WcharMbcsConvertor *wmc = WcharMbcsConvertor::getInstance();
const char * defKwl = wmc->wchar2char(defKwl_generic, CP_ACP);
kwl += defKwl?defKwl:"";
return kwl.c_str();
}
void ScintillaEditView::setMultiSelections(const ColumnModeInfos & cmi)
{
for (size_t i = 0, len = cmi.size(); i < len ; ++i)
{
if (cmi[i].isValid())
{
int selStart = cmi[i]._direction == L2R?cmi[i]._selLpos:cmi[i]._selRpos;
int selEnd = cmi[i]._direction == L2R?cmi[i]._selRpos:cmi[i]._selLpos;
execute(SCI_SETSELECTIONNSTART, i, selStart);
execute(SCI_SETSELECTIONNEND, i, selEnd);
}
//if (cmi[i].hasVirtualSpace())
//{
if (cmi[i]._nbVirtualAnchorSpc)
execute(SCI_SETSELECTIONNANCHORVIRTUALSPACE, i, cmi[i]._nbVirtualAnchorSpc);
if (cmi[i]._nbVirtualCaretSpc)
execute(SCI_SETSELECTIONNCARETVIRTUALSPACE, i, cmi[i]._nbVirtualCaretSpc);
//}
}
}
void ScintillaEditView::currentLineUp() const
{
int currentLine = getCurrentLineNumber();
if (currentLine != 0)
{
execute(SCI_BEGINUNDOACTION);
currentLine--;
execute(SCI_LINETRANSPOSE);
execute(SCI_GOTOLINE, currentLine);
execute(SCI_ENDUNDOACTION);
}
}
void ScintillaEditView::currentLineDown() const
{
int currentLine = getCurrentLineNumber();
if (currentLine != (execute(SCI_GETLINECOUNT) - 1))
{
execute(SCI_BEGINUNDOACTION);
++currentLine;
execute(SCI_GOTOLINE, currentLine);
execute(SCI_LINETRANSPOSE);
execute(SCI_ENDUNDOACTION);
}
}
// Get selection range : (fromLine, toLine)
// return (-1, -1) if multi-selection
pair<int, int> ScintillaEditView::getSelectionLinesRange() const
{
pair<int, int> range(-1, -1);
if (execute(SCI_GETSELECTIONS) > 1) // multi-selection
return range;
int start = execute(SCI_GETSELECTIONSTART);
int end = execute(SCI_GETSELECTIONEND);
range.first = execute(SCI_LINEFROMPOSITION, start);
range.second = execute(SCI_LINEFROMPOSITION, end);
if (range.first > range.second)
{
int temp = range.first;
range.first = range.second;
range.second = temp;
}
return range;
}
void ScintillaEditView::currentLinesUp() const
{
pair<int, int> lineRange = getSelectionLinesRange();
if ((lineRange.first == -1 || lineRange.first == 0))
return;
bool noSel = lineRange.first == lineRange.second;
int nbSelLines = lineRange.second - lineRange.first + 1;
int line2swap = lineRange.first - 1;
int nbChar = execute(SCI_LINELENGTH, line2swap);
int posStart = execute(SCI_POSITIONFROMLINE, lineRange.first);
int posEnd = execute(SCI_GETLINEENDPOSITION, lineRange.second);
execute(SCI_BEGINUNDOACTION);
execute(SCI_GOTOLINE, line2swap);
for (int i = 0 ; i < nbSelLines ; ++i)
{
currentLineDown();
}
execute(SCI_ENDUNDOACTION);
execute(SCI_SETSELECTIONSTART, posStart - nbChar);
execute(SCI_SETSELECTIONEND, noSel?posStart - nbChar:posEnd - nbChar);
}
void ScintillaEditView::currentLinesDown() const
{
pair<int, int> lineRange = getSelectionLinesRange();
if ((lineRange.first == -1 || lineRange.second >= execute(SCI_LINEFROMPOSITION, getCurrentDocLen())))
return;
bool noSel = lineRange.first == lineRange.second;
int nbSelLines = lineRange.second - lineRange.first + 1;
int line2swap = lineRange.second + 1;
int nbChar = execute(SCI_LINELENGTH, line2swap);
if ((line2swap + 1) == execute(SCI_GETLINECOUNT))
nbChar += (execute(SCI_GETEOLMODE)==SC_EOL_CRLF?2:1);
int posStart = execute(SCI_POSITIONFROMLINE, lineRange.first);
int posEnd = execute(SCI_GETLINEENDPOSITION, lineRange.second);
execute(SCI_BEGINUNDOACTION);
execute(SCI_GOTOLINE, line2swap);
for (int i = 0 ; i < nbSelLines ; ++i)
{
currentLineUp();
}
execute(SCI_ENDUNDOACTION);
execute(SCI_SETSELECTIONSTART, posStart + nbChar);
execute(SCI_SETSELECTIONEND, noSel?posStart + nbChar:posEnd + nbChar);
}
void ScintillaEditView::convertSelectedTextTo(bool Case)
{
unsigned int codepage = _codepage;
UniMode um = getCurrentBuffer()->getUnicodeMode();
if (um != uni8Bit)
codepage = CP_UTF8;
if (execute(SCI_GETSELECTIONS) > 1) // Multi-Selection || Column mode
{
execute(SCI_BEGINUNDOACTION);
ColumnModeInfos cmi = getColumnModeSelectInfo();
for (size_t i = 0, cmiLen = cmi.size(); i < cmiLen ; ++i)
{
const int len = cmi[i]._selRpos - cmi[i]._selLpos;
char *srcStr = new char[len+1];
wchar_t *destStr = new wchar_t[len+1];
int start = cmi[i]._selLpos;
int end = cmi[i]._selRpos;
getText(srcStr, start, end);
int nbChar = ::MultiByteToWideChar(codepage, 0, srcStr, len, destStr, len);
for (int j = 0 ; j < nbChar ; ++j)
{
if (Case == UPPERCASE)
destStr[j] = (wchar_t)(UINT_PTR)::CharUpperW((LPWSTR)destStr[j]);
else
destStr[j] = (wchar_t)(UINT_PTR)::CharLowerW((LPWSTR)destStr[j]);
}
::WideCharToMultiByte(codepage, 0, destStr, len, srcStr, len, NULL, NULL);
execute(SCI_SETTARGETSTART, start);
execute(SCI_SETTARGETEND, end);
execute(SCI_REPLACETARGET, (WPARAM)-1, (LPARAM)srcStr);
delete [] srcStr;
delete [] destStr;
}
setMultiSelections(cmi);
//execute(SCI_SETSELECTIONSTART, selStart);
//execute(SCI_SETSELECTIONEND, selEnd);
execute(SCI_ENDUNDOACTION);
return;
}
size_t selectionStart = execute(SCI_GETSELECTIONSTART);
size_t selectionEnd = execute(SCI_GETSELECTIONEND);
int strSize = ((selectionEnd > selectionStart)?(selectionEnd - selectionStart):(selectionStart - selectionEnd))+1;
if (strSize)
{
char *selectedStr = new char[strSize+1];
int strWSize = strSize * 2;
wchar_t *selectedStrW = new wchar_t[strWSize+3];
execute(SCI_GETSELTEXT, 0, (LPARAM)selectedStr);
int nbChar = ::MultiByteToWideChar(codepage, 0, selectedStr, strSize, selectedStrW, strWSize);
for (int i = 0 ; i < nbChar ; ++i)
{
if (Case == UPPERCASE)
selectedStrW[i] = (WCHAR)(UINT_PTR)::CharUpperW((LPWSTR)selectedStrW[i]);
else
selectedStrW[i] = (WCHAR)(UINT_PTR)::CharLowerW((LPWSTR)selectedStrW[i]);
}
::WideCharToMultiByte(codepage, 0, selectedStrW, strWSize, selectedStr, strSize, NULL, NULL);
execute(SCI_SETTARGETSTART, selectionStart);
execute(SCI_SETTARGETEND, selectionEnd);
execute(SCI_REPLACETARGET, strSize - 1, (LPARAM)selectedStr);
execute(SCI_SETSEL, selectionStart, selectionEnd);
delete [] selectedStr;
delete [] selectedStrW;
}
}
pair<int, int> ScintillaEditView::getWordRange()
{
int caretPos = execute(SCI_GETCURRENTPOS, 0, 0);
int startPos = static_cast<int>(execute(SCI_WORDSTARTPOSITION, caretPos, true));
int endPos = static_cast<int>(execute(SCI_WORDENDPOSITION, caretPos, true));
return pair<int, int>(startPos, endPos);
}
bool ScintillaEditView::expandWordSelection()
{
pair<int, int> wordRange = getWordRange();
if (wordRange.first != wordRange.second) {
execute(SCI_SETSELECTIONSTART, wordRange.first);
execute(SCI_SETSELECTIONEND, wordRange.second);
return true;
}
return false;
}
TCHAR * int2str(TCHAR *str, int strLen, int number, int base, int nbChiffre, bool isZeroLeading)
{
if (nbChiffre >= strLen) return NULL;
TCHAR f[64];
TCHAR fStr[2] = TEXT("d");
if (base == 16)
fStr[0] = 'X';
else if (base == 8)
fStr[0] = 'o';
else if (base == 2)
{
const unsigned int MASK_ULONG_BITFORT = 0x80000000;
int nbBits = sizeof(unsigned int) * 8;
int nbBit2Shift = (nbChiffre >= nbBits)?nbBits:(nbBits - nbChiffre);
unsigned long mask = MASK_ULONG_BITFORT >> nbBit2Shift;
int i = 0;
for (; mask > 0 ; ++i)
{
str[i] = (mask & number)?'1':'0';
mask >>= 1;
}
str[i] = '\0';
}
if (!isZeroLeading)
{
if (base == 2)
{
TCHAR *j = str;
for ( ; *j != '\0' ; ++j)
if (*j == '1')
break;
lstrcpy(str, j);
}
else
{
// use sprintf or swprintf instead of wsprintf
// to make octal format work
generic_sprintf(f, TEXT("%%%s"), fStr);
generic_sprintf(str, f, number);
}
int i = lstrlen(str);
for ( ; i < nbChiffre ; ++i)
str[i] = ' ';
str[i] = '\0';
}
else
{
if (base != 2)
{
// use sprintf or swprintf instead of wsprintf
// to make octal format work
generic_sprintf(f, TEXT("%%.%d%s"), nbChiffre, fStr);
generic_sprintf(str, f, number);
}
// else already done.
}
return str;
}
ColumnModeInfos ScintillaEditView::getColumnModeSelectInfo()
{
ColumnModeInfos columnModeInfos;
if (execute(SCI_GETSELECTIONS) > 1) // Multi-Selection || Column mode
{
int nbSel = execute(SCI_GETSELECTIONS);
for (int i = 0 ; i < nbSel ; ++i)
{
int absPosSelStartPerLine = execute(SCI_GETSELECTIONNANCHOR, i);
int absPosSelEndPerLine = execute(SCI_GETSELECTIONNCARET, i);
int nbVirtualAnchorSpc = execute(SCI_GETSELECTIONNANCHORVIRTUALSPACE, i);
int nbVirtualCaretSpc = execute(SCI_GETSELECTIONNCARETVIRTUALSPACE, i);
if (absPosSelStartPerLine == absPosSelEndPerLine && execute(SCI_SELECTIONISRECTANGLE))
{
bool dir = nbVirtualAnchorSpc<nbVirtualCaretSpc?L2R:R2L;
columnModeInfos.push_back(ColumnModeInfo(absPosSelStartPerLine, absPosSelEndPerLine, i, dir, nbVirtualAnchorSpc, nbVirtualCaretSpc));
}
else if (absPosSelStartPerLine > absPosSelEndPerLine)
columnModeInfos.push_back(ColumnModeInfo(absPosSelEndPerLine, absPosSelStartPerLine, i, R2L, nbVirtualAnchorSpc, nbVirtualCaretSpc));
else
columnModeInfos.push_back(ColumnModeInfo(absPosSelStartPerLine, absPosSelEndPerLine, i, L2R, nbVirtualAnchorSpc, nbVirtualCaretSpc));
}
}
return columnModeInfos;
}
void ScintillaEditView::columnReplace(ColumnModeInfos & cmi, const TCHAR *str)
{
int totalDiff = 0;
for (size_t i = 0, len = cmi.size(); i < len ; ++i)
{
if (cmi[i].isValid())
{
int len2beReplace = cmi[i]._selRpos - cmi[i]._selLpos;
int diff = lstrlen(str) - len2beReplace;
cmi[i]._selLpos += totalDiff;
cmi[i]._selRpos += totalDiff;
bool hasVirtualSpc = cmi[i]._nbVirtualAnchorSpc > 0;
if (hasVirtualSpc) // if virtual space is present, then insert space
{
for (int j = 0, k = cmi[i]._selLpos; j < cmi[i]._nbVirtualCaretSpc ; ++j, ++k)
{
execute(SCI_INSERTTEXT, k, (LPARAM)" ");
}
cmi[i]._selLpos += cmi[i]._nbVirtualAnchorSpc;
cmi[i]._selRpos += cmi[i]._nbVirtualCaretSpc;
}
execute(SCI_SETTARGETSTART, cmi[i]._selLpos);
execute(SCI_SETTARGETEND, cmi[i]._selRpos);
WcharMbcsConvertor *wmc = WcharMbcsConvertor::getInstance();
unsigned int cp = execute(SCI_GETCODEPAGE);
const char *strA = wmc->wchar2char(str, cp);
execute(SCI_REPLACETARGET, (WPARAM)-1, (LPARAM)strA);
if (hasVirtualSpc)
{
totalDiff += cmi[i]._nbVirtualAnchorSpc + lstrlen(str);
// Now there's no more virtual space
cmi[i]._nbVirtualAnchorSpc = 0;
cmi[i]._nbVirtualCaretSpc = 0;
}
else
{
totalDiff += diff;
}
cmi[i]._selRpos += diff;
}
}
}
void ScintillaEditView::columnReplace(ColumnModeInfos & cmi, int initial, int incr, int repeat, UCHAR format)
{
assert(repeat > 0);
// 0000 00 00 : Dec BASE_10
// 0000 00 01 : Hex BASE_16
// 0000 00 10 : Oct BASE_08
// 0000 00 11 : Bin BASE_02
// 0000 01 00 : 0 leading
//Defined in ScintillaEditView.h :
//const UCHAR MASK_FORMAT = 0x03;
//const UCHAR MASK_ZERO_LEADING = 0x04;
UCHAR f = format & MASK_FORMAT;
bool isZeroLeading = (MASK_ZERO_LEADING & format) != 0;
int base = 10;
if (f == BASE_16)
base = 16;
else if (f == BASE_08)
base = 8;
else if (f == BASE_02)
base = 2;
const int stringSize = 512;
TCHAR str[stringSize];
// Compute the numbers to be placed at each column.
std::vector<int> numbers;
{
int curNumber = initial;
const unsigned int kiMaxSize = cmi.size();
while(numbers.size() < kiMaxSize)
{
for(int i = 0; i < repeat; i++)
{
numbers.push_back(curNumber);
if (numbers.size() >= kiMaxSize)
{
break;
}
}
curNumber += incr;
}
}
assert(numbers.size()> 0);
const int kibEnd = getNbDigits(*numbers.rbegin(), base);
const int kibInit = getNbDigits(initial, base);
const int kib = std::max<int>(kibInit, kibEnd);
int totalDiff = 0;
const size_t len = cmi.size();
for (size_t i = 0 ; i < len ; i++)
{
if (cmi[i].isValid())
{
const int len2beReplaced = cmi[i]._selRpos - cmi[i]._selLpos;
const int diff = kib - len2beReplaced;
cmi[i]._selLpos += totalDiff;
cmi[i]._selRpos += totalDiff;
int2str(str, stringSize, numbers.at(i), base, kib, isZeroLeading);
const bool hasVirtualSpc = cmi[i]._nbVirtualAnchorSpc > 0;
if (hasVirtualSpc) // if virtual space is present, then insert space
{
for (int j = 0, k = cmi[i]._selLpos; j < cmi[i]._nbVirtualCaretSpc ; ++j, ++k)
{
execute(SCI_INSERTTEXT, k, (LPARAM)" ");
}
cmi[i]._selLpos += cmi[i]._nbVirtualAnchorSpc;
cmi[i]._selRpos += cmi[i]._nbVirtualCaretSpc;
}
execute(SCI_SETTARGETSTART, cmi[i]._selLpos);
execute(SCI_SETTARGETEND, cmi[i]._selRpos);
WcharMbcsConvertor *wmc = WcharMbcsConvertor::getInstance();
unsigned int cp = execute(SCI_GETCODEPAGE);
const char *strA = wmc->wchar2char(str, cp);
execute(SCI_REPLACETARGET, (WPARAM)-1, (LPARAM)strA);
if (hasVirtualSpc)
{
totalDiff += cmi[i]._nbVirtualAnchorSpc + lstrlen(str);
// Now there's no more virtual space
cmi[i]._nbVirtualAnchorSpc = 0;
cmi[i]._nbVirtualCaretSpc = 0;
}
else
{
totalDiff += diff;
}
cmi[i]._selRpos += diff;
}
}
}
void ScintillaEditView::foldChanged(int line, int levelNow, int levelPrev)
{
if (levelNow & SC_FOLDLEVELHEADERFLAG) //line can be folded
{
if (!(levelPrev & SC_FOLDLEVELHEADERFLAG)) //but previously couldnt
{
// Adding a fold point.
execute(SCI_SETFOLDEXPANDED, line, 1);
expand(line, true, false, 0, levelPrev);
}
}
else if (levelPrev & SC_FOLDLEVELHEADERFLAG)
{
if (isFolded(line))
{
// Removing the fold from one that has been contracted so should expand
// otherwise lines are left invisible with no way to make them visible
execute(SCI_SETFOLDEXPANDED, line, 1);
expand(line, true, false, 0, levelPrev);
}
}
else if (!(levelNow & SC_FOLDLEVELWHITEFLAG) &&
((levelPrev & SC_FOLDLEVELNUMBERMASK) > (levelNow & SC_FOLDLEVELNUMBERMASK)))
{
// See if should still be hidden
int parentLine = execute(SCI_GETFOLDPARENT, line);
if ((parentLine < 0) || !isFolded(parentLine && execute(SCI_GETLINEVISIBLE, parentLine)))
execute(SCI_SHOWLINES, line, line);
}
}
void ScintillaEditView::scrollPosToCenter(int pos)
{
execute(SCI_GOTOPOS, pos);
int line = execute(SCI_LINEFROMPOSITION, pos);
int firstVisibleDisplayLine = execute(SCI_GETFIRSTVISIBLELINE);
int firstVisibleDocLine = execute(SCI_DOCLINEFROMVISIBLE, firstVisibleDisplayLine);
int nbLine = execute(SCI_LINESONSCREEN, firstVisibleDisplayLine);
int lastVisibleDocLine = execute(SCI_DOCLINEFROMVISIBLE, firstVisibleDisplayLine + nbLine);
int middleLine;
if (line - firstVisibleDocLine < lastVisibleDocLine - line)
middleLine = firstVisibleDocLine + nbLine/2;
else
middleLine = lastVisibleDocLine - nbLine/2;
int nbLines2scroll = line - middleLine;
scroll(0, nbLines2scroll);
}
void ScintillaEditView::hideLines() {
//Folding can screw up hide lines badly if it unfolds a hidden section.
//Adding runMarkers(hide, foldstart) directly (folding on single document) can help
//Special func on buffer. If markers are added, create notification with location of start, and hide bool set to true
int startLine = execute(SCI_LINEFROMPOSITION, execute(SCI_GETSELECTIONSTART));
int endLine = execute(SCI_LINEFROMPOSITION, execute(SCI_GETSELECTIONEND));
//perform range check: cannot hide very first and very last lines
//Offset them one off the edges, and then check if they are within the reasonable
int nrLines = execute(SCI_GETLINECOUNT);
if (nrLines < 3)
return; //cannot possibly hide anything
if (!startLine)
++startLine;
if (endLine == (nrLines-1))
--endLine;
if (startLine > endLine)
return; //tried to hide line at edge
//Hide the lines. We add marks on the outside of the hidden section and hide the lines
//execute(SCI_HIDELINES, startLine, endLine);
//Add markers
execute(SCI_MARKERADD, startLine-1, MARK_HIDELINESBEGIN);
execute(SCI_MARKERADD, endLine+1, MARK_HIDELINESEND);
//remove any markers in between
int scope = 0;
for(int i = startLine; i <= endLine; ++i) {
int state = execute(SCI_MARKERGET, i);
bool closePresent = ((state & (1 << MARK_HIDELINESEND)) != 0); //check close first, then open, since close closes scope
bool openPresent = ((state & (1 << MARK_HIDELINESBEGIN)) != 0);
if (closePresent) {
execute(SCI_MARKERDELETE, i, MARK_HIDELINESEND);
if (scope > 0) scope--;
}
if (openPresent) {
execute(SCI_MARKERDELETE, i, MARK_HIDELINESBEGIN);
++scope;
}
}
if (scope != 0) { //something went wrong
//Someone managed to make overlapping hidelines sections.
//We cant do anything since this isnt supposed to happen
}
_currentBuffer->setHideLineChanged(true, startLine-1);
}
bool ScintillaEditView::markerMarginClick(int lineNumber) {
int state = execute(SCI_MARKERGET, lineNumber);
bool openPresent = ((state & (1 << MARK_HIDELINESBEGIN)) != 0);
bool closePresent = ((state & (1 << MARK_HIDELINESEND)) != 0);
if (!openPresent && !closePresent)
return false;
//Special func on buffer. First call show with location of opening marker. Then remove the marker manually
if (openPresent) {
_currentBuffer->setHideLineChanged(false, lineNumber);
}
if (closePresent) {
openPresent = false;
for(lineNumber--; lineNumber >= 0 && !openPresent; lineNumber--) {
state = execute(SCI_MARKERGET, lineNumber);
openPresent = ((state & (1 << MARK_HIDELINESBEGIN)) != 0);
}
if (openPresent) {
_currentBuffer->setHideLineChanged(false, lineNumber);
}
}
return true;
}
void ScintillaEditView::notifyMarkers(Buffer * buf, bool isHide, int location, bool del) {
if (buf != _currentBuffer) //if not visible buffer dont do a thing
return;
runMarkers(isHide, location, false, del);
}
//Run through full document. When switching in or opening folding
//hide is false only when user click on margin
void ScintillaEditView::runMarkers(bool doHide, int searchStart, bool endOfDoc, bool doDelete) {
//Removes markers if opening
/*
AllLines = (start,ENDOFDOCUMENT)
Hide:
Run through all lines.
Find open hiding marker:
set hiding start
Find closing:
if (hiding):
Hide lines between now and start
if (endOfDoc = false)
return
else
search for other hidden sections
Show:
Run through all lines
Find open hiding marker
set last start
Find closing:
Show from last start. Stop.
Find closed folding header:
Show from last start to folding header
Skip to LASTCHILD
Set last start to lastchild
*/
int maxLines = execute(SCI_GETLINECOUNT);
if (doHide) {
int startHiding = searchStart;
bool isInSection = false;
for(int i = searchStart; i < maxLines; ++i) {
int state = execute(SCI_MARKERGET, i);
if ( ((state & (1 << MARK_HIDELINESEND)) != 0) ) {
if (isInSection) {
execute(SCI_HIDELINES, startHiding, i-1);
if (!endOfDoc) {
return; //done, only single section requested
} //otherwise keep going
}
isInSection = false;
}
if ( ((state & (1 << MARK_HIDELINESBEGIN)) != 0) ) {
isInSection = true;
startHiding = i+1;
}
}
} else {
int startShowing = searchStart;
bool isInSection = false;
for(int i = searchStart; i < maxLines; ++i) {
int state = execute(SCI_MARKERGET, i);
if ( ((state & (1 << MARK_HIDELINESEND)) != 0) ) {
if (doDelete)
execute(SCI_MARKERDELETE, i, MARK_HIDELINESEND);
else if (isInSection) {
if (startShowing >= i) { //because of fold skipping, we passed the close tag. In that case we cant do anything
if (!endOfDoc) {
return;
} else {
continue;
}
}
execute(SCI_SHOWLINES, startShowing, i-1);
if (!endOfDoc) {
return; //done, only single section requested
} //otherwise keep going
isInSection = false;
}
}
if ( ((state & (1 << MARK_HIDELINESBEGIN)) != 0) ) {
if (doDelete)
execute(SCI_MARKERDELETE, i, MARK_HIDELINESBEGIN);
else {
isInSection = true;
startShowing = i+1;
}
}
int levelLine = execute(SCI_GETFOLDLEVEL, i, 0);
if (levelLine & SC_FOLDLEVELHEADERFLAG) { //fold section. Dont show lines if fold is closed
if (isInSection && !isFolded(i)) {
execute(SCI_SHOWLINES, startShowing, i);
startShowing = execute(SCI_GETLASTCHILD, i, (levelLine & SC_FOLDLEVELNUMBERMASK));
}
}
}
}
}
void ScintillaEditView::setTabSettings(Lang *lang)
{
if (lang && lang->_tabSize != -1 && lang->_tabSize != 0)
{
execute(SCI_SETTABWIDTH, lang->_tabSize);
execute(SCI_SETUSETABS, !lang->_isTabReplacedBySpace);
}
else
{
const NppGUI & nppgui = _pParameter->getNppGUI();
execute(SCI_SETTABWIDTH, nppgui._tabSize);
execute(SCI_SETUSETABS, !nppgui._tabReplacedBySpace);
}
}
void ScintillaEditView::insertNewLineAboveCurrentLine()
{
generic_string newline = getEOLString();
const int current_line = getCurrentLineNumber();
if(current_line == 0)
{
// Special handling if caret is at first line.
insertGenericTextFrom(0, newline.c_str());
}
else
{
const int eol_length = newline.length();
const long position = execute(SCI_POSITIONFROMLINE, current_line) - eol_length;
insertGenericTextFrom(position, newline.c_str());
}
execute(SCI_SETEMPTYSELECTION, execute(SCI_POSITIONFROMLINE, current_line));
}
void ScintillaEditView::insertNewLineBelowCurrentLine()
{
generic_string newline = getEOLString();
const int line_count = execute(SCI_GETLINECOUNT);
const int current_line = getCurrentLineNumber();
if(current_line == line_count - 1)
{
// Special handling if caret is at last line.
appandGenericText(newline.c_str());
}
else
{
const int eol_length = newline.length();
const long position = eol_length + execute(SCI_GETLINEENDPOSITION, current_line);
insertGenericTextFrom(position, newline.c_str());
}
execute(SCI_SETEMPTYSELECTION, execute(SCI_POSITIONFROMLINE, current_line + 1));
}
void ScintillaEditView::sortLines(size_t fromLine, size_t toLine, ISorter *pSort)
{
if (fromLine >= toLine)
{
return;
}
const int startPos = execute(SCI_POSITIONFROMLINE, fromLine);
const int endPos = execute(SCI_POSITIONFROMLINE, toLine) + execute(SCI_LINELENGTH, toLine);
const generic_string text = getGenericTextAsString(startPos, endPos);
std::vector<generic_string> splitText = stringSplit(text, getEOLString());
const size_t lineCount = execute(SCI_GETLINECOUNT);
const bool sortEntireDocument = toLine == lineCount - 1;
if (!sortEntireDocument)
{
if (splitText.rbegin()->empty())
{
splitText.pop_back();
}
}
assert(toLine - fromLine + 1 == splitText.size());
const std::vector<generic_string> sortedText = pSort->sort(splitText);
const generic_string joined = stringJoin(sortedText, getEOLString());
if (sortEntireDocument)
{
assert(joined.length() == text.length());
replaceTarget(joined.c_str(), startPos, endPos);
}
else
{
assert(joined.length() + getEOLString().length() == text.length());
replaceTarget((joined + getEOLString()).c_str(), startPos, endPos);
}
}
bool ScintillaEditView::isTextDirectionRTL() const
{
long exStyle = ::GetWindowLongPtr(_hSelf, GWL_EXSTYLE);
return (exStyle & WS_EX_LAYOUTRTL) != 0;
}
void ScintillaEditView::changeTextDirection(bool isRTL)
{
long exStyle = ::GetWindowLongPtr(_hSelf, GWL_EXSTYLE);
exStyle = isRTL ? exStyle | WS_EX_LAYOUTRTL : exStyle&(~WS_EX_LAYOUTRTL);
::SetWindowLongPtr(_hSelf, GWL_EXSTYLE, exStyle);
}
generic_string ScintillaEditView::getEOLString()
{
const int eol_mode = int(execute(SCI_GETEOLMODE));
string newline;
if (eol_mode == SC_EOL_CRLF)
{
return TEXT("\r\n");
}
else if (eol_mode == SC_EOL_LF)
{
return TEXT("\n");
}
else
{
return TEXT("\r");
}
} | gpl-2.0 |
jakeclements/reelgood-wp | wp-content/plugins/events-calendar-pro/resources/tribe-events-ajax-maps.min.js | 7422 | (function(q,m,b,l,h,d,c,a,f,r){b.extend(tribe_ev.fn,{map_add_marker:function(a,d,f,h,l){a=new google.maps.LatLng(a,d);var n=new google.maps.Marker({position:a,map:c.map,title:f}),m=new google.maps.InfoWindow;d=f;l&&(d=b("<div/>").append(b("<a/>").attr("href",l).text(f)).html());f="Event: "+d;h&&(f=f+"<br/>Address: "+h);m.setContent(f);google.maps.event.addListener(n,"click",function(a){m.open(c.map,n)});c.markers.push(n);c.refine&&n.setVisible(!1);c.bounds.extend(a)}});c.geocoder=new google.maps.Geocoder;
c.bounds=new google.maps.LatLngBounds;b(m).ready(function(){function p(){if(b("#tribe-bar-geoloc").length){var a=b("#tribe-bar-geoloc").val(),c=b("#tribe_events_filter_item_geofence"),d=b("#tribe-bar-geoloc-lat, #tribe-bar-geoloc-lng");a.length?c.show():(c.hide(),d.length&&d.val(""))}}function s(){a.ajax_running=!0;a.params={action:"tribe_geosearch",tribe_paged:a.paged,tribe_event_display:a.view};a.category&&(a.params.tribe_event_category=a.category);b(h).trigger("tribe_ev_serializeBar");a.params=
b.param(a.params);b(h).trigger("tribe_ev_collectParams")}function k(){b("#tribe-events-content .tribe-events-loop").tribe_spin();t();a.popping||(s(),a.pushstate=!1,a.initial_load||(a.do_string=!0));b.post(GeoLoc.ajaxurl,a.params,function(e){b(h).trigger("tribe_ev_ajaxStart").trigger("tribe_ev_mapView_AjaxStart");d.enable_inputs("#tribe_events_filters_form","input, select");if(e.success){a.ajax_running=!1;l.ajax_response={total_count:parseInt(e.total_count),view:e.view,max_pages:e.max_pages,tribe_paged:e.tribe_paged,
timestamp:(new Date).getTime()};a.initial_load=!1;var c="",c=b.isFunction(b.fn.parseHTML)?b.parseHTML(e.html):e.html;b("#tribe-events-content").replaceWith(c);"map"===e.view&&(e.max_pages==e.tribe_paged||0==e.max_pages?b(".tribe-events-nav-next").hide():b(".tribe-events-nav-next").show());b.each(e.markers,function(a,b){d.map_add_marker(b.lat,b.lng,b.title,b.address,b.link)});f.pushstate&&(a.page_title=b("#tribe-events-header").data("title"),m.title=a.page_title,a.do_string&&history.pushState({tribe_paged:a.paged,
tribe_params:a.params},a.page_title,l.cur_url+"?"+a.params),a.pushstate&&history.pushState({tribe_paged:a.paged,tribe_params:a.params},a.page_title,l.cur_url));b(h).trigger("tribe_ev_ajaxSuccess").trigger("tribe_ev_mapView_AjaxSuccess");0<e.markers.length&&n()}})}function x(e){"change_view"!=tribe_events_bar_action&&(e.preventDefault(),a.ajax_running||(a.paged=1,a.view="map",a.popping=!1,f.pushstate?d.pre_ajax(function(){k(null)}):d.pre_ajax(function(){b(h).trigger("tribe_ev_reloadOldBrowser")})))}
function t(){if(c.markers){for(i in c.markers)c.markers[i].setMap(null);c.markers.length=0;c.bounds=new google.maps.LatLngBounds}}function n(){c.map.fitBounds(c.bounds);13<c.map.getZoom()&&c.map.setZoom(13)}function u(){b("#tribe-events-footer, #tribe-events-header").find(".tribe-events-ajax-loading").hide()}p();var y=b("#tribe-events"),z=b("#tribe-bar-geoloc"),v=b("#tribe-geo-options"),g={zoom:5,center:new google.maps.LatLng(TribeEventsPro.geocenter.max_lat,TribeEventsPro.geocenter.max_lng),mapTypeId:google.maps.MapTypeId.ROADMAP};
m.getElementById("tribe-geo-map")&&(c.map=new google.maps.Map(m.getElementById("tribe-geo-map"),g),c.bounds=new google.maps.LatLngBounds,g=new google.maps.LatLng(TribeEventsPro.geocenter.min_lat,TribeEventsPro.geocenter.min_lng),c.bounds.extend(g),g=new google.maps.LatLng(TribeEventsPro.geocenter.max_lat,TribeEventsPro.geocenter.max_lng),c.bounds.extend(g));b().placeholder&&b("#tribe-geo-location").placeholder();if(f.map_view()){var g=d.get_url_param("tribe_paged"),A=d.get_url_param("tribe_event_display");
g&&(a.paged=g);a.view="map";"past"==A&&(a.view="past");d.tooltips()}f.map_view()&&l.params?(g=l.params,0<=d.in_params(g,"tribe_geosearch")||(g+="&action=tribe_geosearch"),0<=d.in_params(g,"tribe_paged")||(g+="&tribe_paged=1"),a.params=g,a.do_string=!1,a.pushstate=!1,a.popping=!0,d.pre_ajax(function(){k()})):f.map_view()&&(a.do_string=!1,a.pushstate=!1,a.popping=!1,a.initial_load=!0,d.pre_ajax(function(){k()}));f.pushstate&&f.map_view()&&(history.replaceState({tribe_paged:a.paged,tribe_params:a.params},
"",location.href),b(q).on("popstate",function(b){if(b=b.originalEvent.state)a.do_string=!1,a.pushstate=!1,a.popping=!0,a.params=b.tribe_params,a.paged=b.tribe_paged,d.pre_ajax(function(){k()}),d.set_form(a.params)}));f.map_view()&&(y.on("click",".tribe-geo-option-link",function(e){e.preventDefault();e.stopPropagation();e=b(this);b(".tribe-geo-option-link").removeClass("tribe-option-loaded");e.addClass("tribe-option-loaded");z.val(e.text());b("#tribe-bar-geoloc-lat").val(c.geocodes[e.data("index")].geometry.location.lat());
b("#tribe-bar-geoloc-lng").val(c.geocodes[e.data("index")].geometry.location.lng());a.do_string=!0;a.pushstate=!1;a.popping=!1;f.pushstate?d.pre_ajax(function(){k();v.hide()}):d.pre_ajax(function(){b(h).trigger("tribe_ev_reloadOldBrowser")})}),b(m).on("click",function(){v.hide()}),d.snap("#tribe-events-content-wrapper","#tribe-events-content-wrapper","#tribe-events-footer .tribe-events-nav-previous a, #tribe-events-footer .tribe-events-nav-next a"));b(h).on("tribe_ev_reloadOldBrowser",function(){s();
q.location=l.cur_url+"?"+a.params});if(f.map_view()){var w;b("#tribe-geo-map-wrapper").resize(function(){w=c.map.getCenter();google.maps.event.trigger(c.map,"resize");c.map.setCenter(w)});b("#tribe-events").on("click","li.tribe-events-nav-next a",function(c){c.preventDefault();a.ajax_running||("past"===a.view?"1"==a.paged?a.view="map":a.paged--:a.paged++,a.popping=!1,f.pushstate?d.pre_ajax(function(){k()}):d.pre_ajax(function(){b(h).trigger("tribe_ev_reloadOldBrowser")}))}).on("click","li.tribe-events-nav-previous a",
function(c){c.preventDefault();a.ajax_running||("map"===a.view?"1"==a.paged?a.view="past":a.paged--:a.paged++,a.popping=!1,f.pushstate?d.pre_ajax(function(){k(null)}):d.pre_ajax(function(){b(h).trigger("tribe_ev_reloadOldBrowser")}))})}if(GeoLoc.map_view&&b("form#tribe-bar-form").length&&f.live_ajax()&&f.pushstate||GeoLoc.map_view&&f.no_bar())b("#tribe-events-bar").on("changeDate","#tribe-bar-date",function(a){x(a)});if(GeoLoc.map_view)b(h).on("tribe_ev_runAjax",function(){k()});f.map_view()&&(b("form#tribe-bar-form").on("submit",
function(){if("change_view"!=tribe_events_bar_action){a.paged=1;b("#tribe-events-footer, #tribe-events-header").find(".tribe-events-ajax-loading").show();b(".tribe-events-sub-nav").remove();var e=b("#tribe-bar-geoloc").val();return""!==e?(a.do_string=!0,a.pushstate=!1,a.popping=!1,t(),b("#tribe-geo-results").empty(),b("#tribe-geo-options").hide(),b("#tribe-geo-options #tribe-geo-links").empty(),d.process_geocoding(e,function(a){c.geocodes=a;u();var e=a[0].geometry.location.lat();a=a[0].geometry.location.lng();
e&&b("#tribe-bar-geoloc-lat").val(e);a&&b("#tribe-bar-geoloc-lng").val(a);1<c.geocodes.length?(d.print_geo_options(),p(),n()):f.pushstate?(p(),k(c.geocodes[0])):b(h).trigger("tribe_ev_reloadOldBrowser")}),!1):""===e?(b("#tribe-bar-geoloc-lat").val(""),b("#tribe-bar-geoloc-lng").val(""),b("#tribe-geo-options").hide(),f.pushstate?(a.do_string=!0,a.pushstate=!1,a.popping=!1,p(),k()):b(h).trigger("tribe_ev_reloadOldBrowser"),u(),!1):!0}}),a.view&&r&&debug.timeEnd("Tribe JS Init Timer"));r&&debug.info("TEC Debug: tribe-events-ajax-maps.js successfully loaded")})})(window,
document,jQuery,tribe_ev.data,tribe_ev.events,tribe_ev.fn,tribe_ev.geoloc,tribe_ev.state,tribe_ev.tests,tribe_debug);
| gpl-2.0 |
ppriest/mame | src/devices/machine/mos6702.cpp | 1739 | // license:BSD-3-Clause
// copyright-holders:Curt Coder
/**********************************************************************
MOS Technology 6702 Mystery Device emulation
**********************************************************************/
#include "mos6702.h"
//**************************************************************************
// MACROS / CONSTANTS
//**************************************************************************
#define LOG 0
//**************************************************************************
// DEVICE DEFINITIONS
//**************************************************************************
const device_type MOS6702 = &device_creator<mos6702_device>;
//**************************************************************************
// LIVE DEVICE
//**************************************************************************
//-------------------------------------------------
// mos6702_device - constructor
//-------------------------------------------------
mos6702_device::mos6702_device(const machine_config &mconfig, const char *tag, device_t *owner, UINT32 clock)
: device_t(mconfig, MOS6702, "MOS6702", tag, owner, clock, "mos6702", __FILE__)
{
}
//-------------------------------------------------
// device_start - device-specific startup
//-------------------------------------------------
void mos6702_device::device_start()
{
}
//-------------------------------------------------
// read -
//-------------------------------------------------
READ8_MEMBER( mos6702_device::read )
{
return 0;
}
//-------------------------------------------------
// write -
//-------------------------------------------------
WRITE8_MEMBER( mos6702_device::write )
{
}
| gpl-2.0 |
RedlineResearch/OpenJDK8 | jdk/src/share/classes/javax/swing/tree/TreeNode.java | 2785 | /*
* Copyright (c) 1997, 2013, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package javax.swing.tree;
import java.util.Enumeration;
/**
* Defines the requirements for an object that can be used as a
* tree node in a JTree.
* <p>
* Implementations of <code>TreeNode</code> that override <code>equals</code>
* will typically need to override <code>hashCode</code> as well. Refer
* to {@link javax.swing.tree.TreeModel} for more information.
*
* For further information and examples of using tree nodes,
* see <a
href="http://docs.oracle.com/javase/tutorial/uiswing/components/tree.html">How to Use Tree Nodes</a>
* in <em>The Java Tutorial.</em>
*
* @author Rob Davis
* @author Scott Violet
*/
public interface TreeNode
{
/**
* Returns the child <code>TreeNode</code> at index
* <code>childIndex</code>.
*/
TreeNode getChildAt(int childIndex);
/**
* Returns the number of children <code>TreeNode</code>s the receiver
* contains.
*/
int getChildCount();
/**
* Returns the parent <code>TreeNode</code> of the receiver.
*/
TreeNode getParent();
/**
* Returns the index of <code>node</code> in the receivers children.
* If the receiver does not contain <code>node</code>, -1 will be
* returned.
*/
int getIndex(TreeNode node);
/**
* Returns true if the receiver allows children.
*/
boolean getAllowsChildren();
/**
* Returns true if the receiver is a leaf.
*/
boolean isLeaf();
/**
* Returns the children of the receiver as an <code>Enumeration</code>.
*/
Enumeration children();
}
| gpl-2.0 |
ezecosystem/ezpublish-kernel | eZ/Publish/Core/Search/Common/Slot/CreateUser.php | 1353 | <?php
/**
* This file is part of the eZ Publish Kernel package.
*
* @copyright Copyright (C) eZ Systems AS. All rights reserved.
* @license For full copyright and license information view LICENSE file distributed with this source code.
*/
namespace eZ\Publish\Core\Search\Common\Slot;
use eZ\Publish\Core\SignalSlot\Signal;
use eZ\Publish\Core\Search\Common\Slot;
/**
* A Search Engine slot handling CreateUserSignal.
*/
class CreateUser extends Slot
{
/**
* Receive the given $signal and react on it.
*
* @param \eZ\Publish\Core\SignalSlot\Signal $signal
*/
public function receive(Signal $signal)
{
if (!$signal instanceof Signal\UserService\CreateUserSignal) {
return;
}
$userContentInfo = $this->persistenceHandler->contentHandler()->loadContentInfo(
$signal->userId
);
$this->searchHandler->indexContent(
$this->persistenceHandler->contentHandler()->load(
$userContentInfo->id,
$userContentInfo->currentVersionNo
)
);
$locations = $this->persistenceHandler->locationHandler()->loadLocationsByContent(
$userContentInfo->id
);
foreach ($locations as $location) {
$this->searchHandler->indexLocation($location);
}
}
}
| gpl-2.0 |
Sulcata/pokemon-online | src/Server/serverconfig.cpp | 7678 | #include <QFormLayout>
#include <QComboBox>
#include <QPlainTextEdit>
#include <QSpinBox>
#include <QCheckBox>
#include <QMessageBox>
#include "serverconfig.h"
#include "server.h"
#include <Utilities/otherwidgets.h>
ServerWindow::ServerWindow(QWidget *parent) : QWidget(parent)
{
setAttribute(Qt::WA_DeleteOnClose);
QFormLayout *l = new QFormLayout(this);
QSettings settings("config", QSettings::IniFormat);
serverPrivate = new QComboBox;
serverPrivate->addItem("Public");
serverPrivate->addItem("Private");
serverPrivate->setCurrentIndex(settings.value("Server/Private").toInt());
l->addRow("Public/Private: ", serverPrivate);
serverName = new QLineEdit(settings.value("Server/Name").toString());
mainChan = new QLineEdit(settings.value("Channels/MainChannel").toString());
serverName->setValidator(new QNickValidator(serverName));
mainChan->setValidator(new QNickValidator(mainChan));
l->addRow("Server Name: ", serverName);
l->addRow("Main Channel: ", mainChan);
serverDesc = new QPlainTextEdit(settings.value("Server/Description").toString());
l->addRow("Server Description: ", serverDesc);
serverAnnouncement = new QPlainTextEdit(settings.value("Server/Announcement").toString());
l->addRow("Announcement: ", serverAnnouncement);
serverPlayerMax = new QSpinBox();
serverPlayerMax->setRange(0,5000);
serverPlayerMax->setSpecialValueText(tr("unlimited"));
serverPlayerMax->setSingleStep(10);
serverPlayerMax->setValue(settings.value("Server/MaxPlayers").toInt());
l->addRow("Max Players: ", serverPlayerMax);
serverPort = new QSpinBox();
serverPort->setRange(0,65535);
if(settings.value("Network/Ports").toInt() == 0)
serverPort->setValue(5080);
else
serverPort->setValue(settings.value("Network/Ports").toInt());
l->addRow("Port(requires restart): ", serverPort);
QPushButton *ok, *cancel;
l->addRow("Extended Logging: ", saveLogs = new QCheckBox("Show all player events and all logging"));
saveLogs->setChecked(settings.value("GUI/ShowLogMessages").toBool());
l->addRow("File Logging for Channels: ", channelFileLog = new QCheckBox("Save channel messages to daily rotating log files"));
channelFileLog->setChecked(settings.value("Channels/LoggingEnabled").toBool());
l->addRow("Delete inactive members in a period of (Days):", deleteInactive = new QSpinBox());
deleteInactive->setRange(1, 728);
if(settings.value("Players/InactiveThresholdInDays").isNull()) {
deleteInactive->setValue(182);
} else {
deleteInactive->setValue(settings.value("Players/InactiveThresholdInDays").toInt());
}
l->addRow("Low Latency: ", lowLatency = new QCheckBox("Sacrifices bandwith for latency (look up Nagle's algorithm)"));
lowLatency->setChecked(settings.value("Network/LowTCPDelay").toBool());
l->addRow("Safe scripts: ", safeScripts = new QCheckBox("Restricts some script functions to improve security."));
safeScripts->setChecked(settings.value("Scripts/SafeMode").toBool());
l->addRow("Minimize to tray: ", minimizeToTray = new QCheckBox("Hide to tray when minimized/switch desktop."));
minimizeToTray->setChecked(settings.value("GUI/MinimizeToTray").toBool());
l->addRow("Show tray popup: ", trayPopup = new QCheckBox("Show tooltip when PO is minimized to tray."));
trayPopup->setChecked(settings.value("GUI/ShowTrayPopup").toBool());
l->addRow("Double Click tray icon", doubleClick = new QCheckBox("Double click to reopen when PO is minimized to tray."));
doubleClick->setChecked(settings.value("GUI/DoubleClickIcon").toBool());
l->addRow("Show Overactive Messages: ", showOveractive = new QCheckBox("Show Overactive Message when someone goes overactive"));
showOveractive->setChecked(settings.value("AntiDOS/ShowOveractiveMessages").toBool());
l->addRow("Proxy Servers: ", proxyServers = new QLineEdit(settings.value("Network/ProxyServers").toString()));
l->addRow(usePassword = new QCheckBox("Require Password: "), serverPassword = new QLineEdit(settings.value("Server/Password").toString()));
usePassword->setChecked(settings.value("Server/RequirePassword").toBool());
minHtml = new QComboBox;
minHtml->addItem("Disabled");
minHtml->addItem("All users");
minHtml->addItem("Moderators and above");
minHtml->addItem("Administrators and above");
minHtml->addItem("Owners and above");
minHtml->addItem("Auth 4 only");
minHtml->setCurrentIndex(settings.value("Server/MinimumHTML").toInt() + 1);
l->addRow("Set who can use html: ", minHtml);
ok = new QPushButton("&Apply");
cancel = new QPushButton("&Cancel");
l->addRow(ok, cancel);
connect(cancel, SIGNAL(clicked()), SLOT(close()));
connect(ok, SIGNAL(clicked()), SLOT(apply()));
}
void ServerWindow::apply()
{
if (usePassword->isChecked() && serverPassword->text().length() == 0) {
QMessageBox msgBox;
msgBox.setText("You need to set the server password if you require it.");
msgBox.exec();
return;
}
QSettings settings("config", QSettings::IniFormat);
settings.setValue("Server/Private", serverPrivate->currentIndex());
settings.setValue("Server/Name", serverName->text());
settings.setValue("Server/Description", serverDesc->toPlainText());
settings.setValue("Server/MaxPlayers", serverPlayerMax->text());
settings.setValue("Network/Ports", serverPort->text());
settings.setValue("Server/Announcement", serverAnnouncement->toPlainText());
settings.setValue("GUI/ShowLogMessages", saveLogs->isChecked());
settings.setValue("Channels/LoggingEnabled", channelFileLog->isChecked());
settings.setValue("Players/InactiveThresholdInDays", deleteInactive->text());
settings.setValue("Channels/MainChannel", mainChan->text());
settings.setValue("Network/LowTCPDelay", lowLatency->isChecked());
settings.setValue("Scripts/SafeMode", safeScripts->isChecked());
settings.setValue("GUI/MinimizeToTray", minimizeToTray->isChecked());
settings.setValue("GUI/ShowTrayPopup", trayPopup->isChecked());
settings.setValue("GUI/DoubleClickIcon", doubleClick->isChecked());
settings.setValue("AntiDOS/ShowOveractiveMessages", showOveractive->isChecked());
settings.setValue("Network/ProxyServers", proxyServers->text());
settings.setValue("Server/Password", serverPassword->text());
settings.setValue("Server/RequirePassword", usePassword->isChecked());
settings.setValue("Server/MinimumHTML", minHtml->currentIndex() - 1);
emit descChanged(serverDesc->toPlainText());
emit nameChanged(serverName->text());
emit maxChanged(serverPlayerMax->value());
emit announcementChanged(serverAnnouncement->toPlainText());
emit privacyChanged(serverPrivate->currentIndex());
emit logSavingChanged(saveLogs->isChecked());
emit useChannelFileLogChanged(channelFileLog->isChecked());
emit mainChanChanged(mainChan->text());
emit inactivePlayersDeleteDaysChanged(deleteInactive->value());
emit latencyChanged(lowLatency->isChecked());
emit safeScriptsChanged(safeScripts->isChecked());
emit overactiveToggleChanged(showOveractive->isChecked());
emit proxyServersChanged(proxyServers->text());
emit serverPasswordChanged(serverPassword->text());
emit usePasswordChanged(usePassword->isChecked());
emit minimizeToTrayChanged(minimizeToTray->isChecked());
emit showTrayPopupChanged(trayPopup->isChecked());
emit clickConditionChanged(doubleClick->isChecked());
emit minHtmlChanged(minHtml->currentIndex() - 1);
close();
}
| gpl-3.0 |
ctruchi/deluge-webui2 | deluge/pluginmanagerbase.py | 7806 | #
# pluginmanagerbase.py
#
# Copyright (C) 2007 Andrew Resch <andrewresch@gmail.com>
#
# Deluge is free software.
#
# You may redistribute it and/or modify it under the terms of the
# GNU General Public License, as published by the Free Software
# Foundation; either version 3 of the License, or (at your option)
# any later version.
#
# deluge is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
# See the GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with deluge. If not, write to:
# The Free Software Foundation, Inc.,
# 51 Franklin Street, Fifth Floor
# Boston, MA 02110-1301, USA.
#
# In addition, as a special exception, the copyright holders give
# permission to link the code of portions of this program with the OpenSSL
# library.
# You must obey the GNU General Public License in all respects for all of
# the code used other than OpenSSL. If you modify file(s) with this
# exception, you may extend this exception to your version of the file(s),
# but you are not obligated to do so. If you do not wish to do so, delete
# this exception statement from your version. If you delete this exception
# statement from all source files in the program, then also delete it here.
#
#
"""PluginManagerBase"""
import os.path
import logging
import pkg_resources
import deluge.common
import deluge.configmanager
import deluge.component as component
log = logging.getLogger(__name__)
METADATA_KEYS = [
"Name",
"License",
"Author",
"Home-page",
"Summary",
"Platform",
"Version",
"Author-email",
"Description",
]
DEPRECATION_WARNING = """
The plugin %s is not using the "deluge.plugins" namespace.
In order to avoid package name clashes between regular python packages and
deluge plugins, the way deluge plugins should be created has changed.
If you're seeing this message and you're not the developer of the plugin which
triggered this warning, please report to it's author.
If you're the developer, please take a look at the plugins hosted on deluge's
git repository to have an idea of what needs to be changed.
"""
class PluginManagerBase:
"""PluginManagerBase is a base class for PluginManagers to inherit"""
def __init__(self, config_file, entry_name):
log.debug("Plugin manager init..")
self.config = deluge.configmanager.ConfigManager(config_file)
# Create the plugins folder if it doesn't exist
if not os.path.exists(os.path.join(deluge.configmanager.get_config_dir(), "plugins")):
os.mkdir(os.path.join(deluge.configmanager.get_config_dir(), "plugins"))
# This is the entry we want to load..
self.entry_name = entry_name
# Loaded plugins
self.plugins = {}
# Scan the plugin folders for plugins
self.scan_for_plugins()
def enable_plugins(self):
# Load plugins that are enabled in the config.
for name in self.config["enabled_plugins"]:
self.enable_plugin(name)
def disable_plugins(self):
# Disable all plugins that are enabled
for key in self.plugins.keys():
self.disable_plugin(key)
def __getitem__(self, key):
return self.plugins[key]
def get_available_plugins(self):
"""Returns a list of the available plugins name"""
return self.available_plugins
def get_enabled_plugins(self):
"""Returns a list of enabled plugins"""
return self.plugins.keys()
def scan_for_plugins(self):
"""Scans for available plugins"""
base_plugin_dir = deluge.common.resource_filename("deluge", "plugins")
pkg_resources.working_set.add_entry(base_plugin_dir)
user_plugin_dir = os.path.join(deluge.configmanager.get_config_dir(), "plugins")
plugins_dirs = [base_plugin_dir]
for dirname in os.listdir(base_plugin_dir):
plugin_dir = os.path.join(base_plugin_dir, dirname)
pkg_resources.working_set.add_entry(plugin_dir)
plugins_dirs.append(plugin_dir)
pkg_resources.working_set.add_entry(user_plugin_dir)
plugins_dirs.append(user_plugin_dir)
self.pkg_env = pkg_resources.Environment(plugins_dirs)
self.available_plugins = []
for name in self.pkg_env:
log.debug("Found plugin: %s %s at %s",
self.pkg_env[name][0].project_name,
self.pkg_env[name][0].version,
self.pkg_env[name][0].location)
self.available_plugins.append(self.pkg_env[name][0].project_name)
def enable_plugin(self, plugin_name):
"""Enables a plugin"""
if plugin_name not in self.available_plugins:
log.warning("Cannot enable non-existant plugin %s", plugin_name)
return
if plugin_name in self.plugins:
log.warning("Cannot enable already enabled plugin %s", plugin_name)
return
plugin_name = plugin_name.replace(" ", "-")
egg = self.pkg_env[plugin_name][0]
egg.activate()
for name in egg.get_entry_map(self.entry_name):
entry_point = egg.get_entry_info(self.entry_name, name)
try:
cls = entry_point.load()
instance = cls(plugin_name.replace("-", "_"))
except Exception, e:
log.error("Unable to instantiate plugin %r from %r!",
name, egg.location)
log.exception(e)
continue
instance.enable()
if not instance.__module__.startswith("deluge.plugins."):
import warnings
warnings.warn_explicit(
DEPRECATION_WARNING % name,
DeprecationWarning,
instance.__module__, 0
)
if self._component_state == "Started":
component.start([instance.plugin._component_name])
plugin_name = plugin_name.replace("-", " ")
self.plugins[plugin_name] = instance
if plugin_name not in self.config["enabled_plugins"]:
log.debug("Adding %s to enabled_plugins list in config",
plugin_name)
self.config["enabled_plugins"].append(plugin_name)
log.info("Plugin %s enabled..", plugin_name)
def disable_plugin(self, name):
"""Disables a plugin"""
try:
self.plugins[name].disable()
component.deregister(self.plugins[name].plugin)
del self.plugins[name]
self.config["enabled_plugins"].remove(name)
except KeyError:
log.warning("Plugin %s is not enabled..", name)
log.info("Plugin %s disabled..", name)
def get_plugin_info(self, name):
"""Returns a dictionary of plugin info from the metadata"""
info = {}.fromkeys(METADATA_KEYS)
last_header = ""
cont_lines = []
for line in self.pkg_env[name][0].get_metadata("PKG-INFO").splitlines():
if not line:
continue
if line[0] in ' \t' and (len(line.split(":", 1)) == 1 or line.split(":", 1)[0] not in info.keys()):
# This is a continuation
cont_lines.append(line.strip())
else:
if cont_lines:
info[last_header] = "\n".join(cont_lines).strip()
cont_lines = []
if line.split(":", 1)[0] in info.keys():
last_header = line.split(":", 1)[0]
info[last_header] = line.split(":", 1)[1].strip()
return info
| gpl-3.0 |
cfjhallgren/shogun | examples/undocumented/python/structure_plif_hmsvm_bmrm.py | 854 | #!/usr/bin/env python
parameter_list=[[50, 125, 10, 2]]
def structure_plif_hmsvm_bmrm (num_examples, example_length, num_features, num_noise_features):
from shogun import RealMatrixFeatures, TwoStateModel, StructuredAccuracy
try:
from shogun import DualLibQPBMSOSVM
except ImportError:
print("DualLibQPBMSOSVM not available")
exit(0)
model = TwoStateModel.simulate_data(num_examples, example_length, num_features, num_noise_features)
sosvm = DualLibQPBMSOSVM(model, model.get_labels(), 5000.0)
sosvm.set_store_train_info(False)
sosvm.train()
#print sosvm.get_w()
predicted = sosvm.apply(model.get_features())
evaluator = StructuredAccuracy()
acc = evaluator.evaluate(predicted, model.get_labels())
#print('Accuracy = %.4f' % acc)
if __name__ == '__main__':
print("PLiF HMSVM BMRM")
structure_plif_hmsvm_bmrm(*parameter_list[0])
| gpl-3.0 |
Velociraptor85/pyload | module/plugins/hoster/FilejungleCom.py | 857 | # -*- coding: utf-8 -*-
from .FileserveCom import FileserveCom
class FilejungleCom(FileserveCom):
__name__ = "FilejungleCom"
__type__ = "hoster"
__version__ = "0.57"
__status__ = "testing"
__pattern__ = r'http://(?:www\.)?filejungle\.com/f/(?P<ID>[^/]+)'
__config__ = [("activated", "bool", "Activated", True)]
__description__ = """Filejungle.com hoster plugin"""
__license__ = "GPLv3"
__authors__ = [("zoidberg", "zoidberg@mujmail.cz")]
URLS = ["http://www.filejungle.com/f/", "http://www.filejungle.com/check_links.php",
"http://www.filejungle.com/checkReCaptcha.php"]
LINKCHECK_TR = r'<li>\s*(<div class="col1">.*?)</li>'
LINKCHECK_TD = r'<div class="(?:col )?col\d">(?:<.*?>| )*([^<]*)'
LONG_WAIT_PATTERN = r'<h1>Please wait for (\d+) (\w+)\s*to download the next file\.</h1>'
| gpl-3.0 |
Zapuss/ZapekFapeCore | src/server/scripts/Northrend/Nexus/Nexus/boss_keristrasza.cpp | 9603 | /*
* Copyright (C) 2011-2012 Project SkyFire <http://www.projectskyfire.org/>
* Copyright (C) 2008-2012 TrinityCore <http://www.trinitycore.org/>
* Copyright (C) 2006-2012 ScriptDev2 <https://scriptdev2.svn.sourceforge.net/>
*
* This program is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License as published by the
* Free Software Foundation; either version 3 of the License, or (at your
* option) any later version.
*
* This program is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
* more details.
*
* You should have received a copy of the GNU General Public License along
* with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include "ScriptPCH.h"
#include "nexus.h"
enum Spells
{
//Spells
SPELL_FROZEN_PRISON = 47854,
SPELL_TAIL_SWEEP = 50155,
SPELL_CRYSTAL_CHAINS = 50997,
SPELL_ENRAGE = 8599,
SPELL_CRYSTALFIRE_BREATH = 48096,
H_SPELL_CRYSTALFIRE_BREATH = 57091,
SPELL_CRYSTALIZE = 48179,
SPELL_INTENSE_COLD = 48094,
SPELL_INTENSE_COLD_TRIGGERED = 48095
};
enum Yells
{
//Yell
SAY_AGGRO = -1576040,
SAY_SLAY = -1576041,
SAY_ENRAGE = -1576042,
SAY_DEATH = -1576043,
SAY_CRYSTAL_NOVA = -1576044
};
enum Misc
{
DATA_INTENSE_COLD = 1,
DATA_CONTAINMENT_SPHERES = 3,
};
class boss_keristrasza : public CreatureScript
{
public:
boss_keristrasza() : CreatureScript("boss_keristrasza") { }
CreatureAI* GetAI(Creature* creature) const
{
return new boss_keristraszaAI (creature);
}
struct boss_keristraszaAI : public ScriptedAI
{
boss_keristraszaAI(Creature* creature) : ScriptedAI(creature)
{
instance = creature->GetInstanceScript();
}
InstanceScript* instance;
std::list<uint64> intenseColdList;
uint64 auiContainmentSphereGUIDs[DATA_CONTAINMENT_SPHERES];
uint32 uiCrystalfireBreathTimer;
uint32 uiCrystalChainsCrystalizeTimer;
uint32 uiTailSweepTimer;
bool intenseCold;
bool bEnrage;
void Reset()
{
uiCrystalfireBreathTimer = 14*IN_MILLISECONDS;
uiCrystalChainsCrystalizeTimer = DUNGEON_MODE(30*IN_MILLISECONDS, 11*IN_MILLISECONDS);
uiTailSweepTimer = 5*IN_MILLISECONDS;
bEnrage = false;
intenseCold = true;
intenseColdList.clear();
me->RemoveFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_STUNNED);
RemovePrison(CheckContainmentSpheres());
if (instance)
instance->SetData(DATA_KERISTRASZA_EVENT, NOT_STARTED);
}
void EnterCombat(Unit* /*who*/)
{
DoScriptText(SAY_AGGRO, me);
DoCastAOE(SPELL_INTENSE_COLD);
if (instance)
instance->SetData(DATA_KERISTRASZA_EVENT, IN_PROGRESS);
}
void JustDied(Unit* /*killer*/)
{
DoScriptText(SAY_DEATH, me);
if (instance)
instance->SetData(DATA_KERISTRASZA_EVENT, DONE);
}
void KilledUnit(Unit* /*victim*/)
{
DoScriptText(SAY_SLAY, me);
}
bool CheckContainmentSpheres(bool remove_prison = false)
{
if (!instance)
return false;
auiContainmentSphereGUIDs[0] = instance->GetData64(ANOMALUS_CONTAINMET_SPHERE);
auiContainmentSphereGUIDs[1] = instance->GetData64(ORMOROKS_CONTAINMET_SPHERE);
auiContainmentSphereGUIDs[2] = instance->GetData64(TELESTRAS_CONTAINMET_SPHERE);
GameObject* ContainmentSpheres[DATA_CONTAINMENT_SPHERES];
for (uint8 i = 0; i < DATA_CONTAINMENT_SPHERES; ++i)
{
ContainmentSpheres[i] = instance->instance->GetGameObject(auiContainmentSphereGUIDs[i]);
if (!ContainmentSpheres[i])
return false;
if (ContainmentSpheres[i]->GetGoState() != GO_STATE_ACTIVE)
return false;
}
if (remove_prison)
RemovePrison(true);
return true;
}
void RemovePrison(bool remove)
{
if (remove)
{
me->RemoveFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_IMMUNE_TO_PC);
me->RemoveFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_NON_ATTACKABLE);
if (me->HasAura(SPELL_FROZEN_PRISON))
me->RemoveAurasDueToSpell(SPELL_FROZEN_PRISON);
}
else
{
me->SetFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_IMMUNE_TO_PC);
me->SetFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_NON_ATTACKABLE);
DoCast(me, SPELL_FROZEN_PRISON, false);
}
}
void SetGUID(uint64 guid, int32 id/* = 0 */)
{
if (id == DATA_INTENSE_COLD)
intenseColdList.push_back(guid);
}
void UpdateAI(const uint32 diff)
{
if (!UpdateVictim())
return;
if (!bEnrage && HealthBelowPct(25))
{
DoScriptText(SAY_ENRAGE, me);
DoCast(me, SPELL_ENRAGE);
bEnrage = true;
}
if (uiCrystalfireBreathTimer <= diff)
{
DoCast(me->getVictim(), SPELL_CRYSTALFIRE_BREATH);
uiCrystalfireBreathTimer = 14*IN_MILLISECONDS;
} else uiCrystalfireBreathTimer -= diff;
if (uiTailSweepTimer <= diff)
{
DoCast(me, SPELL_TAIL_SWEEP);
uiTailSweepTimer = 5*IN_MILLISECONDS;
} else uiTailSweepTimer -= diff;
if (uiCrystalChainsCrystalizeTimer <= diff)
{
DoScriptText(SAY_CRYSTAL_NOVA, me);
if (IsHeroic())
DoCast(me, SPELL_CRYSTALIZE);
else if (Unit* target = SelectTarget(SELECT_TARGET_RANDOM, 0, 100, true))
DoCast(target, SPELL_CRYSTAL_CHAINS);
uiCrystalChainsCrystalizeTimer = DUNGEON_MODE(30*IN_MILLISECONDS, 11*IN_MILLISECONDS);
} else uiCrystalChainsCrystalizeTimer -= diff;
DoMeleeAttackIfReady();
}
};
};
class containment_sphere : public GameObjectScript
{
public:
containment_sphere() : GameObjectScript("containment_sphere") { }
bool OnGossipHello(Player* /*player*/, GameObject* pGO)
{
InstanceScript* instance = pGO->GetInstanceScript();
Creature* pKeristrasza = Unit::GetCreature(*pGO, instance ? instance->GetData64(DATA_KERISTRASZA) : 0);
if (pKeristrasza && pKeristrasza->isAlive())
{
// maybe these are hacks :(
pGO->SetFlag(GAMEOBJECT_FLAGS, GO_FLAG_NOT_SELECTABLE);
pGO->SetGoState(GO_STATE_ACTIVE);
CAST_AI(boss_keristrasza::boss_keristraszaAI, pKeristrasza->AI())->CheckContainmentSpheres(true);
}
return true;
}
};
class spell_intense_cold : public SpellScriptLoader
{
public:
spell_intense_cold() : SpellScriptLoader("spell_intense_cold") { }
class spell_intense_cold_AuraScript : public AuraScript
{
PrepareAuraScript(spell_intense_cold_AuraScript);
void HandlePeriodicTick(AuraEffect const* aurEff)
{
if (aurEff->GetBase()->GetStackAmount() < 2)
return;
Unit* caster = GetCaster();
//TODO: the caster should be boss but not the player
if (!caster || !caster->GetAI())
return;
caster->GetAI()->SetGUID(GetTarget()->GetGUID(), DATA_INTENSE_COLD);
}
void Register()
{
OnEffectPeriodic += AuraEffectPeriodicFn(spell_intense_cold_AuraScript::HandlePeriodicTick, EFFECT_1, SPELL_AURA_PERIODIC_DAMAGE);
}
};
AuraScript* GetAuraScript() const
{
return new spell_intense_cold_AuraScript();
}
};
class achievement_intense_cold : public AchievementCriteriaScript
{
public:
achievement_intense_cold() : AchievementCriteriaScript("achievement_intense_cold")
{
}
bool OnCheck(Player* player, Unit* target)
{
if (!target)
return false;
std::list<uint64> intenseColdList = CAST_AI(boss_keristrasza::boss_keristraszaAI, target->ToCreature()->AI())->intenseColdList;
if (!intenseColdList.empty())
for (std::list<uint64>::iterator itr = intenseColdList.begin(); itr != intenseColdList.end(); ++itr)
if (player->GetGUID() == *itr)
return false;
return true;
}
};
void AddSC_boss_keristrasza()
{
new boss_keristrasza();
new containment_sphere();
new achievement_intense_cold();
new spell_intense_cold();
} | gpl-3.0 |