text
stringlengths 2
100k
| meta
dict |
---|---|
/**
* 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.hadoop.io.erasurecode.rawcoder;
import org.apache.hadoop.HadoopIllegalArgumentException;
import org.apache.hadoop.classification.InterfaceAudience;
import java.nio.ByteBuffer;
/**
* A utility class that maintains encoding state during an encode call using
* byte array inputs.
*/
@InterfaceAudience.Private
class ByteArrayEncodingState extends EncodingState {
byte[][] inputs;
byte[][] outputs;
int[] inputOffsets;
int[] outputOffsets;
ByteArrayEncodingState(RawErasureEncoder encoder,
byte[][] inputs, byte[][] outputs) {
this.encoder = encoder;
byte[] validInput = CoderUtil.findFirstValidInput(inputs);
this.encodeLength = validInput.length;
this.inputs = inputs;
this.outputs = outputs;
checkParameters(inputs, outputs);
checkBuffers(inputs);
checkBuffers(outputs);
this.inputOffsets = new int[inputs.length]; // ALL ZERO
this.outputOffsets = new int[outputs.length]; // ALL ZERO
}
ByteArrayEncodingState(RawErasureEncoder encoder,
int encodeLength,
byte[][] inputs,
int[] inputOffsets,
byte[][] outputs,
int[] outputOffsets) {
this.encoder = encoder;
this.encodeLength = encodeLength;
this.inputs = inputs;
this.outputs = outputs;
this.inputOffsets = inputOffsets;
this.outputOffsets = outputOffsets;
}
/**
* Convert to a ByteBufferEncodingState when it's backed by on-heap arrays.
*/
ByteBufferEncodingState convertToByteBufferState() {
ByteBuffer[] newInputs = new ByteBuffer[inputs.length];
ByteBuffer[] newOutputs = new ByteBuffer[outputs.length];
for (int i = 0; i < inputs.length; i++) {
newInputs[i] = CoderUtil.cloneAsDirectByteBuffer(inputs[i],
inputOffsets[i], encodeLength);
}
for (int i = 0; i < outputs.length; i++) {
newOutputs[i] = ByteBuffer.allocateDirect(encodeLength);
}
ByteBufferEncodingState bbeState = new ByteBufferEncodingState(encoder,
encodeLength, newInputs, newOutputs);
return bbeState;
}
/**
* Check and ensure the buffers are of the desired length.
* @param buffers the buffers to check
*/
void checkBuffers(byte[][] buffers) {
for (byte[] buffer : buffers) {
if (buffer == null) {
throw new HadoopIllegalArgumentException(
"Invalid buffer found, not allowing null");
}
if (buffer.length != encodeLength) {
throw new HadoopIllegalArgumentException(
"Invalid buffer not of length " + encodeLength);
}
}
}
}
|
{
"pile_set_name": "Github"
}
|
import h5py
import numpy as np
from .core import CompartmentReaderABC
from bmtk.utils.hdf5_helper import get_attribute_h5
class _CompartmentPopulationReaderVer01(CompartmentReaderABC):
sonata_columns = ['element_ids', 'element_pos', 'index_pointer', 'node_ids', 'time']
def __init__(self, pop_grp, pop_name):
self._data_grp = pop_grp['data']
self._mapping = pop_grp['mapping']
self._population = pop_name
self._gid2data_table = {}
if self._mapping is None:
raise Exception('could not find /mapping group')
gids_ds = self._mapping[self.node_ids_ds] # ['node_ids']
index_pointer_ds = self._mapping['index_pointer']
for indx, gid in enumerate(gids_ds):
self._gid2data_table[gid] = slice(index_pointer_ds[indx], index_pointer_ds[indx+1])
time_ds = self._mapping['time']
self._t_start = np.float(time_ds[0])
self._t_stop = np.float(time_ds[1])
self._dt = np.float(time_ds[2])
self._n_steps = int((self._t_stop - self._t_start) / self._dt)
self._custom_cols = {col: grp for col, grp in self._mapping.items() if
col not in self.sonata_columns and isinstance(grp, h5py.Dataset)}
def _get_index(self, node_id):
return self._gid2data_table[node_id]
@property
def populations(self):
return [self._population]
@property
def data_ds(self):
return self._data_grp
@property
def node_ids_ds(self):
return 'node_ids'
def get_population(self, population, default=None):
raise NotImplementedError()
def units(self, population=None):
return get_attribute_h5(self.data_ds, 'units', None)
#return self.data_ds.attrs.get('units', None)
def variable(self, population=None):
return get_attribute_h5(self.data_ds, 'variable', None)
#return self.data_ds.attrs.get('variable', None)
def tstart(self, population=None):
return self._t_start
def tstop(self, population=None):
return self._t_stop
def dt(self, population=None):
return self._dt
def n_steps(self, population=None):
return self._n_steps
def time(self, population=None):
return self._mapping['time'][()]
def time_trace(self, population=None):
return np.linspace(self.tstart(), self.tstop(), num=self._n_steps, endpoint=True)
def node_ids(self, population=None):
return self._mapping['node_ids'][()]
def index_pointer(self, population=None):
return self._mapping['index_pointer'][()]
def element_pos(self, node_id=None, population=None):
if node_id is None:
return self._mapping['element_pos'][()]
else:
return self._mapping['element_pos'][self._get_index(node_id)]#[indx_beg:indx_end]
def element_ids(self, node_id=None, population=None):
if node_id is None:
return self._mapping['element_ids'][()]
else:
#indx_beg, indx_end = self._get_index(node_id)
#return self._mapping['element_ids'][self._get_index(node_id)]#[indx_beg:indx_end]
return self._mapping['element_ids'][self._get_index(node_id)]
def n_elements(self, node_id=None, population=None):
return len(self.element_pos(node_id))
def data(self, node_id=None, population=None, time_window=None, sections='all', **opts):
# filtered_data = self._data_grp
multi_compartments = True
if node_id is not None:
node_range = self._get_index(node_id)
if sections == 'origin' or self.n_elements(node_id) == 1:
# Return the first (and possibly only) compartment for said gid
gid_slice = node_range
multi_compartments = False
elif sections == 'all':
# Return all compartments
gid_slice = node_range #slice(node_beg, node_end)
else:
# return all compartments with corresponding element id
compartment_list = list(sections) if np.isscalar(sections) else sections
gid_slice = [i for i in self._get_index(node_id) if self._mapping['element_ids'] in compartment_list]
else:
gid_slice = slice(0, self._data_grp.shape[1])
if time_window is None:
time_slice = slice(0, self._n_steps)
else:
if len(time_window) != 2:
raise Exception('Invalid time_window, expecting tuple [being, end].')
window_beg = max(int((time_window[0] - self.tstart()) / self.dt()), 0)
window_end = min(int((time_window[1] - self.tstart()) / self.dt()), self._n_steps / self.dt())
time_slice = slice(window_beg, window_end)
filtered_data = np.array(self._data_grp[time_slice, gid_slice])
return filtered_data if multi_compartments else filtered_data[:]
def custom_columns(self, population=None):
return {k: v[()] for k,v in self._custom_cols.items()}
def get_column(self, column_name, population=None):
return self._mapping[column_name][()]
def get_element_data(self, node_id, population=None):
pass
def get_report_description(self, population=None):
pass
def __getitem__(self, population):
return self
class _CompartmentPopulationReaderVer00(_CompartmentPopulationReaderVer01):
sonata_columns = ['element_id', 'element_pos', 'index_pointer', 'gids', 'time']
def node_ids(self, population=None):
return self._mapping[self.node_ids_ds][()]
@property
def node_ids_ds(self):
return 'gids'
def element_ids(self, node_id=None, population=None):
if node_id is None:
return self._mapping['element_id'][()]
else:
#indx_beg, indx_end = self._get_index(node_id)
#return self._mapping['element_id'][self._get_index(node_id)]#[indx_beg:indx_end]
return self._mapping['element_id'][self._get_index(node_id)] # [indx_beg:indx_end]
class CompartmentReaderVer01(CompartmentReaderABC):
def __init__(self, filename, mode='r', **params):
self._h5_handle = h5py.File(filename, mode)
self._h5_root = self._h5_handle[params['h5_root']] if 'h5_root' in params else self._h5_handle['/']
self._popgrps = {}
self._mapping = None
if 'report' in self._h5_handle.keys():
report_grp = self._h5_root['report']
for pop_name, pop_grp in report_grp.items():
self._popgrps[pop_name] = _CompartmentPopulationReaderVer01(pop_grp=pop_grp, pop_name=pop_name)
else:
self._default_population = 'pop_na'
self._popgrps[self._default_population] = _CompartmentPopulationReaderVer00(pop_grp=self._h5_root, pop_name=self._default_population)
if 'default_population' in params:
# If user has specified a default population
self._default_population = params['default_population']
if self._default_population not in self._popgrps.keys():
raise Exception('Unknown population {} found in report.'.format(self._default_population))
elif len(self._popgrps.keys()) == 1:
# If there is only one population in the report default to that
self._default_population = list(self._popgrps.keys())[0]
else:
self._default_population = None
@property
def default_population(self):
if self._default_population is None:
raise Exception('Please specify a node population.')
return self._default_population
@property
def populations(self):
return list(self._popgrps.keys())
def get_population(self, population, default=None):
if population not in self.populations:
return default
return self[population]
def units(self, population=None):
population = population or self.default_population
return self[population].units()
def variable(self, population=None):
population = population or self.default_population
return self[population].variable()
def tstart(self, population=None):
population = population or self.default_population
return self[population].tstart()
def tstop(self, population=None):
population = population or self.default_population
return self[population].tstop()
def dt(self, population=None):
population = population or self.default_population
return self[population].dt()
def time_trace(self, population=None):
population = population or self.default_population
return self[population].time_trace()
def node_ids(self, population=None):
population = population or self.default_population
return self[population].node_ids()
def element_pos(self, node_id=None, population=None):
population = population or self.default_population
return self[population].element_pos(node_id)
def element_ids(self, node_id=None, population=None):
population = population or self.default_population
return self[population].element_ids(node_id)
def n_elements(self, node_id=None, population=None):
population = population or self.default_population
return self[population].n_elements(node_id)
def data(self, node_id=None, population=None, time_window=None, sections='all', **opt_attrs):
population = population or self.default_population
return self[population].data(node_id=node_id, time_window=time_window, sections=sections, **opt_attrs)
def custom_columns(self, population=None):
population = population or self.default_population
return self[population].custom_columns(population)
def get_column(self, column_name, population=None):
population = population or self.default_population
return self[population].get_column(column_name)
def get_node_description(self, node_id, population=None):
population = population or self.default_population
return self[population].get_node_description(node_id)
def get_report_description(self, population=None):
population = population or self.default_population
return self[population].get_report_description()
def __getitem__(self, population):
return self._popgrps[population]
|
{
"pile_set_name": "Github"
}
|
//------------------------------------------------------------------------------
// <copyright file="FormsAuthenticationConfiguration.cs" company="Microsoft">
// Copyright (c) Microsoft Corporation. All rights reserved.
// </copyright>
//------------------------------------------------------------------------------
/*****************************************************************************
From machine.config
<!--
authentication Attributes:
mode="[Windows|Forms|Passport|None]"
-->
<authentication mode="Windows">
<!--
forms Attributes:
name="[cookie name]" - Name of the cookie used for Forms Authentication
loginUrl="[url]" - Url to redirect client to for Authentication
protection="[All|None|Encryption|Validation]" - Protection mode for data in cookie
timeout="[minutes]" - Duration of time for cookie to be valid (reset on each request)
path="/" - Sets the path for the cookie
requireSSL="[true|false]" - Should the forms-authentication cookie be sent only over SSL
slidingExpiration="[true|false]" - Should the forms-authentication-cookie and ticket be re-issued if they are about to expire
defaultUrl="string" - Page to redirect to after login, if none has been specified
cookieless="[UseCookies|UseUri|AutoDetect|UseDeviceProfile]" - Use Cookies or the URL path to store the forms authentication ticket
cookieSameSite="[None|Lax|Strict|-1]" - Set SameSite cookie header to the given value, or omit the header for the auth cookie entirely.
domain="string" - Domain of the cookie
-->
<forms
name=".ASPXAUTH"
loginUrl="login.aspx"
protection="All"
timeout="30"
path="/"
requireSSL="false"
slidingExpiration="true"
defaultUrl="default.aspx"
cookieless="UseDeviceProfile"
enableCrossAppRedirects="false"
cookieSameSite="Lax" >
<!--
credentials Attributes:
passwordFormat="[Clear|SHA1|MD5]" - format of user password value stored in <user>
-->
<credentials passwordFormat="SHA1">
<!-- <user name="UserName" password="password" /> -->
</credentials>
</forms>
<!--
passport Attributes:
redirectUrl=["url"] - Specifies the page to redirect to, if the page requires authentication, and the user has not signed on with passport
-->
<passport redirectUrl="internal" />
</authentication>
<authentication mode="Windows">
<forms
name=".ASPXAUTH"
loginUrl="login.aspx"
protection="All"
timeout="30"
path="/"
requireSSL="false"
slidingExpiration="true"
defaultUrl="default.aspx"
cookieless="UseDeviceProfile"
enableCrossAppRedirects="false" >
<credentials passwordFormat="SHA1">
</credentials>
</forms>
<passport redirectUrl="internal" />
</authentication>
******************************************************************************/
namespace System.Web.Configuration {
using System;
using System.Xml;
using System.Configuration;
using System.Collections.Specialized;
using System.Collections;
using System.Globalization;
using System.IO;
using System.Text;
using System.Web.Util;
using System.ComponentModel;
using System.Security.Permissions;
public sealed class FormsAuthenticationConfiguration : ConfigurationElement {
private static readonly ConfigurationElementProperty s_elemProperty =
new ConfigurationElementProperty(new CallbackValidator(typeof(FormsAuthenticationConfiguration), Validate));
private static ConfigurationPropertyCollection _properties;
private static readonly ConfigurationProperty _propCredentials =
new ConfigurationProperty("credentials",
typeof(FormsAuthenticationCredentials),
null,
ConfigurationPropertyOptions.None);
private static readonly ConfigurationProperty _propName =
new ConfigurationProperty("name",
typeof(string),
".ASPXAUTH",
null,
StdValidatorsAndConverters.NonEmptyStringValidator,
ConfigurationPropertyOptions.None);
private static readonly ConfigurationProperty _propLoginUrl =
new ConfigurationProperty("loginUrl",
typeof(string),
"login.aspx",
null,
StdValidatorsAndConverters.NonEmptyStringValidator,
ConfigurationPropertyOptions.None);
private static readonly ConfigurationProperty _propDefaultUrl =
new ConfigurationProperty("defaultUrl",
typeof(string),
"default.aspx",
null,
StdValidatorsAndConverters.NonEmptyStringValidator,
ConfigurationPropertyOptions.None);
private static readonly ConfigurationProperty _propProtection =
new ConfigurationProperty("protection",
typeof(FormsProtectionEnum),
FormsProtectionEnum.All,
ConfigurationPropertyOptions.None);
private static readonly ConfigurationProperty _propTimeout =
new ConfigurationProperty("timeout",
typeof(TimeSpan),
TimeSpan.FromMinutes(30.0),
StdValidatorsAndConverters.TimeSpanMinutesConverter,
new TimeSpanValidator(TimeSpan.FromMinutes(1), TimeSpan.MaxValue),
ConfigurationPropertyOptions.None);
private static readonly ConfigurationProperty _propPath =
new ConfigurationProperty("path",
typeof(string),
"/",
null,
StdValidatorsAndConverters.NonEmptyStringValidator,
ConfigurationPropertyOptions.None);
private static readonly ConfigurationProperty _propRequireSSL =
new ConfigurationProperty("requireSSL",
typeof(bool),
false,
ConfigurationPropertyOptions.None);
private static readonly ConfigurationProperty _propSlidingExpiration =
new ConfigurationProperty("slidingExpiration",
typeof(bool),
true,
ConfigurationPropertyOptions.None);
private static readonly ConfigurationProperty _propCookieless =
new ConfigurationProperty("cookieless",
typeof(HttpCookieMode),
HttpCookieMode.UseDeviceProfile,
ConfigurationPropertyOptions.None);
private static readonly ConfigurationProperty _propDomain =
new ConfigurationProperty("domain",
typeof(string),
null,
ConfigurationPropertyOptions.None);
private static readonly ConfigurationProperty _propEnableCrossAppRedirects =
new ConfigurationProperty("enableCrossAppRedirects",
typeof(bool),
false,
ConfigurationPropertyOptions.None);
private static readonly ConfigurationProperty _propTicketCompatibilityMode =
new ConfigurationProperty("ticketCompatibilityMode",
typeof(TicketCompatibilityMode),
TicketCompatibilityMode.Framework20,
ConfigurationPropertyOptions.None);
private static readonly ConfigurationProperty _propCookieSameSite =
new ConfigurationProperty("cookieSameSite",
typeof(SameSiteMode),
SameSiteMode.Lax,
ConfigurationPropertyOptions.None);
static FormsAuthenticationConfiguration() {
// Property initialization
_properties = new ConfigurationPropertyCollection();
_properties.Add(_propCredentials);
_properties.Add(_propName);
_properties.Add(_propLoginUrl);
_properties.Add(_propDefaultUrl);
_properties.Add(_propProtection);
_properties.Add(_propTimeout);
_properties.Add(_propPath);
_properties.Add(_propRequireSSL);
_properties.Add(_propSlidingExpiration);
_properties.Add(_propCookieless);
_properties.Add(_propDomain);
_properties.Add(_propEnableCrossAppRedirects);
_properties.Add(_propTicketCompatibilityMode);
_properties.Add(_propCookieSameSite);
}
public FormsAuthenticationConfiguration() {
}
protected override ConfigurationPropertyCollection Properties {
get {
return _properties;
}
}
[ConfigurationProperty("credentials")]
public FormsAuthenticationCredentials Credentials {
get {
return (FormsAuthenticationCredentials)base[_propCredentials];
}
}
[ConfigurationProperty("name", DefaultValue = ".ASPXAUTH")]
[StringValidator(MinLength = 1)]
public string Name {
get {
return (string)base[_propName];
}
set {
if (String.IsNullOrEmpty(value)) {
base[_propName] = _propName.DefaultValue;
}
else {
base[_propName] = value;
}
}
}
[ConfigurationProperty("loginUrl", DefaultValue = "login.aspx")]
[StringValidator(MinLength = 1)]
public string LoginUrl {
get {
return (string)base[_propLoginUrl];
}
set {
if (String.IsNullOrEmpty(value)) {
base[_propLoginUrl] = _propLoginUrl.DefaultValue;
}
else {
base[_propLoginUrl] = value;
}
}
}
[ConfigurationProperty("defaultUrl", DefaultValue = "default.aspx")]
[StringValidator(MinLength = 1)]
public string DefaultUrl {
get {
return (string)base[_propDefaultUrl];
}
set {
if (String.IsNullOrEmpty(value)) {
base[_propDefaultUrl] = _propDefaultUrl.DefaultValue;
}
else {
base[_propDefaultUrl] = value;
}
}
}
[ConfigurationProperty("protection", DefaultValue = FormsProtectionEnum.All)]
public FormsProtectionEnum Protection {
get {
return (FormsProtectionEnum)base[_propProtection];
}
set {
base[_propProtection] = value;
}
}
[ConfigurationProperty("timeout", DefaultValue = "00:30:00")]
[TimeSpanValidator(MinValueString="00:01:00", MaxValueString=TimeSpanValidatorAttribute.TimeSpanMaxValue)]
[TypeConverter(typeof(TimeSpanMinutesConverter))]
public TimeSpan Timeout {
get {
return (TimeSpan)base[_propTimeout];
}
set {
base[_propTimeout] = value;
}
}
[ConfigurationProperty("path", DefaultValue = "/")]
[StringValidator(MinLength = 1)]
public string Path {
get {
return (string)base[_propPath];
}
set {
if (String.IsNullOrEmpty(value)) {
base[_propPath] = _propPath.DefaultValue;
}
else {
base[_propPath] = value;
}
}
}
[ConfigurationProperty("requireSSL", DefaultValue = false)]
public bool RequireSSL {
get {
return (bool)base[_propRequireSSL];
}
set {
base[_propRequireSSL] = value;
}
}
[ConfigurationProperty("slidingExpiration", DefaultValue = true)]
public bool SlidingExpiration {
get {
return (bool)base[_propSlidingExpiration];
}
set {
base[_propSlidingExpiration] = value;
}
}
[ConfigurationProperty("enableCrossAppRedirects", DefaultValue = false)]
public bool EnableCrossAppRedirects {
get {
return (bool)base[_propEnableCrossAppRedirects];
}
set {
base[_propEnableCrossAppRedirects] = value;
}
}
[ConfigurationProperty("cookieless", DefaultValue = HttpCookieMode.UseDeviceProfile)]
public HttpCookieMode Cookieless {
get {
return (HttpCookieMode)base[_propCookieless];
}
set {
base[_propCookieless] = value;
}
}
[ConfigurationProperty("domain", DefaultValue = "")]
public string Domain {
get {
return (string)base[_propDomain];
}
set {
base[_propDomain] = value;
}
}
[ConfigurationProperty("ticketCompatibilityMode", DefaultValue = TicketCompatibilityMode.Framework20)]
public TicketCompatibilityMode TicketCompatibilityMode {
get {
return (TicketCompatibilityMode)base[_propTicketCompatibilityMode];
}
set {
base[_propTicketCompatibilityMode] = value;
}
}
[ConfigurationProperty("cookieSameSite")]
public SameSiteMode CookieSameSite {
get {
return (SameSiteMode)base[_propCookieSameSite];
}
set {
base[_propCookieSameSite] = value;
}
}
protected override ConfigurationElementProperty ElementProperty {
get {
return s_elemProperty;
}
}
private static void Validate(object value) {
if (value == null) {
throw new ArgumentNullException("forms");
}
FormsAuthenticationConfiguration elem = (FormsAuthenticationConfiguration)value;
if (StringUtil.StringStartsWith(elem.LoginUrl, "\\\\") ||
(elem.LoginUrl.Length > 1 && elem.LoginUrl[1] == ':')) {
throw new ConfigurationErrorsException(SR.GetString(SR.Auth_bad_url),
elem.ElementInformation.Properties["loginUrl"].Source,
elem.ElementInformation.Properties["loginUrl"].LineNumber);
}
if (StringUtil.StringStartsWith(elem.DefaultUrl, "\\\\") ||
(elem.DefaultUrl.Length > 1 && elem.DefaultUrl[1] == ':')) {
throw new ConfigurationErrorsException(SR.GetString(SR.Auth_bad_url),
elem.ElementInformation.Properties["defaultUrl"].Source,
elem.ElementInformation.Properties["defaultUrl"].LineNumber);
}
}
} // class FormsAuthenticationConfiguration
}
|
{
"pile_set_name": "Github"
}
|
{
"type": "property",
"content": [
{
"type": "ident",
"content": "color",
"syntax": "css",
"start": {
"line": 1,
"column": 1
},
"end": {
"line": 1,
"column": 5
}
}
],
"syntax": "css",
"start": {
"line": 1,
"column": 1
},
"end": {
"line": 1,
"column": 5
}
}
|
{
"pile_set_name": "Github"
}
|
/*
* Copyright 2018 Sergey Khabarov, [email protected]
*
* 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.
*/
#ifndef __DEBUGGER_SRC_COMMON_GENERIC_CMD_REG_GENERIC_H__
#define __DEBUGGER_SRC_COMMON_GENERIC_CMD_REG_GENERIC_H__
#include "api_core.h"
#include "coreservices/icommand.h"
#include "debug/dsumap.h"
namespace debugger {
class CmdRegGeneric : public ICommand {
public:
explicit CmdRegGeneric(ITap *tap);
/** ICommand */
virtual int isValid(AttributeType *args);
virtual void exec(AttributeType *args, AttributeType *res);
protected:
virtual const ECpuRegMapping *getpMappedReg() = 0;
virtual uint64_t reg2addr(const char *name);
};
} // namespace debugger
#endif // __DEBUGGER_SRC_COMMON_GENERIC_CMD_REG_GENERIC_H__
|
{
"pile_set_name": "Github"
}
|
//
// VoipVideoVC.h
// IMDemo
//
// Created by Hanxiaojie on 2018/4/19.
// Copyright © 2018年 Admin. All rights reserved.
//
#import "IFBaseVC.h"
typedef NS_ENUM(NSInteger , VoipVCStatus) {
VoipVCStatus_Calling = 1,
VoipVCStatus_Conversation = 2,
VoipVCStatus_Receiving = 3,
};
typedef NS_ENUM(NSInteger , VoipShowType) {
VoipShowType_Video = 1,
VoipShowType_Audio = 2,
};
@interface VoipVideoVC : IFBaseVC
+ (instancetype)shareInstance;
- (instancetype)initWithNib;
@property (nonatomic, copy) NSString *targetId;//对方用户ID,(可能是呼叫方,也可能是接收方)
- (void)setupTargetId:(NSString*)targetId viopStatus:(VoipVCStatus)voipStatus showType:(VoipShowType)showType;
- (void)updateVoipState:(VoipVCStatus) voipStatus;
- (void)showVoipInViewController:(UIViewController *)delegate;
//返回
- (void)backup;
@end
|
{
"pile_set_name": "Github"
}
|
//
// Generated by class-dump 3.5 (64 bit).
//
// class-dump is Copyright (C) 1997-1998, 2000-2001, 2004-2013 by Steve Nygard.
//
#import "NSObject.h"
@class NSFileVersion, NSOperationQueue, NSURL;
@protocol NSFilePresenter <NSObject>
@property(readonly, retain) NSOperationQueue *presentedItemOperationQueue;
@property(readonly, copy) NSURL *presentedItemURL;
@optional
@property(readonly, copy) NSURL *primaryPresentedItemURL;
- (void)presentedSubitemAtURL:(NSURL *)arg1 didResolveConflictVersion:(NSFileVersion *)arg2;
- (void)presentedSubitemAtURL:(NSURL *)arg1 didLoseVersion:(NSFileVersion *)arg2;
- (void)presentedSubitemAtURL:(NSURL *)arg1 didGainVersion:(NSFileVersion *)arg2;
- (void)presentedSubitemDidChangeAtURL:(NSURL *)arg1;
- (void)presentedSubitemAtURL:(NSURL *)arg1 didMoveToURL:(NSURL *)arg2;
- (void)presentedSubitemDidAppearAtURL:(NSURL *)arg1;
- (void)accommodatePresentedSubitemDeletionAtURL:(NSURL *)arg1 completionHandler:(void (^)(NSError *))arg2;
- (void)presentedItemDidResolveConflictVersion:(NSFileVersion *)arg1;
- (void)presentedItemDidLoseVersion:(NSFileVersion *)arg1;
- (void)presentedItemDidGainVersion:(NSFileVersion *)arg1;
- (void)presentedItemDidChange;
- (void)presentedItemDidMoveToURL:(NSURL *)arg1;
- (void)accommodatePresentedItemDeletionWithCompletionHandler:(void (^)(NSError *))arg1;
- (void)savePresentedItemChangesWithCompletionHandler:(void (^)(NSError *))arg1;
- (void)relinquishPresentedItemToWriter:(void (^)(void (^)(void)))arg1;
- (void)relinquishPresentedItemToReader:(void (^)(void (^)(void)))arg1;
@end
|
{
"pile_set_name": "Github"
}
|
## Python Flask构建可扩展的RESTful API
时长:6小时25分钟
| 章节 | 记录 |
| ------------------------------------------------------------ | ---- |
| **第1章 随便聊聊** | |
| 聊聊Flask与Django,聊聊代码的创造性 | |
| | |
| 1-1 Flask VS Django | |
| 1-2 课程更新维护说明 | |
| | |
| **第2章 起步与红图** | |
| 本章我们初始化项目,探讨与研究Flask的默认层级结构。当我们遇到层级结构不合理时,我们将模仿蓝图自己定义一个“红图”来扩展Flask层级体系 | |
| | |
| 2-1 环境、开发工具与flask1.0 | |
| 2-2 初始化项目 | |
| 2-3 新建入口文件 | |
| 2-4 蓝图分离视图函数的缺陷 | |
| 2-5 打开思维,创建自己的Redprint——红图 | |
| 2-6 实现Redprint | |
| 2-7 优化Redprint | |
| | |
| **第3章 REST基本特征** | |
| 本章我们将探讨REST的基本特征,并结合实际情况给出REST的适用范围与优劣势 | |
| | |
| 3-1 REST的最基本特征(可选观看) | |
| 3-2 为什么标准REST不适合内部开发(可选观看) | |
| | |
| **第4章 自定义异常对象** | |
| 异常处理其实是一个非常严肃而又麻烦的事情,这直接涉及到前端如何对用户做出响应。本章我们将重写HTTPException并建立全局异常处理机制,统一处理框架内的异常,向前端返回统一而标准的异常信息,简化前端的开发流程 | |
| | |
| 4-1 关于“用户”的思考 | |
| 4-2 构建Client验证器 | |
| 4-3 处理不同客户端注册的方案 | |
| 4-4 创建User模型 | |
| 4-5 完成客户端注册 | |
| 4-6 生成用户数据 | |
| 4-7 自定义异常对象 | |
| 4-8 浅谈异常返回的标准与重要性 | |
| 4-9 自定义APIException | |
| | |
| **第5章 理解WTForms并灵活改造她** | |
| WTForms其实是非常强大的验证插件。但很多同学对WTForms的理解仅仅停留在“验证表单”上。那WTForms可以用来做API的参数验证码?完全可以,但这需要你灵活的使用它,对它做出一些“改变” | |
| | |
| 5-1 重写WTForms 一 | |
| 5-2 重写WTForms 二 | |
| 5-3 可以接受定义的复杂,但不能接受调用的复杂 | |
| 5-4 已知异常与未知异常 | |
| 5-5 全局异常处理 | |
| | |
| **第6章 Token与HTTPBasic验证 —— 用令牌来管理用户** | |
| 在我的TP5课程里,我们使用令牌的方式是服务器缓存的方式。那么在Python Flask中我们换一种令牌的发放方式。我们将用户的信息加密后作为令牌返回到客户端,客户端在访问服务器API时必须以HTTP Basic的方式携带令牌,我们再读取令牌信息后,将用户信息存入到g变量中,共业务代码全局使用... | |
| | |
| 6-1 Token概述 | |
| 6-2 获取Token令牌 | |
| 6-3 Token的用处 | |
| 6-4 @auth拦截器执行流程 | |
| 6-5 HTTPBasicAuth基本原理 | |
| 6-6 以BasicAuth的方式发送Token | |
| 6-7 验证Token | |
| 6-8 重写first_or_404与get_or_404 | |
| | |
| **第7章 模型对象的序列化** | |
| 最适合Python JSON序列化的是dict字典类型,每一种语言都有其对应的数据结构用来对应JSON对象,比如在PHP中是它的数组数据结构。而Python是用字典来对应JSON的。如果我们想直接序列化一个对象或者模型对象,那么最笨的办法是把对象的属性读取出来,然后组装成一个字典再序列化。这实在是太麻烦了。本章节我们将深入了解JSO... | |
| | |
| 7-1 鸡汤? | |
| 7-2 理解序列化时的default函数 | |
| 7-3 不完美的对象转字典 | |
| 7-4 深入理解dict的机制 | |
| 7-5 一个元素的元组要特别注意 | |
| 7-6 序列化SQLAlchemy模型 | |
| 7-7 完善序列化 | |
| 7-8 ViewModel对于API有意义吗 | |
| | |
| **第8章 权限控制** | |
| 我看过太多同学编写的API在互联网上疯狂的裸奔了。殊不知这太危险了。API必须提供分层保护机制,根据不同用户的种类来限制其可以访问的API,从而保护接口。比如管理员可以访问哪些接口,普通用户可以访问哪些接口,小程序可以访问哪些,APP又能够访问哪些?灵活而强大的可配置Scope,可以帮助你事半功倍... | |
| | |
| 8-1 删除模型注意事项 | |
| 8-2 g变量中读取uid防止超权 | |
| 8-3 生成超级管理员账号 | |
| 8-4 不太好的权限管理方案 | |
| 8-5 比较好的权限管理方案 | |
| 8-6 实现Scope权限管理 一 | |
| 8-7 globals()实现“反射” | |
| 8-8 实现Scope权限管理 二 | |
| 8-9 Scope优化一 支持权限相加 | |
| 8-10 Scope优化 二 支持权限链式相加 | |
| 8-11 Scope优化 三 所有子类支持相加 | |
| 8-12 Scope优化 四 运算符重载 | |
| 8-13 Scope 优化 探讨模块级别的Scope | |
| 8-14 Scope优化 实现模块级别的Scope | |
| 8-15 Scope优化 七 支持排除 | |
| | |
| **第9章 实现部分鱼书小程序功能** | |
| 理论必须结合实践,我们提供一个简单的鱼书小程序,编写他的业务接口,并用小程序来进行API的检验 | |
| | |
| 9-1 小程序演示API调用效果 | |
| 9-2 模糊搜索书籍 | |
| 9-3 再谈严格型REST的缺陷 | |
| 9-4 实现hide方法 | |
| 9-5 @orm.reconstructor 解决模型对象实例化问题 | |
| 9-6 重构hide与append | |
| 9-7 赠送礼物接口 | |
| 9-8 实现获取令牌信息接口 | |
|
{
"pile_set_name": "Github"
}
|
/* Copyright 2015 The TensorFlow 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.
==============================================================================*/
#ifndef TENSORFLOW_STREAM_EXECUTOR_LIB_DEMANGLE_H_
#define TENSORFLOW_STREAM_EXECUTOR_LIB_DEMANGLE_H_
#include "tensorflow/stream_executor/platform/port.h"
namespace perftools {
namespace gputools {
namespace port {
string Demangle(const char* mangled);
} // namespace port
} // namespace gputools
} // namespace perftools
#endif // TENSORFLOW_STREAM_EXECUTOR_LIB_DEMANGLE_H_
|
{
"pile_set_name": "Github"
}
|
// Boost.TypeErasure library
//
// Copyright 2015 Steven Watanabe
//
// 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)
//
// $Id$
#ifndef BOOST_TYPE_ERASURE_REGISTER_BINDING_HPP_INCLUDED
#define BOOST_TYPE_ERASURE_REGISTER_BINDING_HPP_INCLUDED
#include <boost/type_erasure/detail/check_map.hpp>
#include <boost/type_erasure/detail/get_placeholders.hpp>
#include <boost/type_erasure/detail/rebind_placeholders.hpp>
#include <boost/type_erasure/detail/normalize.hpp>
#include <boost/type_erasure/detail/adapt_to_vtable.hpp>
#include <boost/type_erasure/detail/auto_link.hpp>
#include <boost/type_erasure/static_binding.hpp>
#include <boost/mpl/transform.hpp>
#include <boost/mpl/remove_if.hpp>
#include <boost/mpl/fold.hpp>
#include <boost/mpl/at.hpp>
#include <boost/mpl/has_key.hpp>
#include <boost/mpl/insert.hpp>
#include <boost/mpl/front.hpp>
#include <boost/mpl/size.hpp>
#include <boost/mpl/equal_to.hpp>
#include <boost/mpl/or.hpp>
#include <boost/mpl/set.hpp>
#include <boost/mpl/map.hpp>
#include <boost/mpl/vector.hpp>
#include <boost/mpl/int.hpp>
#include <boost/mpl/bool.hpp>
#include <boost/mpl/pair.hpp>
#include <boost/mpl/back_inserter.hpp>
#include <boost/mpl/for_each.hpp>
#include <vector>
#include <typeinfo>
namespace boost {
namespace type_erasure {
namespace detail {
typedef std::vector<const std::type_info*> key_type;
typedef void (*value_type)();
BOOST_TYPE_ERASURE_DECL void register_function_impl(const key_type& key, value_type fn);
BOOST_TYPE_ERASURE_DECL value_type lookup_function_impl(const key_type& key);
template<class Map>
struct append_to_key_static {
append_to_key_static(key_type* k) : key(k) {}
template<class P>
void operator()(P) {
key->push_back(&typeid(typename ::boost::mpl::at<Map, P>::type));
}
key_type* key;
};
// This placeholder exists solely to create a normalized
// representation of a primitive concept. For the moment
// I'm going to be conservative and require a bijection
// between the original placeholders and the normalized
// placeholders. It should be safe to map everything
// to a single placeholder, though, as long as the
// key includes every instance of each placeholder
// as a separate element. i.e. we should be able to
// turn addable<_a, _b> into addable<_, _> and
// addable<_a, _a> into addable<_, _> as well if we always
// add typeids for both arguments to the search key.
template<int N>
struct _ : ::boost::type_erasure::placeholder {};
struct counting_map_appender
{
template<class State, class Key>
struct apply
{
typedef typename ::boost::mpl::insert<
State,
::boost::mpl::pair<
Key,
::boost::type_erasure::detail::_<
::boost::mpl::size<State>::value
>
>
>::type type;
};
};
template<class Map>
struct register_function {
template<class F>
void operator()(F) {
key_type key;
typedef typename ::boost::type_erasure::detail::get_placeholders<F, ::boost::mpl::set0<> >::type placeholders;
typedef typename ::boost::mpl::fold<
placeholders,
::boost::mpl::map0<>,
::boost::type_erasure::detail::counting_map_appender
>::type placeholder_map;
key.push_back(&typeid(typename ::boost::type_erasure::detail::rebind_placeholders<F, placeholder_map>::type));
::boost::mpl::for_each<placeholders>(append_to_key_static<Map>(&key));
value_type fn = reinterpret_cast<value_type>(&::boost::type_erasure::detail::rebind_placeholders<F, Map>::type::value);
::boost::type_erasure::detail::register_function_impl(key, fn);
}
};
}
/**
* Registers a model of a concept to allow downcasting @ref any
* via @ref dynamic_any_cast.
*/
template<class Concept, class Map>
void register_binding(const static_binding<Map>&)
{
typedef typename ::boost::type_erasure::detail::normalize_concept<
Concept
>::type normalized;
typedef typename ::boost::mpl::transform<normalized,
::boost::type_erasure::detail::maybe_adapt_to_vtable< ::boost::mpl::_1>
>::type actual_concept;
typedef typename ::boost::type_erasure::detail::get_placeholder_normalization_map<
Concept
>::type placeholder_subs;
typedef typename ::boost::type_erasure::detail::add_deductions<Map, placeholder_subs>::type actual_map;
::boost::mpl::for_each<actual_concept>(::boost::type_erasure::detail::register_function<actual_map>());
}
/**
* \overload
*/
template<class Concept, class T>
void register_binding()
{
// Find all placeholders
typedef typename ::boost::type_erasure::detail::normalize_concept_impl<Concept>::type normalized;
typedef typename normalized::first basic;
typedef typename ::boost::mpl::fold<
basic,
::boost::mpl::set0<>,
::boost::type_erasure::detail::get_placeholders< ::boost::mpl::_2, ::boost::mpl::_1>
>::type all_placeholders;
// remove deduced placeholders
typedef typename ::boost::mpl::fold<
typename normalized::second,
::boost::mpl::set0<>,
::boost::mpl::insert< ::boost::mpl::_1, ::boost::mpl::second< ::boost::mpl::_2> >
>::type xtra_deduced;
typedef typename ::boost::mpl::remove_if<
all_placeholders,
::boost::mpl::or_<
::boost::type_erasure::detail::is_deduced< ::boost::mpl::_1>,
::boost::mpl::has_key<xtra_deduced, ::boost::mpl::_1>
>,
::boost::mpl::back_inserter< ::boost::mpl::vector0<> >
>::type unknown_placeholders;
// Bind the single remaining placeholder to T
BOOST_MPL_ASSERT((boost::mpl::equal_to<boost::mpl::size<unknown_placeholders>, boost::mpl::int_<1> >));
register_binding<Concept>(::boost::type_erasure::make_binding<
::boost::mpl::map< ::boost::mpl::pair<typename ::boost::mpl::front<unknown_placeholders>::type, T> > >());
}
}
}
#endif
|
{
"pile_set_name": "Github"
}
|
<?php
namespace Kirby\Form\Fields;
class TagsFieldTest extends TestCase
{
public function testDefaultProps()
{
$field = $this->field('tags');
$this->assertEquals('tags', $field->type());
$this->assertEquals('tags', $field->name());
$this->assertEquals('all', $field->accept());
$this->assertEquals([], $field->value());
$this->assertEquals([], $field->default());
$this->assertEquals([], $field->options());
$this->assertEquals(null, $field->min());
$this->assertEquals(null, $field->max());
$this->assertEquals(',', $field->separator());
$this->assertEquals('tag', $field->icon());
$this->assertEquals(null, $field->counter());
$this->assertTrue($field->save());
}
public function testOptionsQuery()
{
$app = $this->app()->clone([
'site' => [
'children' => [
[
'slug' => 'a',
'content' => [
'tags' => 'design'
],
'files' => [
[
'filename' => 'a.jpg',
'content' => [
'tags' => 'design'
]
],
[
'filename' => 'b.jpg',
'content' => [
'tags' => 'design, photography'
]
],
[
'filename' => 'c.jpg',
'content' => [
'tags' => 'design, architecture'
]
]
]
],
[
'slug' => 'b',
'content' => [
'tags' => 'design, photography'
],
],
[
'slug' => 'c',
'content' => [
'tags' => 'design, architecture'
],
]
]
]
]);
$expected = [
[
'value' => 'design',
'text' => 'design'
],
[
'value' => 'photography',
'text' => 'photography'
],
[
'value' => 'architecture',
'text' => 'architecture'
]
];
$field = $this->field('tags', [
'model' => $app->page('b'),
'options' => 'query',
'query' => 'page.siblings.pluck("tags", ",", true)',
]);
$this->assertEquals($expected, $field->options());
$field = $this->field('tags', [
'model' => $app->file('a/b.jpg'),
'options' => 'query',
'query' => 'file.siblings.pluck("tags", ",", true)',
]);
$this->assertEquals($expected, $field->options());
}
public function testMin()
{
$field = $this->field('tags', [
'value' => 'a',
'options' => ['a', 'b', 'c'],
'min' => 2
]);
$this->assertFalse($field->isValid());
$this->assertArrayHasKey('min', $field->errors());
$this->assertEquals(2, $field->min());
$this->assertTrue($field->required());
}
public function testMax()
{
$field = $this->field('tags', [
'value' => 'a, b',
'options' => ['a', 'b', 'c'],
'max' => 1
]);
$this->assertFalse($field->isValid());
$this->assertEquals(1, $field->max());
$this->assertArrayHasKey('max', $field->errors());
}
public function testRequiredProps()
{
$field = $this->field('tags', [
'options' => ['a', 'b', 'c'],
'required' => true
]);
$this->assertTrue($field->required());
$this->assertEquals(1, $field->min());
}
public function testRequiredInvalid()
{
$field = $this->field('tags', [
'options' => ['a', 'b', 'c'],
'value' => null,
'required' => true
]);
$this->assertFalse($field->isValid());
}
public function testRequiredValid()
{
$field = $this->field('tags', [
'options' => ['a', 'b', 'c'],
'required' => true,
'value' => 'a'
]);
$this->assertTrue($field->isValid());
}
}
|
{
"pile_set_name": "Github"
}
|
<?php
use Symfony\Component\Console\Exception\InvalidArgumentException as SymfonyInvalidArgumentException;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Input\InputOption;
use Symfony\Component\Console\Output\OutputInterface;
use Symfony\Component\Console\Question\ChoiceQuestion;
use Symfony\Component\Console\Style\SymfonyStyle;
/**
* @package redaxo\cronjob
*
* @internal
*/
class rex_command_cronjob_run extends rex_console_command
{
protected function configure()
{
$this
->setDescription('Executes cronjobs of the "script" environment')
->addOption('job', null, InputOption::VALUE_REQUIRED, 'Execute single job (selected interactively or given by id)', false)
;
}
protected function execute(InputInterface $input, OutputInterface $output)
{
$io = $this->getStyle($input, $output);
// indicator constant, kept for BC
define('REX_CRONJOB_SCRIPT', true);
$job = $input->getOption('job');
if (false !== $job) {
return $this->executeSingleJob($io, $job);
}
$nexttime = rex_package::get('cronjob')->getConfig('nexttime', 0);
if (0 != $nexttime && time() >= $nexttime) {
rex_cronjob_manager_sql::factory()->check();
$io->success('Cronjobs checked.');
return 0;
}
$io->success('Cronjobs skipped.');
return 0;
}
private function executeSingleJob(SymfonyStyle $io, $id)
{
$manager = rex_cronjob_manager_sql::factory();
if (null === $id) {
$jobs = rex_sql::factory()->getArray('
SELECT id, name
FROM ' . rex::getTable('cronjob') . '
WHERE environment LIKE "%|script|%"
ORDER BY id
');
$jobs = array_column($jobs, 'name', 'id');
$question = new ChoiceQuestion('Which cronjob should be executed?', $jobs);
$question->setValidator(static function ($selected) use ($jobs) {
$selected = trim($selected);
if (!isset($jobs[$selected])) {
throw new SymfonyInvalidArgumentException(sprintf('Value "%s" is invalid.', $selected));
}
return $selected;
});
$id = $io->askQuestion($question);
$name = $jobs[$id];
} else {
$name = $manager->getName($id);
}
$success = $manager->tryExecute($id);
$msg = '';
if ($manager->hasMessage()) {
$msg = ': '.$manager->getMessage();
}
if ($success) {
$io->success(sprintf('Cronjob "%s" executed successfully%s.', $name, $msg));
return 0;
}
$io->error(sprintf('Cronjob "%s" failed%s.', $name, $msg));
return 1;
}
}
|
{
"pile_set_name": "Github"
}
|
# File src/library/stats/R/splinefun.R
# Part of the R package, https://www.R-project.org
#
# Copyright (C) 1995-2017 The R Core Team
#
# 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.
#
# A copy of the GNU General Public License is available at
# https://www.R-project.org/Licenses/
#### 'spline' and 'splinefun' are very similar --- keep in sync!
#### also consider ``compatibility'' with 'approx' and 'approxfun'
splinefun <-
function(x, y = NULL,
method = c("fmm", "periodic", "natural", "monoH.FC", "hyman"),
ties = mean)
{
x <- regularize.values(x, y, ties) # -> (x,y) numeric of same length
y <- x$y
x <- x$x
nx <- length(x) # large vectors ==> non-integer
if(is.na(nx)) stop(gettextf("invalid value of %s", "length(x)"), domain = NA)
if(nx == 0) stop("zero non-NA points")
method <- match.arg(method)
if(method == "periodic" && y[1L] != y[nx]) {
warning("spline: first and last y values differ - using y[1L] for both")
y[nx] <- y[1L]
}
if(method == "monoH.FC") {
n1 <- nx - 1L
## - - - "Data preprocessing" - - -
dy <- y[-1L] - y[-nx] # = diff(y)
dx <- x[-1L] - x[-nx] # = diff(x)
Sx <- dy / dx # Sx[k] = \Delta_k = (y_{k+1} - y_k)/(x_{k+1} - x_k), k=1:n1
m <- c(Sx[1L], (Sx[-1L] + Sx[-n1])/2, Sx[n1]) ## 1.
## use C, as we need to "serially" progress from left to right:
m <- .Call(C_monoFC_m, m, Sx)
## Hermite spline with (x,y,m) :
return(splinefunH0(x0 = x, y0 = y, m = m, dx = dx))
}
## else
iMeth <- match(method, c("periodic", "natural", "fmm",
"monoH.FC", "hyman"))
if(iMeth == 5L) {
dy <- diff(y)
if(!(all(dy >= 0) || all(dy <= 0)))
stop("'y' must be increasing or decreasing")
}
z <- .Call(C_SplineCoef, min(3L, iMeth), x, y)
if(iMeth == 5L) z <- spl_coef_conv(hyman_filter(z))
rm(x, y, nx, method, iMeth, ties)
function(x, deriv = 0L) {
deriv <- as.integer(deriv)
if (deriv < 0L || deriv > 3L)
stop("'deriv' must be between 0 and 3")
if (deriv > 0L) {
## For deriv >= 2, using approx() should be faster, but doing it correctly
## for all three methods is not worth the programmer's time...
z0 <- double(z$n)
z[c("y", "b", "c")] <-
switch(deriv,
list(y = z$b , b = 2*z$c, c = 3*z$d), # deriv = 1
list(y = 2*z$c, b = 6*z$d, c = z0), # deriv = 2
list(y = 6*z$d, b = z0, c = z0)) # deriv = 3
z[["d"]] <- z0
}
## yout[j] := y[i] + dx*(b[i] + dx*(c[i] + dx* d_i))
## where dx := (u[j]-x[i]); i such that x[i] <= u[j] <= x[i+1},
## u[j]:= xout[j] (unless sometimes for periodic spl.)
## and d_i := d[i] unless for natural splines at left
res <- .splinefun(x, z)
## deal with points to the left of first knot if natural
## splines are used (Bug PR#13132)
if( deriv > 0 && z$method==2 && any(ind <- x<=z$x[1L]) )
res[ind] <- ifelse(deriv == 1, z$y[1L], 0)
res
}
}
## avoid capturing internal calls
.splinefun <- function(x, z) .Call(C_SplineEval, x, z)
## hidden : The exported user function is splinefunH()
splinefunH0 <- function(x0, y0, m, dx = x0[-1L] - x0[-length(x0)])
{
function(x, deriv=0, extrapol = c("linear","cubic"))
{
extrapol <- match.arg(extrapol)
deriv <- as.integer(deriv)
if (deriv < 0 || deriv > 3)
stop("'deriv' must be between 0 and 3")
i <- findInterval(x, x0, all.inside = (extrapol == "cubic"))
if(deriv == 0)
interp <- function(x, i) {
h <- dx[i]
t <- (x - x0[i]) / h
## Compute the 4 Hermite (cubic) polynomials h00, h01,h10, h11
t1 <- t-1
h01 <- t*t*(3 - 2*t)
h00 <- 1 - h01
tt1 <- t*t1
h10 <- tt1 * t1
h11 <- tt1 * t
y0[i] * h00 + h*m[i] * h10 +
y0[i+1]* h01 + h*m[i+1]* h11
}
else if(deriv == 1)
interp <- function(x, i) {
h <- dx[i]
t <- (x - x0[i]) / h
## 1st derivative of Hermite polynomials h00, h01,h10, h11
t1 <- t-1
h01 <- -6*t*t1 # h00 = - h01
h10 <- (3*t - 1) * t1
h11 <- (3*t - 2) * t
(y0[i+1] - y0[i])/h * h01 + m[i] * h10 + m[i+1]* h11
}
else if (deriv == 2)
interp <- function(x, i) {
h <- dx[i]
t <- (x - x0[i]) / h
## 2nd derivative of Hermite polynomials h00, h01,h10, h11
h01 <- 6*(1-2*t) # h00 = - h01
h10 <- 2*(3*t - 2)
h11 <- 2*(3*t - 1)
((y0[i+1] - y0[i])/h * h01 + m[i] * h10 + m[i+1]* h11) / h
}
else # deriv == 3
interp <- function(x, i) {
h <- dx[i]
## 3rd derivative of Hermite polynomials h00, h01,h10, h11
h01 <- -12 # h00 = - h01
h10 <- 6
h11 <- 6
((y0[i+1] - y0[i])/h * h01 + m[i] * h10 + m[i+1]* h11) / h
}
if(extrapol == "linear" &&
any(iXtra <- (iL <- (i == 0)) | (iR <- (i == (n <- length(x0)))))) {
## do linear extrapolation
r <- x
if(any(iL)) r[iL] <- if(deriv == 0) y0[1L] + m[1L]*(x[iL] - x0[1L]) else
if(deriv == 1) m[1L] else 0
if(any(iR)) r[iR] <- if(deriv == 0) y0[n] + m[n]*(x[iR] - x0[n]) else
if(deriv == 1) m[n] else 0
## For internal values, compute "as normal":
ini <- !iXtra
r[ini] <- interp(x[ini], i[ini])
r
}
else { ## use cubic Hermite polynomials, even for extrapolation
interp(x, i)
}
}
}
splinefunH <- function(x, y, m)
{
## Purpose: "Cubic Hermite Spline"
## ----------------------------------------------------------------------
## Arguments: (x,y): points; m: slope at points, all of equal length
## ----------------------------------------------------------------------
## Author: Martin Maechler, Date: 9 Jan 2008
n <- length(x)
stopifnot(is.numeric(x), is.numeric(y), is.numeric(m),
length(y) == n, length(m) == n)
if(is.unsorted(x)) {
i <- sort.list(x)
x <- x[i]
y <- y[i]
m <- m[i]
}
dx <- x[-1L] - x[-n]
if(anyNA(dx) || any(dx == 0))
stop("'x' must be *strictly* increasing (non - NA)")
splinefunH0(x, y, m, dx=dx)
}
|
{
"pile_set_name": "Github"
}
|
//===- llvm/Support/Unicode.cpp - Unicode character properties -*- C++ -*-===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// This file implements functions that allow querying certain properties of
// Unicode characters.
//
//===----------------------------------------------------------------------===//
#include "llvm/Support/Unicode.h"
#include "llvm/Support/ConvertUTF.h"
#include "llvm/Support/UnicodeCharRanges.h"
namespace llvm {
namespace sys {
namespace unicode {
bool isPrintable(int UCS) {
// Sorted list of non-overlapping intervals of code points that are not
// supposed to be printable.
static const UnicodeCharRange NonPrintableRanges[] = {
{ 0x0000, 0x001F }, { 0x007F, 0x009F }, { 0x034F, 0x034F },
{ 0x0378, 0x0379 }, { 0x037F, 0x0383 }, { 0x038B, 0x038B },
{ 0x038D, 0x038D }, { 0x03A2, 0x03A2 }, { 0x0528, 0x0530 },
{ 0x0557, 0x0558 }, { 0x0560, 0x0560 }, { 0x0588, 0x0588 },
{ 0x058B, 0x058E }, { 0x0590, 0x0590 }, { 0x05C8, 0x05CF },
{ 0x05EB, 0x05EF }, { 0x05F5, 0x0605 }, { 0x061C, 0x061D },
{ 0x06DD, 0x06DD }, { 0x070E, 0x070F }, { 0x074B, 0x074C },
{ 0x07B2, 0x07BF }, { 0x07FB, 0x07FF }, { 0x082E, 0x082F },
{ 0x083F, 0x083F }, { 0x085C, 0x085D }, { 0x085F, 0x089F },
{ 0x08A1, 0x08A1 }, { 0x08AD, 0x08E3 }, { 0x08FF, 0x08FF },
{ 0x0978, 0x0978 }, { 0x0980, 0x0980 }, { 0x0984, 0x0984 },
{ 0x098D, 0x098E }, { 0x0991, 0x0992 }, { 0x09A9, 0x09A9 },
{ 0x09B1, 0x09B1 }, { 0x09B3, 0x09B5 }, { 0x09BA, 0x09BB },
{ 0x09C5, 0x09C6 }, { 0x09C9, 0x09CA }, { 0x09CF, 0x09D6 },
{ 0x09D8, 0x09DB }, { 0x09DE, 0x09DE }, { 0x09E4, 0x09E5 },
{ 0x09FC, 0x0A00 }, { 0x0A04, 0x0A04 }, { 0x0A0B, 0x0A0E },
{ 0x0A11, 0x0A12 }, { 0x0A29, 0x0A29 }, { 0x0A31, 0x0A31 },
{ 0x0A34, 0x0A34 }, { 0x0A37, 0x0A37 }, { 0x0A3A, 0x0A3B },
{ 0x0A3D, 0x0A3D }, { 0x0A43, 0x0A46 }, { 0x0A49, 0x0A4A },
{ 0x0A4E, 0x0A50 }, { 0x0A52, 0x0A58 }, { 0x0A5D, 0x0A5D },
{ 0x0A5F, 0x0A65 }, { 0x0A76, 0x0A80 }, { 0x0A84, 0x0A84 },
{ 0x0A8E, 0x0A8E }, { 0x0A92, 0x0A92 }, { 0x0AA9, 0x0AA9 },
{ 0x0AB1, 0x0AB1 }, { 0x0AB4, 0x0AB4 }, { 0x0ABA, 0x0ABB },
{ 0x0AC6, 0x0AC6 }, { 0x0ACA, 0x0ACA }, { 0x0ACE, 0x0ACF },
{ 0x0AD1, 0x0ADF }, { 0x0AE4, 0x0AE5 }, { 0x0AF2, 0x0B00 },
{ 0x0B04, 0x0B04 }, { 0x0B0D, 0x0B0E }, { 0x0B11, 0x0B12 },
{ 0x0B29, 0x0B29 }, { 0x0B31, 0x0B31 }, { 0x0B34, 0x0B34 },
{ 0x0B3A, 0x0B3B }, { 0x0B45, 0x0B46 }, { 0x0B49, 0x0B4A },
{ 0x0B4E, 0x0B55 }, { 0x0B58, 0x0B5B }, { 0x0B5E, 0x0B5E },
{ 0x0B64, 0x0B65 }, { 0x0B78, 0x0B81 }, { 0x0B84, 0x0B84 },
{ 0x0B8B, 0x0B8D }, { 0x0B91, 0x0B91 }, { 0x0B96, 0x0B98 },
{ 0x0B9B, 0x0B9B }, { 0x0B9D, 0x0B9D }, { 0x0BA0, 0x0BA2 },
{ 0x0BA5, 0x0BA7 }, { 0x0BAB, 0x0BAD }, { 0x0BBA, 0x0BBD },
{ 0x0BC3, 0x0BC5 }, { 0x0BC9, 0x0BC9 }, { 0x0BCE, 0x0BCF },
{ 0x0BD1, 0x0BD6 }, { 0x0BD8, 0x0BE5 }, { 0x0BFB, 0x0C00 },
{ 0x0C04, 0x0C04 }, { 0x0C0D, 0x0C0D }, { 0x0C11, 0x0C11 },
{ 0x0C29, 0x0C29 }, { 0x0C34, 0x0C34 }, { 0x0C3A, 0x0C3C },
{ 0x0C45, 0x0C45 }, { 0x0C49, 0x0C49 }, { 0x0C4E, 0x0C54 },
{ 0x0C57, 0x0C57 }, { 0x0C5A, 0x0C5F }, { 0x0C64, 0x0C65 },
{ 0x0C70, 0x0C77 }, { 0x0C80, 0x0C81 }, { 0x0C84, 0x0C84 },
{ 0x0C8D, 0x0C8D }, { 0x0C91, 0x0C91 }, { 0x0CA9, 0x0CA9 },
{ 0x0CB4, 0x0CB4 }, { 0x0CBA, 0x0CBB }, { 0x0CC5, 0x0CC5 },
{ 0x0CC9, 0x0CC9 }, { 0x0CCE, 0x0CD4 }, { 0x0CD7, 0x0CDD },
{ 0x0CDF, 0x0CDF }, { 0x0CE4, 0x0CE5 }, { 0x0CF0, 0x0CF0 },
{ 0x0CF3, 0x0D01 }, { 0x0D04, 0x0D04 }, { 0x0D0D, 0x0D0D },
{ 0x0D11, 0x0D11 }, { 0x0D3B, 0x0D3C }, { 0x0D45, 0x0D45 },
{ 0x0D49, 0x0D49 }, { 0x0D4F, 0x0D56 }, { 0x0D58, 0x0D5F },
{ 0x0D64, 0x0D65 }, { 0x0D76, 0x0D78 }, { 0x0D80, 0x0D81 },
{ 0x0D84, 0x0D84 }, { 0x0D97, 0x0D99 }, { 0x0DB2, 0x0DB2 },
{ 0x0DBC, 0x0DBC }, { 0x0DBE, 0x0DBF }, { 0x0DC7, 0x0DC9 },
{ 0x0DCB, 0x0DCE }, { 0x0DD5, 0x0DD5 }, { 0x0DD7, 0x0DD7 },
{ 0x0DE0, 0x0DF1 }, { 0x0DF5, 0x0E00 }, { 0x0E3B, 0x0E3E },
{ 0x0E5C, 0x0E80 }, { 0x0E83, 0x0E83 }, { 0x0E85, 0x0E86 },
{ 0x0E89, 0x0E89 }, { 0x0E8B, 0x0E8C }, { 0x0E8E, 0x0E93 },
{ 0x0E98, 0x0E98 }, { 0x0EA0, 0x0EA0 }, { 0x0EA4, 0x0EA4 },
{ 0x0EA6, 0x0EA6 }, { 0x0EA8, 0x0EA9 }, { 0x0EAC, 0x0EAC },
{ 0x0EBA, 0x0EBA }, { 0x0EBE, 0x0EBF }, { 0x0EC5, 0x0EC5 },
{ 0x0EC7, 0x0EC7 }, { 0x0ECE, 0x0ECF }, { 0x0EDA, 0x0EDB },
{ 0x0EE0, 0x0EFF }, { 0x0F48, 0x0F48 }, { 0x0F6D, 0x0F70 },
{ 0x0F98, 0x0F98 }, { 0x0FBD, 0x0FBD }, { 0x0FCD, 0x0FCD },
{ 0x0FDB, 0x0FFF }, { 0x10C6, 0x10C6 }, { 0x10C8, 0x10CC },
{ 0x10CE, 0x10CF }, { 0x115F, 0x1160 }, { 0x1249, 0x1249 },
{ 0x124E, 0x124F }, { 0x1257, 0x1257 }, { 0x1259, 0x1259 },
{ 0x125E, 0x125F }, { 0x1289, 0x1289 }, { 0x128E, 0x128F },
{ 0x12B1, 0x12B1 }, { 0x12B6, 0x12B7 }, { 0x12BF, 0x12BF },
{ 0x12C1, 0x12C1 }, { 0x12C6, 0x12C7 }, { 0x12D7, 0x12D7 },
{ 0x1311, 0x1311 }, { 0x1316, 0x1317 }, { 0x135B, 0x135C },
{ 0x137D, 0x137F }, { 0x139A, 0x139F }, { 0x13F5, 0x13FF },
{ 0x169D, 0x169F }, { 0x16F1, 0x16FF }, { 0x170D, 0x170D },
{ 0x1715, 0x171F }, { 0x1737, 0x173F }, { 0x1754, 0x175F },
{ 0x176D, 0x176D }, { 0x1771, 0x1771 }, { 0x1774, 0x177F },
{ 0x17B4, 0x17B5 }, { 0x17DE, 0x17DF }, { 0x17EA, 0x17EF },
{ 0x17FA, 0x17FF }, { 0x180B, 0x180D }, { 0x180F, 0x180F },
{ 0x181A, 0x181F }, { 0x1878, 0x187F }, { 0x18AB, 0x18AF },
{ 0x18F6, 0x18FF }, { 0x191D, 0x191F }, { 0x192C, 0x192F },
{ 0x193C, 0x193F }, { 0x1941, 0x1943 }, { 0x196E, 0x196F },
{ 0x1975, 0x197F }, { 0x19AC, 0x19AF }, { 0x19CA, 0x19CF },
{ 0x19DB, 0x19DD }, { 0x1A1C, 0x1A1D }, { 0x1A5F, 0x1A5F },
{ 0x1A7D, 0x1A7E }, { 0x1A8A, 0x1A8F }, { 0x1A9A, 0x1A9F },
{ 0x1AAE, 0x1AFF }, { 0x1B4C, 0x1B4F }, { 0x1B7D, 0x1B7F },
{ 0x1BF4, 0x1BFB }, { 0x1C38, 0x1C3A }, { 0x1C4A, 0x1C4C },
{ 0x1C80, 0x1CBF }, { 0x1CC8, 0x1CCF }, { 0x1CF7, 0x1CFF },
{ 0x1DE7, 0x1DFB }, { 0x1F16, 0x1F17 }, { 0x1F1E, 0x1F1F },
{ 0x1F46, 0x1F47 }, { 0x1F4E, 0x1F4F }, { 0x1F58, 0x1F58 },
{ 0x1F5A, 0x1F5A }, { 0x1F5C, 0x1F5C }, { 0x1F5E, 0x1F5E },
{ 0x1F7E, 0x1F7F }, { 0x1FB5, 0x1FB5 }, { 0x1FC5, 0x1FC5 },
{ 0x1FD4, 0x1FD5 }, { 0x1FDC, 0x1FDC }, { 0x1FF0, 0x1FF1 },
{ 0x1FF5, 0x1FF5 }, { 0x1FFF, 0x1FFF }, { 0x200B, 0x200F },
{ 0x202A, 0x202E }, { 0x2060, 0x206F }, { 0x2072, 0x2073 },
{ 0x208F, 0x208F }, { 0x209D, 0x209F }, { 0x20BB, 0x20CF },
{ 0x20F1, 0x20FF }, { 0x218A, 0x218F }, { 0x23F4, 0x23FF },
{ 0x2427, 0x243F }, { 0x244B, 0x245F }, { 0x2700, 0x2700 },
{ 0x2B4D, 0x2B4F }, { 0x2B5A, 0x2BFF }, { 0x2C2F, 0x2C2F },
{ 0x2C5F, 0x2C5F }, { 0x2CF4, 0x2CF8 }, { 0x2D26, 0x2D26 },
{ 0x2D28, 0x2D2C }, { 0x2D2E, 0x2D2F }, { 0x2D68, 0x2D6E },
{ 0x2D71, 0x2D7E }, { 0x2D97, 0x2D9F }, { 0x2DA7, 0x2DA7 },
{ 0x2DAF, 0x2DAF }, { 0x2DB7, 0x2DB7 }, { 0x2DBF, 0x2DBF },
{ 0x2DC7, 0x2DC7 }, { 0x2DCF, 0x2DCF }, { 0x2DD7, 0x2DD7 },
{ 0x2DDF, 0x2DDF }, { 0x2E3C, 0x2E7F }, { 0x2E9A, 0x2E9A },
{ 0x2EF4, 0x2EFF }, { 0x2FD6, 0x2FEF }, { 0x2FFC, 0x2FFF },
{ 0x3040, 0x3040 }, { 0x3097, 0x3098 }, { 0x3100, 0x3104 },
{ 0x312E, 0x3130 }, { 0x3164, 0x3164 }, { 0x318F, 0x318F },
{ 0x31BB, 0x31BF }, { 0x31E4, 0x31EF }, { 0x321F, 0x321F },
{ 0x32FF, 0x32FF }, { 0x4DB6, 0x4DBF }, { 0x9FCD, 0x9FFF },
{ 0xA48D, 0xA48F }, { 0xA4C7, 0xA4CF }, { 0xA62C, 0xA63F },
{ 0xA698, 0xA69E }, { 0xA6F8, 0xA6FF }, { 0xA78F, 0xA78F },
{ 0xA794, 0xA79F }, { 0xA7AB, 0xA7F7 }, { 0xA82C, 0xA82F },
{ 0xA83A, 0xA83F }, { 0xA878, 0xA87F }, { 0xA8C5, 0xA8CD },
{ 0xA8DA, 0xA8DF }, { 0xA8FC, 0xA8FF }, { 0xA954, 0xA95E },
{ 0xA97D, 0xA97F }, { 0xA9CE, 0xA9CE }, { 0xA9DA, 0xA9DD },
{ 0xA9E0, 0xA9FF }, { 0xAA37, 0xAA3F }, { 0xAA4E, 0xAA4F },
{ 0xAA5A, 0xAA5B }, { 0xAA7C, 0xAA7F }, { 0xAAC3, 0xAADA },
{ 0xAAF7, 0xAB00 }, { 0xAB07, 0xAB08 }, { 0xAB0F, 0xAB10 },
{ 0xAB17, 0xAB1F }, { 0xAB27, 0xAB27 }, { 0xAB2F, 0xABBF },
{ 0xABEE, 0xABEF }, { 0xABFA, 0xABFF }, { 0xD7A4, 0xD7AF },
{ 0xD7C7, 0xD7CA }, { 0xD7FC, 0xDFFF }, { 0xFA6E, 0xFA6F },
{ 0xFADA, 0xFAFF }, { 0xFB07, 0xFB12 }, { 0xFB18, 0xFB1C },
{ 0xFB37, 0xFB37 }, { 0xFB3D, 0xFB3D }, { 0xFB3F, 0xFB3F },
{ 0xFB42, 0xFB42 }, { 0xFB45, 0xFB45 }, { 0xFBC2, 0xFBD2 },
{ 0xFD40, 0xFD4F }, { 0xFD90, 0xFD91 }, { 0xFDC8, 0xFDEF },
{ 0xFDFE, 0xFE0F }, { 0xFE1A, 0xFE1F }, { 0xFE27, 0xFE2F },
{ 0xFE53, 0xFE53 }, { 0xFE67, 0xFE67 }, { 0xFE6C, 0xFE6F },
{ 0xFE75, 0xFE75 }, { 0xFEFD, 0xFEFF }, { 0xFF00, 0xFF00 },
{ 0xFFA0, 0xFFA0 }, { 0xFFBF, 0xFFC1 }, { 0xFFC8, 0xFFC9 },
{ 0xFFD0, 0xFFD1 }, { 0xFFD8, 0xFFD9 }, { 0xFFDD, 0xFFDF },
{ 0xFFE7, 0xFFE7 }, { 0xFFEF, 0xFFFB }, { 0xFFFE, 0xFFFF },
{ 0x1000C, 0x1000C }, { 0x10027, 0x10027 }, { 0x1003B, 0x1003B },
{ 0x1003E, 0x1003E }, { 0x1004E, 0x1004F }, { 0x1005E, 0x1007F },
{ 0x100FB, 0x100FF }, { 0x10103, 0x10106 }, { 0x10134, 0x10136 },
{ 0x1018B, 0x1018F }, { 0x1019C, 0x101CF }, { 0x101FE, 0x1027F },
{ 0x1029D, 0x1029F }, { 0x102D1, 0x102FF }, { 0x1031F, 0x1031F },
{ 0x10324, 0x1032F }, { 0x1034B, 0x1037F }, { 0x1039E, 0x1039E },
{ 0x103C4, 0x103C7 }, { 0x103D6, 0x103FF }, { 0x1049E, 0x1049F },
{ 0x104AA, 0x107FF }, { 0x10806, 0x10807 }, { 0x10809, 0x10809 },
{ 0x10836, 0x10836 }, { 0x10839, 0x1083B }, { 0x1083D, 0x1083E },
{ 0x10856, 0x10856 }, { 0x10860, 0x108FF }, { 0x1091C, 0x1091E },
{ 0x1093A, 0x1093E }, { 0x10940, 0x1097F }, { 0x109B8, 0x109BD },
{ 0x109C0, 0x109FF }, { 0x10A04, 0x10A04 }, { 0x10A07, 0x10A0B },
{ 0x10A14, 0x10A14 }, { 0x10A18, 0x10A18 }, { 0x10A34, 0x10A37 },
{ 0x10A3B, 0x10A3E }, { 0x10A48, 0x10A4F }, { 0x10A59, 0x10A5F },
{ 0x10A80, 0x10AFF }, { 0x10B36, 0x10B38 }, { 0x10B56, 0x10B57 },
{ 0x10B73, 0x10B77 }, { 0x10B80, 0x10BFF }, { 0x10C49, 0x10E5F },
{ 0x10E7F, 0x10FFF }, { 0x1104E, 0x11051 }, { 0x11070, 0x1107F },
{ 0x110BD, 0x110BD }, { 0x110C2, 0x110CF }, { 0x110E9, 0x110EF },
{ 0x110FA, 0x110FF }, { 0x11135, 0x11135 }, { 0x11144, 0x1117F },
{ 0x111C9, 0x111CF }, { 0x111DA, 0x1167F }, { 0x116B8, 0x116BF },
{ 0x116CA, 0x11FFF }, { 0x1236F, 0x123FF }, { 0x12463, 0x1246F },
{ 0x12474, 0x12FFF }, { 0x1342F, 0x167FF }, { 0x16A39, 0x16EFF },
{ 0x16F45, 0x16F4F }, { 0x16F7F, 0x16F8E }, { 0x16FA0, 0x1AFFF },
{ 0x1B002, 0x1CFFF }, { 0x1D0F6, 0x1D0FF }, { 0x1D127, 0x1D128 },
{ 0x1D173, 0x1D17A }, { 0x1D1DE, 0x1D1FF }, { 0x1D246, 0x1D2FF },
{ 0x1D357, 0x1D35F }, { 0x1D372, 0x1D3FF }, { 0x1D455, 0x1D455 },
{ 0x1D49D, 0x1D49D }, { 0x1D4A0, 0x1D4A1 }, { 0x1D4A3, 0x1D4A4 },
{ 0x1D4A7, 0x1D4A8 }, { 0x1D4AD, 0x1D4AD }, { 0x1D4BA, 0x1D4BA },
{ 0x1D4BC, 0x1D4BC }, { 0x1D4C4, 0x1D4C4 }, { 0x1D506, 0x1D506 },
{ 0x1D50B, 0x1D50C }, { 0x1D515, 0x1D515 }, { 0x1D51D, 0x1D51D },
{ 0x1D53A, 0x1D53A }, { 0x1D53F, 0x1D53F }, { 0x1D545, 0x1D545 },
{ 0x1D547, 0x1D549 }, { 0x1D551, 0x1D551 }, { 0x1D6A6, 0x1D6A7 },
{ 0x1D7CC, 0x1D7CD }, { 0x1D800, 0x1EDFF }, { 0x1EE04, 0x1EE04 },
{ 0x1EE20, 0x1EE20 }, { 0x1EE23, 0x1EE23 }, { 0x1EE25, 0x1EE26 },
{ 0x1EE28, 0x1EE28 }, { 0x1EE33, 0x1EE33 }, { 0x1EE38, 0x1EE38 },
{ 0x1EE3A, 0x1EE3A }, { 0x1EE3C, 0x1EE41 }, { 0x1EE43, 0x1EE46 },
{ 0x1EE48, 0x1EE48 }, { 0x1EE4A, 0x1EE4A }, { 0x1EE4C, 0x1EE4C },
{ 0x1EE50, 0x1EE50 }, { 0x1EE53, 0x1EE53 }, { 0x1EE55, 0x1EE56 },
{ 0x1EE58, 0x1EE58 }, { 0x1EE5A, 0x1EE5A }, { 0x1EE5C, 0x1EE5C },
{ 0x1EE5E, 0x1EE5E }, { 0x1EE60, 0x1EE60 }, { 0x1EE63, 0x1EE63 },
{ 0x1EE65, 0x1EE66 }, { 0x1EE6B, 0x1EE6B }, { 0x1EE73, 0x1EE73 },
{ 0x1EE78, 0x1EE78 }, { 0x1EE7D, 0x1EE7D }, { 0x1EE7F, 0x1EE7F },
{ 0x1EE8A, 0x1EE8A }, { 0x1EE9C, 0x1EEA0 }, { 0x1EEA4, 0x1EEA4 },
{ 0x1EEAA, 0x1EEAA }, { 0x1EEBC, 0x1EEEF }, { 0x1EEF2, 0x1EFFF },
{ 0x1F02C, 0x1F02F }, { 0x1F094, 0x1F09F }, { 0x1F0AF, 0x1F0B0 },
{ 0x1F0BF, 0x1F0C0 }, { 0x1F0D0, 0x1F0D0 }, { 0x1F0E0, 0x1F0FF },
{ 0x1F10B, 0x1F10F }, { 0x1F12F, 0x1F12F }, { 0x1F16C, 0x1F16F },
{ 0x1F19B, 0x1F1E5 }, { 0x1F203, 0x1F20F }, { 0x1F23B, 0x1F23F },
{ 0x1F249, 0x1F24F }, { 0x1F252, 0x1F2FF }, { 0x1F321, 0x1F32F },
{ 0x1F336, 0x1F336 }, { 0x1F37D, 0x1F37F }, { 0x1F394, 0x1F39F },
{ 0x1F3C5, 0x1F3C5 }, { 0x1F3CB, 0x1F3DF }, { 0x1F3F1, 0x1F3FF },
{ 0x1F43F, 0x1F43F }, { 0x1F441, 0x1F441 }, { 0x1F4F8, 0x1F4F8 },
{ 0x1F4FD, 0x1F4FF }, { 0x1F53E, 0x1F53F }, { 0x1F544, 0x1F54F },
{ 0x1F568, 0x1F5FA }, { 0x1F641, 0x1F644 }, { 0x1F650, 0x1F67F },
{ 0x1F6C6, 0x1F6FF }, { 0x1F774, 0x1FFFF }, { 0x2A6D7, 0x2A6FF },
{ 0x2B735, 0x2B73F }, { 0x2B81E, 0x2F7FF }, { 0x2FA1E, 0xF0000 },
{ 0xFFFFE, 0xFFFFF }, { 0x10FFFE, 0x10FFFF }
};
static const UnicodeCharSet NonPrintables(NonPrintableRanges);
return UCS >= 0 && UCS <= 0x10FFFF && !NonPrintables.contains(UCS);
}
/// Gets the number of positions a character is likely to occupy when output
/// on a terminal ("character width"). This depends on the implementation of the
/// terminal, and there's no standard definition of character width.
/// The implementation defines it in a way that is expected to be compatible
/// with a generic Unicode-capable terminal.
/// \return Character width:
/// * ErrorNonPrintableCharacter (-1) for non-printable characters (as
/// identified by isPrintable);
/// * 0 for non-spacing and enclosing combining marks;
/// * 2 for CJK characters excluding halfwidth forms;
/// * 1 for all remaining characters.
static inline int charWidth(int UCS)
{
if (!isPrintable(UCS))
return ErrorNonPrintableCharacter;
// Sorted list of non-spacing and enclosing combining mark intervals as
// defined in "3.6 Combination" of
// http://www.unicode.org/versions/Unicode6.2.0/UnicodeStandard-6.2.pdf
static const UnicodeCharRange CombiningCharacterRanges[] = {
{ 0x0300, 0x036F }, { 0x0483, 0x0489 }, { 0x0591, 0x05BD },
{ 0x05BF, 0x05BF }, { 0x05C1, 0x05C2 }, { 0x05C4, 0x05C5 },
{ 0x05C7, 0x05C7 }, { 0x0610, 0x061A }, { 0x064B, 0x065F },
{ 0x0670, 0x0670 }, { 0x06D6, 0x06DC }, { 0x06DF, 0x06E4 },
{ 0x06E7, 0x06E8 }, { 0x06EA, 0x06ED }, { 0x0711, 0x0711 },
{ 0x0730, 0x074A }, { 0x07A6, 0x07B0 }, { 0x07EB, 0x07F3 },
{ 0x0816, 0x0819 }, { 0x081B, 0x0823 }, { 0x0825, 0x0827 },
{ 0x0829, 0x082D }, { 0x0859, 0x085B }, { 0x08E4, 0x08FE },
{ 0x0900, 0x0902 }, { 0x093A, 0x093A }, { 0x093C, 0x093C },
{ 0x0941, 0x0948 }, { 0x094D, 0x094D }, { 0x0951, 0x0957 },
{ 0x0962, 0x0963 }, { 0x0981, 0x0981 }, { 0x09BC, 0x09BC },
{ 0x09C1, 0x09C4 }, { 0x09CD, 0x09CD }, { 0x09E2, 0x09E3 },
{ 0x0A01, 0x0A02 }, { 0x0A3C, 0x0A3C }, { 0x0A41, 0x0A42 },
{ 0x0A47, 0x0A48 }, { 0x0A4B, 0x0A4D }, { 0x0A51, 0x0A51 },
{ 0x0A70, 0x0A71 }, { 0x0A75, 0x0A75 }, { 0x0A81, 0x0A82 },
{ 0x0ABC, 0x0ABC }, { 0x0AC1, 0x0AC5 }, { 0x0AC7, 0x0AC8 },
{ 0x0ACD, 0x0ACD }, { 0x0AE2, 0x0AE3 }, { 0x0B01, 0x0B01 },
{ 0x0B3C, 0x0B3C }, { 0x0B3F, 0x0B3F }, { 0x0B41, 0x0B44 },
{ 0x0B4D, 0x0B4D }, { 0x0B56, 0x0B56 }, { 0x0B62, 0x0B63 },
{ 0x0B82, 0x0B82 }, { 0x0BC0, 0x0BC0 }, { 0x0BCD, 0x0BCD },
{ 0x0C3E, 0x0C40 }, { 0x0C46, 0x0C48 }, { 0x0C4A, 0x0C4D },
{ 0x0C55, 0x0C56 }, { 0x0C62, 0x0C63 }, { 0x0CBC, 0x0CBC },
{ 0x0CBF, 0x0CBF }, { 0x0CC6, 0x0CC6 }, { 0x0CCC, 0x0CCD },
{ 0x0CE2, 0x0CE3 }, { 0x0D41, 0x0D44 }, { 0x0D4D, 0x0D4D },
{ 0x0D62, 0x0D63 }, { 0x0DCA, 0x0DCA }, { 0x0DD2, 0x0DD4 },
{ 0x0DD6, 0x0DD6 }, { 0x0E31, 0x0E31 }, { 0x0E34, 0x0E3A },
{ 0x0E47, 0x0E4E }, { 0x0EB1, 0x0EB1 }, { 0x0EB4, 0x0EB9 },
{ 0x0EBB, 0x0EBC }, { 0x0EC8, 0x0ECD }, { 0x0F18, 0x0F19 },
{ 0x0F35, 0x0F35 }, { 0x0F37, 0x0F37 }, { 0x0F39, 0x0F39 },
{ 0x0F71, 0x0F7E }, { 0x0F80, 0x0F84 }, { 0x0F86, 0x0F87 },
{ 0x0F8D, 0x0F97 }, { 0x0F99, 0x0FBC }, { 0x0FC6, 0x0FC6 },
{ 0x102D, 0x1030 }, { 0x1032, 0x1037 }, { 0x1039, 0x103A },
{ 0x103D, 0x103E }, { 0x1058, 0x1059 }, { 0x105E, 0x1060 },
{ 0x1071, 0x1074 }, { 0x1082, 0x1082 }, { 0x1085, 0x1086 },
{ 0x108D, 0x108D }, { 0x109D, 0x109D }, { 0x135D, 0x135F },
{ 0x1712, 0x1714 }, { 0x1732, 0x1734 }, { 0x1752, 0x1753 },
{ 0x1772, 0x1773 }, { 0x17B4, 0x17B5 }, { 0x17B7, 0x17BD },
{ 0x17C6, 0x17C6 }, { 0x17C9, 0x17D3 }, { 0x17DD, 0x17DD },
{ 0x180B, 0x180D }, { 0x18A9, 0x18A9 }, { 0x1920, 0x1922 },
{ 0x1927, 0x1928 }, { 0x1932, 0x1932 }, { 0x1939, 0x193B },
{ 0x1A17, 0x1A18 }, { 0x1A56, 0x1A56 }, { 0x1A58, 0x1A5E },
{ 0x1A60, 0x1A60 }, { 0x1A62, 0x1A62 }, { 0x1A65, 0x1A6C },
{ 0x1A73, 0x1A7C }, { 0x1A7F, 0x1A7F }, { 0x1B00, 0x1B03 },
{ 0x1B34, 0x1B34 }, { 0x1B36, 0x1B3A }, { 0x1B3C, 0x1B3C },
{ 0x1B42, 0x1B42 }, { 0x1B6B, 0x1B73 }, { 0x1B80, 0x1B81 },
{ 0x1BA2, 0x1BA5 }, { 0x1BA8, 0x1BA9 }, { 0x1BAB, 0x1BAB },
{ 0x1BE6, 0x1BE6 }, { 0x1BE8, 0x1BE9 }, { 0x1BED, 0x1BED },
{ 0x1BEF, 0x1BF1 }, { 0x1C2C, 0x1C33 }, { 0x1C36, 0x1C37 },
{ 0x1CD0, 0x1CD2 }, { 0x1CD4, 0x1CE0 }, { 0x1CE2, 0x1CE8 },
{ 0x1CED, 0x1CED }, { 0x1CF4, 0x1CF4 }, { 0x1DC0, 0x1DE6 },
{ 0x1DFC, 0x1DFF }, { 0x20D0, 0x20F0 }, { 0x2CEF, 0x2CF1 },
{ 0x2D7F, 0x2D7F }, { 0x2DE0, 0x2DFF }, { 0x302A, 0x302D },
{ 0x3099, 0x309A }, { 0xA66F, 0xA672 }, { 0xA674, 0xA67D },
{ 0xA69F, 0xA69F }, { 0xA6F0, 0xA6F1 }, { 0xA802, 0xA802 },
{ 0xA806, 0xA806 }, { 0xA80B, 0xA80B }, { 0xA825, 0xA826 },
{ 0xA8C4, 0xA8C4 }, { 0xA8E0, 0xA8F1 }, { 0xA926, 0xA92D },
{ 0xA947, 0xA951 }, { 0xA980, 0xA982 }, { 0xA9B3, 0xA9B3 },
{ 0xA9B6, 0xA9B9 }, { 0xA9BC, 0xA9BC }, { 0xAA29, 0xAA2E },
{ 0xAA31, 0xAA32 }, { 0xAA35, 0xAA36 }, { 0xAA43, 0xAA43 },
{ 0xAA4C, 0xAA4C }, { 0xAAB0, 0xAAB0 }, { 0xAAB2, 0xAAB4 },
{ 0xAAB7, 0xAAB8 }, { 0xAABE, 0xAABF }, { 0xAAC1, 0xAAC1 },
{ 0xAAEC, 0xAAED }, { 0xAAF6, 0xAAF6 }, { 0xABE5, 0xABE5 },
{ 0xABE8, 0xABE8 }, { 0xABED, 0xABED }, { 0xFB1E, 0xFB1E },
{ 0xFE00, 0xFE0F }, { 0xFE20, 0xFE26 }, { 0x101FD, 0x101FD },
{ 0x10A01, 0x10A03 }, { 0x10A05, 0x10A06 }, { 0x10A0C, 0x10A0F },
{ 0x10A38, 0x10A3A }, { 0x10A3F, 0x10A3F }, { 0x11001, 0x11001 },
{ 0x11038, 0x11046 }, { 0x11080, 0x11081 }, { 0x110B3, 0x110B6 },
{ 0x110B9, 0x110BA }, { 0x11100, 0x11102 }, { 0x11127, 0x1112B },
{ 0x1112D, 0x11134 }, { 0x11180, 0x11181 }, { 0x111B6, 0x111BE },
{ 0x116AB, 0x116AB }, { 0x116AD, 0x116AD }, { 0x116B0, 0x116B5 },
{ 0x116B7, 0x116B7 }, { 0x16F8F, 0x16F92 }, { 0x1D167, 0x1D169 },
{ 0x1D17B, 0x1D182 }, { 0x1D185, 0x1D18B }, { 0x1D1AA, 0x1D1AD },
{ 0x1D242, 0x1D244 }, { 0xE0100, 0xE01EF },
};
static const UnicodeCharSet CombiningCharacters(CombiningCharacterRanges);
if (CombiningCharacters.contains(UCS))
return 0;
static const UnicodeCharRange DoubleWidthCharacterRanges[] = {
// Hangul Jamo
{ 0x1100, 0x11FF },
// Deprecated fullwidth angle brackets
{ 0x2329, 0x232A },
// CJK Misc, CJK Unified Ideographs, Yijing Hexagrams, Yi
// excluding U+303F (IDEOGRAPHIC HALF FILL SPACE)
{ 0x2E80, 0x303E }, { 0x3040, 0xA4CF },
// Hangul
{ 0xAC00, 0xD7A3 }, { 0xD7B0, 0xD7C6 }, { 0xD7CB, 0xD7FB },
// CJK Unified Ideographs
{ 0xF900, 0xFAFF },
// Vertical forms
{ 0xFE10, 0xFE19 },
// CJK Compatibility Forms + Small Form Variants
{ 0xFE30, 0xFE6F },
// Fullwidth forms
{ 0xFF01, 0xFF60 }, { 0xFFE0, 0xFFE6 },
// CJK Unified Ideographs
{ 0x20000, 0x2A6DF }, { 0x2A700, 0x2B81F }, { 0x2F800, 0x2FA1F }
};
static const UnicodeCharSet DoubleWidthCharacters(DoubleWidthCharacterRanges);
if (DoubleWidthCharacters.contains(UCS))
return 2;
return 1;
}
int columnWidthUTF8(StringRef Text) {
unsigned ColumnWidth = 0;
unsigned Length;
for (size_t i = 0, e = Text.size(); i < e; i += Length) {
Length = getNumBytesForUTF8(Text[i]);
if (Length <= 0 || i + Length > Text.size())
return ErrorInvalidUTF8;
UTF32 buf[1];
const UTF8 *Start = reinterpret_cast<const UTF8 *>(Text.data() + i);
UTF32 *Target = &buf[0];
if (conversionOK != ConvertUTF8toUTF32(&Start, Start + Length, &Target,
Target + 1, strictConversion))
return ErrorInvalidUTF8;
int Width = charWidth(buf[0]);
if (Width < 0)
return ErrorNonPrintableCharacter;
ColumnWidth += Width;
}
return ColumnWidth;
}
} // namespace unicode
} // namespace sys
} // namespace llvm
|
{
"pile_set_name": "Github"
}
|
{
"checks": {
"check_disk": {
"command": "{{ sensu_plugins_dir }}/check-disk.rb",
{% if enable_handlers %}
{% if not multiple_handlers %}
"handler": "{{ default_handler }}",
{% endif %}
{% if multiple_handlers %}
"handlers": [
{% for item in default_handlers %}
"{{ item }}",
{% endfor %}
"{{ default_handler }}"
],
{% endif %}
{% endif %}
"occurences": 3,
"interval": 60,
"subscribers": [ "ALL" ]
}
}
}
|
{
"pile_set_name": "Github"
}
|
pppd: Allow specifying ip-up and ip-down scripts
This patch implements the "ip-up-script" and "ip-down-script" options which
allow to specify the path of the ip-up and ip-down scripts to call.
These options default to _PATH_IPUP and _PATH_IPDOWN to retain the
existing behaviour.
The patch originated from the Debian project.
Signed-off-by: Jo-Philipp Wich <[email protected]>
--- a/pppd/ipcp.c
+++ b/pppd/ipcp.c
@@ -1958,7 +1958,7 @@ ipcp_up(f)
*/
if (ipcp_script_state == s_down && ipcp_script_pid == 0) {
ipcp_script_state = s_up;
- ipcp_script(_PATH_IPUP, 0);
+ ipcp_script(path_ipup, 0);
}
}
@@ -2008,7 +2008,7 @@ ipcp_down(f)
/* Execute the ip-down script */
if (ipcp_script_state == s_up && ipcp_script_pid == 0) {
ipcp_script_state = s_down;
- ipcp_script(_PATH_IPDOWN, 0);
+ ipcp_script(path_ipdown, 0);
}
}
@@ -2062,13 +2062,13 @@ ipcp_script_done(arg)
case s_up:
if (ipcp_fsm[0].state != OPENED) {
ipcp_script_state = s_down;
- ipcp_script(_PATH_IPDOWN, 0);
+ ipcp_script(path_ipdown, 0);
}
break;
case s_down:
if (ipcp_fsm[0].state == OPENED) {
ipcp_script_state = s_up;
- ipcp_script(_PATH_IPUP, 0);
+ ipcp_script(path_ipup, 0);
}
break;
}
--- a/pppd/main.c
+++ b/pppd/main.c
@@ -316,6 +316,9 @@ main(argc, argv)
struct protent *protp;
char numbuf[16];
+ strlcpy(path_ipup, _PATH_IPUP, sizeof(path_ipup));
+ strlcpy(path_ipdown, _PATH_IPDOWN, sizeof(path_ipdown));
+
link_stats_valid = 0;
new_phase(PHASE_INITIALIZE);
--- a/pppd/options.c
+++ b/pppd/options.c
@@ -114,6 +114,8 @@ char linkname[MAXPATHLEN]; /* logical na
bool tune_kernel; /* may alter kernel settings */
int connect_delay = 1000; /* wait this many ms after connect script */
int req_unit = -1; /* requested interface unit */
+char path_ipup[MAXPATHLEN]; /* pathname of ip-up script */
+char path_ipdown[MAXPATHLEN];/* pathname of ip-down script */
bool multilink = 0; /* Enable multilink operation */
char *bundle_name = NULL; /* bundle name for multilink */
bool dump_options; /* print out option values */
@@ -299,6 +301,13 @@ option_t general_options[] = {
"Unset user environment variable",
OPT_A2PRINTER | OPT_NOPRINT, (void *)user_unsetprint },
+ { "ip-up-script", o_string, path_ipup,
+ "Set pathname of ip-up script",
+ OPT_PRIV|OPT_STATIC, NULL, MAXPATHLEN },
+ { "ip-down-script", o_string, path_ipdown,
+ "Set pathname of ip-down script",
+ OPT_PRIV|OPT_STATIC, NULL, MAXPATHLEN },
+
#ifdef HAVE_MULTILINK
{ "multilink", o_bool, &multilink,
"Enable multilink operation", OPT_PRIO | 1 },
--- a/pppd/pppd.h
+++ b/pppd/pppd.h
@@ -318,6 +318,8 @@ extern bool tune_kernel; /* May alter ke
extern int connect_delay; /* Time to delay after connect script */
extern int max_data_rate; /* max bytes/sec through charshunt */
extern int req_unit; /* interface unit number to use */
+extern char path_ipup[MAXPATHLEN]; /* pathname of ip-up script */
+extern char path_ipdown[MAXPATHLEN]; /* pathname of ip-down script */
extern bool multilink; /* enable multilink operation */
extern bool noendpoint; /* don't send or accept endpt. discrim. */
extern char *bundle_name; /* bundle name for multilink */
|
{
"pile_set_name": "Github"
}
|
// Code generated by TestPretty. DO NOT EDIT.
// GENERATED FILE DO NOT EDIT
1:
-
SELECT
NULL AS table_cat,
n.nspname AS table_schem,
ct.relname AS table_name,
a.attname AS column_name,
(i.keys).n AS key_seq,
ci.relname AS pk_name
FROM
pg_catalog.pg_class AS ct
JOIN pg_catalog.pg_attribute AS a ON
ct.oid = a.attrelid
JOIN pg_catalog.pg_namespace AS n ON
ct.relnamespace = n.oid
JOIN (
SELECT
i.indexrelid,
i.indrelid,
i.indisprimary,
information_schema._pg_expandarray(
i.indkey
)
AS keys
FROM
pg_catalog.pg_index AS i
)
AS i ON
a.attnum = (i.keys).x
AND a.attrelid = i.indrelid
JOIN pg_catalog.pg_class AS ci ON
ci.oid = i.indexrelid
WHERE
true
AND ct.relname = 'j'
AND i.indisprimary
ORDER BY
table_name, pk_name, key_seq
|
{
"pile_set_name": "Github"
}
|
# <img alt="NodeBB" src="http://i.imgur.com/mYxPPtB.png" />
[](https://travis-ci.org/NodeBB/NodeBB)
[](https://coveralls.io/github/NodeBB/NodeBB?branch=master)
[](https://david-dm.org/nodebb/nodebb?path=install)
[](https://codeclimate.com/github/NodeBB/NodeBB)
[**NodeBB Forum Software**](https://nodebb.org) is powered by Node.js and built on either a Redis or MongoDB database. It utilizes web sockets for instant interactions and real-time notifications. NodeBB has many modern features out of the box such as social network integration and streaming discussions, while still making sure to be compatible with older browsers.
Additional functionality is enabled through the use of third-party plugins.
* [Demo & Meta Discussion](http://community.nodebb.org)
* [Documentation & Installation Instructions](http://docs.nodebb.org)
* [Help translate NodeBB](https://www.transifex.com/projects/p/nodebb/)
* [NodeBB Blog](http://blog.nodebb.org)
* [Premium Hosting for NodeBB](http://www.nodebb.org/ "NodeBB")
* [Follow us on Twitter](http://www.twitter.com/NodeBB/ "NodeBB Twitter")
* [Like us on Facebook](http://www.facebook.com/NodeBB/ "NodeBB Facebook")
## Screenshots
NodeBB's theming engine is highly flexible and does not restrict your design choices. Check out some themed installs in these screenshots below:
[](http://i.imgur.com/VCoOFyq.png)
[](http://i.imgur.com/FLOUuIq.png)
[](http://i.imgur.com/Ud1LrfI.png)
[](http://i.imgur.com/h6yZ66s.png)
[](http://i.imgur.com/o90kVPi.png)
[](http://i.imgur.com/AaRRrU2.png)
[](http://i.imgur.com/LmHtPho.png)
[](http://i.imgur.com/paiJPJk.jpg)
Our minimalist "Persona" theme gets you going right away, no coding experience required.
[](http://i.imgur.com/HwNEXGu.png)
[](http://i.imgur.com/II1byYs.png)
## How can I follow along/contribute?
* If you are a developer, feel free to check out the source and submit pull requests. We also have a wide array of [plugins](http://community.nodebb.org/category/7/nodebb-plugins) which would be a great starting point for learning the codebase.
* If you are a designer, [NodeBB needs themes](http://community.nodebb.org/category/10/nodebb-themes)! NodeBB's theming system allows extension of the base templates as well as styling via LESS or CSS. NodeBB's base theme utilizes [Bootstrap 3](http://getbootstrap.com/) but themes can choose to use a different framework altogether.
* If you know languages other than English you can help us translate NodeBB. We use [Transifex](https://www.transifex.com/projects/p/nodebb/) for internationalization.
* Please don't forget to **like**, **follow**, and **star our repo**! Join our growing [community](http://community.nodebb.org) to keep up to date with the latest NodeBB development.
## Requirements
NodeBB requires the following software to be installed:
* A version of Node.js at least 10 or greater ([installation/upgrade instructions](https://github.com/nodesource/distributions))
* Redis, version 2.8.9 or greater **or** MongoDB, version 2.6 or greater
* nginx, version 1.3.13 or greater (**only if** intending to use nginx to proxy requests to a NodeBB)
## Installation
[Please refer to platform-specific installation documentation](https://docs.nodebb.org/installing/os)
## Securing NodeBB
It is important to ensure that your NodeBB and database servers are secured. Bear these points in mind:
1. While some distributions set up Redis with a more restrictive configuration, Redis by default listens to all interfaces, which is especially dangerous when a server is open to the public. Some suggestions:
* Set `bind_address` to `127.0.0.1` so as to restrict access to the local machine only
* Use `requirepass` to secure Redis behind a password (preferably a long one)
* Familiarise yourself with [Redis Security](http://redis.io/topics/security)
2. Use `iptables` to secure your server from unintended open ports. In Ubuntu, `ufw` provides a friendlier interface to working with `iptables`.
* e.g. If your NodeBB is proxied, no ports should be open except 80 (and possibly 22, for SSH access)
## Upgrading NodeBB
Detailed upgrade instructions are listed in [Upgrading NodeBB](https://docs.nodebb.org/configuring/upgrade/)
## License
NodeBB is licensed under the **GNU General Public License v3 (GPL-3)** (http://www.gnu.org/copyleft/gpl.html).
Interested in a sublicense agreement for use of NodeBB in a non-free/restrictive environment? Contact us at [email protected].
|
{
"pile_set_name": "Github"
}
|
//// THIS CODE AND INFORMATION IS PROVIDED "AS IS" WITHOUT WARRANTY OF
//// ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING BUT NOT LIMITED TO
//// THE IMPLIED WARRANTIES OF MERCHANTABILITY AND/OR FITNESS FOR A
//// PARTICULAR PURPOSE.
////
//// Copyright (c) Microsoft Corporation. All rights reserved
#include "pch.h"
#include "Camera.h"
#include "StereoProjection.h"
using namespace DirectX;
#undef min // Use __min instead.
#undef max // Use __max instead.
//--------------------------------------------------------------------------------------
Camera::Camera()
{
// Setup the view matrix.
SetViewParams(
XMFLOAT3(0.0f, 0.0f, 0.0f), // Default eye position.
XMFLOAT3(0.0f, 0.0f, 1.0f), // Default look at position.
XMFLOAT3(0.0f, 1.0f, 0.0f) // Default up vector.
);
// Setup the projection matrix.
SetProjParams(XM_PI / 4, 1.0f, 1.0f, 1000.0f);
}
//--------------------------------------------------------------------------------------
void Camera::LookDirection (_In_ XMFLOAT3 lookDirection)
{
XMFLOAT3 lookAt;
lookAt.x = m_eye.x + lookDirection.x;
lookAt.y = m_eye.y + lookDirection.y;
lookAt.z = m_eye.z + lookDirection.z;
SetViewParams(m_eye, lookAt, m_up);
}
//--------------------------------------------------------------------------------------
void Camera::Eye(_In_ XMFLOAT3 eye)
{
SetViewParams(eye, m_lookAt, m_up);
}
//--------------------------------------------------------------------------------------
void Camera::SetViewParams(
_In_ XMFLOAT3 eye,
_In_ XMFLOAT3 lookAt,
_In_ XMFLOAT3 up
)
{
m_eye = eye;
m_lookAt = lookAt;
m_up = up;
// Calculate the view matrix.
XMMATRIX view = XMMatrixLookAtLH(
XMLoadFloat3(&m_eye),
XMLoadFloat3(&m_lookAt),
XMLoadFloat3(&m_up)
);
XMVECTOR det;
XMMATRIX inverseView = XMMatrixInverse(&det, view);
XMStoreFloat4x4(&m_viewMatrix, view);
XMStoreFloat4x4(&m_inverseView, inverseView);
// The axis basis vectors and camera position are stored inside the
// position matrix in the 4 rows of the camera's world matrix.
// To figure out the yaw/pitch of the camera, we just need the Z basis vector.
XMFLOAT3 zBasis;
XMStoreFloat3(&zBasis, inverseView.r[2]);
m_cameraYawAngle = atan2f(zBasis.x, zBasis.z);
float len = sqrtf(zBasis.z * zBasis.z + zBasis.x * zBasis.x);
m_cameraPitchAngle = atan2f(zBasis.y, len);
}
//--------------------------------------------------------------------------------------
void Camera::SetProjParams(
_In_ float fieldOfView,
_In_ float aspectRatio,
_In_ float nearPlane,
_In_ float farPlane
)
{
// Set attributes for the projection matrix.
m_fieldOfView = fieldOfView;
m_aspectRatio = aspectRatio;
m_nearPlane = nearPlane;
m_farPlane = farPlane;
XMStoreFloat4x4(
&m_projectionMatrix,
XMMatrixPerspectiveFovLH(
m_fieldOfView,
m_aspectRatio,
m_nearPlane,
m_farPlane
)
);
STEREO_PARAMETERS* stereoParams = nullptr;
// Update the projection matrix.
XMStoreFloat4x4(
&m_projectionMatrixLeft,
MatrixStereoProjectionFovLH(
stereoParams,
STEREO_CHANNEL::LEFT,
m_fieldOfView,
m_aspectRatio,
m_nearPlane,
m_farPlane,
STEREO_MODE::NORMAL
)
);
XMStoreFloat4x4(
&m_projectionMatrixRight,
MatrixStereoProjectionFovLH(
stereoParams,
STEREO_CHANNEL::RIGHT,
m_fieldOfView,
m_aspectRatio,
m_nearPlane,
m_farPlane,
STEREO_MODE::NORMAL
)
);
}
//--------------------------------------------------------------------------------------
DirectX::XMMATRIX Camera::View()
{
return XMLoadFloat4x4(&m_viewMatrix);
}
//--------------------------------------------------------------------------------------
DirectX::XMMATRIX Camera::Projection()
{
return XMLoadFloat4x4(&m_projectionMatrix);
}
//--------------------------------------------------------------------------------------
DirectX::XMMATRIX Camera::LeftEyeProjection()
{
return XMLoadFloat4x4(&m_projectionMatrixLeft);
}
//--------------------------------------------------------------------------------------
DirectX::XMMATRIX Camera::RightEyeProjection()
{
return XMLoadFloat4x4(&m_projectionMatrixRight);
}
//--------------------------------------------------------------------------------------
DirectX::XMMATRIX Camera::World()
{
return XMLoadFloat4x4(&m_inverseView);
}
//--------------------------------------------------------------------------------------
DirectX::XMFLOAT3 Camera::Eye()
{
return m_eye;
}
//--------------------------------------------------------------------------------------
DirectX::XMFLOAT3 Camera::LookAt()
{
return m_lookAt;
}
//--------------------------------------------------------------------------------------
float Camera::NearClipPlane()
{
return m_nearPlane;
}
//--------------------------------------------------------------------------------------
float Camera::FarClipPlane()
{
return m_farPlane;
}
//--------------------------------------------------------------------------------------
float Camera::Pitch()
{
return m_cameraPitchAngle;
}
//--------------------------------------------------------------------------------------
float Camera::Yaw()
{
return m_cameraYawAngle;
}
//--------------------------------------------------------------------------------------
|
{
"pile_set_name": "Github"
}
|
<testcase>
<info>
<keywords>
HTTP
HTTP POST
followlocation
</keywords>
</info>
#
# Server-side
<reply>
<data>
HTTP/1.1 301 OK swsclose
Location: moo/testcase/10540002
Date: Thu, 31 Jul 2008 14:49:00 GMT
Connection: close
</data>
<data2>
HTTP/1.1 200 OK swsclose
Date: Thu, 31 Jul 2008 14:49:00 GMT
Connection: close
body
</data2>
<datacheck>
HTTP/1.1 301 OK swsclose
Location: moo/testcase/10540002
Date: Thu, 31 Jul 2008 14:49:00 GMT
Connection: close
HTTP/1.1 200 OK swsclose
Date: Thu, 31 Jul 2008 14:49:00 GMT
Connection: close
body
</datacheck>
</reply>
#
# Client-side
<client>
<server>
http
</server>
<name>
HTTP POST from file with 301 redirect and --post301
</name>
<file name="log/test1054.txt">
field=data
</file>
<command>
http://%HOSTIP:%HTTPPORT/blah/1054 -L -d @log/test1054.txt --post301
</command>
</client>
#
# Verify data after the test has been "shot"
<verify>
<strip>
^User-Agent:.*
</strip>
<protocol nonewline="yes">
POST /blah/1054 HTTP/1.1
Host: %HOSTIP:%HTTPPORT
Accept: */*
Content-Length: 10
Content-Type: application/x-www-form-urlencoded
field=dataPOST /blah/moo/testcase/10540002 HTTP/1.1
Host: %HOSTIP:%HTTPPORT
Accept: */*
Content-Length: 10
Content-Type: application/x-www-form-urlencoded
field=data
</protocol>
</verify>
</testcase>
|
{
"pile_set_name": "Github"
}
|
{
"nome": "Salemi",
"codice": "081018",
"zona": {
"codice": "5",
"nome": "Isole"
},
"regione": {
"codice": "19",
"nome": "Sicilia"
},
"provincia": {
"codice": "081",
"nome": "Trapani"
},
"sigla": "TP",
"codiceCatastale": "H700",
"cap": [
"91018"
],
"popolazione": 10871
}
|
{
"pile_set_name": "Github"
}
|
using System;
using System.Collections.Generic;
using System.Text;
using System.Windows.Forms;
namespace LogExpert
{
/// <summary>
/// If your context menu plugin or keyword action plugin has some configuration it should
/// implement this interface.
/// When your plugin has implemented this interface, it will get notified if it has to
/// show a config dialog and to save/load config data.<br></br>
/// Like in the IColumnizerConfigurator, you have to do all the saving and loading stuff
/// by yourself.
/// </summary>
public interface ILogExpertPluginConfigurator
{
#region Public methods
/// <summary>
/// Return whether your plugin will provide an embedded config dialog or wants to provide
/// a 'popup' dialog for the configuration.<br></br><br></br>
/// 'Embedded' means that the dialog is shown directly in the Settings dialog of LogExpert on the
/// right pane of the plugin config tab.
/// </summary>
/// <returns>Return true if your plugin config dialog should be displayed embedded.</returns>
bool HasEmbeddedForm();
/// <summary>
/// This function is called when LogExpert fills the list of plugins in the Settings dialog.
/// This is the right time to create a 'temporary copy' of your current settings. The temporary copy
/// can be used for initializing the config dialogs.
/// </summary>
void StartConfig();
/// <summary>
/// Implement this function if your plugins uses an embedded config dialog.
/// This function is called when the user selects the plugin in the list of the Settings dialog
/// and the plugin uses an embedded dialog.<br></br><br></br>
/// You have to create a non-toplevel dialog and set the given parentPanel as the parent of your
/// dialog. Then make your dialog visible (using Show()).
/// You don't need an OK or Cancel button. Changes made in the dialog should be retrieved
/// to a temporary config every time the <see cref="HideConfigForm"/> function is called.
/// The temporary config should be permanently stored when the <see cref="SaveConfig"/> function
/// is called.
/// </summary>
/// <seealso cref="HasEmbeddedForm"/>
/// <param name="parentPanel">Set this panel as the parent for you config dialog.</param>
void ShowConfigForm(Panel parentPanel);
/// <summary>
/// Implement this function if your plugin uses an own top level dialog for the configuration (modal config dialog).
/// This function is called if the user clicks on the 'Config' button on the plugin settings.
/// <br></br><br></br>
/// You have to create a top level dialog and set the given Form as the owner. Then show
/// the dialog as a modal window (Form.ShowDialog()). Changes made in the dialog should be retrieved
/// after Form.ShowDialog() returns and then put to the temporary copy of your config.
/// The temporary copy config should be permanently stored when the <see cref="SaveConfig"/> function
/// is called.
/// </summary>
/// <seealso cref="HasEmbeddedForm"/>
/// <param name="owner">Set the given Form as the owner of your dialog.</param>
void ShowConfigDialog(Form owner);
/// <summary>
/// This function is called when the user selects another plugin in the list. You should retrieve
/// the changes made in the config dialog to a temporary copy of the config and destroy your dialog.
/// Don't make the changes permanent here, because the user may click the cancel button of LogExpert's
/// Settings dialog. In this case he/she would expect the changes to be discarded.<br></br>
/// The right place for making changes permanent is the <see cref="SaveConfig"/> function.
/// </summary>
/// <remarks>
/// The method is also called when the settings dialog is closed. If the settings dialog is closed
/// by OK button this method is called before the <see cref="SaveConfig"/> method.
/// </remarks>
void HideConfigForm();
/// <summary>
/// Called by LogExpert if the user clicks the OK button in LogExpert's Settings dialog.
/// Save your temporary copy of the config here.
/// </summary>
/// <param name="configDir">The location where LogExpert stores its settings.</param>
void SaveConfig(string configDir);
/// <summary>
/// This function is called when LogExpert is started and scans the plugin directory.
/// You should load your settings here.
/// </summary>
/// <param name="configDir">The location where LogExpert stores its settings.</param>
void LoadConfig(string configDir);
#endregion
}
}
|
{
"pile_set_name": "Github"
}
|
***** ESD.Epp.RegularPaymentCapture.SpecFlow.Features.RegularPaymentGroupServiceCallsFeature.PopulateBusinessPaymentProcessDropDownList("Inputter","Credit Card Repayment,Fee/Interest Transfer,Funds Transfer,Funds Transfer between Own Accounts,Loan Repayment,Without Passbook Withdrawal",null)
Given ESD Epp.RegularPaymentCapture app is loaded with CommSee.v1 theme
-> done: PaymentGroupDetailsSteps.GivenESDEpp_RegularPaymentCaptureAppIsLoadedWithCommSee_VTheme(1) (2.3s)
And the Payment Group Details page is loaded
-> done: PaymentGroupDetailsSteps.GivenThePaymentGroupDetailsPageIsLoaded() (0.0s)
Given I am of Inputter role
-> done: PaymentGroupDetailsSteps.GivenIAmOfRole("Inputter") (0.0s)
Then the BusinessPaymentProcess drop down list is populated with Credit Card Repayment,Fee/Interest Transfer,Funds Transfer,Funds Transfer between Own Accounts,Loan Repayment,Without Passbook Withdrawal
-> done: PaymentGroupDetailsSteps.ThenDropDownListIsPopulated("BusinessPaymentPr...", "Credit Card Repay...") (0.9s)
|
{
"pile_set_name": "Github"
}
|
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<!DOCTYPE html>
<html>
<jsp:include page="../fragments/head.jsp"/>
<body>
<div class="container">
<jsp:include page="../fragments/bodyHeader.jsp" />
<div>
<table class="table table-striped">
<thead>
<tr>
<th>#</th>
<th>이름</th>
<th>도시</th>
<th>주소</th>
<th>우편번호</th>
</tr>
</thead>
<tbody>
<c:forEach items="${members}" var="member">
<tr>
<td>${member.id}</td>
<td>${member.name}</td>
<td>${member.address.city}</td>
<td>${member.address.street}</td>
<td>${member.address.zipcode}</td>
</tr>
</c:forEach>
</tbody>
</table>
</div>
<jsp:include page="../fragments/footer.jsp" />
</div> <!-- /container -->
</body>
</html>
|
{
"pile_set_name": "Github"
}
|
// (C) Copyright Jeremy Siek 2004
// 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)
#ifndef BOOST_DETAIL_DISJOINT_SETS_HPP
#define BOOST_DETAIL_DISJOINT_SETS_HPP
namespace boost {
namespace detail {
template <class ParentPA, class Vertex>
Vertex
find_representative_with_path_halving(ParentPA p, Vertex v)
{
Vertex parent = get(p, v);
Vertex grandparent = get(p, parent);
while (parent != grandparent) {
put(p, v, grandparent);
v = grandparent;
parent = get(p, v);
grandparent = get(p, parent);
}
return parent;
}
template <class ParentPA, class Vertex>
Vertex
find_representative_with_full_compression(ParentPA parent, Vertex v)
{
Vertex old = v;
Vertex ancestor = get(parent, v);
while (ancestor != v) {
v = ancestor;
ancestor = get(parent, v);
}
v = get(parent, old);
while (ancestor != v) {
put(parent, old, ancestor);
old = v;
v = get(parent, old);
}
return ancestor;
}
/* the postcondition of link sets is:
component_representative(i) == component_representative(j)
*/
template <class ParentPA, class RankPA, class Vertex,
class ComponentRepresentative>
inline void
link_sets(ParentPA p, RankPA rank, Vertex i, Vertex j,
ComponentRepresentative comp_rep)
{
i = comp_rep(p, i);
j = comp_rep(p, j);
if (i == j) return;
if (get(rank, i) > get(rank, j))
put(p, j, i);
else {
put(p, i, j);
if (get(rank, i) == get(rank, j))
put(rank, j, get(rank, j) + 1);
}
}
// normalize components has the following postcondidition:
// i >= p[i]
// that is, the representative is the node with the smallest index in its class
// as its precondition it it assumes that the node container is compressed
template <class ParentPA, class Vertex>
inline void
normalize_node(ParentPA p, Vertex i)
{
if (i > get(p,i) || get(p, get(p,i)) != get(p,i))
put(p,i, get(p, get(p,i)));
else {
put(p, get(p,i), i);
put(p, i, i);
}
}
} // namespace detail
} // namespace boost
#endif // BOOST_DETAIL_DISJOINT_SETS_HPP
|
{
"pile_set_name": "Github"
}
|
---
name: "OpenShift"
metadata:
keywords:
- "kubernetes"
- "openshift"
guide: "https://quarkus.io/guides/openshift"
categories:
- "cloud"
status: "stable"
|
{
"pile_set_name": "Github"
}
|
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<!-- NewPage -->
<html lang="en">
<head>
<!-- Generated by javadoc (version 1.7.0_10-ea) on Mon Apr 22 22:09:54 PDT 2013 -->
<meta http-equiv="Content-Type" content="text/html" charset="UTF-8">
<title>Uses of Interface com.fasterxml.jackson.dataformat.xml.util.DefaultXmlPrettyPrinter.Indenter (Jackson-dataformat-XML 2.2.0 API)</title>
<meta name="date" content="2013-04-22">
<link rel="stylesheet" type="text/css" href="../../../../../../../stylesheet.css" title="Style">
</head>
<body>
<script type="text/javascript"><!--
if (location.href.indexOf('is-external=true') == -1) {
parent.document.title="Uses of Interface com.fasterxml.jackson.dataformat.xml.util.DefaultXmlPrettyPrinter.Indenter (Jackson-dataformat-XML 2.2.0 API)";
}
//-->
</script>
<noscript>
<div>JavaScript is disabled on your browser.</div>
</noscript>
<!-- ========= START OF TOP NAVBAR ======= -->
<div class="topNav"><a name="navbar_top">
<!-- -->
</a><a href="#skip-navbar_top" title="Skip navigation links"></a><a name="navbar_top_firstrow">
<!-- -->
</a>
<ul class="navList" title="Navigation">
<li><a href="../../../../../../../overview-summary.html">Overview</a></li>
<li><a href="../package-summary.html">Package</a></li>
<li><a href="../../../../../../../com/fasterxml/jackson/dataformat/xml/util/DefaultXmlPrettyPrinter.Indenter.html" title="interface in com.fasterxml.jackson.dataformat.xml.util">Class</a></li>
<li class="navBarCell1Rev">Use</li>
<li><a href="../package-tree.html">Tree</a></li>
<li><a href="../../../../../../../deprecated-list.html">Deprecated</a></li>
<li><a href="../../../../../../../index-all.html">Index</a></li>
<li><a href="../../../../../../../help-doc.html">Help</a></li>
</ul>
</div>
<div class="subNav">
<ul class="navList">
<li>Prev</li>
<li>Next</li>
</ul>
<ul class="navList">
<li><a href="../../../../../../../index.html?com/fasterxml/jackson/dataformat/xml/util/class-use/DefaultXmlPrettyPrinter.Indenter.html" target="_top">Frames</a></li>
<li><a href="DefaultXmlPrettyPrinter.Indenter.html" target="_top">No Frames</a></li>
</ul>
<ul class="navList" id="allclasses_navbar_top">
<li><a href="../../../../../../../allclasses-noframe.html">All Classes</a></li>
</ul>
<div>
<script type="text/javascript"><!--
allClassesLink = document.getElementById("allclasses_navbar_top");
if(window==top) {
allClassesLink.style.display = "block";
}
else {
allClassesLink.style.display = "none";
}
//-->
</script>
</div>
<a name="skip-navbar_top">
<!-- -->
</a></div>
<!-- ========= END OF TOP NAVBAR ========= -->
<div class="header">
<h2 title="Uses of Interface com.fasterxml.jackson.dataformat.xml.util.DefaultXmlPrettyPrinter.Indenter" class="title">Uses of Interface<br>com.fasterxml.jackson.dataformat.xml.util.DefaultXmlPrettyPrinter.Indenter</h2>
</div>
<div class="classUseContainer">
<ul class="blockList">
<li class="blockList">
<table border="0" cellpadding="3" cellspacing="0" summary="Use table, listing packages, and an explanation">
<caption><span>Packages that use <a href="../../../../../../../com/fasterxml/jackson/dataformat/xml/util/DefaultXmlPrettyPrinter.Indenter.html" title="interface in com.fasterxml.jackson.dataformat.xml.util">DefaultXmlPrettyPrinter.Indenter</a></span><span class="tabEnd"> </span></caption>
<tr>
<th class="colFirst" scope="col">Package</th>
<th class="colLast" scope="col">Description</th>
</tr>
<tbody>
<tr class="altColor">
<td class="colFirst"><a href="#com.fasterxml.jackson.dataformat.xml.util">com.fasterxml.jackson.dataformat.xml.util</a></td>
<td class="colLast"> </td>
</tr>
</tbody>
</table>
</li>
<li class="blockList">
<ul class="blockList">
<li class="blockList"><a name="com.fasterxml.jackson.dataformat.xml.util">
<!-- -->
</a>
<h3>Uses of <a href="../../../../../../../com/fasterxml/jackson/dataformat/xml/util/DefaultXmlPrettyPrinter.Indenter.html" title="interface in com.fasterxml.jackson.dataformat.xml.util">DefaultXmlPrettyPrinter.Indenter</a> in <a href="../../../../../../../com/fasterxml/jackson/dataformat/xml/util/package-summary.html">com.fasterxml.jackson.dataformat.xml.util</a></h3>
<table border="0" cellpadding="3" cellspacing="0" summary="Use table, listing classes, and an explanation">
<caption><span>Classes in <a href="../../../../../../../com/fasterxml/jackson/dataformat/xml/util/package-summary.html">com.fasterxml.jackson.dataformat.xml.util</a> that implement <a href="../../../../../../../com/fasterxml/jackson/dataformat/xml/util/DefaultXmlPrettyPrinter.Indenter.html" title="interface in com.fasterxml.jackson.dataformat.xml.util">DefaultXmlPrettyPrinter.Indenter</a></span><span class="tabEnd"> </span></caption>
<tr>
<th class="colFirst" scope="col">Modifier and Type</th>
<th class="colLast" scope="col">Class and Description</th>
</tr>
<tbody>
<tr class="altColor">
<td class="colFirst"><code>protected static class </code></td>
<td class="colLast"><code><strong><a href="../../../../../../../com/fasterxml/jackson/dataformat/xml/util/DefaultXmlPrettyPrinter.FixedSpaceIndenter.html" title="class in com.fasterxml.jackson.dataformat.xml.util">DefaultXmlPrettyPrinter.FixedSpaceIndenter</a></strong></code>
<div class="block">This is a very simple indenter that only every adds a
single space for indentation.</div>
</td>
</tr>
<tr class="rowColor">
<td class="colFirst"><code>protected static class </code></td>
<td class="colLast"><code><strong><a href="../../../../../../../com/fasterxml/jackson/dataformat/xml/util/DefaultXmlPrettyPrinter.Lf2SpacesIndenter.html" title="class in com.fasterxml.jackson.dataformat.xml.util">DefaultXmlPrettyPrinter.Lf2SpacesIndenter</a></strong></code>
<div class="block">Default linefeed-based indenter uses system-specific linefeeds and
2 spaces for indentation per level.</div>
</td>
</tr>
<tr class="altColor">
<td class="colFirst"><code>protected static class </code></td>
<td class="colLast"><code><strong><a href="../../../../../../../com/fasterxml/jackson/dataformat/xml/util/DefaultXmlPrettyPrinter.NopIndenter.html" title="class in com.fasterxml.jackson.dataformat.xml.util">DefaultXmlPrettyPrinter.NopIndenter</a></strong></code>
<div class="block">Dummy implementation that adds no indentation whatsoever</div>
</td>
</tr>
</tbody>
</table>
<table border="0" cellpadding="3" cellspacing="0" summary="Use table, listing fields, and an explanation">
<caption><span>Fields in <a href="../../../../../../../com/fasterxml/jackson/dataformat/xml/util/package-summary.html">com.fasterxml.jackson.dataformat.xml.util</a> declared as <a href="../../../../../../../com/fasterxml/jackson/dataformat/xml/util/DefaultXmlPrettyPrinter.Indenter.html" title="interface in com.fasterxml.jackson.dataformat.xml.util">DefaultXmlPrettyPrinter.Indenter</a></span><span class="tabEnd"> </span></caption>
<tr>
<th class="colFirst" scope="col">Modifier and Type</th>
<th class="colLast" scope="col">Field and Description</th>
</tr>
<tbody>
<tr class="altColor">
<td class="colFirst"><code>protected <a href="../../../../../../../com/fasterxml/jackson/dataformat/xml/util/DefaultXmlPrettyPrinter.Indenter.html" title="interface in com.fasterxml.jackson.dataformat.xml.util">DefaultXmlPrettyPrinter.Indenter</a></code></td>
<td class="colLast"><span class="strong">DefaultXmlPrettyPrinter.</span><code><strong><a href="../../../../../../../com/fasterxml/jackson/dataformat/xml/util/DefaultXmlPrettyPrinter.html#_arrayIndenter">_arrayIndenter</a></strong></code>
<div class="block">By default, let's use only spaces to separate array values.</div>
</td>
</tr>
<tr class="rowColor">
<td class="colFirst"><code>protected <a href="../../../../../../../com/fasterxml/jackson/dataformat/xml/util/DefaultXmlPrettyPrinter.Indenter.html" title="interface in com.fasterxml.jackson.dataformat.xml.util">DefaultXmlPrettyPrinter.Indenter</a></code></td>
<td class="colLast"><span class="strong">DefaultXmlPrettyPrinter.</span><code><strong><a href="../../../../../../../com/fasterxml/jackson/dataformat/xml/util/DefaultXmlPrettyPrinter.html#_objectIndenter">_objectIndenter</a></strong></code>
<div class="block">By default, let's use linefeed-adding indenter for separate
object entries.</div>
</td>
</tr>
</tbody>
</table>
<table border="0" cellpadding="3" cellspacing="0" summary="Use table, listing methods, and an explanation">
<caption><span>Methods in <a href="../../../../../../../com/fasterxml/jackson/dataformat/xml/util/package-summary.html">com.fasterxml.jackson.dataformat.xml.util</a> with parameters of type <a href="../../../../../../../com/fasterxml/jackson/dataformat/xml/util/DefaultXmlPrettyPrinter.Indenter.html" title="interface in com.fasterxml.jackson.dataformat.xml.util">DefaultXmlPrettyPrinter.Indenter</a></span><span class="tabEnd"> </span></caption>
<tr>
<th class="colFirst" scope="col">Modifier and Type</th>
<th class="colLast" scope="col">Method and Description</th>
</tr>
<tbody>
<tr class="altColor">
<td class="colFirst"><code>void</code></td>
<td class="colLast"><span class="strong">DefaultXmlPrettyPrinter.</span><code><strong><a href="../../../../../../../com/fasterxml/jackson/dataformat/xml/util/DefaultXmlPrettyPrinter.html#indentArraysWith(com.fasterxml.jackson.dataformat.xml.util.DefaultXmlPrettyPrinter.Indenter)">indentArraysWith</a></strong>(<a href="../../../../../../../com/fasterxml/jackson/dataformat/xml/util/DefaultXmlPrettyPrinter.Indenter.html" title="interface in com.fasterxml.jackson.dataformat.xml.util">DefaultXmlPrettyPrinter.Indenter</a> i)</code> </td>
</tr>
<tr class="rowColor">
<td class="colFirst"><code>void</code></td>
<td class="colLast"><span class="strong">DefaultXmlPrettyPrinter.</span><code><strong><a href="../../../../../../../com/fasterxml/jackson/dataformat/xml/util/DefaultXmlPrettyPrinter.html#indentObjectsWith(com.fasterxml.jackson.dataformat.xml.util.DefaultXmlPrettyPrinter.Indenter)">indentObjectsWith</a></strong>(<a href="../../../../../../../com/fasterxml/jackson/dataformat/xml/util/DefaultXmlPrettyPrinter.Indenter.html" title="interface in com.fasterxml.jackson.dataformat.xml.util">DefaultXmlPrettyPrinter.Indenter</a> i)</code> </td>
</tr>
</tbody>
</table>
</li>
</ul>
</li>
</ul>
</div>
<!-- ======= START OF BOTTOM NAVBAR ====== -->
<div class="bottomNav"><a name="navbar_bottom">
<!-- -->
</a><a href="#skip-navbar_bottom" title="Skip navigation links"></a><a name="navbar_bottom_firstrow">
<!-- -->
</a>
<ul class="navList" title="Navigation">
<li><a href="../../../../../../../overview-summary.html">Overview</a></li>
<li><a href="../package-summary.html">Package</a></li>
<li><a href="../../../../../../../com/fasterxml/jackson/dataformat/xml/util/DefaultXmlPrettyPrinter.Indenter.html" title="interface in com.fasterxml.jackson.dataformat.xml.util">Class</a></li>
<li class="navBarCell1Rev">Use</li>
<li><a href="../package-tree.html">Tree</a></li>
<li><a href="../../../../../../../deprecated-list.html">Deprecated</a></li>
<li><a href="../../../../../../../index-all.html">Index</a></li>
<li><a href="../../../../../../../help-doc.html">Help</a></li>
</ul>
</div>
<div class="subNav">
<ul class="navList">
<li>Prev</li>
<li>Next</li>
</ul>
<ul class="navList">
<li><a href="../../../../../../../index.html?com/fasterxml/jackson/dataformat/xml/util/class-use/DefaultXmlPrettyPrinter.Indenter.html" target="_top">Frames</a></li>
<li><a href="DefaultXmlPrettyPrinter.Indenter.html" target="_top">No Frames</a></li>
</ul>
<ul class="navList" id="allclasses_navbar_bottom">
<li><a href="../../../../../../../allclasses-noframe.html">All Classes</a></li>
</ul>
<div>
<script type="text/javascript"><!--
allClassesLink = document.getElementById("allclasses_navbar_bottom");
if(window==top) {
allClassesLink.style.display = "block";
}
else {
allClassesLink.style.display = "none";
}
//-->
</script>
</div>
<a name="skip-navbar_bottom">
<!-- -->
</a></div>
<!-- ======== END OF BOTTOM NAVBAR ======= -->
<p class="legalCopy"><small>Copyright © 2012-2013 <a href="http://fasterxml.com/">FasterXML</a>. All Rights Reserved.</small></p>
</body>
</html>
|
{
"pile_set_name": "Github"
}
|
import * as utils from "../test-utils";
import {EventTimeline} from "../../src/models/event-timeline";
import {RoomState} from "../../src/models/room-state";
function mockRoomStates(timeline) {
timeline._startState = utils.mock(RoomState, "startState");
timeline._endState = utils.mock(RoomState, "endState");
}
describe("EventTimeline", function() {
const roomId = "!foo:bar";
const userA = "@alice:bar";
const userB = "@bertha:bar";
let timeline;
beforeEach(function() {
// XXX: this is a horrid hack; should use sinon or something instead to mock
const timelineSet = { room: { roomId: roomId }};
timelineSet.room.getUnfilteredTimelineSet = function() {
return timelineSet;
};
timeline = new EventTimeline(timelineSet);
});
describe("construction", function() {
it("getRoomId should get room id", function() {
const v = timeline.getRoomId();
expect(v).toEqual(roomId);
});
});
describe("initialiseState", function() {
beforeEach(function() {
mockRoomStates(timeline);
});
it("should copy state events to start and end state", function() {
const events = [
utils.mkMembership({
room: roomId, mship: "invite", user: userB, skey: userA,
event: true,
}),
utils.mkEvent({
type: "m.room.name", room: roomId, user: userB,
event: true,
content: { name: "New room" },
}),
];
timeline.initialiseState(events);
expect(timeline._startState.setStateEvents).toHaveBeenCalledWith(
events,
);
expect(timeline._endState.setStateEvents).toHaveBeenCalledWith(
events,
);
});
it("should raise an exception if called after events are added", function() {
const event =
utils.mkMessage({
room: roomId, user: userA, msg: "Adam stole the plushies",
event: true,
});
const state = [
utils.mkMembership({
room: roomId, mship: "invite", user: userB, skey: userA,
event: true,
}),
];
expect(function() {
timeline.initialiseState(state);
}).not.toThrow();
timeline.addEvent(event, false);
expect(function() {
timeline.initialiseState(state);
}).toThrow();
});
});
describe("paginationTokens", function() {
it("pagination tokens should start null", function() {
expect(timeline.getPaginationToken(EventTimeline.BACKWARDS)).toBe(null);
expect(timeline.getPaginationToken(EventTimeline.FORWARDS)).toBe(null);
});
it("setPaginationToken should set token", function() {
timeline.setPaginationToken("back", EventTimeline.BACKWARDS);
timeline.setPaginationToken("fwd", EventTimeline.FORWARDS);
expect(timeline.getPaginationToken(EventTimeline.BACKWARDS)).toEqual("back");
expect(timeline.getPaginationToken(EventTimeline.FORWARDS)).toEqual("fwd");
});
});
describe("neighbouringTimelines", function() {
it("neighbouring timelines should start null", function() {
expect(timeline.getNeighbouringTimeline(EventTimeline.BACKWARDS)).toBe(null);
expect(timeline.getNeighbouringTimeline(EventTimeline.FORWARDS)).toBe(null);
});
it("setNeighbouringTimeline should set neighbour", function() {
const prev = {a: "a"};
const next = {b: "b"};
timeline.setNeighbouringTimeline(prev, EventTimeline.BACKWARDS);
timeline.setNeighbouringTimeline(next, EventTimeline.FORWARDS);
expect(timeline.getNeighbouringTimeline(EventTimeline.BACKWARDS)).toBe(prev);
expect(timeline.getNeighbouringTimeline(EventTimeline.FORWARDS)).toBe(next);
});
it("setNeighbouringTimeline should throw if called twice", function() {
const prev = {a: "a"};
const next = {b: "b"};
expect(function() {
timeline.setNeighbouringTimeline(prev, EventTimeline.BACKWARDS);
}).not.toThrow();
expect(timeline.getNeighbouringTimeline(EventTimeline.BACKWARDS))
.toBe(prev);
expect(function() {
timeline.setNeighbouringTimeline(prev, EventTimeline.BACKWARDS);
}).toThrow();
expect(function() {
timeline.setNeighbouringTimeline(next, EventTimeline.FORWARDS);
}).not.toThrow();
expect(timeline.getNeighbouringTimeline(EventTimeline.FORWARDS))
.toBe(next);
expect(function() {
timeline.setNeighbouringTimeline(next, EventTimeline.FORWARDS);
}).toThrow();
});
});
describe("addEvent", function() {
beforeEach(function() {
mockRoomStates(timeline);
});
const events = [
utils.mkMessage({
room: roomId, user: userA, msg: "hungry hungry hungry",
event: true,
}),
utils.mkMessage({
room: roomId, user: userB, msg: "nom nom nom",
event: true,
}),
];
it("should be able to add events to the end", function() {
timeline.addEvent(events[0], false);
const initialIndex = timeline.getBaseIndex();
timeline.addEvent(events[1], false);
expect(timeline.getBaseIndex()).toEqual(initialIndex);
expect(timeline.getEvents().length).toEqual(2);
expect(timeline.getEvents()[0]).toEqual(events[0]);
expect(timeline.getEvents()[1]).toEqual(events[1]);
});
it("should be able to add events to the start", function() {
timeline.addEvent(events[0], true);
const initialIndex = timeline.getBaseIndex();
timeline.addEvent(events[1], true);
expect(timeline.getBaseIndex()).toEqual(initialIndex + 1);
expect(timeline.getEvents().length).toEqual(2);
expect(timeline.getEvents()[0]).toEqual(events[1]);
expect(timeline.getEvents()[1]).toEqual(events[0]);
});
it("should set event.sender for new and old events", function() {
const sentinel = {
userId: userA,
membership: "join",
name: "Alice",
};
const oldSentinel = {
userId: userA,
membership: "join",
name: "Old Alice",
};
timeline.getState(EventTimeline.FORWARDS).getSentinelMember
.mockImplementation(function(uid) {
if (uid === userA) {
return sentinel;
}
return null;
});
timeline.getState(EventTimeline.BACKWARDS).getSentinelMember
.mockImplementation(function(uid) {
if (uid === userA) {
return oldSentinel;
}
return null;
});
const newEv = utils.mkEvent({
type: "m.room.name", room: roomId, user: userA, event: true,
content: { name: "New Room Name" },
});
const oldEv = utils.mkEvent({
type: "m.room.name", room: roomId, user: userA, event: true,
content: { name: "Old Room Name" },
});
timeline.addEvent(newEv, false);
expect(newEv.sender).toEqual(sentinel);
timeline.addEvent(oldEv, true);
expect(oldEv.sender).toEqual(oldSentinel);
});
it("should set event.target for new and old m.room.member events",
function() {
const sentinel = {
userId: userA,
membership: "join",
name: "Alice",
};
const oldSentinel = {
userId: userA,
membership: "join",
name: "Old Alice",
};
timeline.getState(EventTimeline.FORWARDS).getSentinelMember
.mockImplementation(function(uid) {
if (uid === userA) {
return sentinel;
}
return null;
});
timeline.getState(EventTimeline.BACKWARDS).getSentinelMember
.mockImplementation(function(uid) {
if (uid === userA) {
return oldSentinel;
}
return null;
});
const newEv = utils.mkMembership({
room: roomId, mship: "invite", user: userB, skey: userA, event: true,
});
const oldEv = utils.mkMembership({
room: roomId, mship: "ban", user: userB, skey: userA, event: true,
});
timeline.addEvent(newEv, false);
expect(newEv.target).toEqual(sentinel);
timeline.addEvent(oldEv, true);
expect(oldEv.target).toEqual(oldSentinel);
});
it("should call setStateEvents on the right RoomState with the right " +
"forwardLooking value for new events", function() {
const events = [
utils.mkMembership({
room: roomId, mship: "invite", user: userB, skey: userA, event: true,
}),
utils.mkEvent({
type: "m.room.name", room: roomId, user: userB, event: true,
content: {
name: "New room",
},
}),
];
timeline.addEvent(events[0], false);
timeline.addEvent(events[1], false);
expect(timeline.getState(EventTimeline.FORWARDS).setStateEvents).
toHaveBeenCalledWith([events[0]]);
expect(timeline.getState(EventTimeline.FORWARDS).setStateEvents).
toHaveBeenCalledWith([events[1]]);
expect(events[0].forwardLooking).toBe(true);
expect(events[1].forwardLooking).toBe(true);
expect(timeline.getState(EventTimeline.BACKWARDS).setStateEvents).
not.toHaveBeenCalled();
});
it("should call setStateEvents on the right RoomState with the right " +
"forwardLooking value for old events", function() {
const events = [
utils.mkMembership({
room: roomId, mship: "invite", user: userB, skey: userA, event: true,
}),
utils.mkEvent({
type: "m.room.name", room: roomId, user: userB, event: true,
content: {
name: "New room",
},
}),
];
timeline.addEvent(events[0], true);
timeline.addEvent(events[1], true);
expect(timeline.getState(EventTimeline.BACKWARDS).setStateEvents).
toHaveBeenCalledWith([events[0]]);
expect(timeline.getState(EventTimeline.BACKWARDS).setStateEvents).
toHaveBeenCalledWith([events[1]]);
expect(events[0].forwardLooking).toBe(false);
expect(events[1].forwardLooking).toBe(false);
expect(timeline.getState(EventTimeline.FORWARDS).setStateEvents).
not.toHaveBeenCalled();
});
});
describe("removeEvent", function() {
const events = [
utils.mkMessage({
room: roomId, user: userA, msg: "hungry hungry hungry",
event: true,
}),
utils.mkMessage({
room: roomId, user: userB, msg: "nom nom nom",
event: true,
}),
utils.mkMessage({
room: roomId, user: userB, msg: "piiie",
event: true,
}),
];
it("should remove events", function() {
timeline.addEvent(events[0], false);
timeline.addEvent(events[1], false);
expect(timeline.getEvents().length).toEqual(2);
let ev = timeline.removeEvent(events[0].getId());
expect(ev).toBe(events[0]);
expect(timeline.getEvents().length).toEqual(1);
ev = timeline.removeEvent(events[1].getId());
expect(ev).toBe(events[1]);
expect(timeline.getEvents().length).toEqual(0);
});
it("should update baseIndex", function() {
timeline.addEvent(events[0], false);
timeline.addEvent(events[1], true);
timeline.addEvent(events[2], false);
expect(timeline.getEvents().length).toEqual(3);
expect(timeline.getBaseIndex()).toEqual(1);
timeline.removeEvent(events[2].getId());
expect(timeline.getEvents().length).toEqual(2);
expect(timeline.getBaseIndex()).toEqual(1);
timeline.removeEvent(events[1].getId());
expect(timeline.getEvents().length).toEqual(1);
expect(timeline.getBaseIndex()).toEqual(0);
});
// this is basically https://github.com/vector-im/vector-web/issues/937
// - removing the last event got baseIndex into such a state that
// further addEvent(ev, false) calls made the index increase.
it("should not make baseIndex assplode when removing the last event",
function() {
timeline.addEvent(events[0], true);
timeline.removeEvent(events[0].getId());
const initialIndex = timeline.getBaseIndex();
timeline.addEvent(events[1], false);
timeline.addEvent(events[2], false);
expect(timeline.getBaseIndex()).toEqual(initialIndex);
expect(timeline.getEvents().length).toEqual(2);
});
});
});
|
{
"pile_set_name": "Github"
}
|
1281 - 整数的各位积和之差(subtract-the-product-and-sum-of-digits-of-an-integer)
===
> Create by **jsliang** on **2020-02-01 17:19:30**
> Recently revised in **2020-02-01 17:56:31**
## <a name="chapter-one" id="chapter-one"></a>一 目录
**不折腾的前端,和咸鱼有什么区别**
| 目录 |
| --- |
| [一 目录](#chapter-one) |
| <a name="catalog-chapter-two" id="catalog-chapter-two"></a>[二 前言](#chapter-two) |
| <a name="catalog-chapter-three" id="catalog-chapter-three"></a>[三 解题及测试](#chapter-three) |
| <a name="catalog-chapter-four" id="catalog-chapter-four"></a>[四 LeetCode Submit](#chapter-four) |
| <a name="catalog-chapter-five" id="catalog-chapter-five"></a>[五 解题思路](#chapter-five) |
## <a name="chapter-two" id="chapter-two"></a>二 前言
> [返回目录](#chapter-one)
* **难度**:简单
* **涉及知识**:数学
* **题目地址**:https://leetcode-cn.com/problems/subtract-the-product-and-sum-of-digits-of-an-integer/
* **题目内容**:
```
给你一个整数 n,
请你帮忙计算并返回该整数「各位数字之积」与「各位数字之和」的差。
示例 1:
输入:n = 234
输出:15
解释:
各位数之积 = 2 * 3 * 4 = 24
各位数之和 = 2 + 3 + 4 = 9
结果 = 24 - 9 = 15
示例 2:
输入:n = 4421
输出:21
解释:
各位数之积 = 4 * 4 * 2 * 1 = 32
各位数之和 = 4 + 4 + 2 + 1 = 11
结果 = 32 - 11 = 21
提示:
1 <= n <= 10^5
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/subtract-the-product-and-sum-of-digits-of-an-integer
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
```
## <a name="chapter-three" id="chapter-three"></a>三 解题及测试
> [返回目录](#chapter-one)
小伙伴可以先自己在本地尝试解题,再回来看看 **jsliang** 的解题思路。
* **LeetCode 给定函数体**:
```js
/**
* @param {number} n
* @return {number}
*/
var subtractProductAndSum = function(n) {
};
```
根据上面的已知函数,尝试破解本题吧~
确定了自己的答案再看下面代码哈~
> index.js
```js
/**
* @name 整数的各位积和之差
* @param {number} n
* @return {number}
*/
const subtractProductAndSum = (n) => {
n = String(n);
let product = Number(n[0]);
let sum = Number(n[0]);
for (let i = 1; i < n.length; i++) {
product *= Number(n[i]);
sum += Number(n[i]);
}
return product - sum;
};
console.log(subtractProductAndSum(234)); // 15
```
`node index.js` 返回:
```js
15
```
## <a name="chapter-four" id="chapter-four"></a>四 LeetCode Submit
> [返回目录](#chapter-one)
```js
Accepted
* 123/123 cases passed (60 ms)
* Your runtime beats 88.13 % of javascript submissions
* Your memory usage beats 62.2 % of javascript submissions (33.8 MB)
```
## <a name="chapter-five" id="chapter-five"></a>五 解题思路
> [返回目录](#chapter-one)
这道题,感觉没点含量啊,连【简单】都不能算了,只能说是【入门】了:
> 暴力破解
```js
const subtractProductAndSum = (n) => {
n = String(n);
let product = Number(n[0]);
let sum = Number(n[0]);
for (let i = 1; i < n.length; i++) {
product *= Number(n[i]);
sum += Number(n[i]);
}
return product - sum;
};
```
Submit 提交:
```js
Accepted
* 123/123 cases passed (60 ms)
* Your runtime beats 88.13 % of javascript submissions
* Your memory usage beats 62.2 % of javascript submissions (33.8 MB)
```
好吧,不知道说啥好了,这道题 over 了。
如果小伙伴有更好的思路想法……enm...真会有么,欢迎评论留言或者私聊 **jsliang**~
---
**不折腾的前端,和咸鱼有什么区别!**

**jsliang** 会每天更新一道 LeetCode 题解,从而帮助小伙伴们夯实原生 JS 基础,了解与学习算法与数据结构。
**浪子神剑** 会每天更新面试题,以面试题为驱动来带动大家学习,坚持每天学习与思考,每天进步一点!
扫描上方二维码,关注 **jsliang** 的公众号(左)和 **浪子神剑** 的公众号(右),让我们一起折腾!
> <a rel="license" href="http://creativecommons.org/licenses/by-nc-sa/4.0/"><img alt="知识共享许可协议" style="border-width:0" src="https://i.creativecommons.org/l/by-nc-sa/4.0/88x31.png" /></a><br /><span xmlns:dct="http://purl.org/dc/terms/" property="dct:title">jsliang 的文档库</span> 由 <a xmlns:cc="http://creativecommons.org/ns#" href="https://github.com/LiangJunrong/document-library" property="cc:attributionName" rel="cc:attributionURL">梁峻荣</a> 采用 <a rel="license" href="http://creativecommons.org/licenses/by-nc-sa/4.0/">知识共享 署名-非商业性使用-相同方式共享 4.0 国际 许可协议</a>进行许可。<br />基于<a xmlns:dct="http://purl.org/dc/terms/" href="https://github.com/LiangJunrong/document-library" rel="dct:source">https://github.com/LiangJunrong/document-library</a>上的作品创作。<br />本许可协议授权之外的使用权限可以从 <a xmlns:cc="http://creativecommons.org/ns#" href="https://creativecommons.org/licenses/by-nc-sa/2.5/cn/" rel="cc:morePermissions">https://creativecommons.org/licenses/by-nc-sa/2.5/cn/</a> 处获得。
|
{
"pile_set_name": "Github"
}
|
<?xml version="1.0" encoding="UTF-8"?>
<!-- Generated with glade 3.20.0 -->
<interface domain="shotwell">
<requires lib="gtk+" version="3.14"/>
<object class="GtkWindow" id="authentication_pane">
<property name="can_focus">False</property>
<child>
<object class="GtkBox" id="content">
<property name="visible">True</property>
<property name="can_focus">False</property>
<property name="margin_left">30</property>
<property name="margin_right">30</property>
<property name="hexpand">True</property>
<property name="orientation">vertical</property>
<property name="spacing">12</property>
<child>
<object class="GtkLabel" id="message_label">
<property name="visible">True</property>
<property name="can_focus">False</property>
<property name="halign">start</property>
<property name="hexpand">True</property>
<property name="vexpand">True</property>
<property name="label">label</property>
<property name="wrap">True</property>
</object>
<packing>
<property name="expand">False</property>
<property name="fill">True</property>
<property name="position">0</property>
</packing>
</child>
<child>
<object class="GtkGrid" id="field_table">
<property name="visible">True</property>
<property name="can_focus">False</property>
<property name="hexpand">True</property>
<property name="row_spacing">6</property>
<property name="column_spacing">12</property>
<child>
<object class="GtkLabel" id="label1">
<property name="visible">True</property>
<property name="can_focus">False</property>
<property name="halign">end</property>
<property name="label" translatable="yes">_URL of your Piwigo photo library</property>
<property name="use_underline">True</property>
<property name="mnemonic_widget">url_entry</property>
</object>
<packing>
<property name="left_attach">0</property>
<property name="top_attach">0</property>
</packing>
</child>
<child>
<object class="GtkEntry" id="url_entry">
<property name="visible">True</property>
<property name="can_focus">True</property>
<property name="hexpand">True</property>
<property name="invisible_char">●</property>
</object>
<packing>
<property name="left_attach">1</property>
<property name="top_attach">0</property>
</packing>
</child>
<child>
<object class="GtkEntry" id="password_entry">
<property name="visible">True</property>
<property name="can_focus">True</property>
<property name="hexpand">True</property>
<property name="visibility">False</property>
<property name="invisible_char">●</property>
</object>
<packing>
<property name="left_attach">1</property>
<property name="top_attach">2</property>
</packing>
</child>
<child>
<object class="GtkSwitch" id="remember_password_checkbutton">
<property name="visible">True</property>
<property name="can_focus">True</property>
<property name="halign">start</property>
</object>
<packing>
<property name="left_attach">1</property>
<property name="top_attach">3</property>
</packing>
</child>
<child>
<object class="GtkLabel" id="label2">
<property name="visible">True</property>
<property name="can_focus">False</property>
<property name="halign">end</property>
<property name="label" translatable="yes">User _name</property>
<property name="use_underline">True</property>
</object>
<packing>
<property name="left_attach">0</property>
<property name="top_attach">1</property>
</packing>
</child>
<child>
<object class="GtkEntry" id="username_entry">
<property name="visible">True</property>
<property name="can_focus">True</property>
<property name="hexpand">True</property>
<property name="invisible_char">●</property>
</object>
<packing>
<property name="left_attach">1</property>
<property name="top_attach">1</property>
</packing>
</child>
<child>
<object class="GtkLabel" id="label3">
<property name="visible">True</property>
<property name="can_focus">False</property>
<property name="halign">end</property>
<property name="label" translatable="yes">_Password</property>
<property name="use_underline">True</property>
<property name="mnemonic_widget">password_entry</property>
</object>
<packing>
<property name="left_attach">0</property>
<property name="top_attach">2</property>
</packing>
</child>
<child>
<object class="GtkLabel">
<property name="visible">True</property>
<property name="can_focus">False</property>
<property name="halign">end</property>
<property name="label" translatable="yes">Remember Password</property>
</object>
<packing>
<property name="left_attach">0</property>
<property name="top_attach">3</property>
</packing>
</child>
</object>
<packing>
<property name="expand">True</property>
<property name="fill">True</property>
<property name="position">1</property>
</packing>
</child>
<child>
<object class="GtkButtonBox" id="hbuttonbox1">
<property name="visible">True</property>
<property name="can_focus">False</property>
<property name="layout_style">center</property>
<child>
<object class="GtkButton" id="login_button">
<property name="label" translatable="yes">Log in</property>
<property name="use_action_appearance">False</property>
<property name="visible">True</property>
<property name="can_focus">True</property>
<property name="receives_default">True</property>
</object>
<packing>
<property name="expand">False</property>
<property name="fill">False</property>
<property name="position">0</property>
</packing>
</child>
</object>
<packing>
<property name="expand">True</property>
<property name="fill">True</property>
<property name="position">2</property>
</packing>
</child>
</object>
</child>
</object>
</interface>
|
{
"pile_set_name": "Github"
}
|
---
layout: default
title: mrflip.github.com/wukong - Overview
collapse: false
---
h1. Thinking Big Data
h2. There's lots of data, Wukong and Hadoop can help
There are two disruptive
* We're instrumenting every realm of human activity
** Conversation
** Relationships
**
* We have linearly scaling multiprocessing
** Old frontier computing: expensive, N log N, SUUUUUUCKS
** It's cheap, it's scaleable and it's fun
h2. == Map|Reduce ==
h3. cat input.tsv | mapper.sh | sort | reducer.sh > output.tsv
* Bobo histogram:
cat twitter_users.tsv | cuttab 3 | cutc 1-6 | sort | uniq -c > histogram.tsv
cat twitter_users.tsv | \
cuttab 3 | # extract the date column \
cutc 1-6 | # chop off all but the yearmonth \
sort | # sort, to ensure locality \
uniq -c > # roll up lines, along with their count \
histogram.tsv # save into output file
h3. Word Count
mapper:
# output each word on its own line
@readlines.each{|line| puts line.split(/[^\w]+/) }@
reducer:
# every word is _guaranteed_ to land in the same place and next to its
# friends, so we can just output the repetition count for each
# distinct line.
uniq -c
h3. Word Count by Person
* Partition Keys vs. Reduce Keys
- reduce by [word, <total>, count] and [word, user_id, count]
h2. == Global Structure ==
h3. Enumerating neighborhood
* adjacency list
* join on center link
* list of 3-paths ==
h2. == Mechanics, HDFS ==
x M _
_ M y
|
{
"pile_set_name": "Github"
}
|
// CodeMirror, copyright (c) by Marijn Haverbeke and others
// Distributed under an MIT license: https://codemirror.net/LICENSE
// Highlighting text that matches the selection
//
// Defines an option highlightSelectionMatches, which, when enabled,
// will style strings that match the selection throughout the
// document.
//
// The option can be set to true to simply enable it, or to a
// {minChars, style, wordsOnly, showToken, delay} object to explicitly
// configure it. minChars is the minimum amount of characters that should be
// selected for the behavior to occur, and style is the token style to
// apply to the matches. This will be prefixed by "cm-" to create an
// actual CSS class name. If wordsOnly is enabled, the matches will be
// highlighted only if the selected text is a word. showToken, when enabled,
// will cause the current token to be highlighted when nothing is selected.
// delay is used to specify how much time to wait, in milliseconds, before
// highlighting the matches. If annotateScrollbar is enabled, the occurences
// will be highlighted on the scrollbar via the matchesonscrollbar addon.
(function(mod) {
if (typeof exports == "object" && typeof module == "object") // CommonJS
mod(require("../../lib/codemirror"), require("./matchesonscrollbar"));
else if (typeof define == "function" && define.amd) // AMD
define(["../../lib/codemirror", "./matchesonscrollbar"], mod);
else // Plain browser env
mod(CodeMirror);
})(function(CodeMirror) {
"use strict";
var defaults = {
style: "matchhighlight",
minChars: 2,
delay: 100,
wordsOnly: false,
annotateScrollbar: false,
showToken: false,
trim: true
}
function State(options) {
this.options = {}
for (var name in defaults)
this.options[name] = (options && options.hasOwnProperty(name) ? options : defaults)[name]
this.overlay = this.timeout = null;
this.matchesonscroll = null;
this.active = false;
}
CodeMirror.defineOption("highlightSelectionMatches", false, function(cm, val, old) {
if (old && old != CodeMirror.Init) {
removeOverlay(cm);
clearTimeout(cm.state.matchHighlighter.timeout);
cm.state.matchHighlighter = null;
cm.off("cursorActivity", cursorActivity);
cm.off("focus", onFocus)
}
if (val) {
var state = cm.state.matchHighlighter = new State(val);
if (cm.hasFocus()) {
state.active = true
highlightMatches(cm)
} else {
cm.on("focus", onFocus)
}
cm.on("cursorActivity", cursorActivity);
}
});
function cursorActivity(cm) {
var state = cm.state.matchHighlighter;
if (state.active || cm.hasFocus()) scheduleHighlight(cm, state)
}
function onFocus(cm) {
var state = cm.state.matchHighlighter
if (!state.active) {
state.active = true
scheduleHighlight(cm, state)
}
}
function scheduleHighlight(cm, state) {
clearTimeout(state.timeout);
state.timeout = setTimeout(function() {highlightMatches(cm);}, state.options.delay);
}
function addOverlay(cm, query, hasBoundary, style) {
var state = cm.state.matchHighlighter;
cm.addOverlay(state.overlay = makeOverlay(query, hasBoundary, style));
if (state.options.annotateScrollbar && cm.showMatchesOnScrollbar) {
var searchFor = hasBoundary ? new RegExp("\\b" + query.replace(/[\\\[.+*?(){|^$]/g, "\\$&") + "\\b") : query;
state.matchesonscroll = cm.showMatchesOnScrollbar(searchFor, false,
{className: "CodeMirror-selection-highlight-scrollbar"});
}
}
function removeOverlay(cm) {
var state = cm.state.matchHighlighter;
if (state.overlay) {
cm.removeOverlay(state.overlay);
state.overlay = null;
if (state.matchesonscroll) {
state.matchesonscroll.clear();
state.matchesonscroll = null;
}
}
}
function highlightMatches(cm) {
cm.operation(function() {
var state = cm.state.matchHighlighter;
removeOverlay(cm);
if (!cm.somethingSelected() && state.options.showToken) {
var re = state.options.showToken === true ? /[\w$]/ : state.options.showToken;
var cur = cm.getCursor(), line = cm.getLine(cur.line), start = cur.ch, end = start;
while (start && re.test(line.charAt(start - 1))) --start;
while (end < line.length && re.test(line.charAt(end))) ++end;
if (start < end)
addOverlay(cm, line.slice(start, end), re, state.options.style);
return;
}
var from = cm.getCursor("from"), to = cm.getCursor("to");
if (from.line != to.line) return;
if (state.options.wordsOnly && !isWord(cm, from, to)) return;
var selection = cm.getRange(from, to)
if (state.options.trim) selection = selection.replace(/^\s+|\s+$/g, "")
if (selection.length >= state.options.minChars)
addOverlay(cm, selection, false, state.options.style);
});
}
function isWord(cm, from, to) {
var str = cm.getRange(from, to);
if (str.match(/^\w+$/) !== null) {
if (from.ch > 0) {
var pos = {line: from.line, ch: from.ch - 1};
var chr = cm.getRange(pos, from);
if (chr.match(/\W/) === null) return false;
}
if (to.ch < cm.getLine(from.line).length) {
var pos = {line: to.line, ch: to.ch + 1};
var chr = cm.getRange(to, pos);
if (chr.match(/\W/) === null) return false;
}
return true;
} else return false;
}
function boundariesAround(stream, re) {
return (!stream.start || !re.test(stream.string.charAt(stream.start - 1))) &&
(stream.pos == stream.string.length || !re.test(stream.string.charAt(stream.pos)));
}
function makeOverlay(query, hasBoundary, style) {
return {token: function(stream) {
if (stream.match(query) &&
(!hasBoundary || boundariesAround(stream, hasBoundary)))
return style;
stream.next();
stream.skipTo(query.charAt(0)) || stream.skipToEnd();
}};
}
});
|
{
"pile_set_name": "Github"
}
|
1..10
# Started on 03/22/16 21:58:32
# Starting class: TestAnotherThing
ok 1 TestAnotherThing.test1_Success1
ok 2 TestAnotherThing.test1_Success2
not ok 3 TestAnotherThing.test3_Fail1
# test/test_with_err_fail_pass.lua:49: expected: 0, actual: 2
not ok 4 TestAnotherThing.test3_Fail2
# test/test_with_err_fail_pass.lua:53: expected: 0, actual: 3
# Starting class: TestSomething
ok 5 TestSomething.test1_Success1
ok 6 TestSomething.test1_Success2
not ok 7 TestSomething.test2_Fail1
# test/test_with_err_fail_pass.lua:15: expected: 0, actual: 2
not ok 8 TestSomething.test2_Fail2
# test/test_with_err_fail_pass.lua:19: expected: 0, actual: 3
not ok 9 testFuncFail1
# test/test_with_err_fail_pass.lua:62: expected: 0, actual: 3
ok 10 testFuncSuccess1
# Ran 10 tests in 0.000 seconds, 5 successes, 5 failures, 5 non-selected
|
{
"pile_set_name": "Github"
}
|
#!/bin/sh
cd "$(dirname "$0")"
REPO=git://repo.or.cz/antiword.git
DIR=antiword-git
HEAD=0680e7ee62e430e0905085e5b4cfb01d31db5936 # antiword 0.37
die () {
echo "$*" >&2
exit 1
}
test -d $DIR ||
( git clone -n $REPO $DIR && cd $DIR && git checkout $HEAD ) ||
die "Could not clone $REPO"
(cd $DIR && git am ../patches/*) ||
die "Could not apply patches"
(cd $DIR &&
make -f Makefile.Linux antiword.exe &&
index=$(/share/msysGit/pre-install.sh) &&
make -f Makefile.Linux global_install &&
/share/msysGit/post-install.sh $index "Install antiword (Git $HEAD)"
) || die "Could not install antiword"
|
{
"pile_set_name": "Github"
}
|
// Copyright 2009 the Sputnik authors. All rights reserved.
// This code is governed by the BSD license found in the LICENSE file.
/**
* The production x >>>= y is the same as x = x >>> y
*
* @path ch11/11.13/11.13.2/S11.13.2_A4.8_T1.4.js
* @description Type(x) and Type(y) vary between Null and Undefined
*/
//CHECK#1
x = null;
x >>>= undefined;
if (x !== 0) {
$ERROR('#1: x = null; x >>>= undefined; x === 0. Actual: ' + (x));
}
//CHECK#2
x = undefined;
x >>>= null;
if (x !== 0) {
$ERROR('#2: x = undefined; x >>>= null; x === 0. Actual: ' + (x));
}
//CHECK#3
x = undefined;
x >>>= undefined;
if (x !== 0) {
$ERROR('#3: x = undefined; x >>>= undefined; x === 0. Actual: ' + (x));
}
//CHECK#4
x = null;
x >>>= null;
if (x !== 0) {
$ERROR('#4: x = null; x >>>= null; x === 0. Actual: ' + (x));
}
|
{
"pile_set_name": "Github"
}
|
// ChildFrm.cpp : implementation of the CChildFrame class
//
#include "stdafx.h"
#include "CursorIconExplorer.h"
#include "ChildFrm.h"
#ifdef _DEBUG
#define new DEBUG_NEW
#undef THIS_FILE
static char THIS_FILE[] = __FILE__;
#endif
/////////////////////////////////////////////////////////////////////////////
// CChildFrame
IMPLEMENT_DYNCREATE(CChildFrame, CMDIChildWnd)
BEGIN_MESSAGE_MAP(CChildFrame, CMDIChildWnd)
//{{AFX_MSG_MAP(CChildFrame)
// NOTE - the ClassWizard will add and remove mapping macros here.
// DO NOT EDIT what you see in these blocks of generated code !
//}}AFX_MSG_MAP
END_MESSAGE_MAP()
/////////////////////////////////////////////////////////////////////////////
// CChildFrame construction/destruction
CChildFrame::CChildFrame()
{
// TODO: add member initialization code here
}
CChildFrame::~CChildFrame()
{
}
BOOL CChildFrame::PreCreateWindow(CREATESTRUCT& cs)
{
// TODO: Modify the Window class or styles here by modifying
// the CREATESTRUCT cs
return CMDIChildWnd::PreCreateWindow(cs);
}
/////////////////////////////////////////////////////////////////////////////
// CChildFrame diagnostics
#ifdef _DEBUG
void CChildFrame::AssertValid() const
{
CMDIChildWnd::AssertValid();
}
void CChildFrame::Dump(CDumpContext& dc) const
{
CMDIChildWnd::Dump(dc);
}
#endif //_DEBUG
/////////////////////////////////////////////////////////////////////////////
// CChildFrame message handlers
|
{
"pile_set_name": "Github"
}
|
#! /usr/bin/env perl
print "$ARGV[0] post script\n";
if ($ARGV[1] eq 0) {
print "Failure\n";
exit(1);
} else {
print "Success\n";
}
|
{
"pile_set_name": "Github"
}
|
["0.1.0"]
git-tree-sha1 = "3cfb2e1f46cdcc35a48d2ca0c320e755aaae28b3"
|
{
"pile_set_name": "Github"
}
|
# coding: utf8
import geocoder
location = 'Ottawa'
coordinates = {'lat': 41.005407, 'lng': 28.978349}
def test_yandex():
g = geocoder.yandex(location)
assert g.ok
def test_yandex_reverse():
g = geocoder.yandex(coordinates, method='reverse')
assert g.ok
def test_multi_results():
g = geocoder.yandex(location, maxRows=3)
assert len(g) == 3
|
{
"pile_set_name": "Github"
}
|
#include <signal.h>
#include <errno.h>
int sigaddset(sigset_t *set, int sig)
{
unsigned s = sig-1;
if (s >= _NSIG-1 || sig-32U < 3) {
errno = EINVAL;
return -1;
}
set->__bits[s/8/sizeof *set->__bits] |= 1UL<<(s&8*sizeof *set->__bits-1);
return 0;
}
|
{
"pile_set_name": "Github"
}
|
.\" Hey, Emacs! This is -*-nroff-*- you know...
.\"
.\" genrb.1: manual page for the genrb utility
.\"
.\" Copyright (C) 2016 and later: Unicode, Inc. and others.
.\" License & terms of use: http://www.unicode.org/copyright.html
.\" Copyright (C) 2000-2002 IBM, Inc. and others.
.\"
.\" Manual page by Yves Arrouye <[email protected]>.
.\"
.TH GENRB 1 "16 April 2002" "ICU MANPAGE" "ICU @VERSION@ Manual"
.SH NAME
.B genrb
\- compile a resource bundle
.SH SYNOPSIS
.B genrb
[
.BR "\-h\fP, \fB\-?\fP, \fB\-\-help"
]
[
.BR "\-V\fP, \fB\-\-version"
]
[
.BR "\-v\fP, \fB\-\-verbose"
]
[
.BI "\-e\fP, \fB\-\-encoding" " encoding"
]
[
.BI "\-j\fP, \fB\-\-write\-java" " \fR[ \fPencoding\fR ]\fP"
]
[
.BI "\-s\fP, \fB\-\-sourcedir" " source"
]
[
.BI "\-d\fP, \fB\-\-destdir" " destination"
]
[
.BI "\-i\fP, \fB\-\-icudatadir" " directory"
]
.IR bundle " \.\.\."
.SH DESCRIPTION
.B genrb
converts the resource
.I bundle
source files passed on the command line to their binary form or to
a Java source file for use with ICU4J.
The resulting binary files have a
.B .res
extension while resource bundle source files typically have a
.B .txt
extension. Java source files have a
.B java
extension and follow the ICU4J naming conventions.
.PP
It is customary to name the resource bundles by their locale name,
i.e. to use a local identifier for the
.I bundle
filename, e.g.
.B ja_JP.txt
for Japanese (Japan) data, or
.B root.txt
for the root bundle.
In any case,
.B genrb
will produce a file whose base name is the name of the locale found
in the resource file, not the base name of the resource file itself.
.PP
The binary files can be read directly by ICU, or used by
.BR pkgdata (1)
for incorporation into a larger archive or library.
.SH OPTIONS
.TP
.BR "\-h\fP, \fB\-?\fP, \fB\-\-help"
Print help about usage and exit.
.TP
.BR "\-V\fP, \fB\-\-version"
Print the version of
.B genrb
and exit.
.TP
.BR "\-v\fP, \fB\-\-verbose"
Display extra informative messages during execution.
.TP
.BI "\-e\fP, \fB\-\-encoding" " encoding"
Set the encoding used to read input files to
.IR encoding .
The default encoding is the invariant (subset of ASCII or EBCDIC)
codepage for the system (see section
.BR "INVARIANT CHARACTERS" ).
The encodings UTF-8, UTF-16BE, and UTF-16LE are automatically detected
if a byte order mark (BOM) is present.
.TP
.BI "\-j\fP, \fB\-\-write\-java" " \fR[ \fPencoding\fR ]\fP"
Generate a Java source code for use with ICU4J. An optional
.I encoding
for the Java file can be given.
.TP
.BI "\-s\fP, \fB\-\-sourcedir" " source"
Set the source directory to
.IR source .
The default source directory is specified by the environment variable
.BR ICU_DATA ,
or the location set when ICU was built if
.B ICU_DATA
is not set.
.TP
.BI "\-d\fP, \fB\-\-destdir" " destination"
Set the destination directory to
.IR destination .
The default destination directory is specified by the environment variable
.BR ICU_DATA
or is the location set when ICU was built if
.B ICU_DATA
is not set.
.TP
.BI "\-i\fP, \fB\-\-icudatadir" " directory"
Look for any necessary ICU data files in
.IR directory .
For example, when processing collation overrides, the file
.B ucadata.dat
must be located.
The default ICU data directory is specified by the environment variable
.BR ICU_DATA .
.SH INVARIANT CHARACTERS
The
.B invariant character set
consists of the following set of characters, expressed as a standard POSIX
regular expression:
.BR "[a-z]|[A-Z]|[0-9]|_| |+|-|*|/" .
This is the set which is guaranteed to be available regardless of code page.
.SH ENVIRONMENT
.TP 10
.B ICU_DATA
Specifies the directory containing ICU data. Defaults to
.BR @thepkgicudatadir@/@PACKAGE@/@VERSION@/ .
Some tools in ICU depend on the presence of the trailing slash. It is thus
important to make sure that it is present if
.B ICU_DATA
is set.
.SH VERSION
@VERSION@
.SH COPYRIGHT
Copyright (C) 2000-2002 IBM, Inc. and others.
.SH SEE ALSO
.BR derb (1)
.br
.BR pkgdata (1)
|
{
"pile_set_name": "Github"
}
|
"""Platform compatibility."""
import platform
import re
import sys
# Jython does not have this attribute
import typing
try:
from socket import SOL_TCP
except ImportError: # pragma: no cover
from socket import IPPROTO_TCP as SOL_TCP # noqa
RE_NUM = re.compile(r'(\d+).+')
def _linux_version_to_tuple(s: str) -> typing.Tuple[int, int, int]:
return tuple(map(_versionatom, s.split('.')[:3]))
def _versionatom(s: str) -> int:
if s.isdigit():
return int(s)
match = RE_NUM.match(s)
return int(match.groups()[0]) if match else 0
# available socket options for TCP level
KNOWN_TCP_OPTS = {
'TCP_CORK', 'TCP_DEFER_ACCEPT', 'TCP_KEEPCNT',
'TCP_KEEPIDLE', 'TCP_KEEPINTVL', 'TCP_LINGER2',
'TCP_MAXSEG', 'TCP_NODELAY', 'TCP_QUICKACK',
'TCP_SYNCNT', 'TCP_USER_TIMEOUT', 'TCP_WINDOW_CLAMP',
}
LINUX_VERSION = None
if sys.platform.startswith('linux'):
LINUX_VERSION = _linux_version_to_tuple(platform.release())
if LINUX_VERSION < (2, 6, 37):
KNOWN_TCP_OPTS.remove('TCP_USER_TIMEOUT')
# Windows Subsystem for Linux is an edge-case: the Python socket library
# returns most TCP_* enums, but they aren't actually supported
if platform.release().endswith("Microsoft"):
KNOWN_TCP_OPTS = {'TCP_NODELAY', 'TCP_KEEPIDLE', 'TCP_KEEPINTVL',
'TCP_KEEPCNT'}
elif sys.platform.startswith('darwin'):
KNOWN_TCP_OPTS.remove('TCP_USER_TIMEOUT')
elif 'bsd' in sys.platform:
KNOWN_TCP_OPTS.remove('TCP_USER_TIMEOUT')
# According to MSDN Windows platforms support getsockopt(TCP_MAXSSEG) but not
# setsockopt(TCP_MAXSEG) on IPPROTO_TCP sockets.
elif sys.platform.startswith('win'):
KNOWN_TCP_OPTS = {'TCP_NODELAY'}
elif sys.platform.startswith('cygwin'):
KNOWN_TCP_OPTS = {'TCP_NODELAY'}
# illumos does not allow to set the TCP_MAXSEG socket option,
# even if the Oracle documentation says otherwise.
elif sys.platform.startswith('sunos'):
KNOWN_TCP_OPTS.remove('TCP_MAXSEG')
# aix does not allow to set the TCP_MAXSEG
# or the TCP_USER_TIMEOUT socket options.
elif sys.platform.startswith('aix'):
KNOWN_TCP_OPTS.remove('TCP_MAXSEG')
KNOWN_TCP_OPTS.remove('TCP_USER_TIMEOUT')
__all__ = (
'LINUX_VERSION',
'SOL_TCP',
'KNOWN_TCP_OPTS',
)
|
{
"pile_set_name": "Github"
}
|
/*
* Copyright (c) 1997, 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. 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 jdk.javadoc.internal.doclets.formats.html;
import jdk.javadoc.internal.doclets.formats.html.markup.Table;
import java.util.*;
import javax.lang.model.element.PackageElement;
import jdk.javadoc.internal.doclets.formats.html.markup.ContentBuilder;
import jdk.javadoc.internal.doclets.formats.html.markup.HtmlStyle;
import jdk.javadoc.internal.doclets.formats.html.markup.HtmlTag;
import jdk.javadoc.internal.doclets.formats.html.markup.HtmlTree;
import jdk.javadoc.internal.doclets.toolkit.Content;
import jdk.javadoc.internal.doclets.toolkit.util.DocFileIOException;
import jdk.javadoc.internal.doclets.toolkit.util.DocPath;
import jdk.javadoc.internal.doclets.toolkit.util.DocPaths;
import jdk.javadoc.internal.doclets.toolkit.util.Group;
/**
* Generate the package index page "overview-summary.html" for the right-hand
* frame. A click on the package name on this page will update the same frame
* with the "package-summary.html" file for the clicked package.
*
* <p><b>This is NOT part of any supported API.
* If you write code that depends on this, you do so at your own risk.
* This code and its internal interfaces are subject to change or
* deletion without notice.</b>
*
* @author Atul M Dambalkar
* @author Bhavesh Patel (Modified)
*/
public class PackageIndexWriter extends AbstractPackageIndexWriter {
/**
* HTML tree for main tag.
*/
private final HtmlTree htmlTree = HtmlTree.MAIN();
/**
* Construct the PackageIndexWriter. Also constructs the grouping
* information as provided on the command line by "-group" option. Stores
* the order of groups specified by the user.
*
* @param configuration the configuration for this doclet
* @param filename the path of the page to be generated
* @see Group
*/
public PackageIndexWriter(HtmlConfiguration configuration, DocPath filename) {
super(configuration, filename);
}
/**
* Generate the package index page for the right-hand frame.
*
* @param configuration the current configuration of the doclet.
* @throws DocFileIOException if there is a problem generating the package index page
*/
public static void generate(HtmlConfiguration configuration) throws DocFileIOException {
DocPath filename = DocPaths.overviewSummary(configuration.frames);
PackageIndexWriter packgen = new PackageIndexWriter(configuration, filename);
packgen.buildPackageIndexFile("doclet.Window_Overview_Summary", true);
}
/**
* Depending upon the grouping information and their titles, add
* separate table indices for each package group.
*
* @param body the documentation tree to which the index will be added
*/
@Override
protected void addIndex(Content body) {
addIndexContents(body);
}
/**
* {@inheritDoc}
*/
@Override
protected void addPackagesList(Content body) {
Map<String, SortedSet<PackageElement>> groupPackageMap
= configuration.group.groupPackages(packages);
if (!groupPackageMap.keySet().isEmpty()) {
String tableSummary = configuration.getText("doclet.Member_Table_Summary",
configuration.getText("doclet.Package_Summary"), configuration.getText("doclet.packages"));
Table table = new Table(configuration.htmlVersion, HtmlStyle.overviewSummary)
.setSummary(tableSummary)
.setHeader(getPackageTableHeader())
.setColumnStyles(HtmlStyle.colFirst, HtmlStyle.colLast)
.setDefaultTab(resources.getText("doclet.All_Packages"))
.setTabScript(i -> "show(" + i + ");")
.setTabId(i -> (i == 0) ? "t0" : ("t" + (1 << (i - 1))));
// add the tabs in command-line order
for (String groupName : configuration.group.getGroupList()) {
Set<PackageElement> groupPackages = groupPackageMap.get(groupName);
if (groupPackages != null) {
table.addTab(groupName, groupPackages::contains);
}
}
for (PackageElement pkg : configuration.packages) {
if (!pkg.isUnnamed()) {
if (!(configuration.nodeprecated && utils.isDeprecated(pkg))) {
Content packageLinkContent = getPackageLink(pkg, getPackageName(pkg));
Content summaryContent = new ContentBuilder();
addSummaryComment(pkg, summaryContent);
table.addRow(pkg, packageLinkContent, summaryContent);
}
}
}
Content div = HtmlTree.DIV(HtmlStyle.contentContainer, table.toContent());
if (configuration.allowTag(HtmlTag.MAIN)) {
htmlTree.addContent(div);
} else {
body.addContent(div);
}
if (table.needsScript()) {
getMainBodyScript().append(table.getScript());
}
}
}
/**
* Adds the overview summary comment for this documentation. Add one line
* summary at the top of the page and generate a link to the description,
* which is added at the end of this page.
*
* @param body the documentation tree to which the overview header will be added
*/
@Override
protected void addOverviewHeader(Content body) {
addConfigurationTitle(body);
if (!utils.getFullBody(configuration.overviewElement).isEmpty()) {
HtmlTree div = new HtmlTree(HtmlTag.DIV);
div.setStyle(HtmlStyle.contentContainer);
addOverviewComment(div);
if (configuration.allowTag(HtmlTag.MAIN)) {
htmlTree.addContent(div);
} else {
body.addContent(div);
}
}
}
/**
* Adds the overview comment as provided in the file specified by the
* "-overview" option on the command line.
*
* @param htmltree the documentation tree to which the overview comment will
* be added
*/
protected void addOverviewComment(Content htmltree) {
if (!utils.getFullBody(configuration.overviewElement).isEmpty()) {
addInlineComment(configuration.overviewElement, htmltree);
}
}
/**
* For HTML 5, add the htmlTree to the body. For HTML 4, do nothing.
*
* @param body the documentation tree to which the overview will be added
*/
@Override
protected void addOverview(Content body) {
if (configuration.allowTag(HtmlTag.MAIN)) {
body.addContent(htmlTree);
}
}
/**
* Adds the top text (from the -top option), the upper
* navigation bar, and then the title (from the"-title"
* option), at the top of page.
*
* @param body the documentation tree to which the navigation bar header will be added
*/
@Override
protected void addNavigationBarHeader(Content body) {
Content tree = (configuration.allowTag(HtmlTag.HEADER))
? HtmlTree.HEADER()
: body;
addTop(tree);
navBar.setUserHeader(getUserHeaderFooter(true));
tree.addContent(navBar.getContent(true));
if (configuration.allowTag(HtmlTag.HEADER)) {
body.addContent(tree);
}
}
/**
* Adds the lower navigation bar and the bottom text
* (from the -bottom option) at the bottom of page.
*
* @param body the documentation tree to which the navigation bar footer will be added
*/
@Override
protected void addNavigationBarFooter(Content body) {
Content tree = (configuration.allowTag(HtmlTag.FOOTER))
? HtmlTree.FOOTER()
: body;
navBar.setUserFooter(getUserHeaderFooter(false));
tree.addContent(navBar.getContent(false));
addBottom(tree);
if (configuration.allowTag(HtmlTag.FOOTER)) {
body.addContent(tree);
}
}
}
|
{
"pile_set_name": "Github"
}
|
// Copyright 2015 the V8 project authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#ifndef V8_WASM_OPCODES_H_
#define V8_WASM_OPCODES_H_
#include "src/machine-type.h"
#include "src/signature.h"
namespace v8 {
namespace internal {
namespace wasm {
// Binary encoding of local types.
enum LocalTypeCode {
kLocalVoid = 0,
kLocalI32 = 1,
kLocalI64 = 2,
kLocalF32 = 3,
kLocalF64 = 4
};
// Binary encoding of memory types.
enum MemTypeCode {
kMemI8 = 0,
kMemU8 = 1,
kMemI16 = 2,
kMemU16 = 3,
kMemI32 = 4,
kMemU32 = 5,
kMemI64 = 6,
kMemU64 = 7,
kMemF32 = 8,
kMemF64 = 9
};
// We reuse the internal machine type to represent WebAssembly AST types.
// A typedef improves readability without adding a whole new type system.
typedef MachineRepresentation LocalType;
const LocalType kAstStmt = MachineRepresentation::kNone;
const LocalType kAstI32 = MachineRepresentation::kWord32;
const LocalType kAstI64 = MachineRepresentation::kWord64;
const LocalType kAstF32 = MachineRepresentation::kFloat32;
const LocalType kAstF64 = MachineRepresentation::kFloat64;
// We use kTagged here because kNone is already used by kAstStmt.
const LocalType kAstEnd = MachineRepresentation::kTagged;
typedef Signature<LocalType> FunctionSig;
std::ostream& operator<<(std::ostream& os, const FunctionSig& function);
struct WasmName {
const char* name;
uint32_t length;
};
// TODO(titzer): Renumber all the opcodes to fill in holes.
// Control expressions and blocks.
#define FOREACH_CONTROL_OPCODE(V) \
V(Nop, 0x00, _) \
V(Block, 0x01, _) \
V(Loop, 0x02, _) \
V(If, 0x03, _) \
V(IfElse, 0x04, _) \
V(Select, 0x05, _) \
V(Br, 0x06, _) \
V(BrIf, 0x07, _) \
V(BrTable, 0x08, _) \
V(Return, 0x14, _) \
V(Unreachable, 0x15, _)
// Constants, locals, globals, and calls.
#define FOREACH_MISC_OPCODE(V) \
V(I8Const, 0x09, _) \
V(I32Const, 0x0a, _) \
V(I64Const, 0x0b, _) \
V(F64Const, 0x0c, _) \
V(F32Const, 0x0d, _) \
V(GetLocal, 0x0e, _) \
V(SetLocal, 0x0f, _) \
V(LoadGlobal, 0x10, _) \
V(StoreGlobal, 0x11, _) \
V(CallFunction, 0x12, _) \
V(CallIndirect, 0x13, _) \
V(CallImport, 0x1F, _) \
V(DeclLocals, 0x1E, _)
// Load memory expressions.
#define FOREACH_LOAD_MEM_OPCODE(V) \
V(I32LoadMem8S, 0x20, i_i) \
V(I32LoadMem8U, 0x21, i_i) \
V(I32LoadMem16S, 0x22, i_i) \
V(I32LoadMem16U, 0x23, i_i) \
V(I64LoadMem8S, 0x24, l_i) \
V(I64LoadMem8U, 0x25, l_i) \
V(I64LoadMem16S, 0x26, l_i) \
V(I64LoadMem16U, 0x27, l_i) \
V(I64LoadMem32S, 0x28, l_i) \
V(I64LoadMem32U, 0x29, l_i) \
V(I32LoadMem, 0x2a, i_i) \
V(I64LoadMem, 0x2b, l_i) \
V(F32LoadMem, 0x2c, f_i) \
V(F64LoadMem, 0x2d, d_i)
// Store memory expressions.
#define FOREACH_STORE_MEM_OPCODE(V) \
V(I32StoreMem8, 0x2e, i_ii) \
V(I32StoreMem16, 0x2f, i_ii) \
V(I64StoreMem8, 0x30, l_il) \
V(I64StoreMem16, 0x31, l_il) \
V(I64StoreMem32, 0x32, l_il) \
V(I32StoreMem, 0x33, i_ii) \
V(I64StoreMem, 0x34, l_il) \
V(F32StoreMem, 0x35, f_if) \
V(F64StoreMem, 0x36, d_id)
// Load memory expressions.
#define FOREACH_MISC_MEM_OPCODE(V) \
V(MemorySize, 0x3b, i_v) \
V(GrowMemory, 0x39, i_i)
// Expressions with signatures.
#define FOREACH_SIMPLE_OPCODE(V) \
V(I32Add, 0x40, i_ii) \
V(I32Sub, 0x41, i_ii) \
V(I32Mul, 0x42, i_ii) \
V(I32DivS, 0x43, i_ii) \
V(I32DivU, 0x44, i_ii) \
V(I32RemS, 0x45, i_ii) \
V(I32RemU, 0x46, i_ii) \
V(I32And, 0x47, i_ii) \
V(I32Ior, 0x48, i_ii) \
V(I32Xor, 0x49, i_ii) \
V(I32Shl, 0x4a, i_ii) \
V(I32ShrU, 0x4b, i_ii) \
V(I32ShrS, 0x4c, i_ii) \
V(I32Eq, 0x4d, i_ii) \
V(I32Ne, 0x4e, i_ii) \
V(I32LtS, 0x4f, i_ii) \
V(I32LeS, 0x50, i_ii) \
V(I32LtU, 0x51, i_ii) \
V(I32LeU, 0x52, i_ii) \
V(I32GtS, 0x53, i_ii) \
V(I32GeS, 0x54, i_ii) \
V(I32GtU, 0x55, i_ii) \
V(I32GeU, 0x56, i_ii) \
V(I32Clz, 0x57, i_i) \
V(I32Ctz, 0x58, i_i) \
V(I32Popcnt, 0x59, i_i) \
V(I32Eqz, 0x5a, i_i) \
V(I64Add, 0x5b, l_ll) \
V(I64Sub, 0x5c, l_ll) \
V(I64Mul, 0x5d, l_ll) \
V(I64DivS, 0x5e, l_ll) \
V(I64DivU, 0x5f, l_ll) \
V(I64RemS, 0x60, l_ll) \
V(I64RemU, 0x61, l_ll) \
V(I64And, 0x62, l_ll) \
V(I64Ior, 0x63, l_ll) \
V(I64Xor, 0x64, l_ll) \
V(I64Shl, 0x65, l_ll) \
V(I64ShrU, 0x66, l_ll) \
V(I64ShrS, 0x67, l_ll) \
V(I64Eq, 0x68, i_ll) \
V(I64Ne, 0x69, i_ll) \
V(I64LtS, 0x6a, i_ll) \
V(I64LeS, 0x6b, i_ll) \
V(I64LtU, 0x6c, i_ll) \
V(I64LeU, 0x6d, i_ll) \
V(I64GtS, 0x6e, i_ll) \
V(I64GeS, 0x6f, i_ll) \
V(I64GtU, 0x70, i_ll) \
V(I64GeU, 0x71, i_ll) \
V(I64Clz, 0x72, l_l) \
V(I64Ctz, 0x73, l_l) \
V(I64Popcnt, 0x74, l_l) \
V(I64Eqz, 0xba, i_l) \
V(F32Add, 0x75, f_ff) \
V(F32Sub, 0x76, f_ff) \
V(F32Mul, 0x77, f_ff) \
V(F32Div, 0x78, f_ff) \
V(F32Min, 0x79, f_ff) \
V(F32Max, 0x7a, f_ff) \
V(F32Abs, 0x7b, f_f) \
V(F32Neg, 0x7c, f_f) \
V(F32CopySign, 0x7d, f_ff) \
V(F32Ceil, 0x7e, f_f) \
V(F32Floor, 0x7f, f_f) \
V(F32Trunc, 0x80, f_f) \
V(F32NearestInt, 0x81, f_f) \
V(F32Sqrt, 0x82, f_f) \
V(F32Eq, 0x83, i_ff) \
V(F32Ne, 0x84, i_ff) \
V(F32Lt, 0x85, i_ff) \
V(F32Le, 0x86, i_ff) \
V(F32Gt, 0x87, i_ff) \
V(F32Ge, 0x88, i_ff) \
V(F64Add, 0x89, d_dd) \
V(F64Sub, 0x8a, d_dd) \
V(F64Mul, 0x8b, d_dd) \
V(F64Div, 0x8c, d_dd) \
V(F64Min, 0x8d, d_dd) \
V(F64Max, 0x8e, d_dd) \
V(F64Abs, 0x8f, d_d) \
V(F64Neg, 0x90, d_d) \
V(F64CopySign, 0x91, d_dd) \
V(F64Ceil, 0x92, d_d) \
V(F64Floor, 0x93, d_d) \
V(F64Trunc, 0x94, d_d) \
V(F64NearestInt, 0x95, d_d) \
V(F64Sqrt, 0x96, d_d) \
V(F64Eq, 0x97, i_dd) \
V(F64Ne, 0x98, i_dd) \
V(F64Lt, 0x99, i_dd) \
V(F64Le, 0x9a, i_dd) \
V(F64Gt, 0x9b, i_dd) \
V(F64Ge, 0x9c, i_dd) \
V(I32SConvertF32, 0x9d, i_f) \
V(I32SConvertF64, 0x9e, i_d) \
V(I32UConvertF32, 0x9f, i_f) \
V(I32UConvertF64, 0xa0, i_d) \
V(I32ConvertI64, 0xa1, i_l) \
V(I64SConvertF32, 0xa2, l_f) \
V(I64SConvertF64, 0xa3, l_d) \
V(I64UConvertF32, 0xa4, l_f) \
V(I64UConvertF64, 0xa5, l_d) \
V(I64SConvertI32, 0xa6, l_i) \
V(I64UConvertI32, 0xa7, l_i) \
V(F32SConvertI32, 0xa8, f_i) \
V(F32UConvertI32, 0xa9, f_i) \
V(F32SConvertI64, 0xaa, f_l) \
V(F32UConvertI64, 0xab, f_l) \
V(F32ConvertF64, 0xac, f_d) \
V(F32ReinterpretI32, 0xad, f_i) \
V(F64SConvertI32, 0xae, d_i) \
V(F64UConvertI32, 0xaf, d_i) \
V(F64SConvertI64, 0xb0, d_l) \
V(F64UConvertI64, 0xb1, d_l) \
V(F64ConvertF32, 0xb2, d_f) \
V(F64ReinterpretI64, 0xb3, d_l) \
V(I32ReinterpretF32, 0xb4, i_f) \
V(I64ReinterpretF64, 0xb5, l_d) \
V(I32Ror, 0xb6, i_ii) \
V(I32Rol, 0xb7, i_ii) \
V(I64Ror, 0xb8, l_ll) \
V(I64Rol, 0xb9, l_ll)
// For compatibility with Asm.js.
#define FOREACH_ASMJS_COMPAT_OPCODE(V) \
V(F64Acos, 0xc0, d_d) \
V(F64Asin, 0xc1, d_d) \
V(F64Atan, 0xc2, d_d) \
V(F64Cos, 0xc3, d_d) \
V(F64Sin, 0xc4, d_d) \
V(F64Tan, 0xc5, d_d) \
V(F64Exp, 0xc6, d_d) \
V(F64Log, 0xc7, d_d) \
V(F64Atan2, 0xc8, d_dd) \
V(F64Pow, 0xc9, d_dd) \
V(F64Mod, 0xca, d_dd)
// TODO(titzer): sketch of asm-js compatibility bytecodes
/* V(I32AsmjsDivS, 0xd0, i_ii) \ */
/* V(I32AsmjsDivU, 0xd1, i_ii) \ */
/* V(I32AsmjsRemS, 0xd2, i_ii) \ */
/* V(I32AsmjsRemU, 0xd3, i_ii) \ */
/* V(I32AsmjsLoad8S, 0xd4, i_i) \ */
/* V(I32AsmjsLoad8U, 0xd5, i_i) \ */
/* V(I32AsmjsLoad16S, 0xd6, i_i) \ */
/* V(I32AsmjsLoad16U, 0xd7, i_i) \ */
/* V(I32AsmjsLoad, 0xd8, i_i) \ */
/* V(F32AsmjsLoad, 0xd9, f_i) \ */
/* V(F64AsmjsLoad, 0xda, d_i) \ */
/* V(I32AsmjsStore8, 0xdb, i_i) \ */
/* V(I32AsmjsStore16, 0xdc, i_i) \ */
/* V(I32AsmjsStore, 0xdd, i_ii) \ */
/* V(F32AsmjsStore, 0xde, i_if) \ */
/* V(F64AsmjsStore, 0xdf, i_id) \ */
/* V(I32SAsmjsConvertF32, 0xe0, i_f) \ */
/* V(I32UAsmjsConvertF32, 0xe1, i_f) \ */
/* V(I32SAsmjsConvertF64, 0xe2, i_d) \ */
/* V(I32SAsmjsConvertF64, 0xe3, i_d) */
// All opcodes.
#define FOREACH_OPCODE(V) \
FOREACH_CONTROL_OPCODE(V) \
FOREACH_MISC_OPCODE(V) \
FOREACH_SIMPLE_OPCODE(V) \
FOREACH_STORE_MEM_OPCODE(V) \
FOREACH_LOAD_MEM_OPCODE(V) \
FOREACH_MISC_MEM_OPCODE(V) \
FOREACH_ASMJS_COMPAT_OPCODE(V)
// All signatures.
#define FOREACH_SIGNATURE(V) \
V(i_ii, kAstI32, kAstI32, kAstI32) \
V(i_i, kAstI32, kAstI32) \
V(i_v, kAstI32) \
V(i_ff, kAstI32, kAstF32, kAstF32) \
V(i_f, kAstI32, kAstF32) \
V(i_dd, kAstI32, kAstF64, kAstF64) \
V(i_d, kAstI32, kAstF64) \
V(i_l, kAstI32, kAstI64) \
V(l_ll, kAstI64, kAstI64, kAstI64) \
V(i_ll, kAstI32, kAstI64, kAstI64) \
V(l_l, kAstI64, kAstI64) \
V(l_i, kAstI64, kAstI32) \
V(l_f, kAstI64, kAstF32) \
V(l_d, kAstI64, kAstF64) \
V(f_ff, kAstF32, kAstF32, kAstF32) \
V(f_f, kAstF32, kAstF32) \
V(f_d, kAstF32, kAstF64) \
V(f_i, kAstF32, kAstI32) \
V(f_l, kAstF32, kAstI64) \
V(d_dd, kAstF64, kAstF64, kAstF64) \
V(d_d, kAstF64, kAstF64) \
V(d_f, kAstF64, kAstF32) \
V(d_i, kAstF64, kAstI32) \
V(d_l, kAstF64, kAstI64) \
V(d_id, kAstF64, kAstI32, kAstF64) \
V(f_if, kAstF32, kAstI32, kAstF32) \
V(l_il, kAstI64, kAstI32, kAstI64)
enum WasmOpcode {
// Declare expression opcodes.
#define DECLARE_NAMED_ENUM(name, opcode, sig) kExpr##name = opcode,
FOREACH_OPCODE(DECLARE_NAMED_ENUM)
#undef DECLARE_NAMED_ENUM
};
// The reason for a trap.
enum TrapReason {
kTrapUnreachable,
kTrapMemOutOfBounds,
kTrapDivByZero,
kTrapDivUnrepresentable,
kTrapRemByZero,
kTrapFloatUnrepresentable,
kTrapFuncInvalid,
kTrapFuncSigMismatch,
kTrapCount
};
// A collection of opcode-related static methods.
class WasmOpcodes {
public:
static bool IsSupported(WasmOpcode opcode);
static const char* OpcodeName(WasmOpcode opcode);
static FunctionSig* Signature(WasmOpcode opcode);
static byte MemSize(MachineType type) {
return 1 << ElementSizeLog2Of(type.representation());
}
static LocalTypeCode LocalTypeCodeFor(LocalType type) {
switch (type) {
case kAstI32:
return kLocalI32;
case kAstI64:
return kLocalI64;
case kAstF32:
return kLocalF32;
case kAstF64:
return kLocalF64;
case kAstStmt:
return kLocalVoid;
default:
UNREACHABLE();
return kLocalVoid;
}
}
static MemTypeCode MemTypeCodeFor(MachineType type) {
if (type == MachineType::Int8()) {
return kMemI8;
} else if (type == MachineType::Uint8()) {
return kMemU8;
} else if (type == MachineType::Int16()) {
return kMemI16;
} else if (type == MachineType::Uint16()) {
return kMemU16;
} else if (type == MachineType::Int32()) {
return kMemI32;
} else if (type == MachineType::Uint32()) {
return kMemU32;
} else if (type == MachineType::Int64()) {
return kMemI64;
} else if (type == MachineType::Uint64()) {
return kMemU64;
} else if (type == MachineType::Float32()) {
return kMemF32;
} else if (type == MachineType::Float64()) {
return kMemF64;
} else {
UNREACHABLE();
return kMemI32;
}
}
static MachineType MachineTypeFor(LocalType type) {
switch (type) {
case kAstI32:
return MachineType::Int32();
case kAstI64:
return MachineType::Int64();
case kAstF32:
return MachineType::Float32();
case kAstF64:
return MachineType::Float64();
case kAstStmt:
return MachineType::None();
default:
UNREACHABLE();
return MachineType::None();
}
}
static LocalType LocalTypeFor(MachineType type) {
if (type == MachineType::Int8()) {
return kAstI32;
} else if (type == MachineType::Uint8()) {
return kAstI32;
} else if (type == MachineType::Int16()) {
return kAstI32;
} else if (type == MachineType::Uint16()) {
return kAstI32;
} else if (type == MachineType::Int32()) {
return kAstI32;
} else if (type == MachineType::Uint32()) {
return kAstI32;
} else if (type == MachineType::Int64()) {
return kAstI64;
} else if (type == MachineType::Uint64()) {
return kAstI64;
} else if (type == MachineType::Float32()) {
return kAstF32;
} else if (type == MachineType::Float64()) {
return kAstF64;
} else {
UNREACHABLE();
return kAstI32;
}
}
static WasmOpcode LoadStoreOpcodeOf(MachineType type, bool store) {
if (type == MachineType::Int8()) {
return store ? kExprI32StoreMem8 : kExprI32LoadMem8S;
} else if (type == MachineType::Uint8()) {
return store ? kExprI32StoreMem8 : kExprI32LoadMem8U;
} else if (type == MachineType::Int16()) {
return store ? kExprI32StoreMem16 : kExprI32LoadMem16S;
} else if (type == MachineType::Uint16()) {
return store ? kExprI32StoreMem16 : kExprI32LoadMem16U;
} else if (type == MachineType::Int32()) {
return store ? kExprI32StoreMem : kExprI32LoadMem;
} else if (type == MachineType::Uint32()) {
return store ? kExprI32StoreMem : kExprI32LoadMem;
} else if (type == MachineType::Int64()) {
return store ? kExprI64StoreMem : kExprI64LoadMem;
} else if (type == MachineType::Uint64()) {
return store ? kExprI64StoreMem : kExprI64LoadMem;
} else if (type == MachineType::Float32()) {
return store ? kExprF32StoreMem : kExprF32LoadMem;
} else if (type == MachineType::Float64()) {
return store ? kExprF64StoreMem : kExprF64LoadMem;
} else {
UNREACHABLE();
return kExprNop;
}
}
static char ShortNameOf(LocalType type) {
switch (type) {
case kAstI32:
return 'i';
case kAstI64:
return 'l';
case kAstF32:
return 'f';
case kAstF64:
return 'd';
case kAstStmt:
return 'v';
case kAstEnd:
return 'x';
default:
UNREACHABLE();
return '?';
}
}
static const char* TypeName(LocalType type) {
switch (type) {
case kAstI32:
return "i32";
case kAstI64:
return "i64";
case kAstF32:
return "f32";
case kAstF64:
return "f64";
case kAstStmt:
return "<stmt>";
case kAstEnd:
return "<end>";
default:
return "<unknown>";
}
}
static const char* TrapReasonName(TrapReason reason) {
switch (reason) {
case kTrapUnreachable:
return "unreachable";
case kTrapMemOutOfBounds:
return "memory access out of bounds";
case kTrapDivByZero:
return "divide by zero";
case kTrapDivUnrepresentable:
return "divide result unrepresentable";
case kTrapRemByZero:
return "remainder by zero";
case kTrapFloatUnrepresentable:
return "integer result unrepresentable";
case kTrapFuncInvalid:
return "invalid function";
case kTrapFuncSigMismatch:
return "function signature mismatch";
default:
return "<?>";
}
}
};
} // namespace wasm
} // namespace internal
} // namespace v8
#endif // V8_WASM_OPCODES_H_
|
{
"pile_set_name": "Github"
}
|
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
<html>
<head>
<meta http-equiv='Content-Type' content='text/html; charset=utf-8'>
<title>Diff Coverage</title>
<style>
.src-snippet { margin-top: 2em; }
.src-name { font-weight: bold; }
.snippets {
border-top: 1px solid #bdbdbd;
border-bottom: 1px solid #bdbdbd;
}
.css { color:red }
</style>
</head>
<body>
<h1>Diff Coverage</h1>
<p>Diff: master</p>
<ul>
<li><b>Total</b>: 12 lines</li>
<li><b>Missing</b>: 4 lines</li>
<li><b>Coverage</b>: 66%</li>
</ul>
<table border="1">
<tr>
<th>Source File</th>
<th>Diff Coverage (%)</th>
<th>Missing Lines</th>
</tr>
<tr>
<td>file1.py</td>
<td>66.7%</td>
<td>10-11</td>
</tr>
<tr>
<td>subdir/file2.py</td>
<td>66.7%</td>
<td>10-11</td>
</tr>
</table>
<div class="src-snippet">
<div class="src-name">file1.py</div>
<div class="snippets">
<div>Snippet with ስ 芒 unicode</div>
<div>Snippet with ስ 芒 unicode</div>
</div>
</div>
<div class="src-snippet">
<div class="src-name">subdir/file2.py</div>
<div class="snippets">
<div>Snippet with ስ 芒 unicode</div>
<div>Snippet with ስ 芒 unicode</div>
</div>
</div>
</body>
</html>
|
{
"pile_set_name": "Github"
}
|
package:
name: cubes
version: 1.1
source:
fn: cubes-1.1.tar.gz
url: https://pypi.python.org/packages/91/78/cefca0763d3042ddfa0cd463cb7464dad11b75aefdf9fca6c6bb0dce9416/cubes-1.1.tar.gz
md5: a7e222f168336306fa43503dadd301c6
build:
entry_points:
- slicer = cubes.slicer.commands:main
requirements:
build:
- python
- setuptools
- jsonschema
- python-dateutil
- expressions >=0.2.3
run:
- python
- click
- flask
- setuptools
- jsonschema
- python-dateutil
- expressions >=0.2.3
test:
commands:
- slicer --help
imports:
- cubes
about:
home: http://cubes.databrewery.org/
license: MIT
summary: A light-weight Python OLAP framework for data warehouses
description: Cubes is a light-weight Python framework and set of tools for
development of reporting and analytical applications,Online Analytical Processing (OLAP),
multidimensional analysis, and browsing of aggregated data.It is part of Data Brewery.
doc_url: http://cubes.readthedocs.io/en/latest/
doc_source_url: https://github.com/DataBrewery/cubes/blob/master/doc/index.rst
dev_url: https://github.com/DataBrewery/cubes
|
{
"pile_set_name": "Github"
}
|
/*
Copyright 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.
*/
// Code generated by client-gen. DO NOT EDIT.
// Package fake has the automatically generated clients.
package fake
|
{
"pile_set_name": "Github"
}
|
import { initModule } from '../../helpers/test-config';
import { test } from 'qunit';
export default function() {
initModule('render/namespaceURI.js');
if (Ractive.svg) {
const html = 'http://www.w3.org/1999/xhtml';
const svg = 'http://www.w3.org/2000/svg';
test('Top-level elements have html namespace by default', t => {
const ractive = new Ractive({
el: fixture,
template: `<p>html</p>`
});
t.equal(ractive.find('p').namespaceURI, html);
});
test('SVG elements have svg namespace', t => {
const ractive = new Ractive({
el: fixture,
template: `<svg><text>svg</text></svg>`
});
t.equal(ractive.find('svg').namespaceURI, svg);
t.equal(ractive.find('text').namespaceURI, svg);
});
test('Top-level elements inherit SVG namespaceURI where appropriate', t => {
const ractive = new Ractive({
el: document.createElementNS(svg, 'svg'),
template: '<text>svg</text>'
});
t.equal(ractive.find('text').namespaceURI, svg);
});
test('Triples inside SVG elements result in correct namespaceURI', t => {
const ractive = new Ractive({
el: document.createElementNS(svg, 'svg'),
template: '{{{code}}}',
data: {
code: '<text>works</text>'
}
});
const text = ractive.find('text');
t.ok(!!text);
t.equal(text.namespaceURI, svg);
});
test('Children of foreignObject elements default to html namespace (#713)', t => {
const ractive = new Ractive({
el: fixture,
template: '<svg><foreignObject><p>foo</p></foreignObject></svg>'
});
// We can't do `ractive.find( 'foreignObject' )` because of a longstanding browser bug
// (https://bugs.webkit.org/show_bug.cgi?id=83438)
t.equal(ractive.find('svg').firstChild.namespaceURI, svg);
t.equal(ractive.find('p').namespaceURI, html);
});
test('Top-level elements in components have the correct namespace (#953)', t => {
const ractive = new Ractive({
el: fixture,
template: '<svg><widget message="yup"/></svg>',
components: {
widget: Ractive.extend({
template: '<text>{{message}}</text>'
})
}
});
t.equal(ractive.find('text').namespaceURI, svg);
t.htmlEqual(fixture.innerHTML, '<svg><text>yup</text></svg>');
});
test('Custom namespaces are supported (#2038)', t => {
new Ractive({
el: fixture,
template: `
<svg xmlns='http://www.w3.org/2000/svg' xmlns:v='http://schemas.microsoft.com/visio/2003/SVGExtensions/' >
<v:documentProperties v:langID='2057' v:viewMarkup='false'></v:documentProperties>
</svg>`
});
const documentProperties = fixture.firstElementChild.firstElementChild;
t.equal(documentProperties.namespaceURI, 'http://www.w3.org/2000/svg');
});
test('Namespaced attributes are set correctly', t => {
const ractive = new Ractive({
template: '<svg><use xlink:href="#yup" /></svg>'
});
ractive.render(fixture);
t.equal(ractive.find('use').getAttributeNS('http://www.w3.org/1999/xlink', 'href'), '#yup');
});
}
}
|
{
"pile_set_name": "Github"
}
|
###########################################################
#
# cairo
#
###########################################################
#
# CAIRO_VERSION, CAIRO_SITE and CAIRO_SOURCE define
# the upstream location of the source code for the package.
# CAIRO_DIR is the directory which is created when the source
# archive is unpacked.
# CAIRO_UNZIP is the command used to unzip the source.
# It is usually "zcat" (for .gz) or "bzcat" (for .bz2)
#
CAIRO_SITE=http://cairographics.org/releases
CAIRO_VERSION=1.14.2
CAIRO_SOURCE=cairo-$(CAIRO_VERSION).tar.xz
CAIRO_DIR=cairo-$(CAIRO_VERSION)
CAIRO_UNZIP=xzcat
CAIRO_MAINTAINER=NSLU2 Linux <[email protected]>
CAIRO_DESCRIPTION=Cairo is a vector graphics library with cross-device output support.
CAIRO_SECTION=lib
CAIRO_PRIORITY=optional
CAIRO_DEPENDS=freetype, fontconfig, libpng, pixman, xrender, xext
#
# CAIRO_IPK_VERSION should be incremented when the ipk changes.
#
CAIRO_IPK_VERSION=2
#
# CAIRO_LOCALES defines which locales get installed
#
CAIRO_LOCALES=
#
# CAIRO_CONFFILES should be a list of user-editable files
#CAIRO_CONFFILES=$(TARGET_PREFIX)/etc/cairo.conf $(TARGET_PREFIX)/etc/init.d/SXXcairo
#
# CAIRO_PATCHES should list any patches, in the the order in
# which they should be applied to the source code.
#
#CAIRO_PATCHES=$(CAIRO_SOURCE_DIR)/configure.patch
#
# If the compilation of the package requires additional
# compilation or linking flags, then list them here.
#
CAIRO_CPPFLAGS=-I$(STAGING_INCLUDE_DIR)/freetype2
CAIRO_LDFLAGS=
#
# CAIRO_BUILD_DIR is the directory in which the build is done.
# CAIRO_SOURCE_DIR is the directory which holds all the
# patches and ipkg control files.
# CAIRO_IPK_DIR is the directory in which the ipk is built.
# CAIRO_IPK is the name of the resulting ipk files.
#
# You should not change any of these variables.
#
CAIRO_BUILD_DIR=$(BUILD_DIR)/cairo
CAIRO_HOST_BUILD_DIR=$(HOST_BUILD_DIR)/cairo
CAIRO_SOURCE_DIR=$(SOURCE_DIR)/cairo
CAIRO_IPK_DIR=$(BUILD_DIR)/cairo-$(CAIRO_VERSION)-ipk
CAIRO_IPK=$(BUILD_DIR)/cairo_$(CAIRO_VERSION)-$(CAIRO_IPK_VERSION)_$(TARGET_ARCH).ipk
#
# Automatically create a ipkg control file
#
$(CAIRO_IPK_DIR)/CONTROL/control:
@$(INSTALL) -d $(@D)
@rm -f $@
@echo "Package: cairo" >>$@
@echo "Architecture: $(TARGET_ARCH)" >>$@
@echo "Priority: $(CAIRO_PRIORITY)" >>$@
@echo "Section: $(CAIRO_SECTION)" >>$@
@echo "Version: $(CAIRO_VERSION)-$(CAIRO_IPK_VERSION)" >>$@
@echo "Maintainer: $(CAIRO_MAINTAINER)" >>$@
@echo "Source: $(CAIRO_SITE)/$(CAIRO_SOURCE)" >>$@
@echo "Description: $(CAIRO_DESCRIPTION)" >>$@
@echo "Depends: $(CAIRO_DEPENDS)" >>$@
#
# This is the dependency on the source code. If the source is missing,
# then it will be fetched from the site using wget.
#
$(DL_DIR)/$(CAIRO_SOURCE):
$(WGET) -P $(@D) $(CAIRO_SITE)/$(@F) || \
$(WGET) -P $(@D) $(SOURCES_NLO_SITE)/$(@F)
#
# The source code depends on it existing within the download directory.
# This target will be called by the top level Makefile to download the
# source code's archive (.tar.gz, .bz2, etc.)
#
cairo-source: $(DL_DIR)/$(CAIRO_SOURCE) $(CAIRO_PATCHES)
#
# This target unpacks the source code in the build directory.
# If the source archive is not .tar.gz or .tar.bz2, then you will need
# to change the commands here. Patches to the source code are also
# applied in this target as required.
#
# This target also configures the build within the build directory.
# Flags such as LDFLAGS and CPPFLAGS should be passed into configure
# and NOT $(MAKE) below. Passing it to configure causes configure to
# correctly BUILD the Makefile with the right paths, where passing it
# to Make causes it to override the default search paths of the compiler.
#
# If the compilation of the package requires other packages to be staged
# first, then do that first (e.g. "$(MAKE) <bar>-stage <baz>-stage").
#
$(CAIRO_BUILD_DIR)/.configured: $(DL_DIR)/$(CAIRO_SOURCE) $(CAIRO_PATCHES) make/cairo.mk
$(MAKE) freetype-stage fontconfig-stage libpng-stage pixman-stage xrender-stage xext-stage
rm -rf $(BUILD_DIR)/$(CAIRO_DIR) $(CAIRO_BUILD_DIR)
$(CAIRO_UNZIP) $(DL_DIR)/$(CAIRO_SOURCE) | tar -C $(BUILD_DIR) -xvf -
mv $(BUILD_DIR)/$(CAIRO_DIR) $(CAIRO_BUILD_DIR)
(cd $(CAIRO_BUILD_DIR); \
$(TARGET_CONFIGURE_OPTS) \
PATH="$(STAGING_DIR)/bin:$$PATH" \
CPPFLAGS="$(STAGING_CPPFLAGS) $(CAIRO_CPPFLAGS)" \
LDFLAGS="$(STAGING_LDFLAGS) $(CAIRO_LDFLAGS)" \
PKG_CONFIG_PATH="$(STAGING_LIB_DIR)/pkgconfig" \
PKG_CONFIG_LIBDIR="$(STAGING_LIB_DIR)/pkgconfig" \
./configure \
--build=$(GNU_HOST_NAME) \
--host=$(GNU_TARGET_NAME) \
--target=$(GNU_TARGET_NAME) \
--x-includes=$(STAGING_INCLUDE_DIR) \
--x-libraries=$(STAGING_LIB_DIR) \
--prefix=$(TARGET_PREFIX) \
--disable-static \
--enable-ft=yes \
--enable-fc=yes \
ac_cv_func_XRenderCreateLinearGradient=yes \
ac_cv_func_XRenderCreateRadialGradient=yes \
ac_cv_func_XRenderCreateConicalGradient=yes \
)
$(PATCH_LIBTOOL) $(CAIRO_BUILD_DIR)/libtool
touch $@
cairo-unpack: $(CAIRO_BUILD_DIR)/.configured
#
# This builds the actual binary. You should change the target to refer
# directly to the main binary which is built.
#
$(CAIRO_BUILD_DIR)/.built: $(CAIRO_BUILD_DIR)/.configured
rm -f $@
$(MAKE) -C $(CAIRO_BUILD_DIR)
touch $@
#
# You should change the dependency to refer directly to the main binary
# which is built.
#
cairo: $(CAIRO_BUILD_DIR)/.built
#
# If you are building a library, then you need to stage it too.
#
$(CAIRO_BUILD_DIR)/.staged: $(CAIRO_BUILD_DIR)/.built
rm -f $@
$(MAKE) -C $(@D) install-strip prefix=$(STAGING_PREFIX)
sed -i -e 's|^prefix=.*|prefix=$(STAGING_PREFIX)|' $(STAGING_LIB_DIR)/pkgconfig/cairo*.pc
rm -f $(STAGING_LIB_DIR)/libcairo*.la
touch $@
cairo-stage: $(CAIRO_BUILD_DIR)/.staged
$(CAIRO_HOST_BUILD_DIR)/.staged: host/.configured $(DL_DIR)/$(CAIRO_SOURCE) $(CAIRO_PATCHES) make/cairo.mk
$(MAKE) glib-host-stage freetype-host-stage
rm -rf $(HOST_BUILD_DIR)/$(CAIRO_DIR) $(@D)
$(CAIRO_UNZIP) $(DL_DIR)/$(CAIRO_SOURCE) | tar -C $(HOST_BUILD_DIR) -xvf -
mv $(HOST_BUILD_DIR)/$(CAIRO_DIR) $(@D)
(cd $(@D); \
CPPFLAGS="-I$(HOST_STAGING_INCLUDE_DIR) -I$(HOST_STAGING_INCLUDE_DIR)/freetype2" \
LDFLAGS="-L$(HOST_STAGING_LIB_DIR) -fPIC" \
./configure \
--prefix=$(HOST_STAGING_PREFIX) \
--disable-shared \
--enable-xlib=no \
--enable-xlib-xrender=no \
--enable-xcb=no \
--enable-xlib-xcb=no \
--enable-xcb-shm=no \
--enable-ft=yes \
--enable-fc=no \
)
$(MAKE) -C $(@D) install
rm -f $(HOST_STAGING_LIB_DIR)/libcairo.la
touch $@
cairo-host-stage: $(CAIRO_HOST_BUILD_DIR)/.staged
#
# This builds the IPK file.
#
# Binaries should be installed into $(CAIRO_IPK_DIR)$(TARGET_PREFIX)/sbin or $(CAIRO_IPK_DIR)$(TARGET_PREFIX)/bin
# (use the location in a well-known Linux distro as a guide for choosing sbin or bin).
# Libraries and include files should be installed into $(CAIRO_IPK_DIR)$(TARGET_PREFIX)/{lib,include}
# Configuration files should be installed in $(CAIRO_IPK_DIR)$(TARGET_PREFIX)/etc/cairo/...
# Documentation files should be installed in $(CAIRO_IPK_DIR)$(TARGET_PREFIX)/doc/cairo/...
# Daemon startup scripts should be installed in $(CAIRO_IPK_DIR)$(TARGET_PREFIX)/etc/init.d/S??cairo
#
# You may need to patch your application to make it use these locations.
#
$(CAIRO_IPK): $(CAIRO_BUILD_DIR)/.built
rm -rf $(CAIRO_IPK_DIR) $(BUILD_DIR)/cairo_*_$(TARGET_ARCH).ipk
$(MAKE) -C $(CAIRO_BUILD_DIR) DESTDIR=$(CAIRO_IPK_DIR) install-strip
rm -f $(CAIRO_IPK_DIR)$(TARGET_PREFIX)/lib/*.la
rm -rf $(CAIRO_IPK_DIR)$(TARGET_PREFIX)/share/gtk-doc
$(MAKE) $(CAIRO_IPK_DIR)/CONTROL/control
cd $(BUILD_DIR); $(IPKG_BUILD) $(CAIRO_IPK_DIR)
#
# This is called from the top level makefile to create the IPK file.
#
cairo-ipk: $(CAIRO_IPK)
#
# This is called from the top level makefile to clean all of the built files.
#
cairo-clean:
-$(MAKE) -C $(CAIRO_BUILD_DIR) clean
#
# This is called from the top level makefile to clean all dynamically created
# directories.
#
cairo-dirclean:
rm -rf $(BUILD_DIR)/$(CAIRO_DIR) $(CAIRO_BUILD_DIR) $(CAIRO_IPK_DIR) $(CAIRO_IPK)
|
{
"pile_set_name": "Github"
}
|
## This test shows that we include the tool name in error/warning messages.
# RUN: not llvm-objcopy %S/non-existent 2>&1 | FileCheck --check-prefix=ERR %s -DTOOL=objcopy
# RUN: not llvm-strip %S/non-existent 2>&1 | FileCheck --check-prefix=ERR %s -DTOOL=strip
# ERR: llvm-[[TOOL]]{{(\.exe)?}}: error: '{{.*}}': {{[Nn]}}o such file or directory
## Currently llvm-objcopy does not issue warnings, so it is not tested.
# RUN: yaml2obj %s -o %t
# RUN: llvm-strip %t %t 2>&1 | FileCheck --check-prefix=WARN %s
# WARN: llvm-strip{{(\.exe)?}}: warning: '{{.*}}' was already specified
--- !ELF
FileHeader:
Class: ELFCLASS64
Data: ELFDATA2LSB
Type: ET_DYN
Machine: EM_RISCV
|
{
"pile_set_name": "Github"
}
|
[BREAKPOINTS]
ForceImpTypeAny = 0
ShowInfoWin = 1
EnableFlashBP = 2
BPDuringExecution = 0
[CFI]
CFISize = 0x00
CFIAddr = 0x00
[CPU]
OverrideMemMap = 0
AllowSimulation = 1
ScriptFile=""
[FLASH]
CacheExcludeSize = 0x00
CacheExcludeAddr = 0x00
MinNumBytesFlashDL = 0
SkipProgOnCRCMatch = 1
VerifyDownload = 1
AllowCaching = 1
EnableFlashDL = 2
Override = 0
Device="UNSPECIFIED"
[GENERAL]
WorkRAMSize = 0x00
WorkRAMAddr = 0x00
RAMUsageLimit = 0x00
[SWO]
SWOLogFile=""
[MEM]
RdOverrideOrMask = 0x00
RdOverrideAndMask = 0xFFFFFFFF
RdOverrideAddr = 0xFFFFFFFF
WrOverrideOrMask = 0x00
WrOverrideAndMask = 0xFFFFFFFF
WrOverrideAddr = 0xFFFFFFFF
|
{
"pile_set_name": "Github"
}
|
/*
* Copyright (C) 2007 The Android Open Source Project
*
* 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 tests.api.org.xml.sax;
import junit.framework.TestCase;
import org.xml.sax.SAXException;
import org.xml.sax.SAXParseException;
public class SAXExceptionTest extends TestCase {
public static final String ERR = "Houston, we have a problem";
public void testSAXParseException() {
SAXException e = new SAXException();
assertNull(e.getMessage());
assertNull(e.getException());
}
public void testSAXException_String_Exception() {
Exception c = new Exception();
// Ordinary case
SAXException e = new SAXException(ERR, c);
assertEquals(ERR, e.getMessage());
assertEquals(c, e.getException());
// No message
e = new SAXException(null, c);
assertNull(e.getMessage());
assertEquals(c, e.getException());
// No cause
e = new SAXParseException(ERR, null);
assertEquals(ERR, e.getMessage());
assertNull(e.getException());
}
public void testSAXException_String() {
// Ordinary case
SAXException e = new SAXException(ERR);
assertEquals(ERR, e.getMessage());
assertNull(e.getException());
// No message
e = new SAXException((String)null);
assertNull(e.getMessage());
assertNull(e.getException());
}
public void testSAXException_Exception() {
Exception c = new Exception();
// Ordinary case
SAXException e = new SAXException(c);
assertNull(e.getMessage());
assertEquals(c, e.getException());
// No cause
e = new SAXException((Exception)null);
assertNull(e.getMessage());
assertNull(e.getException());
}
public void testToString() {
// Ordinary case
SAXException e = new SAXException(ERR);
String s = e.toString();
assertTrue(s.contains(ERR));
// No message
e = new SAXException();
s = e.toString();
assertFalse(s.contains(ERR));
}
}
|
{
"pile_set_name": "Github"
}
|
package cmconfig
import (
"context"
"fmt"
v1 "k8s.io/api/core/v1"
"k8s.io/apimachinery/pkg/api/errors"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
apimachinerytypes "k8s.io/apimachinery/pkg/types"
"k8s.io/client-go/kubernetes"
"k8s.io/client-go/tools/cache"
"k8s.io/client-go/tools/record"
"k8s.io/ingress-gce/pkg/utils"
"k8s.io/klog"
)
// ConfigMapConfigController is the ConfigMap based config controller.
// If cmConfigModeEnabled set to true, it will load the config from configmap: configMapNamespace/configMapName and restart ingress controller if the config has any ligeal changes.
// If cmConfigModeEnabled set to false, it will return the default values for the configs.
type ConfigMapConfigController struct {
configMapNamespace string
configMapName string
currentConfig *Config
currentConfigMapObject *v1.ConfigMap
kubeClient kubernetes.Interface
recorder record.EventRecorder
}
// NewConfigMapConfigController creates a new ConfigMapConfigController, it will load the config from the target configmap
func NewConfigMapConfigController(kubeClient kubernetes.Interface, recorder record.EventRecorder, configMapNamespace, configMapName string) *ConfigMapConfigController {
currentConfig := NewConfig()
cm, err := kubeClient.CoreV1().ConfigMaps(configMapNamespace).Get(context.TODO(), configMapName, metav1.GetOptions{})
if err != nil {
if errors.IsNotFound(err) {
klog.Infof("ConfigMapConfigController: Not found the configmap based config, using default config: %v", currentConfig)
} else {
klog.Warningf("ConfigMapConfigController failed to load config from api server, using the defualt config. Error: %v", err)
}
} else {
if err := currentConfig.LoadValue(cm.Data); err != nil {
if recorder != nil {
recorder.Event(cm, "Warning", "LoadValueError", err.Error())
}
klog.Warningf("LoadValue error: %s", err.Error())
}
klog.Infof("ConfigMapConfigController: loaded config from configmap, config %v", currentConfig)
}
c := &ConfigMapConfigController{
configMapNamespace: configMapNamespace,
configMapName: configMapName,
currentConfig: ¤tConfig,
kubeClient: kubeClient,
recorder: recorder,
currentConfigMapObject: cm,
}
return c
}
// GetConfig returns the internal Config
func (c *ConfigMapConfigController) GetConfig() Config {
return *c.currentConfig
}
func (c *ConfigMapConfigController) updateASMReady(status string) {
patchBytes, err := utils.StrategicMergePatchBytes(v1.ConfigMap{Data: map[string]string{}},
v1.ConfigMap{Data: map[string]string{asmReady: status}}, v1.ConfigMap{})
if err != nil {
c.RecordEvent("Warning", "FailedToUpdateASMStatus", fmt.Sprintf("Failed to update ASM Status, failed to create patch for ASM ConfigMap, error: %s", err))
return
}
cm, err := c.kubeClient.CoreV1().ConfigMaps(c.configMapNamespace).Patch(context.TODO(), c.configMapName, apimachinerytypes.MergePatchType, patchBytes, metav1.PatchOptions{}, "")
if err != nil {
if errors.IsNotFound(err) {
return
}
c.RecordEvent("Warning", "FailedToUpdateASMStatus", fmt.Sprintf("Failed to patch ASM ConfigMap, error: %s", err))
return
}
c.currentConfigMapObject = cm
}
// DisableASM sets the internal ASM mode to off and update the ASMReady to False.
func (c *ConfigMapConfigController) DisableASM() {
c.currentConfig.EnableASM = false
c.updateASMReady(falseValue)
}
// SetASMReadyTrue update the ASMReady to True.
func (c *ConfigMapConfigController) SetASMReadyTrue() {
c.updateASMReady(trueValue)
}
// SetASMReadyFalse update the ASMReady to False.
func (c *ConfigMapConfigController) SetASMReadyFalse() {
c.updateASMReady(falseValue)
}
// RecordEvent records a event to the ASMConfigmap
func (c *ConfigMapConfigController) RecordEvent(eventtype, reason, message string) bool {
if c.recorder == nil || c.currentConfigMapObject == nil {
return false
}
c.recorder.Event(c.currentConfigMapObject, eventtype, reason, message)
return true
}
// RegisterInformer regjister the configmap based config controller handler to the configapInformer which will watch the target
// configmap and send stop message to the stopCh if any valid change detected.
func (c *ConfigMapConfigController) RegisterInformer(configMapInformer cache.SharedIndexInformer, cancel func()) {
configMapInformer.AddEventHandler(cache.ResourceEventHandlerFuncs{
AddFunc: func(obj interface{}) {
c.processItem(obj, cancel)
},
DeleteFunc: func(obj interface{}) {
c.processItem(obj, cancel)
},
UpdateFunc: func(_, cur interface{}) {
c.processItem(cur, cancel)
},
})
}
func (c *ConfigMapConfigController) processItem(obj interface{}, cancel func()) {
configMap, ok := obj.(*v1.ConfigMap)
if !ok {
klog.Errorf("ConfigMapConfigController: failed to convert informer object to ConfigMap.")
}
if configMap.Namespace != c.configMapNamespace || configMap.Name != c.configMapName {
return
}
config := NewConfig()
cm, err := c.kubeClient.CoreV1().ConfigMaps(c.configMapNamespace).Get(context.TODO(), c.configMapName, metav1.GetOptions{})
if err != nil {
if errors.IsNotFound(err) {
klog.Infof("ConfigMapConfigController: Not found the configmap based config, using default config: %v", config)
} else {
klog.Warningf("ConfigMapConfigController failed to load config from api server, using the defualt config. Error: %v", err)
}
} else {
c.currentConfigMapObject = cm
if err := config.LoadValue(cm.Data); err != nil {
c.RecordEvent("Warning", "LoadValueError", err.Error())
}
}
if !config.Equals(c.currentConfig) {
c.RecordEvent("Normal", "ASMConfigMapTiggerRestart", "ConfigMapConfigController: Get a update on the ConfigMapConfig, Restarting Ingress controller")
cancel()
} else {
// If the config has no change, make sure the ASMReady is updated.
if config.EnableASM {
c.SetASMReadyTrue()
} else {
c.SetASMReadyFalse()
}
}
}
|
{
"pile_set_name": "Github"
}
|
// +build f411xe
package usb
// DO NOT EDIT THIS FILE. GENERATED BY xgen.
import (
"bits"
"mmio"
"unsafe"
"stm32/o/f411xe/mmap"
)
type USB_OTG_Host_Periph struct {
HCFG RHCFG
HFIR RHFIR
HFNUM RHFNUM
_ uint32
HPTXSTS RHPTXSTS
HAINT RHAINT
HAINTMSK RHAINTMSK
}
func (p *USB_OTG_Host_Periph) BaseAddr() uintptr {
return uintptr(unsafe.Pointer(p))
}
type HCFG uint32
func (b HCFG) Field(mask HCFG) int {
return bits.Field32(uint32(b), uint32(mask))
}
func (mask HCFG) J(v int) HCFG {
return HCFG(bits.MakeField32(v, uint32(mask)))
}
type RHCFG struct{ mmio.U32 }
func (r *RHCFG) Bits(mask HCFG) HCFG { return HCFG(r.U32.Bits(uint32(mask))) }
func (r *RHCFG) StoreBits(mask, b HCFG) { r.U32.StoreBits(uint32(mask), uint32(b)) }
func (r *RHCFG) SetBits(mask HCFG) { r.U32.SetBits(uint32(mask)) }
func (r *RHCFG) ClearBits(mask HCFG) { r.U32.ClearBits(uint32(mask)) }
func (r *RHCFG) Load() HCFG { return HCFG(r.U32.Load()) }
func (r *RHCFG) Store(b HCFG) { r.U32.Store(uint32(b)) }
func (r *RHCFG) AtomicStoreBits(mask, b HCFG) { r.U32.AtomicStoreBits(uint32(mask), uint32(b)) }
func (r *RHCFG) AtomicSetBits(mask HCFG) { r.U32.AtomicSetBits(uint32(mask)) }
func (r *RHCFG) AtomicClearBits(mask HCFG) { r.U32.AtomicClearBits(uint32(mask)) }
type RMHCFG struct{ mmio.UM32 }
func (rm RMHCFG) Load() HCFG { return HCFG(rm.UM32.Load()) }
func (rm RMHCFG) Store(b HCFG) { rm.UM32.Store(uint32(b)) }
func (p *USB_OTG_Host_Periph) FSLSPCS() RMHCFG {
return RMHCFG{mmio.UM32{&p.HCFG.U32, uint32(FSLSPCS)}}
}
func (p *USB_OTG_Host_Periph) FSLSS() RMHCFG {
return RMHCFG{mmio.UM32{&p.HCFG.U32, uint32(FSLSS)}}
}
type HFIR uint32
func (b HFIR) Field(mask HFIR) int {
return bits.Field32(uint32(b), uint32(mask))
}
func (mask HFIR) J(v int) HFIR {
return HFIR(bits.MakeField32(v, uint32(mask)))
}
type RHFIR struct{ mmio.U32 }
func (r *RHFIR) Bits(mask HFIR) HFIR { return HFIR(r.U32.Bits(uint32(mask))) }
func (r *RHFIR) StoreBits(mask, b HFIR) { r.U32.StoreBits(uint32(mask), uint32(b)) }
func (r *RHFIR) SetBits(mask HFIR) { r.U32.SetBits(uint32(mask)) }
func (r *RHFIR) ClearBits(mask HFIR) { r.U32.ClearBits(uint32(mask)) }
func (r *RHFIR) Load() HFIR { return HFIR(r.U32.Load()) }
func (r *RHFIR) Store(b HFIR) { r.U32.Store(uint32(b)) }
func (r *RHFIR) AtomicStoreBits(mask, b HFIR) { r.U32.AtomicStoreBits(uint32(mask), uint32(b)) }
func (r *RHFIR) AtomicSetBits(mask HFIR) { r.U32.AtomicSetBits(uint32(mask)) }
func (r *RHFIR) AtomicClearBits(mask HFIR) { r.U32.AtomicClearBits(uint32(mask)) }
type RMHFIR struct{ mmio.UM32 }
func (rm RMHFIR) Load() HFIR { return HFIR(rm.UM32.Load()) }
func (rm RMHFIR) Store(b HFIR) { rm.UM32.Store(uint32(b)) }
func (p *USB_OTG_Host_Periph) FRIVL() RMHFIR {
return RMHFIR{mmio.UM32{&p.HFIR.U32, uint32(FRIVL)}}
}
type HFNUM uint32
func (b HFNUM) Field(mask HFNUM) int {
return bits.Field32(uint32(b), uint32(mask))
}
func (mask HFNUM) J(v int) HFNUM {
return HFNUM(bits.MakeField32(v, uint32(mask)))
}
type RHFNUM struct{ mmio.U32 }
func (r *RHFNUM) Bits(mask HFNUM) HFNUM { return HFNUM(r.U32.Bits(uint32(mask))) }
func (r *RHFNUM) StoreBits(mask, b HFNUM) { r.U32.StoreBits(uint32(mask), uint32(b)) }
func (r *RHFNUM) SetBits(mask HFNUM) { r.U32.SetBits(uint32(mask)) }
func (r *RHFNUM) ClearBits(mask HFNUM) { r.U32.ClearBits(uint32(mask)) }
func (r *RHFNUM) Load() HFNUM { return HFNUM(r.U32.Load()) }
func (r *RHFNUM) Store(b HFNUM) { r.U32.Store(uint32(b)) }
func (r *RHFNUM) AtomicStoreBits(mask, b HFNUM) { r.U32.AtomicStoreBits(uint32(mask), uint32(b)) }
func (r *RHFNUM) AtomicSetBits(mask HFNUM) { r.U32.AtomicSetBits(uint32(mask)) }
func (r *RHFNUM) AtomicClearBits(mask HFNUM) { r.U32.AtomicClearBits(uint32(mask)) }
type RMHFNUM struct{ mmio.UM32 }
func (rm RMHFNUM) Load() HFNUM { return HFNUM(rm.UM32.Load()) }
func (rm RMHFNUM) Store(b HFNUM) { rm.UM32.Store(uint32(b)) }
func (p *USB_OTG_Host_Periph) FRNUM() RMHFNUM {
return RMHFNUM{mmio.UM32{&p.HFNUM.U32, uint32(FRNUM)}}
}
func (p *USB_OTG_Host_Periph) FTREM() RMHFNUM {
return RMHFNUM{mmio.UM32{&p.HFNUM.U32, uint32(FTREM)}}
}
type HPTXSTS uint32
func (b HPTXSTS) Field(mask HPTXSTS) int {
return bits.Field32(uint32(b), uint32(mask))
}
func (mask HPTXSTS) J(v int) HPTXSTS {
return HPTXSTS(bits.MakeField32(v, uint32(mask)))
}
type RHPTXSTS struct{ mmio.U32 }
func (r *RHPTXSTS) Bits(mask HPTXSTS) HPTXSTS { return HPTXSTS(r.U32.Bits(uint32(mask))) }
func (r *RHPTXSTS) StoreBits(mask, b HPTXSTS) { r.U32.StoreBits(uint32(mask), uint32(b)) }
func (r *RHPTXSTS) SetBits(mask HPTXSTS) { r.U32.SetBits(uint32(mask)) }
func (r *RHPTXSTS) ClearBits(mask HPTXSTS) { r.U32.ClearBits(uint32(mask)) }
func (r *RHPTXSTS) Load() HPTXSTS { return HPTXSTS(r.U32.Load()) }
func (r *RHPTXSTS) Store(b HPTXSTS) { r.U32.Store(uint32(b)) }
func (r *RHPTXSTS) AtomicStoreBits(mask, b HPTXSTS) { r.U32.AtomicStoreBits(uint32(mask), uint32(b)) }
func (r *RHPTXSTS) AtomicSetBits(mask HPTXSTS) { r.U32.AtomicSetBits(uint32(mask)) }
func (r *RHPTXSTS) AtomicClearBits(mask HPTXSTS) { r.U32.AtomicClearBits(uint32(mask)) }
type RMHPTXSTS struct{ mmio.UM32 }
func (rm RMHPTXSTS) Load() HPTXSTS { return HPTXSTS(rm.UM32.Load()) }
func (rm RMHPTXSTS) Store(b HPTXSTS) { rm.UM32.Store(uint32(b)) }
func (p *USB_OTG_Host_Periph) PTXFSAVL() RMHPTXSTS {
return RMHPTXSTS{mmio.UM32{&p.HPTXSTS.U32, uint32(PTXFSAVL)}}
}
func (p *USB_OTG_Host_Periph) PTXQSAV() RMHPTXSTS {
return RMHPTXSTS{mmio.UM32{&p.HPTXSTS.U32, uint32(PTXQSAV)}}
}
func (p *USB_OTG_Host_Periph) PTXQTOP() RMHPTXSTS {
return RMHPTXSTS{mmio.UM32{&p.HPTXSTS.U32, uint32(PTXQTOP)}}
}
type HAINT uint32
func (b HAINT) Field(mask HAINT) int {
return bits.Field32(uint32(b), uint32(mask))
}
func (mask HAINT) J(v int) HAINT {
return HAINT(bits.MakeField32(v, uint32(mask)))
}
type RHAINT struct{ mmio.U32 }
func (r *RHAINT) Bits(mask HAINT) HAINT { return HAINT(r.U32.Bits(uint32(mask))) }
func (r *RHAINT) StoreBits(mask, b HAINT) { r.U32.StoreBits(uint32(mask), uint32(b)) }
func (r *RHAINT) SetBits(mask HAINT) { r.U32.SetBits(uint32(mask)) }
func (r *RHAINT) ClearBits(mask HAINT) { r.U32.ClearBits(uint32(mask)) }
func (r *RHAINT) Load() HAINT { return HAINT(r.U32.Load()) }
func (r *RHAINT) Store(b HAINT) { r.U32.Store(uint32(b)) }
func (r *RHAINT) AtomicStoreBits(mask, b HAINT) { r.U32.AtomicStoreBits(uint32(mask), uint32(b)) }
func (r *RHAINT) AtomicSetBits(mask HAINT) { r.U32.AtomicSetBits(uint32(mask)) }
func (r *RHAINT) AtomicClearBits(mask HAINT) { r.U32.AtomicClearBits(uint32(mask)) }
type RMHAINT struct{ mmio.UM32 }
func (rm RMHAINT) Load() HAINT { return HAINT(rm.UM32.Load()) }
func (rm RMHAINT) Store(b HAINT) { rm.UM32.Store(uint32(b)) }
type HAINTMSK uint32
func (b HAINTMSK) Field(mask HAINTMSK) int {
return bits.Field32(uint32(b), uint32(mask))
}
func (mask HAINTMSK) J(v int) HAINTMSK {
return HAINTMSK(bits.MakeField32(v, uint32(mask)))
}
type RHAINTMSK struct{ mmio.U32 }
func (r *RHAINTMSK) Bits(mask HAINTMSK) HAINTMSK { return HAINTMSK(r.U32.Bits(uint32(mask))) }
func (r *RHAINTMSK) StoreBits(mask, b HAINTMSK) { r.U32.StoreBits(uint32(mask), uint32(b)) }
func (r *RHAINTMSK) SetBits(mask HAINTMSK) { r.U32.SetBits(uint32(mask)) }
func (r *RHAINTMSK) ClearBits(mask HAINTMSK) { r.U32.ClearBits(uint32(mask)) }
func (r *RHAINTMSK) Load() HAINTMSK { return HAINTMSK(r.U32.Load()) }
func (r *RHAINTMSK) Store(b HAINTMSK) { r.U32.Store(uint32(b)) }
func (r *RHAINTMSK) AtomicStoreBits(mask, b HAINTMSK) { r.U32.AtomicStoreBits(uint32(mask), uint32(b)) }
func (r *RHAINTMSK) AtomicSetBits(mask HAINTMSK) { r.U32.AtomicSetBits(uint32(mask)) }
func (r *RHAINTMSK) AtomicClearBits(mask HAINTMSK) { r.U32.AtomicClearBits(uint32(mask)) }
type RMHAINTMSK struct{ mmio.UM32 }
func (rm RMHAINTMSK) Load() HAINTMSK { return HAINTMSK(rm.UM32.Load()) }
func (rm RMHAINTMSK) Store(b HAINTMSK) { rm.UM32.Store(uint32(b)) }
func (p *USB_OTG_Host_Periph) HAINTM() RMHAINTMSK {
return RMHAINTMSK{mmio.UM32{&p.HAINTMSK.U32, uint32(HAINTM)}}
}
|
{
"pile_set_name": "Github"
}
|
#include "Precompile.h"
#include "CheckBoxWidget.h"
#include <wx/checkbox.h>
#include <wx/panel.h>
HELIUM_DEFINE_CLASS( Helium::Editor::CheckBoxWidget );
using namespace Helium;
using namespace Helium::Editor;
CheckBoxWindow::CheckBoxWindow( wxWindow* parent, CheckBoxWidget* checkBoxWidget )
: wxCheckBox( parent, wxID_ANY, wxEmptyString, wxDefaultPosition, wxDefaultSize, wxCHK_3STATE )
, m_CheckBoxWidget( checkBoxWidget )
, m_Override( false )
{
Connect( wxID_ANY, wxEVT_COMMAND_CHECKBOX_CLICKED, wxCommandEventHandler( CheckBoxWindow::OnChecked ) );
}
void CheckBoxWindow::OnChecked( wxCommandEvent& )
{
if ( !m_Override )
{
m_CheckBoxWidget->GetControl()->Write();
}
}
CheckBoxWidget::CheckBoxWidget( Inspect::CheckBox* checkBox )
: m_CheckBoxControl( checkBox )
, m_CheckBoxWindow( NULL )
{
SetControl( checkBox );
}
void CheckBoxWidget::CreateWindow( wxWindow* parent )
{
HELIUM_ASSERT( !m_CheckBoxWindow );
// allocate window and connect common listeners
SetWindow( m_CheckBoxWindow = new CheckBoxWindow( parent, this ) );
// init layout metrics
//wxSize size( m_Control->GetCanvas()->GetDefaultSize( SingleAxes::X ), m_Control->GetCanvas()->GetDefaultSize( SingleAxes::Y ) );
//m_CheckBoxWindow->SetSize( size );
//m_CheckBoxWindow->SetMinSize( size );
// add listeners
m_CheckBoxControl->a_Highlight.Changed().AddMethod( this, &CheckBoxWidget::HighlightChanged );
// update state of attributes that are not refreshed during Read()
m_CheckBoxControl->a_Highlight.RaiseChanged();
}
void CheckBoxWidget::DestroyWindow()
{
HELIUM_ASSERT( m_CheckBoxWindow );
SetWindow( NULL );
// remove listeners
m_CheckBoxControl->a_Highlight.Changed().RemoveMethod( this, &CheckBoxWidget::HighlightChanged );
// destroy window
m_CheckBoxWindow->Destroy();
m_CheckBoxWindow = NULL;
}
void CheckBoxWidget::Read()
{
HELIUM_ASSERT( m_CheckBoxControl->IsBound() );
std::string text;
m_CheckBoxControl->ReadStringData( text );
m_CheckBoxWindow->SetOverride( true );
if ( text == Inspect::MULTI_VALUE_STRING || text == Inspect::UNDEF_VALUE_STRING )
{
m_CheckBoxWindow->SetUndetermined();
}
else
{
std::stringstream str ( text );
int value = 0;
str >> value;
m_CheckBoxWindow->SetValue( value == 1 ? true : false );
}
m_CheckBoxWindow->SetOverride( false );
}
bool CheckBoxWidget::Write()
{
HELIUM_ASSERT( m_CheckBoxControl->IsBound() );
std::string text = m_CheckBoxWindow->GetValue() ? "1" : "0";
m_CheckBoxWindow->SetOverride( true );
bool result = m_CheckBoxControl->WriteStringData( text );
m_CheckBoxWindow->SetOverride( false );
return result;
}
void CheckBoxWidget::IsReadOnlyChanged( const Attribute<bool>::ChangeArgs& args )
{
if ( args.m_NewValue )
{
m_CheckBoxWindow->Enable();
}
else
{
m_CheckBoxWindow->Disable();
}
}
void CheckBoxWidget::HighlightChanged( const Attribute< bool >::ChangeArgs& args )
{
if ( args.m_NewValue )
{
m_CheckBoxWindow->SetForegroundColour(wxSystemSettings::GetColour(wxSYS_COLOUR_WINDOWTEXT));
m_CheckBoxWindow->SetBackgroundColour(wxSystemSettings::GetColour(wxSYS_COLOUR_BTNSHADOW));
}
else
{
m_CheckBoxWindow->SetForegroundColour(wxSystemSettings::GetColour(wxSYS_COLOUR_WINDOWTEXT));
m_CheckBoxWindow->SetBackgroundColour(wxSystemSettings::GetColour(wxSYS_COLOUR_BTNFACE));
}
}
|
{
"pile_set_name": "Github"
}
|
# linear_congruential_engine
* random[meta header]
* std[meta namespace]
* class template[meta id-type]
* [mathjax enable]
* cpp11[meta cpp]
```cpp
namespace std {
template <class UIntType, UIntType a, UIntType c, UIntType m>
class linear_congruential_engine;
using minstd_rand0 = …;
using minstd_rand = …;
}
```
* minstd_rand0[link minstd_rand0.md]
* minstd_rand[link minstd_rand.md]
## 概要
`linear_congruential_engine`クラスは、線形合同法による擬似乱数生成エンジンである。
前の擬似乱数と定数a、c、mを保持し、以下の漸化式により次の擬似乱数を生成する。
$$x_{n+1}= (a \times x_n + c) \bmod m$$
テンプレートパラメータの意味は以下の通り:
* `a`: 乗数。`m` が非 0 の場合 `a < m` でなければならない。
* `c`: 増分。`m` が非 0 の場合 `c < m` でなければならない。
* `m`: 法。0 の場合 [`std::numeric_limits`](/reference/limits/numeric_limits.md)`<result_type>::`[`max()`](/reference/limits/numeric_limits/max.md)。
線形合同法は、以下の特徴を持つ:
* 省メモリで高速
* 周期が短い(2<sup>31</sup>-1)
省メモリで高速という点から、多くの言語で、標準の乱数生成法として使用されている。
C言語から引き継いだ標準ライブラリ関数[`std::rand()`](/reference/cstdlib/rand.md.nolink)の乱数生成法は実装定義だが、多くの実装で線形合同法が使用されている。
しかし、メモリ使用量がそれほど問題にならないのであれば、メルセンヌ・ツイスター([`mt19937`](mt19937.md))の使用を検討した方がいいだろう。
標準にはないが、メモリ使用量が少なく、高速で、周期も長い(メルセンヌ・ツイスターほどではない)、xorshiftという乱数生成法も存在する。
## メンバ関数
### 構築・シード
| 名前 | 説明 | 対応バージョン |
|-------------------------------------------------------------------------------|------------------|-------|
| [`(constructor)`](linear_congruential_engine/op_constructor.md) | コンストラクタ | C++11 |
| `~linear_congruential_engine() = default;` | デストラクタ | C++11 |
| [`seed`](linear_congruential_engine/seed.md) | シードを設定する | C++11 |
### 生成
| 名前 | 説明 | 対応バージョン |
|---------------------------------------------------------|--------------------|-------|
| [`operator()`](linear_congruential_engine/op_call.md) | 擬似乱数を生成する | C++11 |
| [`discard`](linear_congruential_engine/discard.md) | 指定した回数だけ擬似乱数を生成し、内部状態を進める | C++11 |
## 静的メンバ関数
### エンジンの特性
| 名前 | 説明 | 対応バージョン |
|----------------------------------------------|--------------------------------|-------|
| [`min`](linear_congruential_engine/min.md) | 生成し得る値の最小値を取得する | C++11 |
| [`max`](linear_congruential_engine/max.md) | 生成し得る値の最大値を取得する | C++11 |
## メンバ型
| 型 | 説明 | 対応バージョン |
|---------------|-------------------|-------|
| `result_type` | 擬似乱数生成結果の符号なし整数型 `UIntType`。 | C++11 |
## メンバ定数
| 定数 | 説明 | 対応バージョン |
|---------------|-------------------|---------|
| `static constexpr result_type multiplier` | 乗数a。テンプレートパラメータ`a`。 | C++11 |
| `static constexpr result_type increment` | 増分c。状態シーケンスの要素数。テンプレートパラメータ`c`。 | C++11 |
| `static constexpr result_type modulus` | 法m。テンプレートパラメータ`m`。 | C++11 |
| `static constexpr result_type default_seed` | デフォルトのシード値。`1u` | C++11 |
## 非メンバ関数
| 名前 | 説明 | 対応バージョン |
|--------------------------------------------------------------|----------------------|-------|
| [`operator==`](linear_congruential_engine/op_equal.md) | 等値比較 | C++11 |
| [`operator!=`](linear_congruential_engine/op_not_equal.md) | 非等値比較 | C++11 |
| [`operator<<`](linear_congruential_engine/op_ostream.md) | ストリームへの出力 | C++11 |
| [`operator>>`](linear_congruential_engine/op_istream.md) | ストリームからの入力 | C++11 |
## 例
```cpp example
#include <iostream>
#include <random>
int main()
{
std::random_device seed_gen;
// linear_congruential_engineのパラメータ設定済み別名であるminstd_randを使用する。
// ランダムなシードを使用して初期化
std::minstd_rand engine(seed_gen());
for (int i = 0; i < 10; ++i) {
// 乱数を生成
std::uint32_t result = engine();
std::cout << result << std::endl;
}
}
```
* std::minstd_rand[color ff0000]
* std::uint32_t[link /reference/cstdint/uint32_t.md]
* engine()[link linear_congruential_engine/op_call.md]
### 出力
```
822915164
932862885
1787211539
1775131785
641394788
496072749
1485002929
1719732546
81869534
554365234
```
## バージョン
### 言語
- C++11
### 処理系
- [Clang](/implementation.md#clang):
- [GCC](/implementation.md#gcc): 4.7.2
- [ICC](/implementation.md#icc):
- [Visual C++](/implementation.md#visual_cpp):
|
{
"pile_set_name": "Github"
}
|
+prefix-classes($prefix)
.checkbox-container
border-bottom: 1px solid $lightcolor
font-family $fontfamily
font-size $cellfontsize
height $rowheight
overflow hidden
padding 0 10px
position relative
text-overflow ellipsis
width 10px
|
{
"pile_set_name": "Github"
}
|
#!/usr/bin/env bash
set -e
stack build
stack exec ghc -- -e ":q" --interactive async.hs
stack exec ghc -- -e ":q" --interactive par.hs
stack exec ghc -- -e ":q" --interactive spark.hs
stack exec ghc -- -e ":q" --interactive sparks.hs
stack exec ghc -- -e ":q" --interactive stm.hs
stack exec ghc -- -e ":q" --interactive strategies.hs
stack exec ghc -- -e ":q" --interactive strategies_param.hs
|
{
"pile_set_name": "Github"
}
|
/* Code automatically generated by Vult https://github.com/modlfo/vult */
#include "saw_ptr1.h"
void Util__ctx_type_3_init(Util__ctx_type_3 &_output_){
Util__ctx_type_3 _ctx;
_ctx.y1 = 0.0f;
_ctx.x1 = 0.0f;
_output_ = _ctx;
return ;
}
float Util_dcblock(Util__ctx_type_3 &_ctx, float x0){
float y0;
y0 = (x0 + (- _ctx.x1) + (0.995f * _ctx.y1));
_ctx.x1 = x0;
_ctx.y1 = y0;
return y0;
}
void Saw_ptr1__ctx_type_0_init(Saw_ptr1__ctx_type_0 &_output_){
Saw_ptr1__ctx_type_0 _ctx;
_ctx.rate = 0.0f;
_ctx.phase = 0.0f;
Util__ctx_type_1_init(_ctx._inst13b);
Saw_ptr1_default(_ctx);
_output_ = _ctx;
return ;
}
float Saw_ptr1_process(Saw_ptr1__ctx_type_0 &_ctx, float cv){
if(Util_change(_ctx._inst13b,cv)){
_ctx.rate = Util_cvToRate(cv);
}
float out;
float s1;
s1 = _ctx.rate;
float dc;
dc = -1.f;
_ctx.phase = (_ctx.phase + _ctx.rate);
if(_ctx.phase > 1.f){
_ctx.phase = (-1.f + _ctx.phase);
}
if(_ctx.phase < s1){
float d;
d = (_ctx.phase / _ctx.rate);
out = (2.f + dc + (-2.f * d));
}
else
{
out = ((- dc) + (2.f * _ctx.phase));
}
return out;
}
|
{
"pile_set_name": "Github"
}
|
// cmd/9l/noop.c, cmd/9l/pass.c, cmd/9l/span.c from Vita Nuova.
//
// Copyright © 1994-1999 Lucent Technologies Inc. All rights reserved.
// Portions Copyright © 1995-1997 C H Forsyth ([email protected])
// Portions Copyright © 1997-1999 Vita Nuova Limited
// Portions Copyright © 2000-2008 Vita Nuova Holdings Limited (www.vitanuova.com)
// Portions Copyright © 2004,2006 Bruce Ellis
// Portions Copyright © 2005-2007 C H Forsyth ([email protected])
// Revisions Copyright © 2000-2008 Lucent Technologies Inc. and others
// Portions Copyright © 2009 The Go Authors. All rights reserved.
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
package ppc64
import (
"cmd/internal/obj"
"cmd/internal/sys"
"fmt"
"math"
)
func progedit(ctxt *obj.Link, p *obj.Prog) {
p.From.Class = 0
p.To.Class = 0
// Rewrite BR/BL to symbol as TYPE_BRANCH.
switch p.As {
case ABR,
ABL,
obj.ARET,
obj.ADUFFZERO,
obj.ADUFFCOPY:
if p.To.Sym != nil {
p.To.Type = obj.TYPE_BRANCH
}
}
// Rewrite float constants to values stored in memory.
switch p.As {
case AFMOVS:
if p.From.Type == obj.TYPE_FCONST {
f32 := float32(p.From.Val.(float64))
i32 := math.Float32bits(f32)
literal := fmt.Sprintf("$f32.%08x", i32)
s := obj.Linklookup(ctxt, literal, 0)
s.Size = 4
p.From.Type = obj.TYPE_MEM
p.From.Sym = s
p.From.Sym.Local = true
p.From.Name = obj.NAME_EXTERN
p.From.Offset = 0
}
case AFMOVD:
if p.From.Type == obj.TYPE_FCONST {
i64 := math.Float64bits(p.From.Val.(float64))
literal := fmt.Sprintf("$f64.%016x", i64)
s := obj.Linklookup(ctxt, literal, 0)
s.Size = 8
p.From.Type = obj.TYPE_MEM
p.From.Sym = s
p.From.Sym.Local = true
p.From.Name = obj.NAME_EXTERN
p.From.Offset = 0
}
// Put >32-bit constants in memory and load them
case AMOVD:
if p.From.Type == obj.TYPE_CONST && p.From.Name == obj.NAME_NONE && p.From.Reg == 0 && int64(int32(p.From.Offset)) != p.From.Offset {
literal := fmt.Sprintf("$i64.%016x", uint64(p.From.Offset))
s := obj.Linklookup(ctxt, literal, 0)
s.Size = 8
p.From.Type = obj.TYPE_MEM
p.From.Sym = s
p.From.Sym.Local = true
p.From.Name = obj.NAME_EXTERN
p.From.Offset = 0
}
}
// Rewrite SUB constants into ADD.
switch p.As {
case ASUBC:
if p.From.Type == obj.TYPE_CONST {
p.From.Offset = -p.From.Offset
p.As = AADDC
}
case ASUBCCC:
if p.From.Type == obj.TYPE_CONST {
p.From.Offset = -p.From.Offset
p.As = AADDCCC
}
case ASUB:
if p.From.Type == obj.TYPE_CONST {
p.From.Offset = -p.From.Offset
p.As = AADD
}
}
if ctxt.Flag_dynlink {
rewriteToUseGot(ctxt, p)
}
}
// Rewrite p, if necessary, to access global data via the global offset table.
func rewriteToUseGot(ctxt *obj.Link, p *obj.Prog) {
if p.As == obj.ADUFFCOPY || p.As == obj.ADUFFZERO {
// ADUFFxxx $offset
// becomes
// MOVD runtime.duffxxx@GOT, R12
// ADD $offset, R12
// MOVD R12, CTR
// BL (CTR)
var sym *obj.LSym
if p.As == obj.ADUFFZERO {
sym = obj.Linklookup(ctxt, "runtime.duffzero", 0)
} else {
sym = obj.Linklookup(ctxt, "runtime.duffcopy", 0)
}
offset := p.To.Offset
p.As = AMOVD
p.From.Type = obj.TYPE_MEM
p.From.Name = obj.NAME_GOTREF
p.From.Sym = sym
p.To.Type = obj.TYPE_REG
p.To.Reg = REG_R12
p.To.Name = obj.NAME_NONE
p.To.Offset = 0
p.To.Sym = nil
p1 := obj.Appendp(ctxt, p)
p1.As = AADD
p1.From.Type = obj.TYPE_CONST
p1.From.Offset = offset
p1.To.Type = obj.TYPE_REG
p1.To.Reg = REG_R12
p2 := obj.Appendp(ctxt, p1)
p2.As = AMOVD
p2.From.Type = obj.TYPE_REG
p2.From.Reg = REG_R12
p2.To.Type = obj.TYPE_REG
p2.To.Reg = REG_CTR
p3 := obj.Appendp(ctxt, p2)
p3.As = obj.ACALL
p3.From.Type = obj.TYPE_REG
p3.From.Reg = REG_R12
p3.To.Type = obj.TYPE_REG
p3.To.Reg = REG_CTR
}
// We only care about global data: NAME_EXTERN means a global
// symbol in the Go sense, and p.Sym.Local is true for a few
// internally defined symbols.
if p.From.Type == obj.TYPE_ADDR && p.From.Name == obj.NAME_EXTERN && !p.From.Sym.Local {
// MOVD $sym, Rx becomes MOVD sym@GOT, Rx
// MOVD $sym+<off>, Rx becomes MOVD sym@GOT, Rx; ADD <off>, Rx
if p.As != AMOVD {
ctxt.Diag("do not know how to handle TYPE_ADDR in %v with -dynlink", p)
}
if p.To.Type != obj.TYPE_REG {
ctxt.Diag("do not know how to handle LEAQ-type insn to non-register in %v with -dynlink", p)
}
p.From.Type = obj.TYPE_MEM
p.From.Name = obj.NAME_GOTREF
if p.From.Offset != 0 {
q := obj.Appendp(ctxt, p)
q.As = AADD
q.From.Type = obj.TYPE_CONST
q.From.Offset = p.From.Offset
q.To = p.To
p.From.Offset = 0
}
}
if p.From3 != nil && p.From3.Name == obj.NAME_EXTERN {
ctxt.Diag("don't know how to handle %v with -dynlink", p)
}
var source *obj.Addr
// MOVx sym, Ry becomes MOVD sym@GOT, REGTMP; MOVx (REGTMP), Ry
// MOVx Ry, sym becomes MOVD sym@GOT, REGTMP; MOVx Ry, (REGTMP)
// An addition may be inserted between the two MOVs if there is an offset.
if p.From.Name == obj.NAME_EXTERN && !p.From.Sym.Local {
if p.To.Name == obj.NAME_EXTERN && !p.To.Sym.Local {
ctxt.Diag("cannot handle NAME_EXTERN on both sides in %v with -dynlink", p)
}
source = &p.From
} else if p.To.Name == obj.NAME_EXTERN && !p.To.Sym.Local {
source = &p.To
} else {
return
}
if p.As == obj.ATEXT || p.As == obj.AFUNCDATA || p.As == obj.ACALL || p.As == obj.ARET || p.As == obj.AJMP {
return
}
if source.Sym.Type == obj.STLSBSS {
return
}
if source.Type != obj.TYPE_MEM {
ctxt.Diag("don't know how to handle %v with -dynlink", p)
}
p1 := obj.Appendp(ctxt, p)
p2 := obj.Appendp(ctxt, p1)
p1.As = AMOVD
p1.From.Type = obj.TYPE_MEM
p1.From.Sym = source.Sym
p1.From.Name = obj.NAME_GOTREF
p1.To.Type = obj.TYPE_REG
p1.To.Reg = REGTMP
p2.As = p.As
p2.From = p.From
p2.To = p.To
if p.From.Name == obj.NAME_EXTERN {
p2.From.Reg = REGTMP
p2.From.Name = obj.NAME_NONE
p2.From.Sym = nil
} else if p.To.Name == obj.NAME_EXTERN {
p2.To.Reg = REGTMP
p2.To.Name = obj.NAME_NONE
p2.To.Sym = nil
} else {
return
}
obj.Nopout(p)
}
func preprocess(ctxt *obj.Link, cursym *obj.LSym) {
// TODO(minux): add morestack short-cuts with small fixed frame-size.
ctxt.Cursym = cursym
if cursym.Text == nil || cursym.Text.Link == nil {
return
}
p := cursym.Text
textstksiz := p.To.Offset
if textstksiz == -8 {
// Compatibility hack.
p.From3.Offset |= obj.NOFRAME
textstksiz = 0
}
if textstksiz%8 != 0 {
ctxt.Diag("frame size %d not a multiple of 8", textstksiz)
}
if p.From3.Offset&obj.NOFRAME != 0 {
if textstksiz != 0 {
ctxt.Diag("NOFRAME functions must have a frame size of 0, not %d", textstksiz)
}
}
cursym.Args = p.To.Val.(int32)
cursym.Locals = int32(textstksiz)
/*
* find leaf subroutines
* strip NOPs
* expand RET
* expand BECOME pseudo
*/
if ctxt.Debugvlog != 0 {
fmt.Fprintf(ctxt.Bso, "%5.2f noops\n", obj.Cputime())
}
ctxt.Bso.Flush()
var q *obj.Prog
var q1 *obj.Prog
for p := cursym.Text; p != nil; p = p.Link {
switch p.As {
/* too hard, just leave alone */
case obj.ATEXT:
q = p
p.Mark |= LABEL | LEAF | SYNC
if p.Link != nil {
p.Link.Mark |= LABEL
}
case ANOR:
q = p
if p.To.Type == obj.TYPE_REG {
if p.To.Reg == REGZERO {
p.Mark |= LABEL | SYNC
}
}
case ALWAR,
ALBAR,
ASTBCCC,
ASTWCCC,
AECIWX,
AECOWX,
AEIEIO,
AICBI,
AISYNC,
ATLBIE,
ATLBIEL,
ASLBIA,
ASLBIE,
ASLBMFEE,
ASLBMFEV,
ASLBMTE,
ADCBF,
ADCBI,
ADCBST,
ADCBT,
ADCBTST,
ADCBZ,
ASYNC,
ATLBSYNC,
APTESYNC,
ALWSYNC,
ATW,
AWORD,
ARFI,
ARFCI,
ARFID,
AHRFID:
q = p
p.Mark |= LABEL | SYNC
continue
case AMOVW, AMOVWZ, AMOVD:
q = p
if p.From.Reg >= REG_SPECIAL || p.To.Reg >= REG_SPECIAL {
p.Mark |= LABEL | SYNC
}
continue
case AFABS,
AFABSCC,
AFADD,
AFADDCC,
AFCTIW,
AFCTIWCC,
AFCTIWZ,
AFCTIWZCC,
AFDIV,
AFDIVCC,
AFMADD,
AFMADDCC,
AFMOVD,
AFMOVDU,
/* case AFMOVDS: */
AFMOVS,
AFMOVSU,
/* case AFMOVSD: */
AFMSUB,
AFMSUBCC,
AFMUL,
AFMULCC,
AFNABS,
AFNABSCC,
AFNEG,
AFNEGCC,
AFNMADD,
AFNMADDCC,
AFNMSUB,
AFNMSUBCC,
AFRSP,
AFRSPCC,
AFSUB,
AFSUBCC:
q = p
p.Mark |= FLOAT
continue
case ABL,
ABCL,
obj.ADUFFZERO,
obj.ADUFFCOPY:
cursym.Text.Mark &^= LEAF
fallthrough
case ABC,
ABEQ,
ABGE,
ABGT,
ABLE,
ABLT,
ABNE,
ABR,
ABVC,
ABVS:
p.Mark |= BRANCH
q = p
q1 = p.Pcond
if q1 != nil {
for q1.As == obj.ANOP {
q1 = q1.Link
p.Pcond = q1
}
if q1.Mark&LEAF == 0 {
q1.Mark |= LABEL
}
} else {
p.Mark |= LABEL
}
q1 = p.Link
if q1 != nil {
q1.Mark |= LABEL
}
continue
case AFCMPO, AFCMPU:
q = p
p.Mark |= FCMP | FLOAT
continue
case obj.ARET:
q = p
if p.Link != nil {
p.Link.Mark |= LABEL
}
continue
case obj.ANOP:
q1 = p.Link
q.Link = q1 /* q is non-nop */
q1.Mark |= p.Mark
continue
default:
q = p
continue
}
}
autosize := int32(0)
var aoffset int
var mov obj.As
var p1 *obj.Prog
var p2 *obj.Prog
for p := cursym.Text; p != nil; p = p.Link {
o := p.As
switch o {
case obj.ATEXT:
mov = AMOVD
aoffset = 0
autosize = int32(textstksiz)
if p.Mark&LEAF != 0 && autosize == 0 && p.From3.Offset&obj.NOFRAME == 0 {
// A leaf function with no locals has no frame.
p.From3.Offset |= obj.NOFRAME
}
if p.From3.Offset&obj.NOFRAME == 0 {
// If there is a stack frame at all, it includes
// space to save the LR.
autosize += int32(ctxt.FixedFrameSize())
}
p.To.Offset = int64(autosize)
q = p
if ctxt.Flag_shared && cursym.Name != "runtime.duffzero" && cursym.Name != "runtime.duffcopy" && cursym.Name != "runtime.stackBarrier" {
// When compiling Go into PIC, all functions must start
// with instructions to load the TOC pointer into r2:
//
// addis r2, r12, .TOC.-func@ha
// addi r2, r2, .TOC.-func@l+4
//
// We could probably skip this prologue in some situations
// but it's a bit subtle. However, it is both safe and
// necessary to leave the prologue off duffzero and
// duffcopy as we rely on being able to jump to a specific
// instruction offset for them, and stackBarrier is only
// ever called from an overwritten LR-save slot on the
// stack (when r12 will not be remotely the right thing)
// but fortunately does not access global data.
//
// These are AWORDS because there is no (afaict) way to
// generate the addis instruction except as part of the
// load of a large constant, and in that case there is no
// way to use r12 as the source.
q = obj.Appendp(ctxt, q)
q.As = AWORD
q.Lineno = p.Lineno
q.From.Type = obj.TYPE_CONST
q.From.Offset = 0x3c4c0000
q = obj.Appendp(ctxt, q)
q.As = AWORD
q.Lineno = p.Lineno
q.From.Type = obj.TYPE_CONST
q.From.Offset = 0x38420000
rel := obj.Addrel(ctxt.Cursym)
rel.Off = 0
rel.Siz = 8
rel.Sym = obj.Linklookup(ctxt, ".TOC.", 0)
rel.Type = obj.R_ADDRPOWER_PCREL
}
if cursym.Text.From3.Offset&obj.NOSPLIT == 0 {
q = stacksplit(ctxt, q, autosize) // emit split check
}
if autosize != 0 {
/* use MOVDU to adjust R1 when saving R31, if autosize is small */
if cursym.Text.Mark&LEAF == 0 && autosize >= -BIG && autosize <= BIG {
mov = AMOVDU
aoffset = int(-autosize)
} else {
q = obj.Appendp(ctxt, q)
q.As = AADD
q.Lineno = p.Lineno
q.From.Type = obj.TYPE_CONST
q.From.Offset = int64(-autosize)
q.To.Type = obj.TYPE_REG
q.To.Reg = REGSP
q.Spadj = +autosize
}
} else if cursym.Text.Mark&LEAF == 0 {
// A very few functions that do not return to their caller
// (e.g. gogo) are not identified as leaves but still have
// no frame.
cursym.Text.Mark |= LEAF
}
if cursym.Text.Mark&LEAF != 0 {
cursym.Leaf = true
break
}
q = obj.Appendp(ctxt, q)
q.As = AMOVD
q.Lineno = p.Lineno
q.From.Type = obj.TYPE_REG
q.From.Reg = REG_LR
q.To.Type = obj.TYPE_REG
q.To.Reg = REGTMP
q = obj.Appendp(ctxt, q)
q.As = mov
q.Lineno = p.Lineno
q.From.Type = obj.TYPE_REG
q.From.Reg = REGTMP
q.To.Type = obj.TYPE_MEM
q.To.Offset = int64(aoffset)
q.To.Reg = REGSP
if q.As == AMOVDU {
q.Spadj = int32(-aoffset)
}
if ctxt.Flag_shared {
q = obj.Appendp(ctxt, q)
q.As = AMOVD
q.Lineno = p.Lineno
q.From.Type = obj.TYPE_REG
q.From.Reg = REG_R2
q.To.Type = obj.TYPE_MEM
q.To.Reg = REGSP
q.To.Offset = 24
}
if cursym.Text.From3.Offset&obj.WRAPPER != 0 {
// if(g->panic != nil && g->panic->argp == FP) g->panic->argp = bottom-of-frame
//
// MOVD g_panic(g), R3
// CMP R0, R3
// BEQ end
// MOVD panic_argp(R3), R4
// ADD $(autosize+8), R1, R5
// CMP R4, R5
// BNE end
// ADD $8, R1, R6
// MOVD R6, panic_argp(R3)
// end:
// NOP
//
// The NOP is needed to give the jumps somewhere to land.
// It is a liblink NOP, not a ppc64 NOP: it encodes to 0 instruction bytes.
q = obj.Appendp(ctxt, q)
q.As = AMOVD
q.From.Type = obj.TYPE_MEM
q.From.Reg = REGG
q.From.Offset = 4 * int64(ctxt.Arch.PtrSize) // G.panic
q.To.Type = obj.TYPE_REG
q.To.Reg = REG_R3
q = obj.Appendp(ctxt, q)
q.As = ACMP
q.From.Type = obj.TYPE_REG
q.From.Reg = REG_R0
q.To.Type = obj.TYPE_REG
q.To.Reg = REG_R3
q = obj.Appendp(ctxt, q)
q.As = ABEQ
q.To.Type = obj.TYPE_BRANCH
p1 = q
q = obj.Appendp(ctxt, q)
q.As = AMOVD
q.From.Type = obj.TYPE_MEM
q.From.Reg = REG_R3
q.From.Offset = 0 // Panic.argp
q.To.Type = obj.TYPE_REG
q.To.Reg = REG_R4
q = obj.Appendp(ctxt, q)
q.As = AADD
q.From.Type = obj.TYPE_CONST
q.From.Offset = int64(autosize) + ctxt.FixedFrameSize()
q.Reg = REGSP
q.To.Type = obj.TYPE_REG
q.To.Reg = REG_R5
q = obj.Appendp(ctxt, q)
q.As = ACMP
q.From.Type = obj.TYPE_REG
q.From.Reg = REG_R4
q.To.Type = obj.TYPE_REG
q.To.Reg = REG_R5
q = obj.Appendp(ctxt, q)
q.As = ABNE
q.To.Type = obj.TYPE_BRANCH
p2 = q
q = obj.Appendp(ctxt, q)
q.As = AADD
q.From.Type = obj.TYPE_CONST
q.From.Offset = ctxt.FixedFrameSize()
q.Reg = REGSP
q.To.Type = obj.TYPE_REG
q.To.Reg = REG_R6
q = obj.Appendp(ctxt, q)
q.As = AMOVD
q.From.Type = obj.TYPE_REG
q.From.Reg = REG_R6
q.To.Type = obj.TYPE_MEM
q.To.Reg = REG_R3
q.To.Offset = 0 // Panic.argp
q = obj.Appendp(ctxt, q)
q.As = obj.ANOP
p1.Pcond = q
p2.Pcond = q
}
case obj.ARET:
if p.From.Type == obj.TYPE_CONST {
ctxt.Diag("using BECOME (%v) is not supported!", p)
break
}
retTarget := p.To.Sym
if cursym.Text.Mark&LEAF != 0 {
if autosize == 0 {
p.As = ABR
p.From = obj.Addr{}
if retTarget == nil {
p.To.Type = obj.TYPE_REG
p.To.Reg = REG_LR
} else {
p.To.Type = obj.TYPE_BRANCH
p.To.Sym = retTarget
}
p.Mark |= BRANCH
break
}
p.As = AADD
p.From.Type = obj.TYPE_CONST
p.From.Offset = int64(autosize)
p.To.Type = obj.TYPE_REG
p.To.Reg = REGSP
p.Spadj = -autosize
q = ctxt.NewProg()
q.As = ABR
q.Lineno = p.Lineno
q.To.Type = obj.TYPE_REG
q.To.Reg = REG_LR
q.Mark |= BRANCH
q.Spadj = +autosize
q.Link = p.Link
p.Link = q
break
}
p.As = AMOVD
p.From.Type = obj.TYPE_MEM
p.From.Offset = 0
p.From.Reg = REGSP
p.To.Type = obj.TYPE_REG
p.To.Reg = REGTMP
q = ctxt.NewProg()
q.As = AMOVD
q.Lineno = p.Lineno
q.From.Type = obj.TYPE_REG
q.From.Reg = REGTMP
q.To.Type = obj.TYPE_REG
q.To.Reg = REG_LR
q.Link = p.Link
p.Link = q
p = q
if false {
// Debug bad returns
q = ctxt.NewProg()
q.As = AMOVD
q.Lineno = p.Lineno
q.From.Type = obj.TYPE_MEM
q.From.Offset = 0
q.From.Reg = REGTMP
q.To.Type = obj.TYPE_REG
q.To.Reg = REGTMP
q.Link = p.Link
p.Link = q
p = q
}
if autosize != 0 {
q = ctxt.NewProg()
q.As = AADD
q.Lineno = p.Lineno
q.From.Type = obj.TYPE_CONST
q.From.Offset = int64(autosize)
q.To.Type = obj.TYPE_REG
q.To.Reg = REGSP
q.Spadj = -autosize
q.Link = p.Link
p.Link = q
}
q1 = ctxt.NewProg()
q1.As = ABR
q1.Lineno = p.Lineno
if retTarget == nil {
q1.To.Type = obj.TYPE_REG
q1.To.Reg = REG_LR
} else {
q1.To.Type = obj.TYPE_BRANCH
q1.To.Sym = retTarget
}
q1.Mark |= BRANCH
q1.Spadj = +autosize
q1.Link = q.Link
q.Link = q1
case AADD:
if p.To.Type == obj.TYPE_REG && p.To.Reg == REGSP && p.From.Type == obj.TYPE_CONST {
p.Spadj = int32(-p.From.Offset)
}
}
}
}
/*
// instruction scheduling
if(debug['Q'] == 0)
return;
curtext = nil;
q = nil; // p - 1
q1 = firstp; // top of block
o = 0; // count of instructions
for(p = firstp; p != nil; p = p1) {
p1 = p->link;
o++;
if(p->mark & NOSCHED){
if(q1 != p){
sched(q1, q);
}
for(; p != nil; p = p->link){
if(!(p->mark & NOSCHED))
break;
q = p;
}
p1 = p;
q1 = p;
o = 0;
continue;
}
if(p->mark & (LABEL|SYNC)) {
if(q1 != p)
sched(q1, q);
q1 = p;
o = 1;
}
if(p->mark & (BRANCH|SYNC)) {
sched(q1, p);
q1 = p1;
o = 0;
}
if(o >= NSCHED) {
sched(q1, p);
q1 = p1;
o = 0;
}
q = p;
}
*/
func stacksplit(ctxt *obj.Link, p *obj.Prog, framesize int32) *obj.Prog {
// MOVD g_stackguard(g), R3
p = obj.Appendp(ctxt, p)
p.As = AMOVD
p.From.Type = obj.TYPE_MEM
p.From.Reg = REGG
p.From.Offset = 2 * int64(ctxt.Arch.PtrSize) // G.stackguard0
if ctxt.Cursym.Cfunc {
p.From.Offset = 3 * int64(ctxt.Arch.PtrSize) // G.stackguard1
}
p.To.Type = obj.TYPE_REG
p.To.Reg = REG_R3
var q *obj.Prog
if framesize <= obj.StackSmall {
// small stack: SP < stackguard
// CMP stackguard, SP
p = obj.Appendp(ctxt, p)
p.As = ACMPU
p.From.Type = obj.TYPE_REG
p.From.Reg = REG_R3
p.To.Type = obj.TYPE_REG
p.To.Reg = REGSP
} else if framesize <= obj.StackBig {
// large stack: SP-framesize < stackguard-StackSmall
// ADD $-framesize, SP, R4
// CMP stackguard, R4
p = obj.Appendp(ctxt, p)
p.As = AADD
p.From.Type = obj.TYPE_CONST
p.From.Offset = int64(-framesize)
p.Reg = REGSP
p.To.Type = obj.TYPE_REG
p.To.Reg = REG_R4
p = obj.Appendp(ctxt, p)
p.As = ACMPU
p.From.Type = obj.TYPE_REG
p.From.Reg = REG_R3
p.To.Type = obj.TYPE_REG
p.To.Reg = REG_R4
} else {
// Such a large stack we need to protect against wraparound.
// If SP is close to zero:
// SP-stackguard+StackGuard <= framesize + (StackGuard-StackSmall)
// The +StackGuard on both sides is required to keep the left side positive:
// SP is allowed to be slightly below stackguard. See stack.h.
//
// Preemption sets stackguard to StackPreempt, a very large value.
// That breaks the math above, so we have to check for that explicitly.
// // stackguard is R3
// CMP R3, $StackPreempt
// BEQ label-of-call-to-morestack
// ADD $StackGuard, SP, R4
// SUB R3, R4
// MOVD $(framesize+(StackGuard-StackSmall)), R31
// CMPU R31, R4
p = obj.Appendp(ctxt, p)
p.As = ACMP
p.From.Type = obj.TYPE_REG
p.From.Reg = REG_R3
p.To.Type = obj.TYPE_CONST
p.To.Offset = obj.StackPreempt
p = obj.Appendp(ctxt, p)
q = p
p.As = ABEQ
p.To.Type = obj.TYPE_BRANCH
p = obj.Appendp(ctxt, p)
p.As = AADD
p.From.Type = obj.TYPE_CONST
p.From.Offset = obj.StackGuard
p.Reg = REGSP
p.To.Type = obj.TYPE_REG
p.To.Reg = REG_R4
p = obj.Appendp(ctxt, p)
p.As = ASUB
p.From.Type = obj.TYPE_REG
p.From.Reg = REG_R3
p.To.Type = obj.TYPE_REG
p.To.Reg = REG_R4
p = obj.Appendp(ctxt, p)
p.As = AMOVD
p.From.Type = obj.TYPE_CONST
p.From.Offset = int64(framesize) + obj.StackGuard - obj.StackSmall
p.To.Type = obj.TYPE_REG
p.To.Reg = REGTMP
p = obj.Appendp(ctxt, p)
p.As = ACMPU
p.From.Type = obj.TYPE_REG
p.From.Reg = REGTMP
p.To.Type = obj.TYPE_REG
p.To.Reg = REG_R4
}
// q1: BLT done
p = obj.Appendp(ctxt, p)
q1 := p
p.As = ABLT
p.To.Type = obj.TYPE_BRANCH
// MOVD LR, R5
p = obj.Appendp(ctxt, p)
p.As = AMOVD
p.From.Type = obj.TYPE_REG
p.From.Reg = REG_LR
p.To.Type = obj.TYPE_REG
p.To.Reg = REG_R5
if q != nil {
q.Pcond = p
}
var morestacksym *obj.LSym
if ctxt.Cursym.Cfunc {
morestacksym = obj.Linklookup(ctxt, "runtime.morestackc", 0)
} else if ctxt.Cursym.Text.From3.Offset&obj.NEEDCTXT == 0 {
morestacksym = obj.Linklookup(ctxt, "runtime.morestack_noctxt", 0)
} else {
morestacksym = obj.Linklookup(ctxt, "runtime.morestack", 0)
}
if ctxt.Flag_dynlink {
// Avoid calling morestack via a PLT when dynamically linking. The
// PLT stubs generated by the system linker on ppc64le when "std r2,
// 24(r1)" to save the TOC pointer in their callers stack
// frame. Unfortunately (and necessarily) morestack is called before
// the function that calls it sets up its frame and so the PLT ends
// up smashing the saved TOC pointer for its caller's caller.
//
// According to the ABI documentation there is a mechanism to avoid
// the TOC save that the PLT stub does (put a R_PPC64_TOCSAVE
// relocation on the nop after the call to morestack) but at the time
// of writing it is not supported at all by gold and my attempt to
// use it with ld.bfd caused an internal linker error. So this hack
// seems preferable.
// MOVD $runtime.morestack(SB), R12
p = obj.Appendp(ctxt, p)
p.As = AMOVD
p.From.Type = obj.TYPE_MEM
p.From.Sym = morestacksym
p.From.Name = obj.NAME_GOTREF
p.To.Type = obj.TYPE_REG
p.To.Reg = REG_R12
// MOVD R12, CTR
p = obj.Appendp(ctxt, p)
p.As = AMOVD
p.From.Type = obj.TYPE_REG
p.From.Reg = REG_R12
p.To.Type = obj.TYPE_REG
p.To.Reg = REG_CTR
// BL CTR
p = obj.Appendp(ctxt, p)
p.As = obj.ACALL
p.From.Type = obj.TYPE_REG
p.From.Reg = REG_R12
p.To.Type = obj.TYPE_REG
p.To.Reg = REG_CTR
} else {
// BL runtime.morestack(SB)
p = obj.Appendp(ctxt, p)
p.As = ABL
p.To.Type = obj.TYPE_BRANCH
p.To.Sym = morestacksym
}
// BR start
p = obj.Appendp(ctxt, p)
p.As = ABR
p.To.Type = obj.TYPE_BRANCH
p.Pcond = ctxt.Cursym.Text.Link
// placeholder for q1's jump target
p = obj.Appendp(ctxt, p)
p.As = obj.ANOP // zero-width place holder
q1.Pcond = p
return p
}
func follow(ctxt *obj.Link, s *obj.LSym) {
ctxt.Cursym = s
firstp := ctxt.NewProg()
lastp := firstp
xfol(ctxt, s.Text, &lastp)
lastp.Link = nil
s.Text = firstp.Link
}
func relinv(a obj.As) obj.As {
switch a {
case ABEQ:
return ABNE
case ABNE:
return ABEQ
case ABGE:
return ABLT
case ABLT:
return ABGE
case ABGT:
return ABLE
case ABLE:
return ABGT
case ABVC:
return ABVS
case ABVS:
return ABVC
}
return 0
}
func xfol(ctxt *obj.Link, p *obj.Prog, last **obj.Prog) {
var q *obj.Prog
var r *obj.Prog
var b obj.As
var i int
loop:
if p == nil {
return
}
a := p.As
if a == ABR {
q = p.Pcond
if (p.Mark&NOSCHED != 0) || q != nil && (q.Mark&NOSCHED != 0) {
p.Mark |= FOLL
(*last).Link = p
*last = p
p = p.Link
xfol(ctxt, p, last)
p = q
if p != nil && p.Mark&FOLL == 0 {
goto loop
}
return
}
if q != nil {
p.Mark |= FOLL
p = q
if p.Mark&FOLL == 0 {
goto loop
}
}
}
if p.Mark&FOLL != 0 {
i = 0
q = p
for ; i < 4; i, q = i+1, q.Link {
if q == *last || (q.Mark&NOSCHED != 0) {
break
}
b = 0 /* set */
a = q.As
if a == obj.ANOP {
i--
continue
}
if a == ABR || a == obj.ARET || a == ARFI || a == ARFCI || a == ARFID || a == AHRFID {
goto copy
}
if q.Pcond == nil || (q.Pcond.Mark&FOLL != 0) {
continue
}
b = relinv(a)
if b == 0 {
continue
}
copy:
for {
r = ctxt.NewProg()
*r = *p
if r.Mark&FOLL == 0 {
fmt.Printf("can't happen 1\n")
}
r.Mark |= FOLL
if p != q {
p = p.Link
(*last).Link = r
*last = r
continue
}
(*last).Link = r
*last = r
if a == ABR || a == obj.ARET || a == ARFI || a == ARFCI || a == ARFID || a == AHRFID {
return
}
r.As = b
r.Pcond = p.Link
r.Link = p.Pcond
if r.Link.Mark&FOLL == 0 {
xfol(ctxt, r.Link, last)
}
if r.Pcond.Mark&FOLL == 0 {
fmt.Printf("can't happen 2\n")
}
return
}
}
a = ABR
q = ctxt.NewProg()
q.As = a
q.Lineno = p.Lineno
q.To.Type = obj.TYPE_BRANCH
q.To.Offset = p.Pc
q.Pcond = p
p = q
}
p.Mark |= FOLL
(*last).Link = p
*last = p
if a == ABR || a == obj.ARET || a == ARFI || a == ARFCI || a == ARFID || a == AHRFID {
if p.Mark&NOSCHED != 0 {
p = p.Link
goto loop
}
return
}
if p.Pcond != nil {
if a != ABL && p.Link != nil {
xfol(ctxt, p.Link, last)
p = p.Pcond
if p == nil || (p.Mark&FOLL != 0) {
return
}
goto loop
}
}
p = p.Link
goto loop
}
var Linkppc64 = obj.LinkArch{
Arch: sys.ArchPPC64,
Preprocess: preprocess,
Assemble: span9,
Follow: follow,
Progedit: progedit,
}
var Linkppc64le = obj.LinkArch{
Arch: sys.ArchPPC64LE,
Preprocess: preprocess,
Assemble: span9,
Follow: follow,
Progedit: progedit,
}
|
{
"pile_set_name": "Github"
}
|
#
# SEEQ device configuration
#
config NET_VENDOR_SEEQ
bool "SEEQ devices"
default y
depends on HAS_IOMEM
---help---
If you have a network (Ethernet) card belonging to this class, say Y.
Note that the answer to this question doesn't directly affect the
kernel: saying N will just cause the configurator to skip all
the questions about SEEQ devices. If you say Y, you will be asked for
your specific card in the following questions.
if NET_VENDOR_SEEQ
config ARM_ETHER3
tristate "Acorn/ANT Ether3 support"
depends on ARM && ARCH_ACORN
---help---
If you have an Acorn system with one of these network cards, you
should say Y to this option if you wish to use it with Linux.
config SGISEEQ
tristate "SGI Seeq ethernet controller support"
depends on SGI_HAS_SEEQ
---help---
Say Y here if you have an Seeq based Ethernet network card. This is
used in many Silicon Graphics machines.
endif # NET_VENDOR_SEEQ
|
{
"pile_set_name": "Github"
}
|
/*
* Copyright (c) 2000, 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.
*/
/*
*
* (C) Copyright IBM Corp. 1999 All Rights Reserved.
* Copyright 1997 The Open Group Research Institute. All rights reserved.
*/
package sun.security.krb5;
import sun.security.krb5.internal.*;
import sun.security.util.*;
import java.net.*;
import java.util.Vector;
import java.util.Locale;
import java.io.IOException;
import java.math.BigInteger;
import java.util.Arrays;
import sun.security.krb5.internal.ccache.CCacheOutputStream;
import sun.security.krb5.internal.util.KerberosString;
/**
* Implements the ASN.1 PrincipalName type and its realm in a single class.
* <pre>{@code
* Realm ::= KerberosString
*
* PrincipalName ::= SEQUENCE {
* name-type [0] Int32,
* name-string [1] SEQUENCE OF KerberosString
* }
* }</pre>
* This class is immutable.
* @see Realm
*/
public class PrincipalName implements Cloneable {
//name types
/**
* Name type not known
*/
public static final int KRB_NT_UNKNOWN = 0;
/**
* Just the name of the principal as in DCE, or for users
*/
public static final int KRB_NT_PRINCIPAL = 1;
/**
* Service and other unique instance (krbtgt)
*/
public static final int KRB_NT_SRV_INST = 2;
/**
* Service with host name as instance (telnet, rcommands)
*/
public static final int KRB_NT_SRV_HST = 3;
/**
* Service with host as remaining components
*/
public static final int KRB_NT_SRV_XHST = 4;
/**
* Unique ID
*/
public static final int KRB_NT_UID = 5;
/**
* TGS Name
*/
public static final String TGS_DEFAULT_SRV_NAME = "krbtgt";
public static final int TGS_DEFAULT_NT = KRB_NT_SRV_INST;
public static final char NAME_COMPONENT_SEPARATOR = '/';
public static final char NAME_REALM_SEPARATOR = '@';
public static final char REALM_COMPONENT_SEPARATOR = '.';
public static final String NAME_COMPONENT_SEPARATOR_STR = "/";
public static final String NAME_REALM_SEPARATOR_STR = "@";
public static final String REALM_COMPONENT_SEPARATOR_STR = ".";
// Instance fields.
/**
* The name type, from PrincipalName's name-type field.
*/
private final int nameType;
/**
* The name strings, from PrincipalName's name-strings field. This field
* must be neither null nor empty. Each entry of it must also be neither
* null nor empty. Make sure to clone the field when it's passed in or out.
*/
private final String[] nameStrings;
/**
* The realm this principal belongs to.
*/
private final Realm nameRealm; // not null
/**
* When constructing a PrincipalName, whether the realm is included in
* the input, or deduced from default realm or domain-realm mapping.
*/
private final boolean realmDeduced;
// cached default salt, not used in clone
private transient String salt = null;
// There are 3 basic constructors. All other constructors must call them.
// All basic constructors must call validateNameStrings.
// 1. From name components
// 2. From name
// 3. From DER encoding
/**
* Creates a PrincipalName.
*/
public PrincipalName(int nameType, String[] nameStrings, Realm nameRealm) {
if (nameRealm == null) {
throw new IllegalArgumentException("Null realm not allowed");
}
validateNameStrings(nameStrings);
this.nameType = nameType;
this.nameStrings = nameStrings.clone();
this.nameRealm = nameRealm;
this.realmDeduced = false;
}
// This method is called by Windows NativeCred.c
public PrincipalName(String[] nameParts, String realm) throws RealmException {
this(KRB_NT_UNKNOWN, nameParts, new Realm(realm));
}
// Validate a nameStrings argument
private static void validateNameStrings(String[] ns) {
if (ns == null) {
throw new IllegalArgumentException("Null nameStrings not allowed");
}
if (ns.length == 0) {
throw new IllegalArgumentException("Empty nameStrings not allowed");
}
for (String s: ns) {
if (s == null) {
throw new IllegalArgumentException("Null nameString not allowed");
}
if (s.isEmpty()) {
throw new IllegalArgumentException("Empty nameString not allowed");
}
}
}
public Object clone() {
try {
PrincipalName pName = (PrincipalName) super.clone();
UNSAFE.putObject(this, NAME_STRINGS_OFFSET, nameStrings.clone());
return pName;
} catch (CloneNotSupportedException ex) {
throw new AssertionError("Should never happen");
}
}
private static final long NAME_STRINGS_OFFSET;
private static final jdk.internal.misc.Unsafe UNSAFE;
static {
try {
jdk.internal.misc.Unsafe unsafe = jdk.internal.misc.Unsafe.getUnsafe();
NAME_STRINGS_OFFSET = unsafe.objectFieldOffset(
PrincipalName.class.getDeclaredField("nameStrings"));
UNSAFE = unsafe;
} catch (ReflectiveOperationException e) {
throw new Error(e);
}
}
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (o instanceof PrincipalName) {
PrincipalName other = (PrincipalName)o;
return nameRealm.equals(other.nameRealm) &&
Arrays.equals(nameStrings, other.nameStrings);
}
return false;
}
/**
* Returns the ASN.1 encoding of the
* <pre>{@code
* PrincipalName ::= SEQUENCE {
* name-type [0] Int32,
* name-string [1] SEQUENCE OF KerberosString
* }
*
* KerberosString ::= GeneralString (IA5String)
* }</pre>
*
* <p>
* This definition reflects the Network Working Group RFC 4120
* specification available at
* <a href="http://www.ietf.org/rfc/rfc4120.txt">
* http://www.ietf.org/rfc/rfc4120.txt</a>.
*
* @param encoding DER-encoded PrincipalName (without Realm)
* @param realm the realm for this name
* @exception Asn1Exception if an error occurs while decoding
* an ASN1 encoded data.
* @exception Asn1Exception if there is an ASN1 encoding error
* @exception IOException if an I/O error occurs
* @exception IllegalArgumentException if encoding is null
* reading encoded data.
*/
public PrincipalName(DerValue encoding, Realm realm)
throws Asn1Exception, IOException {
if (realm == null) {
throw new IllegalArgumentException("Null realm not allowed");
}
realmDeduced = false;
nameRealm = realm;
DerValue der;
if (encoding == null) {
throw new IllegalArgumentException("Null encoding not allowed");
}
if (encoding.getTag() != DerValue.tag_Sequence) {
throw new Asn1Exception(Krb5.ASN1_BAD_ID);
}
der = encoding.getData().getDerValue();
if ((der.getTag() & 0x1F) == 0x00) {
BigInteger bint = der.getData().getBigInteger();
nameType = bint.intValue();
} else {
throw new Asn1Exception(Krb5.ASN1_BAD_ID);
}
der = encoding.getData().getDerValue();
if ((der.getTag() & 0x01F) == 0x01) {
DerValue subDer = der.getData().getDerValue();
if (subDer.getTag() != DerValue.tag_SequenceOf) {
throw new Asn1Exception(Krb5.ASN1_BAD_ID);
}
Vector<String> v = new Vector<>();
DerValue subSubDer;
while(subDer.getData().available() > 0) {
subSubDer = subDer.getData().getDerValue();
String namePart = new KerberosString(subSubDer).toString();
v.addElement(namePart);
}
nameStrings = new String[v.size()];
v.copyInto(nameStrings);
validateNameStrings(nameStrings);
} else {
throw new Asn1Exception(Krb5.ASN1_BAD_ID);
}
}
/**
* Parse (unmarshal) a <code>PrincipalName</code> from a DER
* input stream. This form
* parsing might be used when expanding a value which is part of
* a constructed sequence and uses explicitly tagged type.
*
* @exception Asn1Exception on error.
* @param data the Der input stream value, which contains one or
* more marshaled value.
* @param explicitTag tag number.
* @param optional indicate if this data field is optional
* @param realm the realm for the name
* @return an instance of <code>PrincipalName</code>, or null if the
* field is optional and missing.
*/
public static PrincipalName parse(DerInputStream data,
byte explicitTag, boolean
optional,
Realm realm)
throws Asn1Exception, IOException, RealmException {
if ((optional) && (((byte)data.peekByte() & (byte)0x1F) !=
explicitTag))
return null;
DerValue der = data.getDerValue();
if (explicitTag != (der.getTag() & (byte)0x1F)) {
throw new Asn1Exception(Krb5.ASN1_BAD_ID);
} else {
DerValue subDer = der.getData().getDerValue();
if (realm == null) {
realm = Realm.getDefault();
}
return new PrincipalName(subDer, realm);
}
}
// XXX Error checkin consistent with MIT krb5_parse_name
// Code repetition, realm parsed again by class Realm
private static String[] parseName(String name) {
Vector<String> tempStrings = new Vector<>();
String temp = name;
int i = 0;
int componentStart = 0;
String component;
while (i < temp.length()) {
if (temp.charAt(i) == NAME_COMPONENT_SEPARATOR) {
/*
* If this separator is escaped then don't treat it
* as a separator
*/
if (i > 0 && temp.charAt(i - 1) == '\\') {
temp = temp.substring(0, i - 1) +
temp.substring(i, temp.length());
continue;
}
else {
if (componentStart <= i) {
component = temp.substring(componentStart, i);
tempStrings.addElement(component);
}
componentStart = i + 1;
}
} else {
if (temp.charAt(i) == NAME_REALM_SEPARATOR) {
/*
* If this separator is escaped then don't treat it
* as a separator
*/
if (i > 0 && temp.charAt(i - 1) == '\\') {
temp = temp.substring(0, i - 1) +
temp.substring(i, temp.length());
continue;
} else {
if (componentStart < i) {
component = temp.substring(componentStart, i);
tempStrings.addElement(component);
}
componentStart = i + 1;
break;
}
}
}
i++;
}
if (i == temp.length()) {
component = temp.substring(componentStart, i);
tempStrings.addElement(component);
}
String[] result = new String[tempStrings.size()];
tempStrings.copyInto(result);
return result;
}
/**
* Constructs a PrincipalName from a string.
* @param name the name
* @param type the type
* @param realm the realm, null if not known. Note that when realm is not
* null, it will be always used even if there is a realm part in name. When
* realm is null, will read realm part from name, or try to map a realm
* (for KRB_NT_SRV_HST), or use the default realm, or fail
* @throws RealmException
*/
public PrincipalName(String name, int type, String realm)
throws RealmException {
if (name == null) {
throw new IllegalArgumentException("Null name not allowed");
}
String[] nameParts = parseName(name);
validateNameStrings(nameParts);
if (realm == null) {
realm = Realm.parseRealmAtSeparator(name);
}
// No realm info from parameter and string, must deduce later
realmDeduced = realm == null;
switch (type) {
case KRB_NT_SRV_HST:
if (nameParts.length >= 2) {
String hostName = nameParts[1];
try {
// RFC4120 does not recommend canonicalizing a hostname.
// However, for compatibility reason, we will try
// canonicalize it and see if the output looks better.
String canonicalized = (InetAddress.getByName(hostName)).
getCanonicalHostName();
// Looks if canonicalized is a longer format of hostName,
// we accept cases like
// bunny -> bunny.rabbit.hole
if (canonicalized.toLowerCase(Locale.ENGLISH).startsWith(
hostName.toLowerCase(Locale.ENGLISH)+".")) {
hostName = canonicalized;
}
} catch (UnknownHostException | SecurityException e) {
// not canonicalized or no permission to do so, use old
}
if (hostName.endsWith(".")) {
hostName = hostName.substring(0, hostName.length() - 1);
}
nameParts[1] = hostName.toLowerCase(Locale.ENGLISH);
}
nameStrings = nameParts;
nameType = type;
if (realm != null) {
nameRealm = new Realm(realm);
} else {
// We will try to get realm name from the mapping in
// the configuration. If it is not specified
// we will use the default realm. This nametype does
// not allow a realm to be specified. The name string must of
// the form service@host and this is internally changed into
// service/host by Kerberos
String mapRealm = mapHostToRealm(nameParts[1]);
if (mapRealm != null) {
nameRealm = new Realm(mapRealm);
} else {
nameRealm = Realm.getDefault();
}
}
break;
case KRB_NT_UNKNOWN:
case KRB_NT_PRINCIPAL:
case KRB_NT_SRV_INST:
case KRB_NT_SRV_XHST:
case KRB_NT_UID:
nameStrings = nameParts;
nameType = type;
if (realm != null) {
nameRealm = new Realm(realm);
} else {
nameRealm = Realm.getDefault();
}
break;
default:
throw new IllegalArgumentException("Illegal name type");
}
}
public PrincipalName(String name, int type) throws RealmException {
this(name, type, (String)null);
}
public PrincipalName(String name) throws RealmException {
this(name, KRB_NT_UNKNOWN);
}
public PrincipalName(String name, String realm) throws RealmException {
this(name, KRB_NT_UNKNOWN, realm);
}
public static PrincipalName tgsService(String r1, String r2)
throws KrbException {
return new PrincipalName(PrincipalName.KRB_NT_SRV_INST,
new String[] {PrincipalName.TGS_DEFAULT_SRV_NAME, r1},
new Realm(r2));
}
public String getRealmAsString() {
return getRealmString();
}
public String getPrincipalNameAsString() {
StringBuilder temp = new StringBuilder(nameStrings[0]);
for (int i = 1; i < nameStrings.length; i++)
temp.append(nameStrings[i]);
return temp.toString();
}
public int hashCode() {
return toString().hashCode();
}
public String getName() {
return toString();
}
public int getNameType() {
return nameType;
}
public String[] getNameStrings() {
return nameStrings.clone();
}
public byte[][] toByteArray() {
byte[][] result = new byte[nameStrings.length][];
for (int i = 0; i < nameStrings.length; i++) {
result[i] = new byte[nameStrings[i].length()];
result[i] = nameStrings[i].getBytes();
}
return result;
}
public String getRealmString() {
return nameRealm.toString();
}
public Realm getRealm() {
return nameRealm;
}
public String getSalt() {
if (salt == null) {
StringBuilder salt = new StringBuilder();
salt.append(nameRealm.toString());
for (int i = 0; i < nameStrings.length; i++) {
salt.append(nameStrings[i]);
}
return salt.toString();
}
return salt;
}
public String toString() {
StringBuilder str = new StringBuilder();
for (int i = 0; i < nameStrings.length; i++) {
if (i > 0)
str.append("/");
str.append(nameStrings[i]);
}
str.append("@");
str.append(nameRealm.toString());
return str.toString();
}
public String getNameString() {
StringBuilder str = new StringBuilder();
for (int i = 0; i < nameStrings.length; i++) {
if (i > 0)
str.append("/");
str.append(nameStrings[i]);
}
return str.toString();
}
/**
* Encodes a <code>PrincipalName</code> object. Note that only the type and
* names are encoded. To encode the realm, call getRealm().asn1Encode().
* @return the byte array of the encoded PrncipalName object.
* @exception Asn1Exception if an error occurs while decoding an ASN1 encoded data.
* @exception IOException if an I/O error occurs while reading encoded data.
*
*/
public byte[] asn1Encode() throws Asn1Exception, IOException {
DerOutputStream bytes = new DerOutputStream();
DerOutputStream temp = new DerOutputStream();
BigInteger bint = BigInteger.valueOf(this.nameType);
temp.putInteger(bint);
bytes.write(DerValue.createTag(DerValue.TAG_CONTEXT, true, (byte)0x00), temp);
temp = new DerOutputStream();
DerValue[] der = new DerValue[nameStrings.length];
for (int i = 0; i < nameStrings.length; i++) {
der[i] = new KerberosString(nameStrings[i]).toDerValue();
}
temp.putSequence(der);
bytes.write(DerValue.createTag(DerValue.TAG_CONTEXT, true, (byte)0x01), temp);
temp = new DerOutputStream();
temp.write(DerValue.tag_Sequence, bytes);
return temp.toByteArray();
}
/**
* Checks if two <code>PrincipalName</code> objects have identical values in their corresponding data fields.
*
* @param pname the other <code>PrincipalName</code> object.
* @return true if two have identical values, otherwise, return false.
*/
// It is used in <code>sun.security.krb5.internal.ccache</code> package.
public boolean match(PrincipalName pname) {
boolean matched = true;
//name type is just a hint, no two names can be the same ignoring name type.
// if (this.nameType != pname.nameType) {
// matched = false;
// }
if ((this.nameRealm != null) && (pname.nameRealm != null)) {
if (!(this.nameRealm.toString().equalsIgnoreCase(pname.nameRealm.toString()))) {
matched = false;
}
}
if (this.nameStrings.length != pname.nameStrings.length) {
matched = false;
} else {
for (int i = 0; i < this.nameStrings.length; i++) {
if (!(this.nameStrings[i].equalsIgnoreCase(pname.nameStrings[i]))) {
matched = false;
}
}
}
return matched;
}
/**
* Writes data field values of <code>PrincipalName</code> in FCC format to an output stream.
*
* @param cos a <code>CCacheOutputStream</code> for writing data.
* @exception IOException if an I/O exception occurs.
* @see sun.security.krb5.internal.ccache.CCacheOutputStream
*/
public void writePrincipal(CCacheOutputStream cos) throws IOException {
cos.write32(nameType);
cos.write32(nameStrings.length);
byte[] realmBytes = null;
realmBytes = nameRealm.toString().getBytes();
cos.write32(realmBytes.length);
cos.write(realmBytes, 0, realmBytes.length);
byte[] bytes = null;
for (int i = 0; i < nameStrings.length; i++) {
bytes = nameStrings[i].getBytes();
cos.write32(bytes.length);
cos.write(bytes, 0, bytes.length);
}
}
/**
* Returns the instance component of a name.
* In a multi-component name such as a KRB_NT_SRV_INST
* name, the second component is returned.
* Null is returned if there are not two or more
* components in the name.
*
* @return instance component of a multi-component name.
*/
public String getInstanceComponent()
{
if (nameStrings != null && nameStrings.length >= 2)
{
return new String(nameStrings[1]);
}
return null;
}
static String mapHostToRealm(String name) {
String result = null;
try {
String subname = null;
Config c = Config.getInstance();
if ((result = c.get("domain_realm", name)) != null)
return result;
else {
for (int i = 1; i < name.length(); i++) {
if ((name.charAt(i) == '.') && (i != name.length() - 1)) { //mapping could be .ibm.com = AUSTIN.IBM.COM
subname = name.substring(i);
result = c.get("domain_realm", subname);
if (result != null) {
break;
}
else {
subname = name.substring(i + 1); //or mapping could be ibm.com = AUSTIN.IBM.COM
result = c.get("domain_realm", subname);
if (result != null) {
break;
}
}
}
}
}
} catch (KrbException e) {
}
return result;
}
public boolean isRealmDeduced() {
return realmDeduced;
}
}
|
{
"pile_set_name": "Github"
}
|
using System;
using System.Reflection;
using System.Runtime.InteropServices;
// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyCulture("")]
// Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]
// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid("700af0fd-e66f-4781-8f58-c37513f9f9cf")]
[assembly: CLSCompliant(true)]
|
{
"pile_set_name": "Github"
}
|
/******/ (function(modules) { // webpackBootstrap
/******/ // The module cache
/******/ var installedModules = {};
/******/ // The require function
/******/ function __webpack_require__(moduleId) {
/******/ // Check if module is in cache
/******/ if(installedModules[moduleId])
/******/ return installedModules[moduleId].exports;
/******/ // Create a new module (and put it into the cache)
/******/ var module = installedModules[moduleId] = {
/******/ exports: {},
/******/ id: moduleId,
/******/ loaded: false
/******/ };
/******/ // Execute the module function
/******/ modules[moduleId].call(module.exports, module, module.exports, __webpack_require__);
/******/ // Flag the module as loaded
/******/ module.loaded = true;
/******/ // Return the exports of the module
/******/ return module.exports;
/******/ }
/******/ // expose the modules object (__webpack_modules__)
/******/ __webpack_require__.m = modules;
/******/ // expose the module cache
/******/ __webpack_require__.c = installedModules;
/******/ // __webpack_public_path__
/******/ __webpack_require__.p = "";
/******/ // Load entry module and return exports
/******/ return __webpack_require__(0);
/******/ })
/************************************************************************/
/******/ ({
/***/ 0:
/***/ function(module, exports, __webpack_require__) {
var __weex_template__ = __webpack_require__(302)
var __weex_style__ = __webpack_require__(303)
var __weex_script__ = __webpack_require__(304)
__weex_define__('@weex-component/c937c6469f381ff87a1a888cb6c33f48', [], function(__weex_require__, __weex_exports__, __weex_module__) {
__weex_script__(__weex_module__, __weex_exports__, __weex_require__)
if (__weex_exports__.__esModule && __weex_exports__.default) {
__weex_module__.exports = __weex_exports__.default
}
__weex_module__.exports.template = __weex_template__
__weex_module__.exports.style = __weex_style__
})
__weex_bootstrap__('@weex-component/c937c6469f381ff87a1a888cb6c33f48',undefined,undefined)
/***/ },
/***/ 302:
/***/ function(module, exports) {
module.exports = {
"type": "div",
"classList": [
"wrapper"
],
"children": [
{
"type": "image",
"attr": {
"src": function () {return this.logoUrl}
},
"classList": [
"logo"
]
},
{
"type": "text",
"classList": [
"title"
],
"attr": {
"value": function () {return 'Hello ' + (this.target)}
}
}
]
}
/***/ },
/***/ 303:
/***/ function(module, exports) {
module.exports = {
"wrapper": {
"alignItems": "center",
"marginTop": 120
},
"title": {
"fontSize": 48
},
"logo": {
"width": 360,
"height": 82
}
}
/***/ },
/***/ 304:
/***/ function(module, exports) {
module.exports = function(module, exports, __weex_require__){'use strict';
module.exports = {
data: function () {return {
logoUrl: 'http://alibaba.github.io/weex/img/[email protected]',
target: 'World'
}}
};}
/* generated by weex-loader */
/***/ }
/******/ });
|
{
"pile_set_name": "Github"
}
|
# Copyright 2009-2018 Noviat
# Copyright 2019 Tecnativa - Pedro M. Baeza
# License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl).
import calendar
import logging
from datetime import date
from functools import reduce
from sys import exc_info
from traceback import format_exception
from dateutil.relativedelta import relativedelta
from odoo import _, api, fields, models
from odoo.exceptions import UserError
from odoo.osv import expression
_logger = logging.getLogger(__name__)
READONLY_STATES = {
"open": [("readonly", True)],
"close": [("readonly", True)],
"removed": [("readonly", True)],
}
class DummyFy(object):
def __init__(self, *args, **argv):
for key, arg in argv.items():
setattr(self, key, arg)
class AccountAsset(models.Model):
_name = "account.asset"
_description = "Asset"
_order = "date_start desc, code, name"
account_move_line_ids = fields.One2many(
comodel_name="account.move.line",
inverse_name="asset_id",
string="Entries",
readonly=True,
copy=False,
)
move_line_check = fields.Boolean(
compute="_compute_move_line_check", string="Has accounting entries"
)
name = fields.Char(string="Asset Name", required=True, states=READONLY_STATES,)
code = fields.Char(string="Reference", size=32, states=READONLY_STATES,)
purchase_value = fields.Float(
string="Purchase Value",
required=True,
states=READONLY_STATES,
help="This amount represent the initial value of the asset."
"\nThe Depreciation Base is calculated as follows:"
"\nPurchase Value - Salvage Value.",
)
salvage_value = fields.Float(
string="Salvage Value",
digits="Account",
states=READONLY_STATES,
help="The estimated value that an asset will realize upon "
"its sale at the end of its useful life.\n"
"This value is used to determine the depreciation amounts.",
)
depreciation_base = fields.Float(
compute="_compute_depreciation_base",
digits="Account",
string="Depreciation Base",
store=True,
help="This amount represent the depreciation base "
"of the asset (Purchase Value - Salvage Value).",
)
value_residual = fields.Float(
compute="_compute_depreciation",
digits="Account",
string="Residual Value",
store=True,
)
value_depreciated = fields.Float(
compute="_compute_depreciation",
digits="Account",
string="Depreciated Value",
store=True,
)
note = fields.Text("Note")
profile_id = fields.Many2one(
comodel_name="account.asset.profile",
string="Asset Profile",
change_default=True,
required=True,
states=READONLY_STATES,
)
group_ids = fields.Many2many(
comodel_name="account.asset.group",
compute="_compute_group_ids",
readonly=False,
store=True,
relation="account_asset_group_rel",
column1="asset_id",
column2="group_id",
string="Asset Groups",
)
date_start = fields.Date(
string="Asset Start Date",
required=True,
states=READONLY_STATES,
help="You should manually add depreciation lines "
"with the depreciations of previous fiscal years "
"if the Depreciation Start Date is different from the date "
"for which accounting entries need to be generated.",
)
date_remove = fields.Date(string="Asset Removal Date", readonly=True)
state = fields.Selection(
selection=[
("draft", "Draft"),
("open", "Running"),
("close", "Close"),
("removed", "Removed"),
],
string="Status",
required=True,
default="draft",
copy=False,
help="When an asset is created, the status is 'Draft'.\n"
"If the asset is confirmed, the status goes in 'Running' "
"and the depreciation lines can be posted "
"to the accounting.\n"
"If the last depreciation line is posted, "
"the asset goes into the 'Close' status.\n"
"When the removal entries are generated, "
"the asset goes into the 'Removed' status.",
)
active = fields.Boolean(default=True)
partner_id = fields.Many2one(
comodel_name="res.partner", string="Partner", states=READONLY_STATES,
)
method = fields.Selection(
selection=lambda self: self.env["account.asset.profile"]._selection_method(),
string="Computation Method",
compute="_compute_method",
readonly=False,
store=True,
states=READONLY_STATES,
help="Choose the method to use to compute the depreciation lines.\n"
" * Linear: Calculated on basis of: "
"Depreciation Base / Number of Depreciations. "
"Depreciation Base = Purchase Value - Salvage Value.\n"
" * Linear-Limit: Linear up to Salvage Value. "
"Depreciation Base = Purchase Value.\n"
" * Degressive: Calculated on basis of: "
"Residual Value * Degressive Factor.\n"
" * Degressive-Linear (only for Time Method = Year): "
"Degressive becomes linear when the annual linear "
"depreciation exceeds the annual degressive depreciation.\n"
" * Degressive-Limit: Degressive up to Salvage Value. "
"The Depreciation Base is equal to the asset value.",
)
method_number = fields.Integer(
string="Number of Years",
compute="_compute_method_number",
readonly=False,
store=True,
states=READONLY_STATES,
help="The number of years needed to depreciate your asset",
)
method_period = fields.Selection(
selection=lambda self: self.env[
"account.asset.profile"
]._selection_method_period(),
string="Period Length",
compute="_compute_method_period",
readonly=False,
store=True,
states=READONLY_STATES,
help="Period length for the depreciation accounting entries",
)
method_end = fields.Date(
string="Ending Date",
compute="_compute_method_end",
readonly=False,
store=True,
states=READONLY_STATES,
)
method_progress_factor = fields.Float(
string="Degressive Factor",
compute="_compute_method_progress_factor",
readonly=False,
store=True,
states=READONLY_STATES,
)
method_time = fields.Selection(
selection=lambda self: self.env[
"account.asset.profile"
]._selection_method_time(),
string="Time Method",
compute="_compute_method_time",
readonly=False,
store=True,
states=READONLY_STATES,
help="Choose the method to use to compute the dates and "
"number of depreciation lines.\n"
" * Number of Years: Specify the number of years "
"for the depreciation.\n",
)
days_calc = fields.Boolean(
string="Calculate by days",
compute="_compute_days_calc",
readonly=False,
store=True,
help="Use number of days to calculate depreciation amount",
)
use_leap_years = fields.Boolean(
string="Use leap years",
compute="_compute_use_leap_years",
readonly=False,
store=True,
help="If not set, the system will distribute evenly the amount to "
"amortize across the years, based on the number of years. "
"So the amount per year will be the "
"depreciation base / number of years.\n "
"If set, the system will consider if the current year "
"is a leap year. The amount to depreciate per year will be "
"calculated as depreciation base / (depreciation end date - "
"start date + 1) * days in the current year.",
)
prorata = fields.Boolean(
string="Prorata Temporis",
compute="_compute_prorrata",
readonly=False,
store=True,
states=READONLY_STATES,
help="Indicates that the first depreciation entry for this asset "
"has to be done from the depreciation start date instead of "
"the first day of the fiscal year.",
)
depreciation_line_ids = fields.One2many(
comodel_name="account.asset.line",
inverse_name="asset_id",
string="Depreciation Lines",
copy=False,
states=READONLY_STATES,
)
company_id = fields.Many2one(
comodel_name="res.company",
string="Company",
required=True,
readonly=True,
default=lambda self: self._default_company_id(),
)
company_currency_id = fields.Many2one(
comodel_name="res.currency",
related="company_id.currency_id",
string="Company Currency",
store=True,
readonly=True,
)
account_analytic_id = fields.Many2one(
comodel_name="account.analytic.account",
string="Analytic account",
compute="_compute_account_analytic_id",
readonly=False,
store=True,
)
@api.model
def _default_company_id(self):
return self.env.company
@api.depends("depreciation_line_ids.move_id")
def _compute_move_line_check(self):
for asset in self:
asset.move_line_check = bool(
asset.depreciation_line_ids.filtered("move_id")
)
@api.depends("purchase_value", "salvage_value", "method")
def _compute_depreciation_base(self):
for asset in self:
if asset.method in ["linear-limit", "degr-limit"]:
asset.depreciation_base = asset.purchase_value
else:
asset.depreciation_base = asset.purchase_value - asset.salvage_value
@api.depends(
"depreciation_base",
"depreciation_line_ids.type",
"depreciation_line_ids.amount",
"depreciation_line_ids.previous_id",
"depreciation_line_ids.init_entry",
"depreciation_line_ids.move_check",
)
def _compute_depreciation(self):
for asset in self:
lines = asset.depreciation_line_ids.filtered(
lambda l: l.type in ("depreciate", "remove")
and (l.init_entry or l.move_check)
)
value_depreciated = sum([line.amount for line in lines])
residual = asset.depreciation_base - value_depreciated
depreciated = value_depreciated
asset.update({"value_residual": residual, "value_depreciated": depreciated})
@api.depends("profile_id")
def _compute_group_ids(self):
for asset in self.filtered("profile_id"):
asset.group_ids = asset.profile_id.group_ids
@api.depends("profile_id")
def _compute_method(self):
for asset in self:
asset.method = asset.profile_id.method
@api.depends("profile_id", "method_end")
def _compute_method_number(self):
for asset in self:
if asset.method_end:
asset.method_number = 0
else:
asset.method_number = asset.profile_id.method_number
@api.depends("profile_id")
def _compute_method_period(self):
for asset in self:
asset.method_period = asset.profile_id.method_period
@api.depends("method_number")
def _compute_method_end(self):
for asset in self:
if asset.method_number:
asset.method_end = False
@api.depends("profile_id")
def _compute_method_progress_factor(self):
for asset in self:
asset.method_progress_factor = asset.profile_id.method_progress_factor
@api.depends("profile_id")
def _compute_method_time(self):
for asset in self:
asset.method_time = asset.profile_id.method_time
@api.depends("profile_id")
def _compute_days_calc(self):
for asset in self:
asset.days_calc = asset.profile_id.days_calc
@api.depends("profile_id")
def _compute_use_leap_years(self):
for asset in self:
asset.use_leap_years = asset.profile_id.use_leap_years
@api.depends("profile_id", "method_time")
def _compute_prorrata(self):
for asset in self:
if asset.method_time != "year":
asset.prorata = True
else:
asset.prorata = asset.profile_id.prorata
@api.depends("profile_id")
def _compute_account_analytic_id(self):
for asset in self:
asset.account_analytic_id = asset.profile_id.account_analytic_id
@api.constrains("method", "method_time")
def _check_method(self):
if self.filtered(
lambda a: a.method == "degr-linear" and a.method_time != "year"
):
raise UserError(
_("Degressive-Linear is only supported for Time Method = Year.")
)
@api.constrains("date_start", "method_end", "method_time")
def _check_dates(self):
if self.filtered(
lambda a: a.method_time == "end" and a.method_end <= a.date_start
):
raise UserError(_("The Start Date must precede the Ending Date."))
@api.constrains("profile_id")
def _check_profile_change(self):
if self.depreciation_line_ids.filtered("move_id"):
raise UserError(
_(
"You cannot change the profile of an asset "
"with accounting entries."
)
)
@api.onchange("purchase_value", "salvage_value", "date_start", "method")
def _onchange_purchase_salvage_value(self):
if self.method in ["linear-limit", "degr-limit"]:
self.depreciation_base = self.purchase_value or 0.0
else:
purchase_value = self.purchase_value or 0.0
salvage_value = self.salvage_value or 0.0
self.depreciation_base = purchase_value - salvage_value
dl_create_line = self.depreciation_line_ids.filtered(
lambda r: r.type == "create"
)
if dl_create_line:
dl_create_line.update(
{"amount": self.depreciation_base, "line_date": self.date_start}
)
@api.model
def create(self, vals):
asset = super().create(vals)
if self.env.context.get("create_asset_from_move_line"):
# Trigger compute of depreciation_base
asset.salvage_value = 0.0
asset._create_first_asset_line()
return asset
def write(self, vals):
res = super().write(vals)
for asset in self:
if self.env.context.get("asset_validate_from_write"):
continue
asset._create_first_asset_line()
if asset.profile_id.open_asset and self.env.context.get(
"create_asset_from_move_line"
):
asset.compute_depreciation_board()
# extra context to avoid recursion
asset.with_context(asset_validate_from_write=True).validate()
return res
def _create_first_asset_line(self):
self.ensure_one()
if self.depreciation_base and not self.depreciation_line_ids:
asset_line_obj = self.env["account.asset.line"]
line_name = self._get_depreciation_entry_name(0)
asset_line_vals = {
"amount": self.depreciation_base,
"asset_id": self.id,
"name": line_name,
"line_date": self.date_start,
"init_entry": True,
"type": "create",
}
asset_line = asset_line_obj.create(asset_line_vals)
if self.env.context.get("create_asset_from_move_line"):
asset_line.move_id = self.env.context["move_id"]
def unlink(self):
for asset in self:
if asset.state != "draft":
raise UserError(_("You can only delete assets in draft state."))
if asset.depreciation_line_ids.filtered(
lambda r: r.type == "depreciate" and r.move_check
):
raise UserError(
_(
"You cannot delete an asset that contains "
"posted depreciation lines."
)
)
# update accounting entries linked to lines of type 'create'
amls = self.with_context(allow_asset_removal=True).mapped(
"account_move_line_ids"
)
amls.write({"asset_id": False})
return super().unlink()
@api.model
def name_search(self, name, args=None, operator="ilike", limit=100):
args = args or []
domain = []
if name:
domain = ["|", ("code", "=ilike", name + "%"), ("name", operator, name)]
if operator in expression.NEGATIVE_TERM_OPERATORS:
domain = ["&", "!"] + domain[1:]
assets = self.search(domain + args, limit=limit)
return assets.name_get()
@api.depends("name", "code")
def name_get(self):
result = []
for asset in self:
name = asset.name
if asset.code:
name = " - ".join([asset.code, name])
result.append((asset.id, name))
return result
def validate(self):
for asset in self:
if asset.company_currency_id.is_zero(asset.value_residual):
asset.state = "close"
else:
asset.state = "open"
if not asset.depreciation_line_ids.filtered(
lambda l: l.type != "create"
):
asset.compute_depreciation_board()
return True
def remove(self):
self.ensure_one()
ctx = dict(self.env.context, active_ids=self.ids, active_id=self.id)
early_removal = False
if self.method in ["linear-limit", "degr-limit"]:
if self.value_residual != self.salvage_value:
early_removal = True
elif self.value_residual:
early_removal = True
if early_removal:
ctx.update({"early_removal": True})
return {
"name": _("Generate Asset Removal entries"),
"view_mode": "form",
"res_model": "account.asset.remove",
"target": "new",
"type": "ir.actions.act_window",
"context": ctx,
}
def set_to_draft(self):
return self.write({"state": "draft"})
def open_entries(self):
self.ensure_one()
# needed for avoiding errors after grouping in assets
context = dict(self.env.context)
context.pop("group_by", None)
return {
"name": _("Journal Entries"),
"view_mode": "tree,form",
"res_model": "account.move",
"view_id": False,
"type": "ir.actions.act_window",
"context": context,
"domain": [("id", "in", self.account_move_line_ids.mapped("move_id").ids)],
}
def _group_lines(self, table):
"""group lines prior to depreciation start period."""
def group_lines(x, y):
y.update({"amount": x["amount"] + y["amount"]})
return y
depreciation_start_date = self.date_start
lines = table[0]["lines"]
lines1 = []
lines2 = []
flag = lines[0]["date"] < depreciation_start_date
for line in lines:
if flag:
lines1.append(line)
if line["date"] >= depreciation_start_date:
flag = False
else:
lines2.append(line)
if lines1:
lines1 = [reduce(group_lines, lines1)]
lines1[0]["depreciated_value"] = 0.0
table[0]["lines"] = lines1 + lines2
def _compute_depreciation_line(
self,
depreciated_value_posted,
table_i_start,
line_i_start,
table,
last_line,
posted_lines,
):
digits = self.env["decimal.precision"].precision_get("Account")
seq = len(posted_lines)
depr_line = last_line
last_date = table[-1]["lines"][-1]["date"]
depreciated_value = depreciated_value_posted
for entry in table[table_i_start:]:
for line in entry["lines"][line_i_start:]:
seq += 1
name = self._get_depreciation_entry_name(seq)
amount = line["amount"]
if line["date"] == last_date:
# ensure that the last entry of the table always
# depreciates the remaining value
amount = self.depreciation_base - depreciated_value
if self.method in ["linear-limit", "degr-limit"]:
amount -= self.salvage_value
if amount:
vals = {
"previous_id": depr_line.id,
"amount": round(amount, digits),
"asset_id": self.id,
"name": name,
"line_date": line["date"],
"line_days": line["days"],
"init_entry": entry["init"],
}
depreciated_value += round(amount, digits)
depr_line = self.env["account.asset.line"].create(vals)
else:
seq -= 1
line_i_start = 0
def compute_depreciation_board(self):
line_obj = self.env["account.asset.line"]
digits = self.env["decimal.precision"].precision_get("Account")
for asset in self:
if asset.value_residual == 0.0:
continue
domain = [
("asset_id", "=", asset.id),
("type", "=", "depreciate"),
"|",
("move_check", "=", True),
("init_entry", "=", True),
]
posted_lines = line_obj.search(domain, order="line_date desc")
if posted_lines:
last_line = posted_lines[0]
else:
last_line = line_obj
domain = [
("asset_id", "=", asset.id),
("type", "=", "depreciate"),
("move_id", "=", False),
("init_entry", "=", False),
]
old_lines = line_obj.search(domain)
if old_lines:
old_lines.unlink()
table = asset._compute_depreciation_table()
if not table:
continue
asset._group_lines(table)
# check table with posted entries and
# recompute in case of deviation
depreciated_value_posted = depreciated_value = 0.0
if posted_lines:
last_depreciation_date = last_line.line_date
last_date_in_table = table[-1]["lines"][-1]["date"]
if last_date_in_table <= last_depreciation_date:
raise UserError(
_(
"The duration of the asset conflicts with the "
"posted depreciation table entry dates."
)
)
for _table_i, entry in enumerate(table):
residual_amount_table = entry["lines"][-1]["remaining_value"]
if (
entry["date_start"]
<= last_depreciation_date
<= entry["date_stop"]
):
break
if entry["date_stop"] == last_depreciation_date:
_table_i += 1
_line_i = 0
else:
entry = table[_table_i]
date_min = entry["date_start"]
for _line_i, line in enumerate(entry["lines"]):
residual_amount_table = line["remaining_value"]
if date_min <= last_depreciation_date <= line["date"]:
break
date_min = line["date"]
if line["date"] == last_depreciation_date:
_line_i += 1
table_i_start = _table_i
line_i_start = _line_i
# check if residual value corresponds with table
# and adjust table when needed
depreciated_value_posted = depreciated_value = sum(
[posted_line.amount for posted_line in posted_lines]
)
residual_amount = asset.depreciation_base - depreciated_value
amount_diff = round(residual_amount_table - residual_amount, digits)
if amount_diff:
# compensate in first depreciation entry
# after last posting
line = table[table_i_start]["lines"][line_i_start]
line["amount"] -= amount_diff
else: # no posted lines
table_i_start = 0
line_i_start = 0
asset._compute_depreciation_line(
depreciated_value_posted,
table_i_start,
line_i_start,
table,
last_line,
posted_lines,
)
return True
def _get_fy_duration(self, fy, option="days"):
"""Returns fiscal year duration.
@param option:
- days: duration in days
- months: duration in months,
a started month is counted as a full month
- years: duration in calendar years, considering also leap years
"""
fy_date_start = fy.date_from
fy_date_stop = fy.date_to
days = (fy_date_stop - fy_date_start).days + 1
months = (
(fy_date_stop.year - fy_date_start.year) * 12
+ (fy_date_stop.month - fy_date_start.month)
+ 1
)
if option == "days":
return days
elif option == "months":
return months
elif option == "years":
year = fy_date_start.year
cnt = fy_date_stop.year - fy_date_start.year + 1
for i in range(cnt):
cy_days = calendar.isleap(year) and 366 or 365
if i == 0: # first year
if fy_date_stop.year == year:
duration = (fy_date_stop - fy_date_start).days + 1
else:
duration = (date(year, 12, 31) - fy_date_start).days + 1
factor = float(duration) / cy_days
elif i == cnt - 1: # last year
duration = (fy_date_stop - date(year, 1, 1)).days + 1
factor += float(duration) / cy_days
else:
factor += 1.0
year += 1
return factor
def _get_fy_duration_factor(self, entry, firstyear):
"""
localization: override this method to change the logic used to
calculate the impact of extended/shortened fiscal years
"""
duration_factor = 1.0
fy = entry["fy"]
if self.prorata:
if firstyear:
depreciation_date_start = self.date_start
fy_date_stop = entry["date_stop"]
first_fy_asset_days = (fy_date_stop - depreciation_date_start).days + 1
first_fy_duration = self._get_fy_duration(fy, option="days")
first_fy_year_factor = self._get_fy_duration(fy, option="years")
duration_factor = (
float(first_fy_asset_days)
/ first_fy_duration
* first_fy_year_factor
)
else:
duration_factor = self._get_fy_duration(fy, option="years")
else:
fy_months = self._get_fy_duration(fy, option="months")
duration_factor = float(fy_months) / 12
return duration_factor
def _get_depreciation_start_date(self, fy):
"""
In case of 'Linear': the first month is counted as a full month
if the fiscal year starts in the middle of a month.
"""
if self.prorata:
depreciation_start_date = self.date_start
else:
depreciation_start_date = fy.date_from
return depreciation_start_date
def _get_depreciation_stop_date(self, depreciation_start_date):
if self.method_time == "year" and not self.method_end:
depreciation_stop_date = depreciation_start_date + relativedelta(
years=self.method_number, days=-1
)
elif self.method_time == "number":
if self.method_period == "month":
depreciation_stop_date = depreciation_start_date + relativedelta(
months=self.method_number, days=-1
)
elif self.method_period == "quarter":
m = [x for x in [3, 6, 9, 12] if x >= depreciation_start_date.month][0]
first_line_date = depreciation_start_date + relativedelta(
month=m, day=31
)
months = self.method_number * 3
depreciation_stop_date = first_line_date + relativedelta(
months=months - 1, days=-1
)
elif self.method_period == "year":
depreciation_stop_date = depreciation_start_date + relativedelta(
years=self.method_number, days=-1
)
elif self.method_time == "year" and self.method_end:
depreciation_stop_date = self.method_end
return depreciation_stop_date
def _get_first_period_amount(
self, table, entry, depreciation_start_date, line_dates
):
"""
Return prorata amount for Time Method 'Year' in case of
'Prorata Temporis'
"""
amount = entry.get("period_amount")
if self.prorata and self.method_time == "year":
dates = [x for x in line_dates if x <= entry["date_stop"]]
full_periods = len(dates) - 1
amount = entry["fy_amount"] - amount * full_periods
return amount
def _get_amount_linear(
self, depreciation_start_date, depreciation_stop_date, entry
):
"""
Override this method if you want to compute differently the
yearly amount.
"""
if not self.use_leap_years and self.method_number:
return self.depreciation_base / self.method_number
year = entry["date_stop"].year
cy_days = calendar.isleap(year) and 366 or 365
days = (depreciation_stop_date - depreciation_start_date).days + 1
return (self.depreciation_base / days) * cy_days
def _compute_year_amount(
self, residual_amount, depreciation_start_date, depreciation_stop_date, entry
):
"""
Localization: override this method to change the degressive-linear
calculation logic according to local legislation.
"""
if self.method_time != "year":
raise UserError(
_(
"The '_compute_year_amount' method is only intended for "
"Time Method 'Number of Years'."
)
)
year_amount_linear = self._get_amount_linear(
depreciation_start_date, depreciation_stop_date, entry
)
if self.method == "linear":
return year_amount_linear
if self.method == "linear-limit":
if (residual_amount - year_amount_linear) < self.salvage_value:
return residual_amount - self.salvage_value
else:
return year_amount_linear
year_amount_degressive = residual_amount * self.method_progress_factor
if self.method == "degressive":
return year_amount_degressive
if self.method == "degr-linear":
if year_amount_linear > year_amount_degressive:
return min(year_amount_linear, residual_amount)
else:
return min(year_amount_degressive, residual_amount)
if self.method == "degr-limit":
if (residual_amount - year_amount_degressive) < self.salvage_value:
return residual_amount - self.salvage_value
else:
return year_amount_degressive
else:
raise UserError(_("Illegal value %s in asset.method.") % self.method)
def _compute_line_dates(self, table, start_date, stop_date):
"""
The posting dates of the accounting entries depend on the
chosen 'Period Length' as follows:
- month: last day of the month
- quarter: last of the quarter
- year: last day of the fiscal year
Override this method if another posting date logic is required.
"""
line_dates = []
if self.method_period == "month":
line_date = start_date + relativedelta(day=31)
if self.method_period == "quarter":
m = [x for x in [3, 6, 9, 12] if x >= start_date.month][0]
line_date = start_date + relativedelta(month=m, day=31)
elif self.method_period == "year":
line_date = table[0]["date_stop"]
i = 1
while line_date < stop_date:
line_dates.append(line_date)
if self.method_period == "month":
line_date = line_date + relativedelta(months=1, day=31)
elif self.method_period == "quarter":
line_date = line_date + relativedelta(months=3, day=31)
elif self.method_period == "year":
line_date = table[i]["date_stop"]
i += 1
# last entry
if not (self.method_time == "number" and len(line_dates) == self.method_number):
if self.days_calc:
line_dates.append(stop_date)
else:
line_dates.append(line_date)
return line_dates
def _compute_depreciation_amount_per_fiscal_year(
self, table, line_dates, depreciation_start_date, depreciation_stop_date
):
digits = self.env["decimal.precision"].precision_get("Account")
fy_residual_amount = self.depreciation_base
i_max = len(table) - 1
asset_sign = self.depreciation_base >= 0 and 1 or -1
day_amount = 0.0
if self.days_calc:
days = (depreciation_stop_date - depreciation_start_date).days + 1
day_amount = self.depreciation_base / days
for i, entry in enumerate(table):
if self.method_time == "year":
year_amount = self._compute_year_amount(
fy_residual_amount,
depreciation_start_date,
depreciation_stop_date,
entry,
)
if self.method_period == "year":
period_amount = year_amount
elif self.method_period == "quarter":
period_amount = year_amount / 4
elif self.method_period == "month":
period_amount = year_amount / 12
if i == i_max:
if self.method in ["linear-limit", "degr-limit"]:
fy_amount = fy_residual_amount - self.salvage_value
else:
fy_amount = fy_residual_amount
else:
firstyear = i == 0 and True or False
fy_factor = self._get_fy_duration_factor(entry, firstyear)
fy_amount = year_amount * fy_factor
if asset_sign * (fy_amount - fy_residual_amount) > 0:
fy_amount = fy_residual_amount
period_amount = round(period_amount, digits)
fy_amount = round(fy_amount, digits)
else:
fy_amount = False
if self.method_time == "number":
number = self.method_number
else:
number = len(line_dates)
period_amount = round(self.depreciation_base / number, digits)
entry.update(
{
"period_amount": period_amount,
"fy_amount": fy_amount,
"day_amount": day_amount,
}
)
if self.method_time == "year":
fy_residual_amount -= fy_amount
if round(fy_residual_amount, digits) == 0:
break
i_max = i
table = table[: i_max + 1]
return table
def _compute_depreciation_table_lines(
self, table, depreciation_start_date, depreciation_stop_date, line_dates
):
digits = self.env["decimal.precision"].precision_get("Account")
asset_sign = 1 if self.depreciation_base >= 0 else -1
i_max = len(table) - 1
remaining_value = self.depreciation_base
depreciated_value = 0.0
for i, entry in enumerate(table):
lines = []
fy_amount_check = 0.0
fy_amount = entry["fy_amount"]
li_max = len(line_dates) - 1
prev_date = max(entry["date_start"], depreciation_start_date)
for li, line_date in enumerate(line_dates):
line_days = (line_date - prev_date).days + 1
if round(remaining_value, digits) == 0.0:
break
if line_date > min(entry["date_stop"], depreciation_stop_date) and not (
i == i_max and li == li_max
):
prev_date = line_date
break
else:
prev_date = line_date + relativedelta(days=1)
if (
self.method == "degr-linear"
and asset_sign * (fy_amount - fy_amount_check) < 0
):
break
if i == 0 and li == 0:
if entry.get("day_amount") > 0.0:
amount = line_days * entry.get("day_amount")
else:
amount = self._get_first_period_amount(
table, entry, depreciation_start_date, line_dates
)
amount = round(amount, digits)
else:
if entry.get("day_amount") > 0.0:
amount = line_days * entry.get("day_amount")
else:
amount = entry.get("period_amount")
# last year, last entry
# Handle rounding deviations.
if i == i_max and li == li_max:
amount = remaining_value
remaining_value = 0.0
else:
remaining_value -= amount
fy_amount_check += amount
line = {
"date": line_date,
"days": line_days,
"amount": amount,
"depreciated_value": depreciated_value,
"remaining_value": remaining_value,
}
lines.append(line)
depreciated_value += amount
# Handle rounding and extended/shortened FY deviations.
#
# Remark:
# In account_asset_management version < 8.0.2.8.0
# the FY deviation for the first FY
# was compensated in the first FY depreciation line.
# The code has now been simplified with compensation
# always in last FT depreciation line.
if self.method_time == "year" and not entry.get("day_amount"):
if round(fy_amount_check - fy_amount, digits) != 0:
diff = fy_amount_check - fy_amount
amount = amount - diff
remaining_value += diff
lines[-1].update(
{"amount": amount, "remaining_value": remaining_value}
)
depreciated_value -= diff
if not lines:
table.pop(i)
else:
entry["lines"] = lines
line_dates = line_dates[li:]
for entry in table:
if not entry["fy_amount"]:
entry["fy_amount"] = sum([line["amount"] for line in entry["lines"]])
def _get_fy_info(self, date):
"""Return an homogeneus data structure for fiscal years."""
fy_info = self.company_id.compute_fiscalyear_dates(date)
if "record" not in fy_info:
fy_info["record"] = DummyFy(
date_from=fy_info["date_from"], date_to=fy_info["date_to"]
)
return fy_info
def _compute_depreciation_table(self):
table = []
if (
self.method_time in ["year", "number"]
and not self.method_number
and not self.method_end
):
return table
company = self.company_id
asset_date_start = self.date_start
fiscalyear_lock_date = company.fiscalyear_lock_date or fields.Date.to_date(
"1901-01-01"
)
depreciation_start_date = self._get_depreciation_start_date(
self._get_fy_info(asset_date_start)["record"]
)
depreciation_stop_date = self._get_depreciation_stop_date(
depreciation_start_date
)
fy_date_start = asset_date_start
while fy_date_start <= depreciation_stop_date:
fy_info = self._get_fy_info(fy_date_start)
table.append(
{
"fy": fy_info["record"],
"date_start": fy_info["date_from"],
"date_stop": fy_info["date_to"],
"init": fiscalyear_lock_date >= fy_info["date_from"],
}
)
fy_date_start = fy_info["date_to"] + relativedelta(days=1)
# Step 1:
# Calculate depreciation amount per fiscal year.
# This is calculation is skipped for method_time != 'year'.
line_dates = self._compute_line_dates(
table, depreciation_start_date, depreciation_stop_date
)
table = self._compute_depreciation_amount_per_fiscal_year(
table, line_dates, depreciation_start_date, depreciation_stop_date
)
# Step 2:
# Spread depreciation amount per fiscal year
# over the depreciation periods.
self._compute_depreciation_table_lines(
table, depreciation_start_date, depreciation_stop_date, line_dates
)
return table
def _get_depreciation_entry_name(self, seq):
""" use this method to customise the name of the accounting entry """
return (self.code or str(self.id)) + "/" + str(seq)
def _compute_entries(self, date_end, check_triggers=False):
# TODO : add ir_cron job calling this method to
# generate periodical accounting entries
result = []
error_log = ""
if check_triggers:
recompute_obj = self.env["account.asset.recompute.trigger"]
recomputes = recompute_obj.sudo().search([("state", "=", "open")])
if recomputes:
trigger_companies = recomputes.mapped("company_id")
for asset in self:
if asset.company_id.id in trigger_companies.ids:
asset.compute_depreciation_board()
depreciations = self.env["account.asset.line"].search(
[
("asset_id", "in", self.ids),
("type", "=", "depreciate"),
("init_entry", "=", False),
("line_date", "<=", date_end),
("move_check", "=", False),
],
order="line_date",
)
for depreciation in depreciations:
try:
with self.env.cr.savepoint():
result += depreciation.create_move()
except Exception:
e = exc_info()[0]
tb = "".join(format_exception(*exc_info()))
asset_ref = depreciation.asset_id.name
if depreciation.asset_id.code:
asset_ref = "[{}] {}".format(depreciation.asset_id.code, asset_ref)
error_log += _("\nError while processing asset '%s': %s") % (
asset_ref,
str(e),
)
error_msg = _("Error while processing asset '%s': \n\n%s") % (
asset_ref,
tb,
)
_logger.error("%s, %s", self._name, error_msg)
if check_triggers and recomputes:
companies = recomputes.mapped("company_id")
triggers = recomputes.filtered(lambda r: r.company_id.id in companies.ids)
if triggers:
recompute_vals = {
"date_completed": fields.Datetime.now(),
"state": "done",
}
triggers.sudo().write(recompute_vals)
return (result, error_log)
|
{
"pile_set_name": "Github"
}
|
// Copyright (c) 2014, the Dart project authors. Please see the AUTHORS file
// for details. All rights reserved. Use of this source code is governed by a
// BSD-style license that can be found in the LICENSE file.
library edit.domain;
import 'dart:async';
import 'package:analysis_server/edit/assist/assist_core.dart';
import 'package:analysis_server/edit/fix/fix_core.dart';
import 'package:analysis_server/src/analysis_server.dart';
import 'package:analysis_server/src/collections.dart';
import 'package:analysis_server/src/constants.dart';
import 'package:analysis_server/src/plugin/server_plugin.dart';
import 'package:analysis_server/src/protocol_server.dart' hide Element;
import 'package:analysis_server/src/services/correction/assist.dart';
import 'package:analysis_server/src/services/correction/fix.dart';
import 'package:analysis_server/src/services/correction/sort_members.dart';
import 'package:analysis_server/src/services/correction/status.dart';
import 'package:analysis_server/src/services/refactoring/refactoring.dart';
import 'package:analysis_server/src/services/search/search_engine.dart';
import 'package:analyzer/src/generated/ast.dart';
import 'package:analyzer/src/generated/element.dart';
import 'package:analyzer/src/generated/engine.dart' as engine;
import 'package:analyzer/src/generated/error.dart' as engine;
import 'package:analyzer/src/generated/parser.dart' as engine;
import 'package:analyzer/src/generated/scanner.dart' as engine;
import 'package:analyzer/src/generated/source.dart';
import 'package:dart_style/dart_style.dart';
bool test_simulateRefactoringException_change = false;
bool test_simulateRefactoringException_final = false;
bool test_simulateRefactoringException_init = false;
/**
* Instances of the class [EditDomainHandler] implement a [RequestHandler]
* that handles requests in the edit domain.
*/
class EditDomainHandler implements RequestHandler {
/**
* The analysis server that is using this handler to process requests.
*/
final AnalysisServer server;
/**
* The server plugin that defines the extension points used by this handler.
*/
final ServerPlugin plugin;
/**
* The [SearchEngine] for this server.
*/
SearchEngine searchEngine;
_RefactoringManager refactoringManager;
/**
* Initialize a newly created handler to handle requests for the given [server].
*/
EditDomainHandler(this.server, this.plugin) {
searchEngine = server.searchEngine;
_newRefactoringManager();
}
Response format(Request request) {
EditFormatParams params = new EditFormatParams.fromRequest(request);
String file = params.file;
ContextSourcePair contextSource = server.getContextSourcePair(file);
engine.AnalysisContext context = contextSource.context;
if (context == null) {
return new Response.formatInvalidFile(request);
}
Source source = contextSource.source;
engine.TimestampedData<String> contents;
try {
contents = context.getContents(source);
} catch (e) {
return new Response.formatInvalidFile(request);
}
String unformattedSource = contents.data;
int start = params.selectionOffset;
int length = params.selectionLength;
// No need to preserve 0,0 selection
if (start == 0 && length == 0) {
start = null;
length = null;
}
SourceCode code = new SourceCode(unformattedSource,
uri: null,
isCompilationUnit: true,
selectionStart: start,
selectionLength: length);
DartFormatter formatter = new DartFormatter();
SourceCode formattedResult;
try {
formattedResult = formatter.formatSource(code);
} on FormatterException {
return new Response.formatWithErrors(request);
}
String formattedSource = formattedResult.text;
List<SourceEdit> edits = <SourceEdit>[];
if (formattedSource != unformattedSource) {
//TODO: replace full replacements with smaller, more targeted edits
SourceEdit edit =
new SourceEdit(0, unformattedSource.length, formattedSource);
edits.add(edit);
}
int newStart = formattedResult.selectionStart;
int newLength = formattedResult.selectionLength;
// Sending null start/length values would violate protocol, so convert back
// to 0.
if (newStart == null) {
newStart = 0;
}
if (newLength == null) {
newLength = 0;
}
return new EditFormatResult(edits, newStart, newLength)
.toResponse(request.id);
}
Response getAssists(Request request) {
EditGetAssistsParams params = new EditGetAssistsParams.fromRequest(request);
ContextSourcePair pair = server.getContextSourcePair(params.file);
engine.AnalysisContext context = pair.context;
Source source = pair.source;
List<SourceChange> changes = <SourceChange>[];
if (context != null && source != null) {
List<Assist> assists =
computeAssists(plugin, context, source, params.offset, params.length);
assists.forEach((Assist assist) {
changes.add(assist.change);
});
}
return new EditGetAssistsResult(changes).toResponse(request.id);
}
Response getFixes(Request request) {
var params = new EditGetFixesParams.fromRequest(request);
String file = params.file;
int offset = params.offset;
// add fixes
List<AnalysisErrorFixes> errorFixesList = <AnalysisErrorFixes>[];
List<CompilationUnit> units = server.getResolvedCompilationUnits(file);
for (CompilationUnit unit in units) {
engine.AnalysisErrorInfo errorInfo = server.getErrors(file);
if (errorInfo != null) {
LineInfo lineInfo = errorInfo.lineInfo;
int requestLine = lineInfo.getLocation(offset).lineNumber;
for (engine.AnalysisError error in errorInfo.errors) {
int errorLine = lineInfo.getLocation(error.offset).lineNumber;
if (errorLine == requestLine) {
List<Fix> fixes = computeFixes(plugin, unit.element.context, error);
if (fixes.isNotEmpty) {
AnalysisError serverError =
newAnalysisError_fromEngine(lineInfo, error);
AnalysisErrorFixes errorFixes =
new AnalysisErrorFixes(serverError);
errorFixesList.add(errorFixes);
fixes.forEach((fix) {
errorFixes.fixes.add(fix.change);
});
}
}
}
}
}
// respond
return new EditGetFixesResult(errorFixesList).toResponse(request.id);
}
@override
Response handleRequest(Request request) {
try {
String requestName = request.method;
if (requestName == EDIT_FORMAT) {
return format(request);
} else if (requestName == EDIT_GET_ASSISTS) {
return getAssists(request);
} else if (requestName == EDIT_GET_AVAILABLE_REFACTORINGS) {
return _getAvailableRefactorings(request);
} else if (requestName == EDIT_GET_FIXES) {
return getFixes(request);
} else if (requestName == EDIT_GET_REFACTORING) {
return _getRefactoring(request);
} else if (requestName == EDIT_SORT_MEMBERS) {
return sortMembers(request);
}
} on RequestFailure catch (exception) {
return exception.response;
}
return null;
}
Response sortMembers(Request request) {
var params = new EditSortMembersParams.fromRequest(request);
// prepare file
String file = params.file;
if (!engine.AnalysisEngine.isDartFileName(file)) {
return new Response.sortMembersInvalidFile(request);
}
// prepare resolved units
List<CompilationUnit> units = server.getResolvedCompilationUnits(file);
if (units.isEmpty) {
return new Response.sortMembersInvalidFile(request);
}
// prepare context
CompilationUnit unit = units.first;
engine.AnalysisContext context = unit.element.context;
Source source = unit.element.source;
// check if there are no scan/parse errors in the file
engine.AnalysisErrorInfo errors = context.getErrors(source);
int numScanParseErrors = 0;
errors.errors.forEach((engine.AnalysisError error) {
if (error.errorCode is engine.ScannerErrorCode ||
error.errorCode is engine.ParserErrorCode) {
numScanParseErrors++;
}
});
if (numScanParseErrors != 0) {
return new Response.sortMembersParseErrors(request, numScanParseErrors);
}
// do sort
int fileStamp = context.getModificationStamp(source);
String code = context.getContents(source).data;
MemberSorter sorter = new MemberSorter(code, unit);
List<SourceEdit> edits = sorter.sort();
SourceFileEdit fileEdit = new SourceFileEdit(file, fileStamp, edits: edits);
return new EditSortMembersResult(fileEdit).toResponse(request.id);
}
Response _getAvailableRefactorings(Request request) {
if (searchEngine == null) {
return new Response.noIndexGenerated(request);
}
_getAvailableRefactoringsImpl(request);
return Response.DELAYED_RESPONSE;
}
Future _getAvailableRefactoringsImpl(Request request) async {
// prepare parameters
var params = new EditGetAvailableRefactoringsParams.fromRequest(request);
String file = params.file;
int offset = params.offset;
int length = params.length;
// add refactoring kinds
List<RefactoringKind> kinds = <RefactoringKind>[];
// try EXTRACT_*
if (length != 0) {
kinds.add(RefactoringKind.EXTRACT_LOCAL_VARIABLE);
kinds.add(RefactoringKind.EXTRACT_METHOD);
}
// check elements
{
List<Element> elements = server.getElementsAtOffset(file, offset);
if (elements.isNotEmpty) {
Element element = elements[0];
// try CONVERT_METHOD_TO_GETTER
if (element is ExecutableElement) {
Refactoring refactoring =
new ConvertMethodToGetterRefactoring(searchEngine, element);
RefactoringStatus status = await refactoring.checkInitialConditions();
if (!status.hasFatalError) {
kinds.add(RefactoringKind.CONVERT_METHOD_TO_GETTER);
}
}
// try RENAME
{
RenameRefactoring renameRefactoring =
new RenameRefactoring(searchEngine, element);
if (renameRefactoring != null) {
kinds.add(RefactoringKind.RENAME);
}
}
}
}
// respond
var result = new EditGetAvailableRefactoringsResult(kinds);
server.sendResponse(result.toResponse(request.id));
}
Response _getRefactoring(Request request) {
if (searchEngine == null) {
return new Response.noIndexGenerated(request);
}
if (refactoringManager.hasPendingRequest) {
refactoringManager.cancel();
_newRefactoringManager();
}
refactoringManager.getRefactoring(request);
return Response.DELAYED_RESPONSE;
}
/**
* Initializes [refactoringManager] with a new instance.
*/
void _newRefactoringManager() {
refactoringManager = new _RefactoringManager(server, searchEngine);
}
}
/**
* An object managing a single [Refactoring] instance.
*
* The instance is identified by its kind, file, offset and length.
* It is initialized when the a set of parameters is given for the first time.
* All subsequent requests are performed on this [Refactoring] instance.
*
* Once new set of parameters is received, the previous [Refactoring] instance
* is invalidated and a new one is created and initialized.
*/
class _RefactoringManager {
static const List<RefactoringProblem> EMPTY_PROBLEM_LIST =
const <RefactoringProblem>[];
final AnalysisServer server;
final SearchEngine searchEngine;
StreamSubscription onAnalysisStartedSubscription;
RefactoringKind kind;
String file;
int offset;
int length;
Refactoring refactoring;
RefactoringFeedback feedback;
RefactoringStatus initStatus;
RefactoringStatus optionsStatus;
RefactoringStatus finalStatus;
Request request;
EditGetRefactoringResult result;
_RefactoringManager(this.server, this.searchEngine) {
onAnalysisStartedSubscription = server.onAnalysisStarted.listen(_reset);
_reset();
}
/**
* Returns `true` if a response for the current request has not yet been sent.
*/
bool get hasPendingRequest => request != null;
bool get _hasFatalError {
return initStatus.hasFatalError ||
optionsStatus.hasFatalError ||
finalStatus.hasFatalError;
}
/**
* Checks if [refactoring] requires options.
*/
bool get _requiresOptions {
return refactoring is ExtractLocalRefactoring ||
refactoring is ExtractMethodRefactoring ||
refactoring is InlineMethodRefactoring ||
refactoring is MoveFileRefactoring ||
refactoring is RenameRefactoring;
}
/**
* Cancels processing of the current request and cleans up.
*/
void cancel() {
onAnalysisStartedSubscription.cancel();
server.sendResponse(new Response.refactoringRequestCancelled(request));
request = null;
}
void getRefactoring(Request _request) {
// prepare for processing the request
request = _request;
result = new EditGetRefactoringResult(
EMPTY_PROBLEM_LIST, EMPTY_PROBLEM_LIST, EMPTY_PROBLEM_LIST);
// process the request
var params = new EditGetRefactoringParams.fromRequest(_request);
runZoned(() async {
await _init(params.kind, params.file, params.offset, params.length);
if (initStatus.hasFatalError) {
feedback = null;
_sendResultResponse();
return;
}
// set options
if (_requiresOptions) {
if (params.options == null) {
optionsStatus = new RefactoringStatus();
_sendResultResponse();
return;
}
optionsStatus = _setOptions(params);
if (_hasFatalError) {
_sendResultResponse();
return;
}
}
// done if just validation
if (params.validateOnly) {
finalStatus = new RefactoringStatus();
_sendResultResponse();
return;
}
// simulate an exception
if (test_simulateRefactoringException_final) {
throw 'A simulated refactoring exception - final.';
}
// validation and create change
finalStatus = await refactoring.checkFinalConditions();
if (_hasFatalError) {
_sendResultResponse();
return;
}
// simulate an exception
if (test_simulateRefactoringException_change) {
throw 'A simulated refactoring exception - change.';
}
// create change
result.change = await refactoring.createChange();
result.potentialEdits = nullIfEmpty(refactoring.potentialEditIds);
_sendResultResponse();
}, onError: (exception, stackTrace) {
server.instrumentationService.logException(exception, stackTrace);
server.sendResponse(
new Response.serverError(_request, exception, stackTrace));
_reset();
});
}
/**
* Initializes this context to perform a refactoring with the specified
* parameters. The existing [Refactoring] is reused or created as needed.
*/
Future _init(
RefactoringKind kind, String file, int offset, int length) async {
await server.onAnalysisComplete;
// check if we can continue with the existing Refactoring instance
if (this.kind == kind &&
this.file == file &&
this.offset == offset &&
this.length == length) {
return;
}
_reset();
this.kind = kind;
this.file = file;
this.offset = offset;
this.length = length;
// simulate an exception
if (test_simulateRefactoringException_init) {
throw 'A simulated refactoring exception - init.';
}
// create a new Refactoring instance
if (kind == RefactoringKind.CONVERT_GETTER_TO_METHOD) {
List<Element> elements = server.getElementsAtOffset(file, offset);
if (elements.isNotEmpty) {
Element element = elements[0];
if (element is ExecutableElement) {
refactoring =
new ConvertGetterToMethodRefactoring(searchEngine, element);
}
}
}
if (kind == RefactoringKind.CONVERT_METHOD_TO_GETTER) {
List<Element> elements = server.getElementsAtOffset(file, offset);
if (elements.isNotEmpty) {
Element element = elements[0];
if (element is ExecutableElement) {
refactoring =
new ConvertMethodToGetterRefactoring(searchEngine, element);
}
}
}
if (kind == RefactoringKind.EXTRACT_LOCAL_VARIABLE) {
List<CompilationUnit> units = server.getResolvedCompilationUnits(file);
if (units.isNotEmpty) {
refactoring = new ExtractLocalRefactoring(units[0], offset, length);
feedback = new ExtractLocalVariableFeedback([], [], []);
}
}
if (kind == RefactoringKind.EXTRACT_METHOD) {
List<CompilationUnit> units = server.getResolvedCompilationUnits(file);
if (units.isNotEmpty) {
refactoring = new ExtractMethodRefactoring(
searchEngine, units[0], offset, length);
feedback = new ExtractMethodFeedback(
offset, length, '', [], false, [], [], []);
}
}
if (kind == RefactoringKind.INLINE_LOCAL_VARIABLE) {
List<CompilationUnit> units = server.getResolvedCompilationUnits(file);
if (units.isNotEmpty) {
refactoring =
new InlineLocalRefactoring(searchEngine, units[0], offset);
}
}
if (kind == RefactoringKind.INLINE_METHOD) {
List<CompilationUnit> units = server.getResolvedCompilationUnits(file);
if (units.isNotEmpty) {
refactoring =
new InlineMethodRefactoring(searchEngine, units[0], offset);
}
}
if (kind == RefactoringKind.MOVE_FILE) {
ContextSourcePair contextSource = server.getContextSourcePair(file);
engine.AnalysisContext context = contextSource.context;
Source source = contextSource.source;
refactoring = new MoveFileRefactoring(
server.resourceProvider, searchEngine, context, source, file);
}
if (kind == RefactoringKind.RENAME) {
List<AstNode> nodes = server.getNodesAtOffset(file, offset);
List<Element> elements = server.getElementsOfNodes(nodes, offset);
if (nodes.isNotEmpty && elements.isNotEmpty) {
AstNode node = nodes[0];
Element element = elements[0];
if (element is FieldFormalParameterElement) {
element = (element as FieldFormalParameterElement).field;
}
// climb from "Class" in "new Class.named()" to "Class.named"
if (node.parent is TypeName && node.parent.parent is ConstructorName) {
ConstructorName constructor = node.parent.parent;
node = constructor;
element = constructor.staticElement;
}
// do create the refactoring
refactoring = new RenameRefactoring(searchEngine, element);
feedback =
new RenameFeedback(node.offset, node.length, 'kind', 'oldName');
}
}
if (refactoring == null) {
initStatus =
new RefactoringStatus.fatal('Unable to create a refactoring');
return;
}
// check initial conditions
initStatus = await refactoring.checkInitialConditions();
if (refactoring is ExtractLocalRefactoring) {
ExtractLocalRefactoring refactoring = this.refactoring;
ExtractLocalVariableFeedback feedback = this.feedback;
feedback.names = refactoring.names;
feedback.offsets = refactoring.offsets;
feedback.lengths = refactoring.lengths;
}
if (refactoring is ExtractMethodRefactoring) {
ExtractMethodRefactoring refactoring = this.refactoring;
ExtractMethodFeedback feedback = this.feedback;
feedback.canCreateGetter = refactoring.canCreateGetter;
feedback.returnType = refactoring.returnType;
feedback.names = refactoring.names;
feedback.parameters = refactoring.parameters;
feedback.offsets = refactoring.offsets;
feedback.lengths = refactoring.lengths;
}
if (refactoring is InlineLocalRefactoring) {
InlineLocalRefactoring refactoring = this.refactoring;
if (!initStatus.hasFatalError) {
feedback = new InlineLocalVariableFeedback(
refactoring.variableName, refactoring.referenceCount);
}
}
if (refactoring is InlineMethodRefactoring) {
InlineMethodRefactoring refactoring = this.refactoring;
if (!initStatus.hasFatalError) {
feedback = new InlineMethodFeedback(
refactoring.methodName, refactoring.isDeclaration,
className: refactoring.className);
}
}
if (refactoring is RenameRefactoring) {
RenameRefactoring refactoring = this.refactoring;
RenameFeedback feedback = this.feedback;
feedback.elementKindName = refactoring.elementKindName;
feedback.oldName = refactoring.oldName;
}
}
void _reset([engine.AnalysisContext context]) {
kind = null;
offset = null;
length = null;
refactoring = null;
feedback = null;
initStatus = new RefactoringStatus();
optionsStatus = new RefactoringStatus();
finalStatus = new RefactoringStatus();
}
void _sendResultResponse() {
// ignore if was cancelled
if (request == null) {
return;
}
// set feedback
result.feedback = feedback;
// set problems
result.initialProblems = initStatus.problems;
result.optionsProblems = optionsStatus.problems;
result.finalProblems = finalStatus.problems;
// send the response
server.sendResponse(result.toResponse(request.id));
// done with this request
request = null;
result = null;
}
RefactoringStatus _setOptions(EditGetRefactoringParams params) {
if (refactoring is ExtractLocalRefactoring) {
ExtractLocalRefactoring extractRefactoring = refactoring;
ExtractLocalVariableOptions extractOptions = params.options;
extractRefactoring.name = extractOptions.name;
extractRefactoring.extractAll = extractOptions.extractAll;
return extractRefactoring.checkName();
}
if (refactoring is ExtractMethodRefactoring) {
ExtractMethodRefactoring extractRefactoring = this.refactoring;
ExtractMethodOptions extractOptions = params.options;
extractRefactoring.createGetter = extractOptions.createGetter;
extractRefactoring.extractAll = extractOptions.extractAll;
extractRefactoring.name = extractOptions.name;
if (extractOptions.parameters != null) {
extractRefactoring.parameters = extractOptions.parameters;
}
extractRefactoring.returnType = extractOptions.returnType;
return extractRefactoring.checkName();
}
if (refactoring is InlineMethodRefactoring) {
InlineMethodRefactoring inlineRefactoring = this.refactoring;
InlineMethodOptions inlineOptions = params.options;
inlineRefactoring.deleteSource = inlineOptions.deleteSource;
inlineRefactoring.inlineAll = inlineOptions.inlineAll;
return new RefactoringStatus();
}
if (refactoring is MoveFileRefactoring) {
MoveFileRefactoring moveRefactoring = this.refactoring;
MoveFileOptions moveOptions = params.options;
moveRefactoring.newFile = moveOptions.newFile;
return new RefactoringStatus();
}
if (refactoring is RenameRefactoring) {
RenameRefactoring renameRefactoring = refactoring;
RenameOptions renameOptions = params.options;
renameRefactoring.newName = renameOptions.newName;
return renameRefactoring.checkNewName();
}
return new RefactoringStatus();
}
}
|
{
"pile_set_name": "Github"
}
|
<?xml version="1.0" encoding="UTF-8" ?>
<!--
Copyright (c) 2003-2004,-2010 Oracle and/or its affiliates. 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 Oracle 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.
-->
<!--
Identity transformation (changing from the J2EE namespace
to the Java EE namespace), added for flexibility.
1. Change the <taglib> element to read as follows:
<taglib xmlns="http://java.sun.com/xml/ns/j2ee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee
http://java.sun.com/xml/ns/j2ee/web-jsptaglibrary_2_0.xsd">
Author: Mark Roth
-->
<xsl:stylesheet version="1.0"
xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
xmlns:j2ee="http://java.sun.com/xml/ns/j2ee">
<xsl:output method="xml" indent="yes"/>
<xsl:template match="/j2ee:taglib">
<xsl:element name="taglib" namespace="http://java.sun.com/xml/ns/javaee">
<xsl:attribute name="xsi:schemaLocation" namespace="http://www.w3.org/2001/XMLSchema-instance">http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-jsptaglibrary_2_1.xsd</xsl:attribute>
<xsl:attribute name="version">2.1</xsl:attribute>
<xsl:apply-templates select="*"/>
</xsl:element>
</xsl:template>
<xsl:template match="j2ee:*">
<xsl:element name="{local-name()}" namespace="http://java.sun.com/xml/ns/javaee">
<xsl:copy-of select="@*"/>
<xsl:apply-templates/>
</xsl:element>
</xsl:template>
</xsl:stylesheet>
|
{
"pile_set_name": "Github"
}
|
angular.module('platformWebApp')
.controller('platformWebApp.assets.assetSelectController', ['$scope', 'platformWebApp.assets.api', 'platformWebApp.bladeNavigationService', 'platformWebApp.bladeUtils', 'platformWebApp.uiGridHelper',
function ($scope, assetsApi, bladeNavigationService, bladeUtils, uiGridHelper) {
var blade = $scope.blade;
blade.template = '$(Platform)/Scripts/app/assets/blades/asset-select.tpl.html';
blade.headIcon = 'fa-folder-o';
if (!blade.currentEntity) {
blade.currentEntity = {};
}
if (blade.folder) {
blade.currentEntity.url = '/' + blade.folder;
}
blade.refresh = function () {
blade.isLoading = true;
assetsApi.search(
{
keyword: blade.searchKeyword,
folderUrl: blade.currentEntity.url
},
function (data) {
$scope.pageSettings.totalItems = data.totalCount;
_.each(data.results, function (x) { x.isImage = x.contentType && x.contentType.startsWith('image/'); });
$scope.listEntries = data.results;
blade.isLoading = false;
//Set navigation breadcrumbs
setBreadcrumbs();
}, function (error) {
bladeNavigationService.setError('Error ' + error.status, blade);
});
};
//Breadcrumbs
function setBreadcrumbs() {
if (blade.breadcrumbs) {
//Clone array (angular.copy leaves the same reference)
var breadcrumbs = blade.breadcrumbs.slice(0);
//prevent duplicate items
if (blade.currentEntity.url && _.all(breadcrumbs, function (x) { return x.id !== blade.currentEntity.url; })) {
var breadCrumb = generateBreadcrumb(blade.currentEntity.url, blade.currentEntity.name);
breadcrumbs.push(breadCrumb);
}
blade.breadcrumbs = breadcrumbs;
} else {
var name = "all";
if (blade.folder)
name = blade.folder;
blade.breadcrumbs = [generateBreadcrumb(blade.currentEntity.url, name)];
}
}
function generateBreadcrumb(id, name) {
return {
id: id,
name: name,
blade: blade,
navigate: function (breadcrumb) {
bladeNavigationService.closeBlade(blade,
function () {
blade.disableOpenAnimation = true;
bladeNavigationService.showBlade(blade, blade.parentBlade);
});
}
}
}
function isItemsChecked() {
return $scope.gridApi && _.any($scope.gridApi.selection.getSelectedRows());
}
function getSelectedAssets() {
return $scope.gridApi.selection.getSelectedRows();
}
$scope.selectNode = function (listItem) {
if (listItem.type === 'folder') {
var newBlade = {
id: blade.id,
title: blade.title,
breadcrumbs: blade.breadcrumbs,
currentEntity: listItem,
disableOpenAnimation: true,
controller: blade.controller,
template: blade.template,
isClosingDisabled: blade.isClosingDisabled,
onSelect: blade.onSelect
};
bladeNavigationService.showBlade(newBlade, blade.parentBlade);
}
};
blade.toolbarCommands = [
{
name: 'platform.commands.confirm',
icon: 'fa fa-check',
executeMethod: function () { $scope.saveChanges(); },
canExecuteMethod: function () {
return isItemsChecked();
}
}
];
$scope.saveChanges = function () {
if (blade.onSelect)
blade.onSelect(getSelectedAssets());
$scope.bladeClose();
};
// ui-grid
$scope.setGridOptions = function (gridOptions) {
uiGridHelper.initialize($scope, gridOptions,
function (gridApi) {
$scope.$watch('pageSettings.currentPage', gridApi.pagination.seek);
});
};
bladeUtils.initializePagination($scope, true);
blade.refresh();
}]);
|
{
"pile_set_name": "Github"
}
|
/*
* An implementation of key value pair (KVP) functionality for Linux.
*
*
* Copyright (C) 2010, Novell, Inc.
* Author : K. Y. Srinivasan <[email protected]>
*
* 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, GOOD TITLE or
* NON INFRINGEMENT. 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 St, Fifth Floor, Boston, MA 02110-1301 USA.
*
*/
#include <sys/types.h>
#include <sys/socket.h>
#include <sys/poll.h>
#include <sys/utsname.h>
#include <linux/types.h>
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <string.h>
#include <errno.h>
#include <arpa/inet.h>
#include <linux/connector.h>
#include <linux/hyperv.h>
#include <linux/netlink.h>
#include <ifaddrs.h>
#include <netdb.h>
#include <syslog.h>
#include <sys/stat.h>
#include <fcntl.h>
/*
* KVP protocol: The user mode component first registers with the
* the kernel component. Subsequently, the kernel component requests, data
* for the specified keys. In response to this message the user mode component
* fills in the value corresponding to the specified key. We overload the
* sequence field in the cn_msg header to define our KVP message types.
*
* We use this infrastructure for also supporting queries from user mode
* application for state that may be maintained in the KVP kernel component.
*
*/
enum key_index {
FullyQualifiedDomainName = 0,
IntegrationServicesVersion, /*This key is serviced in the kernel*/
NetworkAddressIPv4,
NetworkAddressIPv6,
OSBuildNumber,
OSName,
OSMajorVersion,
OSMinorVersion,
OSVersion,
ProcessorArchitecture
};
static char kvp_send_buffer[4096];
static char kvp_recv_buffer[4096];
static struct sockaddr_nl addr;
static char *os_name = "";
static char *os_major = "";
static char *os_minor = "";
static char *processor_arch;
static char *os_build;
static char *lic_version;
static struct utsname uts_buf;
#define MAX_FILE_NAME 100
#define ENTRIES_PER_BLOCK 50
struct kvp_record {
__u8 key[HV_KVP_EXCHANGE_MAX_KEY_SIZE];
__u8 value[HV_KVP_EXCHANGE_MAX_VALUE_SIZE];
};
struct kvp_file_state {
int fd;
int num_blocks;
struct kvp_record *records;
int num_records;
__u8 fname[MAX_FILE_NAME];
};
static struct kvp_file_state kvp_file_info[KVP_POOL_COUNT];
static void kvp_acquire_lock(int pool)
{
struct flock fl = {F_WRLCK, SEEK_SET, 0, 0, 0};
fl.l_pid = getpid();
if (fcntl(kvp_file_info[pool].fd, F_SETLKW, &fl) == -1) {
syslog(LOG_ERR, "Failed to acquire the lock pool: %d", pool);
exit(-1);
}
}
static void kvp_release_lock(int pool)
{
struct flock fl = {F_UNLCK, SEEK_SET, 0, 0, 0};
fl.l_pid = getpid();
if (fcntl(kvp_file_info[pool].fd, F_SETLK, &fl) == -1) {
perror("fcntl");
syslog(LOG_ERR, "Failed to release the lock pool: %d", pool);
exit(-1);
}
}
static void kvp_update_file(int pool)
{
FILE *filep;
size_t bytes_written;
/*
* We are going to write our in-memory registry out to
* disk; acquire the lock first.
*/
kvp_acquire_lock(pool);
filep = fopen(kvp_file_info[pool].fname, "w");
if (!filep) {
kvp_release_lock(pool);
syslog(LOG_ERR, "Failed to open file, pool: %d", pool);
exit(-1);
}
bytes_written = fwrite(kvp_file_info[pool].records,
sizeof(struct kvp_record),
kvp_file_info[pool].num_records, filep);
fflush(filep);
kvp_release_lock(pool);
}
static void kvp_update_mem_state(int pool)
{
FILE *filep;
size_t records_read = 0;
struct kvp_record *record = kvp_file_info[pool].records;
struct kvp_record *readp;
int num_blocks = kvp_file_info[pool].num_blocks;
int alloc_unit = sizeof(struct kvp_record) * ENTRIES_PER_BLOCK;
kvp_acquire_lock(pool);
filep = fopen(kvp_file_info[pool].fname, "r");
if (!filep) {
kvp_release_lock(pool);
syslog(LOG_ERR, "Failed to open file, pool: %d", pool);
exit(-1);
}
while (!feof(filep)) {
readp = &record[records_read];
records_read += fread(readp, sizeof(struct kvp_record),
ENTRIES_PER_BLOCK * num_blocks,
filep);
if (!feof(filep)) {
/*
* We have more data to read.
*/
num_blocks++;
record = realloc(record, alloc_unit * num_blocks);
if (record == NULL) {
syslog(LOG_ERR, "malloc failed");
exit(-1);
}
continue;
}
break;
}
kvp_file_info[pool].num_blocks = num_blocks;
kvp_file_info[pool].records = record;
kvp_file_info[pool].num_records = records_read;
kvp_release_lock(pool);
}
static int kvp_file_init(void)
{
int ret, fd;
FILE *filep;
size_t records_read;
__u8 *fname;
struct kvp_record *record;
struct kvp_record *readp;
int num_blocks;
int i;
int alloc_unit = sizeof(struct kvp_record) * ENTRIES_PER_BLOCK;
if (access("/var/opt/hyperv", F_OK)) {
if (mkdir("/var/opt/hyperv", S_IRUSR | S_IWUSR | S_IROTH)) {
syslog(LOG_ERR, " Failed to create /var/opt/hyperv");
exit(-1);
}
}
for (i = 0; i < KVP_POOL_COUNT; i++) {
fname = kvp_file_info[i].fname;
records_read = 0;
num_blocks = 1;
sprintf(fname, "/var/opt/hyperv/.kvp_pool_%d", i);
fd = open(fname, O_RDWR | O_CREAT, S_IRUSR | S_IWUSR | S_IROTH);
if (fd == -1)
return 1;
filep = fopen(fname, "r");
if (!filep)
return 1;
record = malloc(alloc_unit * num_blocks);
if (record == NULL) {
fclose(filep);
return 1;
}
while (!feof(filep)) {
readp = &record[records_read];
records_read += fread(readp, sizeof(struct kvp_record),
ENTRIES_PER_BLOCK,
filep);
if (!feof(filep)) {
/*
* We have more data to read.
*/
num_blocks++;
record = realloc(record, alloc_unit *
num_blocks);
if (record == NULL) {
fclose(filep);
return 1;
}
continue;
}
break;
}
kvp_file_info[i].fd = fd;
kvp_file_info[i].num_blocks = num_blocks;
kvp_file_info[i].records = record;
kvp_file_info[i].num_records = records_read;
fclose(filep);
}
return 0;
}
static int kvp_key_delete(int pool, __u8 *key, int key_size)
{
int i;
int j, k;
int num_records;
struct kvp_record *record;
/*
* First update the in-memory state.
*/
kvp_update_mem_state(pool);
num_records = kvp_file_info[pool].num_records;
record = kvp_file_info[pool].records;
for (i = 0; i < num_records; i++) {
if (memcmp(key, record[i].key, key_size))
continue;
/*
* Found a match; just move the remaining
* entries up.
*/
if (i == num_records) {
kvp_file_info[pool].num_records--;
kvp_update_file(pool);
return 0;
}
j = i;
k = j + 1;
for (; k < num_records; k++) {
strcpy(record[j].key, record[k].key);
strcpy(record[j].value, record[k].value);
j++;
}
kvp_file_info[pool].num_records--;
kvp_update_file(pool);
return 0;
}
return 1;
}
static int kvp_key_add_or_modify(int pool, __u8 *key, int key_size, __u8 *value,
int value_size)
{
int i;
int j, k;
int num_records;
struct kvp_record *record;
int num_blocks;
if ((key_size > HV_KVP_EXCHANGE_MAX_KEY_SIZE) ||
(value_size > HV_KVP_EXCHANGE_MAX_VALUE_SIZE))
return 1;
/*
* First update the in-memory state.
*/
kvp_update_mem_state(pool);
num_records = kvp_file_info[pool].num_records;
record = kvp_file_info[pool].records;
num_blocks = kvp_file_info[pool].num_blocks;
for (i = 0; i < num_records; i++) {
if (memcmp(key, record[i].key, key_size))
continue;
/*
* Found a match; just update the value -
* this is the modify case.
*/
memcpy(record[i].value, value, value_size);
kvp_update_file(pool);
return 0;
}
/*
* Need to add a new entry;
*/
if (num_records == (ENTRIES_PER_BLOCK * num_blocks)) {
/* Need to allocate a larger array for reg entries. */
record = realloc(record, sizeof(struct kvp_record) *
ENTRIES_PER_BLOCK * (num_blocks + 1));
if (record == NULL)
return 1;
kvp_file_info[pool].num_blocks++;
}
memcpy(record[i].value, value, value_size);
memcpy(record[i].key, key, key_size);
kvp_file_info[pool].records = record;
kvp_file_info[pool].num_records++;
kvp_update_file(pool);
return 0;
}
static int kvp_get_value(int pool, __u8 *key, int key_size, __u8 *value,
int value_size)
{
int i;
int num_records;
struct kvp_record *record;
if ((key_size > HV_KVP_EXCHANGE_MAX_KEY_SIZE) ||
(value_size > HV_KVP_EXCHANGE_MAX_VALUE_SIZE))
return 1;
/*
* First update the in-memory state.
*/
kvp_update_mem_state(pool);
num_records = kvp_file_info[pool].num_records;
record = kvp_file_info[pool].records;
for (i = 0; i < num_records; i++) {
if (memcmp(key, record[i].key, key_size))
continue;
/*
* Found a match; just copy the value out.
*/
memcpy(value, record[i].value, value_size);
return 0;
}
return 1;
}
static void kvp_pool_enumerate(int pool, int index, __u8 *key, int key_size,
__u8 *value, int value_size)
{
struct kvp_record *record;
/*
* First update our in-memory database.
*/
kvp_update_mem_state(pool);
record = kvp_file_info[pool].records;
if (index >= kvp_file_info[pool].num_records) {
/*
* This is an invalid index; terminate enumeration;
* - a NULL value will do the trick.
*/
strcpy(value, "");
return;
}
memcpy(key, record[index].key, key_size);
memcpy(value, record[index].value, value_size);
}
void kvp_get_os_info(void)
{
FILE *file;
char *p, buf[512];
uname(&uts_buf);
os_build = uts_buf.release;
processor_arch = uts_buf.machine;
/*
* The current windows host (win7) expects the build
* string to be of the form: x.y.z
* Strip additional information we may have.
*/
p = strchr(os_build, '-');
if (p)
*p = '\0';
file = fopen("/etc/SuSE-release", "r");
if (file != NULL)
goto kvp_osinfo_found;
file = fopen("/etc/redhat-release", "r");
if (file != NULL)
goto kvp_osinfo_found;
/*
* Add code for other supported platforms.
*/
/*
* We don't have information about the os.
*/
os_name = uts_buf.sysname;
return;
kvp_osinfo_found:
/* up to three lines */
p = fgets(buf, sizeof(buf), file);
if (p) {
p = strchr(buf, '\n');
if (p)
*p = '\0';
p = strdup(buf);
if (!p)
goto done;
os_name = p;
/* second line */
p = fgets(buf, sizeof(buf), file);
if (p) {
p = strchr(buf, '\n');
if (p)
*p = '\0';
p = strdup(buf);
if (!p)
goto done;
os_major = p;
/* third line */
p = fgets(buf, sizeof(buf), file);
if (p) {
p = strchr(buf, '\n');
if (p)
*p = '\0';
p = strdup(buf);
if (p)
os_minor = p;
}
}
}
done:
fclose(file);
return;
}
static int
kvp_get_ip_address(int family, char *buffer, int length)
{
struct ifaddrs *ifap;
struct ifaddrs *curp;
int ipv4_len = strlen("255.255.255.255") + 1;
int ipv6_len = strlen("ffff:ffff:ffff:ffff:ffff:ffff:ffff:ffff")+1;
int offset = 0;
const char *str;
char tmp[50];
int error = 0;
/*
* On entry into this function, the buffer is capable of holding the
* maximum key value (2048 bytes).
*/
if (getifaddrs(&ifap)) {
strcpy(buffer, "getifaddrs failed\n");
return 1;
}
curp = ifap;
while (curp != NULL) {
if ((curp->ifa_addr != NULL) &&
(curp->ifa_addr->sa_family == family)) {
if (family == AF_INET) {
struct sockaddr_in *addr =
(struct sockaddr_in *) curp->ifa_addr;
str = inet_ntop(family, &addr->sin_addr,
tmp, 50);
if (str == NULL) {
strcpy(buffer, "inet_ntop failed\n");
error = 1;
goto getaddr_done;
}
if (offset == 0)
strcpy(buffer, tmp);
else
strcat(buffer, tmp);
strcat(buffer, ";");
offset += strlen(str) + 1;
if ((length - offset) < (ipv4_len + 1))
goto getaddr_done;
} else {
/*
* We only support AF_INET and AF_INET6
* and the list of addresses is separated by a ";".
*/
struct sockaddr_in6 *addr =
(struct sockaddr_in6 *) curp->ifa_addr;
str = inet_ntop(family,
&addr->sin6_addr.s6_addr,
tmp, 50);
if (str == NULL) {
strcpy(buffer, "inet_ntop failed\n");
error = 1;
goto getaddr_done;
}
if (offset == 0)
strcpy(buffer, tmp);
else
strcat(buffer, tmp);
strcat(buffer, ";");
offset += strlen(str) + 1;
if ((length - offset) < (ipv6_len + 1))
goto getaddr_done;
}
}
curp = curp->ifa_next;
}
getaddr_done:
freeifaddrs(ifap);
return error;
}
static int
kvp_get_domain_name(char *buffer, int length)
{
struct addrinfo hints, *info ;
int error = 0;
gethostname(buffer, length);
memset(&hints, 0, sizeof(hints));
hints.ai_family = AF_INET; /*Get only ipv4 addrinfo. */
hints.ai_socktype = SOCK_STREAM;
hints.ai_flags = AI_CANONNAME;
error = getaddrinfo(buffer, NULL, &hints, &info);
if (error != 0) {
strcpy(buffer, "getaddrinfo failed\n");
return error;
}
strcpy(buffer, info->ai_canonname);
freeaddrinfo(info);
return error;
}
static int
netlink_send(int fd, struct cn_msg *msg)
{
struct nlmsghdr *nlh;
unsigned int size;
struct msghdr message;
char buffer[64];
struct iovec iov[2];
size = NLMSG_SPACE(sizeof(struct cn_msg) + msg->len);
nlh = (struct nlmsghdr *)buffer;
nlh->nlmsg_seq = 0;
nlh->nlmsg_pid = getpid();
nlh->nlmsg_type = NLMSG_DONE;
nlh->nlmsg_len = NLMSG_LENGTH(size - sizeof(*nlh));
nlh->nlmsg_flags = 0;
iov[0].iov_base = nlh;
iov[0].iov_len = sizeof(*nlh);
iov[1].iov_base = msg;
iov[1].iov_len = size;
memset(&message, 0, sizeof(message));
message.msg_name = &addr;
message.msg_namelen = sizeof(addr);
message.msg_iov = iov;
message.msg_iovlen = 2;
return sendmsg(fd, &message, 0);
}
int main(void)
{
int fd, len, sock_opt;
int error;
struct cn_msg *message;
struct pollfd pfd;
struct nlmsghdr *incoming_msg;
struct cn_msg *incoming_cn_msg;
struct hv_kvp_msg *hv_msg;
char *p;
char *key_value;
char *key_name;
daemon(1, 0);
openlog("KVP", 0, LOG_USER);
syslog(LOG_INFO, "KVP starting; pid is:%d", getpid());
/*
* Retrieve OS release information.
*/
kvp_get_os_info();
if (kvp_file_init()) {
syslog(LOG_ERR, "Failed to initialize the pools");
exit(-1);
}
fd = socket(AF_NETLINK, SOCK_DGRAM, NETLINK_CONNECTOR);
if (fd < 0) {
syslog(LOG_ERR, "netlink socket creation failed; error:%d", fd);
exit(-1);
}
addr.nl_family = AF_NETLINK;
addr.nl_pad = 0;
addr.nl_pid = 0;
addr.nl_groups = CN_KVP_IDX;
error = bind(fd, (struct sockaddr *)&addr, sizeof(addr));
if (error < 0) {
syslog(LOG_ERR, "bind failed; error:%d", error);
close(fd);
exit(-1);
}
sock_opt = addr.nl_groups;
setsockopt(fd, 270, 1, &sock_opt, sizeof(sock_opt));
/*
* Register ourselves with the kernel.
*/
message = (struct cn_msg *)kvp_send_buffer;
message->id.idx = CN_KVP_IDX;
message->id.val = CN_KVP_VAL;
hv_msg = (struct hv_kvp_msg *)message->data;
hv_msg->kvp_hdr.operation = KVP_OP_REGISTER;
message->ack = 0;
message->len = sizeof(struct hv_kvp_msg);
len = netlink_send(fd, message);
if (len < 0) {
syslog(LOG_ERR, "netlink_send failed; error:%d", len);
close(fd);
exit(-1);
}
pfd.fd = fd;
while (1) {
pfd.events = POLLIN;
pfd.revents = 0;
poll(&pfd, 1, -1);
len = recv(fd, kvp_recv_buffer, sizeof(kvp_recv_buffer), 0);
if (len < 0) {
syslog(LOG_ERR, "recv failed; error:%d", len);
close(fd);
return -1;
}
incoming_msg = (struct nlmsghdr *)kvp_recv_buffer;
incoming_cn_msg = (struct cn_msg *)NLMSG_DATA(incoming_msg);
hv_msg = (struct hv_kvp_msg *)incoming_cn_msg->data;
switch (hv_msg->kvp_hdr.operation) {
case KVP_OP_REGISTER:
/*
* Driver is registering with us; stash away the version
* information.
*/
p = (char *)hv_msg->body.kvp_register.version;
lic_version = malloc(strlen(p) + 1);
if (lic_version) {
strcpy(lic_version, p);
syslog(LOG_INFO, "KVP LIC Version: %s",
lic_version);
} else {
syslog(LOG_ERR, "malloc failed");
}
continue;
/*
* The current protocol with the kernel component uses a
* NULL key name to pass an error condition.
* For the SET, GET and DELETE operations,
* use the existing protocol to pass back error.
*/
case KVP_OP_SET:
if (kvp_key_add_or_modify(hv_msg->kvp_hdr.pool,
hv_msg->body.kvp_set.data.key,
hv_msg->body.kvp_set.data.key_size,
hv_msg->body.kvp_set.data.value,
hv_msg->body.kvp_set.data.value_size))
strcpy(hv_msg->body.kvp_set.data.key, "");
break;
case KVP_OP_GET:
if (kvp_get_value(hv_msg->kvp_hdr.pool,
hv_msg->body.kvp_set.data.key,
hv_msg->body.kvp_set.data.key_size,
hv_msg->body.kvp_set.data.value,
hv_msg->body.kvp_set.data.value_size))
strcpy(hv_msg->body.kvp_set.data.key, "");
break;
case KVP_OP_DELETE:
if (kvp_key_delete(hv_msg->kvp_hdr.pool,
hv_msg->body.kvp_delete.key,
hv_msg->body.kvp_delete.key_size))
strcpy(hv_msg->body.kvp_delete.key, "");
break;
default:
break;
}
if (hv_msg->kvp_hdr.operation != KVP_OP_ENUMERATE)
goto kvp_done;
/*
* If the pool is KVP_POOL_AUTO, dynamically generate
* both the key and the value; if not read from the
* appropriate pool.
*/
if (hv_msg->kvp_hdr.pool != KVP_POOL_AUTO) {
kvp_pool_enumerate(hv_msg->kvp_hdr.pool,
hv_msg->body.kvp_enum_data.index,
hv_msg->body.kvp_enum_data.data.key,
HV_KVP_EXCHANGE_MAX_KEY_SIZE,
hv_msg->body.kvp_enum_data.data.value,
HV_KVP_EXCHANGE_MAX_VALUE_SIZE);
goto kvp_done;
}
hv_msg = (struct hv_kvp_msg *)incoming_cn_msg->data;
key_name = (char *)hv_msg->body.kvp_enum_data.data.key;
key_value = (char *)hv_msg->body.kvp_enum_data.data.value;
switch (hv_msg->body.kvp_enum_data.index) {
case FullyQualifiedDomainName:
kvp_get_domain_name(key_value,
HV_KVP_EXCHANGE_MAX_VALUE_SIZE);
strcpy(key_name, "FullyQualifiedDomainName");
break;
case IntegrationServicesVersion:
strcpy(key_name, "IntegrationServicesVersion");
strcpy(key_value, lic_version);
break;
case NetworkAddressIPv4:
kvp_get_ip_address(AF_INET, key_value,
HV_KVP_EXCHANGE_MAX_VALUE_SIZE);
strcpy(key_name, "NetworkAddressIPv4");
break;
case NetworkAddressIPv6:
kvp_get_ip_address(AF_INET6, key_value,
HV_KVP_EXCHANGE_MAX_VALUE_SIZE);
strcpy(key_name, "NetworkAddressIPv6");
break;
case OSBuildNumber:
strcpy(key_value, os_build);
strcpy(key_name, "OSBuildNumber");
break;
case OSName:
strcpy(key_value, os_name);
strcpy(key_name, "OSName");
break;
case OSMajorVersion:
strcpy(key_value, os_major);
strcpy(key_name, "OSMajorVersion");
break;
case OSMinorVersion:
strcpy(key_value, os_minor);
strcpy(key_name, "OSMinorVersion");
break;
case OSVersion:
strcpy(key_value, os_build);
strcpy(key_name, "OSVersion");
break;
case ProcessorArchitecture:
strcpy(key_value, processor_arch);
strcpy(key_name, "ProcessorArchitecture");
break;
default:
strcpy(key_value, "Unknown Key");
/*
* We use a null key name to terminate enumeration.
*/
strcpy(key_name, "");
break;
}
/*
* Send the value back to the kernel. The response is
* already in the receive buffer. Update the cn_msg header to
* reflect the key value that has been added to the message
*/
kvp_done:
incoming_cn_msg->id.idx = CN_KVP_IDX;
incoming_cn_msg->id.val = CN_KVP_VAL;
incoming_cn_msg->ack = 0;
incoming_cn_msg->len = sizeof(struct hv_kvp_msg);
len = netlink_send(fd, incoming_cn_msg);
if (len < 0) {
syslog(LOG_ERR, "net_link send failed; error:%d", len);
exit(-1);
}
}
}
|
{
"pile_set_name": "Github"
}
|
import { css } from "@emotion/core"
import lineSvg from "../../../../static/assets/line.svg"
const styles = css`
.e404.layout-wrapper .layout-inner {
background: #fff;
}
.e404 .data-section {
color: #000;
}
.aboutme.layout-wrapper .layout-inner {
background: #fff;
}
.aboutme .data-section {
color: #000;
}
.aboutme .hamburgercolr::before,
.aboutme .hamburgercolr::after,
.e404 .hamburgercolr::before,
.e404 .hamburgercolr::after {
background-color: #000;
}
.home.layout-wrapper .layout-inner {
background: #0e0f11;
background: #0e0f11 url(${lineSvg}) center center fixed;
background-size: contain;
}
.home.layout-wrapper h1,
.home.layout-wrapper h2 {
color: #fff;
}
.skill.layout-wrapper .layout-inner {
color: #fff;
background: #9d316e;
background: url(${lineSvg}) center center fixed,
linear-gradient(45deg, #9d316e, #de2d3e);
background-size: cover;
}
.experience.layout-wrapper .layout-inner {
background: #3a3d98;
background: url(${lineSvg}) center center fixed,
linear-gradient(45deg, #6f22b9, #3a3d98);
background-size: cover;
}
.home .hamburgercolr::before,
.home .hamburgercolr::after,
.skill .hamburgercolr::before,
.skill .hamburgercolr::after,
.experience .hamburgercolr::before,
.experience .hamburgercolr::after {
background-color: #fff;
}
.home .btn-contact-color,
.experience .btn-contact-color {
color: #fff;
}
.aboutme .btn-contact-color,
.e404 .btn-contact-color {
color: #000;
}
`
export default styles
|
{
"pile_set_name": "Github"
}
|
<?xml version="1.0" encoding="UTF-8"?>
<Scheme
LastUpgradeVersion = "0820"
version = "1.3">
<BuildAction
parallelizeBuildables = "NO"
buildImplicitDependencies = "YES">
<BuildActionEntries>
<BuildActionEntry
buildForTesting = "YES"
buildForRunning = "YES"
buildForProfiling = "YES"
buildForArchiving = "YES"
buildForAnalyzing = "YES">
<BuildableReference
BuildableIdentifier = "primary"
BlueprintIdentifier = "2D2A28121D9B038B00D4039D"
BuildableName = "libReact.a"
BlueprintName = "React-tvOS"
ReferencedContainer = "container:../node_modules/react-native/React/React.xcodeproj">
</BuildableReference>
</BuildActionEntry>
<BuildActionEntry
buildForTesting = "YES"
buildForRunning = "YES"
buildForProfiling = "YES"
buildForArchiving = "YES"
buildForAnalyzing = "YES">
<BuildableReference
BuildableIdentifier = "primary"
BlueprintIdentifier = "2D02E47A1E0B4A5D006451C7"
BuildableName = "example-tvOS.app"
BlueprintName = "example-tvOS"
ReferencedContainer = "container:example.xcodeproj">
</BuildableReference>
</BuildActionEntry>
<BuildActionEntry
buildForTesting = "YES"
buildForRunning = "YES"
buildForProfiling = "NO"
buildForArchiving = "NO"
buildForAnalyzing = "YES">
<BuildableReference
BuildableIdentifier = "primary"
BlueprintIdentifier = "2D02E48F1E0B4A5D006451C7"
BuildableName = "example-tvOSTests.xctest"
BlueprintName = "example-tvOSTests"
ReferencedContainer = "container:example.xcodeproj">
</BuildableReference>
</BuildActionEntry>
</BuildActionEntries>
</BuildAction>
<TestAction
buildConfiguration = "Debug"
selectedDebuggerIdentifier = "Xcode.DebuggerFoundation.Debugger.LLDB"
selectedLauncherIdentifier = "Xcode.DebuggerFoundation.Launcher.LLDB"
shouldUseLaunchSchemeArgsEnv = "YES">
<Testables>
<TestableReference
skipped = "NO">
<BuildableReference
BuildableIdentifier = "primary"
BlueprintIdentifier = "2D02E48F1E0B4A5D006451C7"
BuildableName = "example-tvOSTests.xctest"
BlueprintName = "example-tvOSTests"
ReferencedContainer = "container:example.xcodeproj">
</BuildableReference>
</TestableReference>
</Testables>
<MacroExpansion>
<BuildableReference
BuildableIdentifier = "primary"
BlueprintIdentifier = "2D02E47A1E0B4A5D006451C7"
BuildableName = "example-tvOS.app"
BlueprintName = "example-tvOS"
ReferencedContainer = "container:example.xcodeproj">
</BuildableReference>
</MacroExpansion>
<AdditionalOptions>
</AdditionalOptions>
</TestAction>
<LaunchAction
buildConfiguration = "Debug"
selectedDebuggerIdentifier = "Xcode.DebuggerFoundation.Debugger.LLDB"
selectedLauncherIdentifier = "Xcode.DebuggerFoundation.Launcher.LLDB"
launchStyle = "0"
useCustomWorkingDirectory = "NO"
ignoresPersistentStateOnLaunch = "NO"
debugDocumentVersioning = "YES"
debugServiceExtension = "internal"
allowLocationSimulation = "YES">
<BuildableProductRunnable
runnableDebuggingMode = "0">
<BuildableReference
BuildableIdentifier = "primary"
BlueprintIdentifier = "2D02E47A1E0B4A5D006451C7"
BuildableName = "example-tvOS.app"
BlueprintName = "example-tvOS"
ReferencedContainer = "container:example.xcodeproj">
</BuildableReference>
</BuildableProductRunnable>
<AdditionalOptions>
</AdditionalOptions>
</LaunchAction>
<ProfileAction
buildConfiguration = "Release"
shouldUseLaunchSchemeArgsEnv = "YES"
savedToolIdentifier = ""
useCustomWorkingDirectory = "NO"
debugDocumentVersioning = "YES">
<BuildableProductRunnable
runnableDebuggingMode = "0">
<BuildableReference
BuildableIdentifier = "primary"
BlueprintIdentifier = "2D02E47A1E0B4A5D006451C7"
BuildableName = "example-tvOS.app"
BlueprintName = "example-tvOS"
ReferencedContainer = "container:example.xcodeproj">
</BuildableReference>
</BuildableProductRunnable>
</ProfileAction>
<AnalyzeAction
buildConfiguration = "Debug">
</AnalyzeAction>
<ArchiveAction
buildConfiguration = "Release"
revealArchiveInOrganizer = "YES">
</ArchiveAction>
</Scheme>
|
{
"pile_set_name": "Github"
}
|
<?php
declare(strict_types=1);
namespace App\Model\Element;
use Swagger\Annotations as SWG;
class NoteElement extends AbstractElement
{
private const TYPE_NAME = 'note';
/**
* {@inheritdoc}
*/
public static function getType(): string
{
return self::TYPE_NAME;
}
/**
* {@inheritdoc}
*/
public static function getSupportedExtensions(): array
{
return [
'txt',
'md',
];
}
/**
* @var string
*
* @SWG\Property(type="string")
*/
private $content;
/**
* {@inheritdoc}
*/
public static function shouldLoadContent(): bool
{
return true;
}
/**
* {@inheritdoc}
*/
public function getContent(): string
{
return $this->content;
}
/**
* {@inheritdoc}
*/
public function setContent($content): void
{
$this->content = $content;
}
}
|
{
"pile_set_name": "Github"
}
|
//
// Scaffolding
// --------------------------------------------------
// Body reset
// -------------------------
body {
margin: 0;
font-family: $baseFontFamily;
font-size: $baseFontSize;
line-height: $baseLineHeight;
color: $textColor;
background-color: $bodyBackground;
}
// Links
// -------------------------
a {
color: $linkColor;
text-decoration: none;
}
a:hover {
color: $linkColorHover;
text-decoration: underline;
}
// Images
// -------------------------
.img-rounded {
border-radius: 6px;
}
.img-polaroid {
padding: 4px;
background-color: #fff;
border: 1px solid #ccc;
border: 1px solid rgba(0,0,0,.2);
box-shadow: 0 1px 3px rgba(0,0,0,.1);
}
.img-circle {
border-radius: 500px;
}
|
{
"pile_set_name": "Github"
}
|
// Copyright (c) 2006, Google Inc.
// 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 Google Inc. 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.
#ifndef GOOGLE_PROTOBUF_STUBS_MUTEX_H_
#define GOOGLE_PROTOBUF_STUBS_MUTEX_H_
#include <mutex>
#ifdef GOOGLE_PROTOBUF_SUPPORT_WINDOWS_XP
#include <windows.h>
// GetMessage conflicts with GeneratedMessageReflection::GetMessage().
#ifdef GetMessage
#undef GetMessage
#endif
#endif
#include <google/protobuf/stubs/macros.h>
// Define thread-safety annotations for use below, if we are building with
// Clang.
#if defined(__clang__) && !defined(SWIG)
#define GOOGLE_PROTOBUF_ACQUIRE(...) \
__attribute__((acquire_capability(__VA_ARGS__)))
#define GOOGLE_PROTOBUF_RELEASE(...) \
__attribute__((release_capability(__VA_ARGS__)))
#define GOOGLE_PROTOBUF_CAPABILITY(x) __attribute__((capability(x)))
#else
#define GOOGLE_PROTOBUF_ACQUIRE(...)
#define GOOGLE_PROTOBUF_RELEASE(...)
#define GOOGLE_PROTOBUF_CAPABILITY(x)
#endif
#include <google/protobuf/port_def.inc>
// ===================================================================
// emulates google3/base/mutex.h
namespace google {
namespace protobuf {
namespace internal {
#define GOOGLE_PROTOBUF_LINKER_INITIALIZED
#ifdef GOOGLE_PROTOBUF_SUPPORT_WINDOWS_XP
// This class is a lightweight replacement for std::mutex on Windows platforms.
// std::mutex does not work on Windows XP SP2 with the latest VC++ libraries,
// because it utilizes the Concurrency Runtime that is only supported on Windows
// XP SP3 and above.
class PROTOBUF_EXPORT CriticalSectionLock {
public:
CriticalSectionLock() { InitializeCriticalSection(&critical_section_); }
~CriticalSectionLock() { DeleteCriticalSection(&critical_section_); }
void lock() { EnterCriticalSection(&critical_section_); }
void unlock() { LeaveCriticalSection(&critical_section_); }
private:
CRITICAL_SECTION critical_section_;
GOOGLE_DISALLOW_EVIL_CONSTRUCTORS(CriticalSectionLock);
};
#endif
// Mutex is a natural type to wrap. As both google and other organization have
// specialized mutexes. gRPC also provides an injection mechanism for custom
// mutexes.
class GOOGLE_PROTOBUF_CAPABILITY("mutex") PROTOBUF_EXPORT WrappedMutex {
public:
WrappedMutex() = default;
void Lock() GOOGLE_PROTOBUF_ACQUIRE() { mu_.lock(); }
void Unlock() GOOGLE_PROTOBUF_RELEASE() { mu_.unlock(); }
// Crash if this Mutex is not held exclusively by this thread.
// May fail to crash when it should; will never crash when it should not.
void AssertHeld() const {}
private:
#ifndef GOOGLE_PROTOBUF_SUPPORT_WINDOWS_XP
std::mutex mu_;
#else // ifndef GOOGLE_PROTOBUF_SUPPORT_WINDOWS_XP
CriticalSectionLock mu_;
#endif // #ifndef GOOGLE_PROTOBUF_SUPPORT_WINDOWS_XP
};
using Mutex = WrappedMutex;
// MutexLock(mu) acquires mu when constructed and releases it when destroyed.
class PROTOBUF_EXPORT MutexLock {
public:
explicit MutexLock(Mutex *mu) : mu_(mu) { this->mu_->Lock(); }
~MutexLock() { this->mu_->Unlock(); }
private:
Mutex *const mu_;
GOOGLE_DISALLOW_EVIL_CONSTRUCTORS(MutexLock);
};
// TODO(kenton): Implement these? Hard to implement portably.
typedef MutexLock ReaderMutexLock;
typedef MutexLock WriterMutexLock;
// MutexLockMaybe is like MutexLock, but is a no-op when mu is nullptr.
class PROTOBUF_EXPORT MutexLockMaybe {
public:
explicit MutexLockMaybe(Mutex *mu) :
mu_(mu) { if (this->mu_ != nullptr) { this->mu_->Lock(); } }
~MutexLockMaybe() { if (this->mu_ != nullptr) { this->mu_->Unlock(); } }
private:
Mutex *const mu_;
GOOGLE_DISALLOW_EVIL_CONSTRUCTORS(MutexLockMaybe);
};
#if defined(GOOGLE_PROTOBUF_NO_THREADLOCAL)
template<typename T>
class ThreadLocalStorage {
public:
ThreadLocalStorage() {
pthread_key_create(&key_, &ThreadLocalStorage::Delete);
}
~ThreadLocalStorage() {
pthread_key_delete(key_);
}
T* Get() {
T* result = static_cast<T*>(pthread_getspecific(key_));
if (result == nullptr) {
result = new T();
pthread_setspecific(key_, result);
}
return result;
}
private:
static void Delete(void* value) {
delete static_cast<T*>(value);
}
pthread_key_t key_;
GOOGLE_DISALLOW_EVIL_CONSTRUCTORS(ThreadLocalStorage);
};
#endif
} // namespace internal
// We made these internal so that they would show up as such in the docs,
// but we don't want to stick "internal::" in front of them everywhere.
using internal::Mutex;
using internal::MutexLock;
using internal::ReaderMutexLock;
using internal::WriterMutexLock;
using internal::MutexLockMaybe;
} // namespace protobuf
} // namespace google
#undef GOOGLE_PROTOBUF_ACQUIRE
#undef GOOGLE_PROTOBUF_RELEASE
#include <google/protobuf/port_undef.inc>
#endif // GOOGLE_PROTOBUF_STUBS_MUTEX_H_
|
{
"pile_set_name": "Github"
}
|
<?xml version="1.0" encoding="utf-8"?>
<Project ToolsVersion="4.0" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
<ItemGroup>
<Filter Include="Header Files">
<UniqueIdentifier>{93995380-89BD-4b04-88EB-625FBE52EBFB}</UniqueIdentifier>
<Extensions>h;hpp;hxx;hm;inl;inc;xsd</Extensions>
</Filter>
<Filter Include="Source Files">
<UniqueIdentifier>{4FC737F1-C7A5-4376-A066-2A32D752A2FF}</UniqueIdentifier>
<Extensions>cpp;c;cc;cxx;def;odl;idl;hpj;bat;asm;asmx</Extensions>
</Filter>
<Filter Include="Public Header Files">
<UniqueIdentifier>{d4e83ff0-6406-4b76-bd64-6192e6b8e47a}</UniqueIdentifier>
</Filter>
<Filter Include="Public Header Files\grabbag">
<UniqueIdentifier>{82df5da8-3a2c-402e-a7cd-a88de1a7be91}</UniqueIdentifier>
</Filter>
</ItemGroup>
<ItemGroup>
<ClCompile Include="alloc.c">
<Filter>Source Files</Filter>
</ClCompile>
<ClCompile Include="cuesheet.c">
<Filter>Source Files</Filter>
</ClCompile>
<ClCompile Include="file.c">
<Filter>Source Files</Filter>
</ClCompile>
<ClCompile Include="picture.c">
<Filter>Source Files</Filter>
</ClCompile>
<ClCompile Include="replaygain.c">
<Filter>Source Files</Filter>
</ClCompile>
<ClCompile Include="seektable.c">
<Filter>Source Files</Filter>
</ClCompile>
<ClCompile Include="snprintf.c">
<Filter>Source Files</Filter>
</ClCompile>
</ItemGroup>
<ItemGroup>
<ClInclude Include="..\..\..\include\share\grabbag.h">
<Filter>Public Header Files</Filter>
</ClInclude>
<ClInclude Include="..\..\..\include\share\grabbag\cuesheet.h">
<Filter>Public Header Files\grabbag</Filter>
</ClInclude>
<ClInclude Include="..\..\..\include\share\grabbag\file.h">
<Filter>Public Header Files\grabbag</Filter>
</ClInclude>
<ClInclude Include="..\..\..\include\share\grabbag\picture.h">
<Filter>Public Header Files\grabbag</Filter>
</ClInclude>
<ClInclude Include="..\..\..\include\share\grabbag\replaygain.h">
<Filter>Public Header Files\grabbag</Filter>
</ClInclude>
<ClInclude Include="..\..\..\include\share\grabbag\seektable.h">
<Filter>Public Header Files\grabbag</Filter>
</ClInclude>
</ItemGroup>
</Project>
|
{
"pile_set_name": "Github"
}
|
var Backbone = require('backbone');
var CoreView = require('backbone/core-view');
var Infobox = require('builder/components/infobox/infobox-factory');
var InfoboxModel = require('builder/components/infobox/infobox-model');
var InfoboxCollection = require('builder/components/infobox/infobox-collection');
var PanelWithOptionsView = require('builder/components/view-options/panel-with-options-view');
var panelTemplate = require('./panel-with-options.tpl');
var AnalysesContentView = require('./analyses-content-view');
var OnboardingLauncher = require('builder/components/onboardings/generic/generic-onboarding-launcher');
var OnboardingView = require('builder/components/onboardings/layers/analysis-onboarding/analysis-onboarding-view');
var checkAndBuildOpts = require('builder/helpers/required-opts');
var ONBOARDING_KEY = 'layer-analyses-onboarding';
var REQUIRED_OPTS = [
'userActions',
'analysisFormsCollection',
'layerDefinitionModel',
'analysisDefinitionNodesCollection',
'configModel',
'userModel',
'editorModel',
'stackLayoutModel',
'onboardings',
'onboardingNotification',
'layerContentModel'
];
module.exports = CoreView.extend({
module: 'editor/layers/layer-content-views/analyses/analyses-view',
initialize: function (opts) {
checkAndBuildOpts(opts, REQUIRED_OPTS, this);
this._selectedNodeId = opts.selectedNodeId;
this._deleteAnalysisModel = new Backbone.Model({
analysisId: null
});
this._infoboxModel = new InfoboxModel({
state: ''
});
this._overlayModel = new Backbone.Model({
visible: this._isLayerHidden()
});
this._onboardingLauncher = new OnboardingLauncher({
view: OnboardingView,
onboardingNotification: this._onboardingNotification,
notificationKey: ONBOARDING_KEY,
onboardings: this._onboardings
}, {
editorModel: this._editorModel,
selector: 'LayerOnboarding'
});
this._getQueryAndCheckState();
this._initBinds();
},
render: function () {
this._launchOnboarding();
this.clearSubViews();
this.$el.empty();
this._initViews();
this._infoboxState();
return this;
},
_initBinds: function () {
this.listenTo(this._layerDefinitionModel, 'change:visible', this._infoboxState);
this.listenTo(this._deleteAnalysisModel, 'change:analysisId', this._infoboxState);
this.listenTo(this._analysisFormsCollection, 'reset remove', this._getQueryAndCheckState);
},
_initViews: function () {
var self = this;
var infoboxSstates = [
{
state: 'layer-hidden',
createContentView: function () {
return Infobox.createWithAction({
type: 'alert',
title: _t('editor.messages.layer-hidden.title'),
body: _t('editor.messages.layer-hidden.body'),
action: {
label: _t('editor.messages.layer-hidden.show')
}
});
},
onAction: self._showHiddenLayer.bind(self)
},
{
state: 'deleting-analysis',
createContentView: function () {
return Infobox.createWithAction({
type: 'alert',
title: _t('editor.messages.deleting-analysis.title'),
body: _t('editor.messages.deleting-analysis.body'),
action: {
label: _t('editor.messages.deleting-analysis.delete')
}
});
},
onClose: self._resetDeletingAnalysis.bind(self),
onAction: self._deleteAnalysis.bind(self)
}
];
var infoboxCollection = new InfoboxCollection(infoboxSstates);
var panelWithOptionsView = new PanelWithOptionsView({
template: panelTemplate,
className: 'Editor-content',
editorModel: self._editorModel,
infoboxModel: self._infoboxModel,
infoboxCollection: infoboxCollection,
createContentView: function () {
return new AnalysesContentView({
className: 'Editor-content',
userActions: self._userActions,
analysisDefinitionNodesCollection: self._analysisDefinitionNodesCollection,
userModel: self._userModel,
analysisFormsCollection: self._analysisFormsCollection,
configModel: self._configModel,
layerDefinitionModel: self._layerDefinitionModel,
stackLayoutModel: self._stackLayoutModel,
selectedNodeId: self._selectedNodeId,
overlayModel: self._overlayModel,
layerContentModel: self._layerContentModel,
deleteAnalysisModel: self._deleteAnalysisModel
});
}
});
this.$el.append(panelWithOptionsView.render().el);
this.addView(panelWithOptionsView);
},
_getQueryAndCheckState: function () {
if (!this._analysisFormsCollection.isEmpty()) {
this._infoboxState();
}
},
_launchOnboarding: function () {
if (this._onboardingNotification.getKey(ONBOARDING_KEY)) {
return;
}
if (this._analysisFormsCollection.isEmpty()) {
this._onboardingLauncher.launch();
}
this._layerDefinitionModel.canBeGeoreferenced()
.then(function (canBeGeoreferenced) {
if (canBeGeoreferenced) {
this._onboardingNotification.setKey(ONBOARDING_KEY, true);
}
}.bind(this));
},
_infoboxState: function () {
if (this._isLayerHidden()) {
this._infoboxModel.set({ state: 'layer-hidden' });
this._overlayModel.set({ visible: true });
} else if (this._deleteAnalysisModel.get('analysisId')) {
this._infoboxModel.set({ state: 'deleting-analysis' });
this._overlayModel.set({ visible: true });
} else {
this._infoboxModel.set({ state: '' });
this._overlayModel.set({ visible: false });
}
},
_showHiddenLayer: function () {
this._layerDefinitionModel.toggleVisible();
this._userActions.saveLayer(this._layerDefinitionModel);
this._infoboxState();
},
_isLayerHidden: function () {
return this._layerDefinitionModel.get('visible') === false;
},
_resetDeletingAnalysis: function () {
this._deleteAnalysisModel.unset('analysisId');
},
_deleteAnalysis: function () {
this._analysisFormsCollection.deleteNode(this._deleteAnalysisModel.get('analysisId'));
this._resetDeletingAnalysis();
}
});
|
{
"pile_set_name": "Github"
}
|
{
"$schema": "http://json-schema.org/schema#",
"required": [
"repository"
],
"type": "object",
"description": "Represents a volume that is populated with the contents of a git repository. Git repo volumes do not support ownership management. Git repo volumes support SELinux relabeling.",
"properties": {
"directory": {
"type": [
"string",
"null"
],
"description": "Target directory name. Must not contain or start with '..'. If '.' is supplied, the volume directory will be the git repository. Otherwise, if specified, the volume will contain the git repository in the subdirectory with the given name."
},
"repository": {
"type": [
"string",
"null"
],
"description": "Repository URL"
},
"revision": {
"type": [
"string",
"null"
],
"description": "Commit hash for the specified revision."
}
}
}
|
{
"pile_set_name": "Github"
}
|
(function($){
/*
* WYSIWYG
*
* jQuery functionality for this field type
*
* @type object
* @date 20/07/13
*
* @param N/A
* @return N/A
*/
var _wysiwyg = acf.fields.wysiwyg = {
$el: null,
$textarea: null,
o: {},
set: function( o ){
// merge in new option
$.extend( this, o );
// find textarea
this.$textarea = this.$el.find('textarea');
// get options
this.o = acf.helpers.get_atts( this.$el );
this.o.id = this.$textarea.attr('id');
// return this for chaining
return this;
},
has_tinymce : function(){
var r = false;
if( typeof(tinyMCE) == "object" )
{
r = true;
}
return r;
},
get_toolbar : function(){
// safely get toolbar
if( acf.helpers.isset( this, 'toolbars', this.o.toolbar ) ) {
return this.toolbars[ this.o.toolbar ];
}
// return
return false;
},
init : function(){
// is clone field?
if( acf.helpers.is_clone_field( this.$textarea ) )
{
return;
}
// vars
var id = this.o.id,
toolbar = this.get_toolbar(),
command = 'mceAddControl',
setting = 'theme_advanced_buttons{i}';
// backup
var _settings = $.extend( {}, tinyMCE.settings );
// v4 settings
if( tinymce.majorVersion == 4 ) {
command = 'mceAddEditor';
setting = 'toolbar{i}';
}
// add toolbars
if( toolbar ) {
for( var i = 1; i < 5; i++ ) {
// vars
var v = '';
// load toolbar
if( acf.helpers.isset( toolbar, 'theme_advanced_buttons' + i ) ) {
v = toolbar['theme_advanced_buttons' + i];
}
// update setting
tinyMCE.settings[ setting.replace('{i}', i) ] = v;
}
}
// add editor
tinyMCE.execCommand( command, false, id);
// events - load
$(document).trigger('acf/wysiwyg/load', id);
// add events (click, focus, blur) for inserting image into correct editor
setTimeout(function(){
_wysiwyg.add_events( id );
}, 100);
// restore tinyMCE.settings
tinyMCE.settings = _settings;
// set active editor to null
wpActiveEditor = null;
},
add_events: function( id ){
// vars
var editor = tinyMCE.get( id );
// validate
if( !editor ) return;
// vars
var $container = $('#wp-' + id + '-wrap'),
$body = $( editor.getBody() );
// events
$container.on('click', function(){
$(document).trigger('acf/wysiwyg/click', id);
});
$body.on('focus', function(){
$(document).trigger('acf/wysiwyg/focus', id);
});
$body.on('blur', function(){
$(document).trigger('acf/wysiwyg/blur', id);
});
},
destroy : function(){
// vars
var id = this.o.id,
command = 'mceRemoveControl';
// Remove tinymcy functionality.
// Due to the media popup destroying and creating the field within such a short amount of time,
// a JS error will be thrown when launching the edit window twice in a row.
try {
// vars
var editor = tinyMCE.get( id );
// validate
if( !editor ) {
return;
}
// v4 settings
if( tinymce.majorVersion == 4 ) {
command = 'mceRemoveEditor';
}
// store value
var val = editor.getContent();
// remove editor
tinyMCE.execCommand(command, false, id);
// set value
this.$textarea.val( val );
} catch(e) {
//console.log( e );
}
// set active editor to null
wpActiveEditor = null;
}
};
/*
* acf/setup_fields
*
* run init function on all elements for this field
*
* @type event
* @date 20/07/13
*
* @param {object} e event object
* @param {object} el DOM object which may contain new ACF elements
* @return N/A
*/
$(document).on('acf/setup_fields', function(e, el){
// validate
if( ! _wysiwyg.has_tinymce() )
{
return;
}
// Destory all WYSIWYG fields
// This hack will fix a problem when the WP popup is created and hidden, then the ACF popup (image/file field) is opened
$(el).find('.acf_wysiwyg').each(function(){
_wysiwyg.set({ $el : $(this) }).destroy();
});
// Add WYSIWYG fields
setTimeout(function(){
$(el).find('.acf_wysiwyg').each(function(){
_wysiwyg.set({ $el : $(this) }).init();
});
}, 0);
});
/*
* acf/remove_fields
*
* This action is called when the $el is being removed from the DOM
*
* @type event
* @date 20/07/13
*
* @param {object} e event object
* @param {object} $el jQuery element being removed
* @return N/A
*/
$(document).on('acf/remove_fields', function(e, $el){
// validate
if( ! _wysiwyg.has_tinymce() )
{
return;
}
$el.find('.acf_wysiwyg').each(function(){
_wysiwyg.set({ $el : $(this) }).destroy();
});
});
/*
* acf/wysiwyg/click
*
* this event is run when a user clicks on a WYSIWYG field
*
* @type event
* @date 17/01/13
*
* @param {object} e event object
* @param {int} id WYSIWYG ID
* @return N/A
*/
$(document).on('acf/wysiwyg/click', function(e, id){
wpActiveEditor = id;
container = $('#wp-' + id + '-wrap').closest('.field').removeClass('error');
});
/*
* acf/wysiwyg/focus
*
* this event is run when a user focuses on a WYSIWYG field body
*
* @type event
* @date 17/01/13
*
* @param {object} e event object
* @param {int} id WYSIWYG ID
* @return N/A
*/
$(document).on('acf/wysiwyg/focus', function(e, id){
wpActiveEditor = id;
container = $('#wp-' + id + '-wrap').closest('.field').removeClass('error');
});
/*
* acf/wysiwyg/blur
*
* this event is run when a user loses focus on a WYSIWYG field body
*
* @type event
* @date 17/01/13
*
* @param {object} e event object
* @param {int} id WYSIWYG ID
* @return N/A
*/
$(document).on('acf/wysiwyg/blur', function(e, id){
wpActiveEditor = null;
// update the hidden textarea
// - This fixes a but when adding a taxonomy term as the form is not posted and the hidden tetarea is never populated!
var editor = tinyMCE.get( id );
// validate
if( !editor )
{
return;
}
var el = editor.getElement();
// save to textarea
editor.save();
// trigger change on textarea
$( el ).trigger('change');
});
/*
* acf/sortable_start
*
* this event is run when a element is being drag / dropped
*
* @type event
* @date 10/11/12
*
* @param {object} e event object
* @param {object} el DOM object which may contain new ACF elements
* @return N/A
*/
$(document).on('acf/sortable_start', function(e, el) {
// validate
if( ! _wysiwyg.has_tinymce() )
{
return;
}
$(el).find('.acf_wysiwyg').each(function(){
_wysiwyg.set({ $el : $(this) }).destroy();
});
});
/*
* acf/sortable_stop
*
* this event is run when a element has finnished being drag / dropped
*
* @type event
* @date 10/11/12
*
* @param {object} e event object
* @param {object} el DOM object which may contain new ACF elements
* @return N/A
*/
$(document).on('acf/sortable_stop', function(e, el) {
// validate
if( ! _wysiwyg.has_tinymce() )
{
return;
}
$(el).find('.acf_wysiwyg').each(function(){
_wysiwyg.set({ $el : $(this) }).init();
});
});
/*
* window load
*
* @description:
* @since: 3.5.5
* @created: 22/12/12
*/
$(window).on('load', function(){
// validate
if( ! _wysiwyg.has_tinymce() )
{
return;
}
// vars
var wp_content = $('#wp-content-wrap').exists(),
wp_acf_settings = $('#wp-acf_settings-wrap').exists()
mode = 'tmce';
// has_editor
if( wp_acf_settings )
{
// html_mode
if( $('#wp-acf_settings-wrap').hasClass('html-active') )
{
mode = 'html';
}
}
setTimeout(function(){
// trigger click on hidden wysiwyg (to get in HTML mode)
if( wp_acf_settings && mode == 'html' )
{
$('#acf_settings-tmce').trigger('click');
}
}, 1);
setTimeout(function(){
// trigger html mode for people who want to stay in HTML mode
if( wp_acf_settings && mode == 'html' )
{
$('#acf_settings-html').trigger('click');
}
// Add events to content editor
if( wp_content )
{
_wysiwyg.add_events('content');
}
}, 11);
});
/*
* Full screen
*
* @description: this hack will hide the 'image upload' button in the wysiwyg full screen mode if the field has disabled image uploads!
* @since: 3.6
* @created: 26/02/13
*/
$(document).on('click', '.acf_wysiwyg a.mce_fullscreen', function(){
// vars
var wysiwyg = $(this).closest('.acf_wysiwyg'),
upload = wysiwyg.attr('data-upload');
if( upload == 'no' )
{
$('#mce_fullscreen_container td.mceToolbar .mce_add_media').remove();
}
});
})(jQuery);
|
{
"pile_set_name": "Github"
}
|
<?php
/*
* $Id$
*
* 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.
*
* This software consists of voluntary contributions made by many individuals
* and is licensed under the MIT license. For more information, see
* <http://www.doctrine-project.org>.
*/
namespace Doctrine\Common\Cache;
/**
* Interface for cache drivers.
*
* @license http://www.opensource.org/licenses/lgpl-license.php LGPL
* @link www.doctrine-project.org
* @since 2.0
* @author Benjamin Eberlei <[email protected]>
* @author Guilherme Blanco <[email protected]>
* @author Jonathan Wage <[email protected]>
* @author Roman Borschel <[email protected]>
* @author Fabio B. Silva <[email protected]>
*/
interface Cache
{
const STATS_HITS = 'hits';
const STATS_MISSES = 'misses';
const STATS_UPTIME = 'uptime';
const STATS_MEMORY_USAGE = 'memory_usage';
const STATS_MEMORY_AVAILIABLE = 'memory_available';
/**
* Fetches an entry from the cache.
*
* @param string $id cache id The id of the cache entry to fetch.
* @return mixed The cached data or FALSE, if no cache entry exists for the given id.
*/
function fetch($id);
/**
* Test if an entry exists in the cache.
*
* @param string $id cache id The cache id of the entry to check for.
* @return boolean TRUE if a cache entry exists for the given cache id, FALSE otherwise.
*/
function contains($id);
/**
* Puts data into the cache.
*
* @param string $id The cache id.
* @param mixed $data The cache entry/data.
* @param int $lifeTime The lifetime. If != 0, sets a specific lifetime for this cache entry (0 => infinite lifeTime).
* @return boolean TRUE if the entry was successfully stored in the cache, FALSE otherwise.
*/
function save($id, $data, $lifeTime = 0);
/**
* Deletes a cache entry.
*
* @param string $id cache id
* @return boolean TRUE if the cache entry was successfully deleted, FALSE otherwise.
*/
function delete($id);
/**
* Retrieves cached information from data store
*
* The server's statistics array has the following values:
*
* - <b>hits</b>
* Number of keys that have been requested and found present.
*
* - <b>misses</b>
* Number of items that have been requested and not found.
*
* - <b>uptime</b>
* Time that the server is running.
*
* - <b>memory_usage</b>
* Memory used by this server to store items.
*
* - <b>memory_available</b>
* Memory allowed to use for storage.
*
* @since 2.2
* @var array Associative array with server's statistics if available, NULL otherwise.
*/
function getStats();
}
|
{
"pile_set_name": "Github"
}
|
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<!-- NewPage -->
<html lang="en">
<head>
<!-- Generated by javadoc (1.8.0_162) on Sat Apr 25 13:07:03 PDT 2020 -->
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Uses of Class com.ctc.wstx.util.TextBuilder (Woodstox 6.2.0 API)</title>
<meta name="date" content="2020-04-25">
<link rel="stylesheet" type="text/css" href="../../../../../stylesheet.css" title="Style">
<script type="text/javascript" src="../../../../../script.js"></script>
</head>
<body>
<script type="text/javascript"><!--
try {
if (location.href.indexOf('is-external=true') == -1) {
parent.document.title="Uses of Class com.ctc.wstx.util.TextBuilder (Woodstox 6.2.0 API)";
}
}
catch(err) {
}
//-->
</script>
<noscript>
<div>JavaScript is disabled on your browser.</div>
</noscript>
<!-- ========= START OF TOP NAVBAR ======= -->
<div class="topNav"><a name="navbar.top">
<!-- -->
</a>
<div class="skipNav"><a href="#skip.navbar.top" title="Skip navigation links">Skip navigation links</a></div>
<a name="navbar.top.firstrow">
<!-- -->
</a>
<ul class="navList" title="Navigation">
<li><a href="../../../../../overview-summary.html">Overview</a></li>
<li><a href="../package-summary.html">Package</a></li>
<li><a href="../../../../../com/ctc/wstx/util/TextBuilder.html" title="class in com.ctc.wstx.util">Class</a></li>
<li class="navBarCell1Rev">Use</li>
<li><a href="../package-tree.html">Tree</a></li>
<li><a href="../../../../../deprecated-list.html">Deprecated</a></li>
<li><a href="../../../../../index-all.html">Index</a></li>
<li><a href="../../../../../help-doc.html">Help</a></li>
</ul>
</div>
<div class="subNav">
<ul class="navList">
<li>Prev</li>
<li>Next</li>
</ul>
<ul class="navList">
<li><a href="../../../../../index.html?com/ctc/wstx/util/class-use/TextBuilder.html" target="_top">Frames</a></li>
<li><a href="TextBuilder.html" target="_top">No Frames</a></li>
</ul>
<ul class="navList" id="allclasses_navbar_top">
<li><a href="../../../../../allclasses-noframe.html">All Classes</a></li>
</ul>
<div>
<script type="text/javascript"><!--
allClassesLink = document.getElementById("allclasses_navbar_top");
if(window==top) {
allClassesLink.style.display = "block";
}
else {
allClassesLink.style.display = "none";
}
//-->
</script>
</div>
<a name="skip.navbar.top">
<!-- -->
</a></div>
<!-- ========= END OF TOP NAVBAR ========= -->
<div class="header">
<h2 title="Uses of Class com.ctc.wstx.util.TextBuilder" class="title">Uses of Class<br>com.ctc.wstx.util.TextBuilder</h2>
</div>
<div class="classUseContainer">
<ul class="blockList">
<li class="blockList">
<table class="useSummary" border="0" cellpadding="3" cellspacing="0" summary="Use table, listing packages, and an explanation">
<caption><span>Packages that use <a href="../../../../../com/ctc/wstx/util/TextBuilder.html" title="class in com.ctc.wstx.util">TextBuilder</a></span><span class="tabEnd"> </span></caption>
<tr>
<th class="colFirst" scope="col">Package</th>
<th class="colLast" scope="col">Description</th>
</tr>
<tbody>
<tr class="altColor">
<td class="colFirst"><a href="#com.ctc.wstx.sr">com.ctc.wstx.sr</a></td>
<td class="colLast">
<div class="block">This package contains supporting code for handling namespace information;
element stacks that keep track of elements parsed and such.</div>
</td>
</tr>
</tbody>
</table>
</li>
<li class="blockList">
<ul class="blockList">
<li class="blockList"><a name="com.ctc.wstx.sr">
<!-- -->
</a>
<h3>Uses of <a href="../../../../../com/ctc/wstx/util/TextBuilder.html" title="class in com.ctc.wstx.util">TextBuilder</a> in <a href="../../../../../com/ctc/wstx/sr/package-summary.html">com.ctc.wstx.sr</a></h3>
<table class="useSummary" border="0" cellpadding="3" cellspacing="0" summary="Use table, listing fields, and an explanation">
<caption><span>Fields in <a href="../../../../../com/ctc/wstx/sr/package-summary.html">com.ctc.wstx.sr</a> declared as <a href="../../../../../com/ctc/wstx/util/TextBuilder.html" title="class in com.ctc.wstx.util">TextBuilder</a></span><span class="tabEnd"> </span></caption>
<tr>
<th class="colFirst" scope="col">Modifier and Type</th>
<th class="colLast" scope="col">Field and Description</th>
</tr>
<tbody>
<tr class="altColor">
<td class="colFirst"><code>protected <a href="../../../../../com/ctc/wstx/util/TextBuilder.html" title="class in com.ctc.wstx.util">TextBuilder</a></code></td>
<td class="colLast"><span class="typeNameLabel">AttributeCollector.</span><code><span class="memberNameLink"><a href="../../../../../com/ctc/wstx/sr/AttributeCollector.html#mValueBuilder">mValueBuilder</a></span></code>
<div class="block">TextBuilder into which values of all attributes are appended
to, including default valued ones (defaults are added after
explicit ones).</div>
</td>
</tr>
</tbody>
</table>
<table class="useSummary" border="0" cellpadding="3" cellspacing="0" summary="Use table, listing methods, and an explanation">
<caption><span>Methods in <a href="../../../../../com/ctc/wstx/sr/package-summary.html">com.ctc.wstx.sr</a> that return <a href="../../../../../com/ctc/wstx/util/TextBuilder.html" title="class in com.ctc.wstx.util">TextBuilder</a></span><span class="tabEnd"> </span></caption>
<tr>
<th class="colFirst" scope="col">Modifier and Type</th>
<th class="colLast" scope="col">Method and Description</th>
</tr>
<tbody>
<tr class="altColor">
<td class="colFirst"><code><a href="../../../../../com/ctc/wstx/util/TextBuilder.html" title="class in com.ctc.wstx.util">TextBuilder</a></code></td>
<td class="colLast"><span class="typeNameLabel">AttributeCollector.</span><code><span class="memberNameLink"><a href="../../../../../com/ctc/wstx/sr/AttributeCollector.html#getAttrBuilder-java.lang.String-java.lang.String-">getAttrBuilder</a></span>(<a href="https://docs.oracle.com/javase/6/docs/api/java/lang/String.html?is-external=true" title="class or interface in java.lang">String</a> attrPrefix,
<a href="https://docs.oracle.com/javase/6/docs/api/java/lang/String.html?is-external=true" title="class or interface in java.lang">String</a> attrLocalName)</code>
<div class="block">Low-level accessor method that attribute validation code may call
for certain types of attributes; generally only for id and idref/idrefs
attributes.</div>
</td>
</tr>
<tr class="rowColor">
<td class="colFirst"><code><a href="../../../../../com/ctc/wstx/util/TextBuilder.html" title="class in com.ctc.wstx.util">TextBuilder</a></code></td>
<td class="colLast"><span class="typeNameLabel">AttributeCollector.</span><code><span class="memberNameLink"><a href="../../../../../com/ctc/wstx/sr/AttributeCollector.html#getDefaultNsBuilder--">getDefaultNsBuilder</a></span>()</code> </td>
</tr>
<tr class="altColor">
<td class="colFirst"><code><a href="../../../../../com/ctc/wstx/util/TextBuilder.html" title="class in com.ctc.wstx.util">TextBuilder</a></code></td>
<td class="colLast"><span class="typeNameLabel">AttributeCollector.</span><code><span class="memberNameLink"><a href="../../../../../com/ctc/wstx/sr/AttributeCollector.html#getNsBuilder-java.lang.String-">getNsBuilder</a></span>(<a href="https://docs.oracle.com/javase/6/docs/api/java/lang/String.html?is-external=true" title="class or interface in java.lang">String</a> prefix)</code> </td>
</tr>
</tbody>
</table>
</li>
</ul>
</li>
</ul>
</div>
<!-- ======= START OF BOTTOM NAVBAR ====== -->
<div class="bottomNav"><a name="navbar.bottom">
<!-- -->
</a>
<div class="skipNav"><a href="#skip.navbar.bottom" title="Skip navigation links">Skip navigation links</a></div>
<a name="navbar.bottom.firstrow">
<!-- -->
</a>
<ul class="navList" title="Navigation">
<li><a href="../../../../../overview-summary.html">Overview</a></li>
<li><a href="../package-summary.html">Package</a></li>
<li><a href="../../../../../com/ctc/wstx/util/TextBuilder.html" title="class in com.ctc.wstx.util">Class</a></li>
<li class="navBarCell1Rev">Use</li>
<li><a href="../package-tree.html">Tree</a></li>
<li><a href="../../../../../deprecated-list.html">Deprecated</a></li>
<li><a href="../../../../../index-all.html">Index</a></li>
<li><a href="../../../../../help-doc.html">Help</a></li>
</ul>
</div>
<div class="subNav">
<ul class="navList">
<li>Prev</li>
<li>Next</li>
</ul>
<ul class="navList">
<li><a href="../../../../../index.html?com/ctc/wstx/util/class-use/TextBuilder.html" target="_top">Frames</a></li>
<li><a href="TextBuilder.html" target="_top">No Frames</a></li>
</ul>
<ul class="navList" id="allclasses_navbar_bottom">
<li><a href="../../../../../allclasses-noframe.html">All Classes</a></li>
</ul>
<div>
<script type="text/javascript"><!--
allClassesLink = document.getElementById("allclasses_navbar_bottom");
if(window==top) {
allClassesLink.style.display = "block";
}
else {
allClassesLink.style.display = "none";
}
//-->
</script>
</div>
<a name="skip.navbar.bottom">
<!-- -->
</a></div>
<!-- ======== END OF BOTTOM NAVBAR ======= -->
<p class="legalCopy"><small>Copyright © 2020 <a href="http://fasterxml.com">FasterXML</a>. All rights reserved.</small></p>
</body>
</html>
|
{
"pile_set_name": "Github"
}
|
"use strict";
import { UseCase } from "almin";
import todoListRepository, { TodoListRepository } from "../infra/TodoListRepository";
export class ToggleAllTodoItemFactory {
static create() {
return new ToggleAllTodoItemUseCase({
todoListRepository
});
}
}
export class ToggleAllTodoItemUseCase extends UseCase {
private todoListRepository: TodoListRepository;
/**
* @param {TodoListRepository} todoListRepository
*/
constructor({ todoListRepository }: { todoListRepository: TodoListRepository }) {
super();
this.todoListRepository = todoListRepository;
}
execute() {
const todoList = this.todoListRepository.lastUsed();
todoList.toggleCompleteAll();
this.todoListRepository.save(todoList);
}
}
|
{
"pile_set_name": "Github"
}
|
col_layer = -1
invisible = 1
distort_magnitude = 0.6
distort_gen = <<< distortions.ripple(2, 7) >>>
distort_size = [155,155]
on timer(5)
shoot_particles( unicornrippleeffect2.obj, 1)
remove()
|
{
"pile_set_name": "Github"
}
|
#!/bin/sh
# SPDX-License-Identifier: GPL-2.0
# Test for gcc 'asm goto' support
# Copyright (C) 2010, Jason Baron <[email protected]>
cat << "END" | $@ -x c - -fno-PIE -c -o /dev/null
int main(void)
{
#if defined(__arm__) || defined(__aarch64__)
/*
* Not related to asm goto, but used by jump label
* and broken on some ARM GCC versions (see GCC Bug 48637).
*/
static struct { int dummy; int state; } tp;
asm (".long %c0" :: "i" (&tp.state));
#endif
entry:
asm goto ("" :::: entry);
return 0;
}
END
|
{
"pile_set_name": "Github"
}
|
/*
* MPlayer AAC decoder using libfaad2
*
* Copyright (C) 2002 Felix Buenemann <atmosfear at users.sourceforge.net>
*
* This file is part of MPlayer.
*
* MPlayer 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.
*
* MPlayer 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 MPlayer; if not, write to the Free Software Foundation, Inc.,
* 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
*/
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <faad.h>
#include "config.h"
#include "mp_msg.h"
#include "ad_internal.h"
#include "dec_audio.h"
#include "libaf/reorder_ch.h"
static const ad_info_t info =
{
"AAC (MPEG2/4 Advanced Audio Coding)",
"faad",
"Felix Buenemann",
"faad2",
"uses libfaad2"
};
LIBAD_EXTERN(faad)
/* configure maximum supported channels, *
* this is theoretically max. 64 chans */
#define FAAD_MAX_CHANNELS 8
#define FAAD_BUFFLEN (FAAD_MIN_STREAMSIZE*FAAD_MAX_CHANNELS)
//#define AAC_DUMP_COMPRESSED
static faacDecHandle faac_hdec;
static faacDecFrameInfo faac_finfo;
static int preinit(sh_audio_t *sh)
{
sh->audio_out_minsize=8192*FAAD_MAX_CHANNELS;
sh->audio_in_minsize=FAAD_BUFFLEN;
return 1;
}
static int aac_probe(unsigned char *buffer, int len)
{
int i = 0, pos = 0;
mp_msg(MSGT_DECAUDIO,MSGL_V, "\nAAC_PROBE: %d bytes\n", len);
while(i <= len-4) {
if(
((buffer[i] == 0xff) && ((buffer[i+1] & 0xf6) == 0xf0)) ||
(buffer[i] == 'A' && buffer[i+1] == 'D' && buffer[i+2] == 'I' && buffer[i+3] == 'F')
) {
pos = i;
break;
}
mp_msg(MSGT_DECAUDIO,MSGL_V, "AUDIO PAYLOAD: %x %x %x %x\n", buffer[i], buffer[i+1], buffer[i+2], buffer[i+3]);
i++;
}
mp_msg(MSGT_DECAUDIO,MSGL_V, "\nAAC_PROBE: ret %d\n", pos);
return pos;
}
static int init(sh_audio_t *sh)
{
unsigned long faac_samplerate;
unsigned char faac_channels;
int faac_init, pos = 0;
faac_hdec = faacDecOpen();
// If we don't get the ES descriptor, try manual config
if(!sh->codecdata_len && sh->wf) {
sh->codecdata_len = sh->wf->cbSize;
sh->codecdata = malloc(sh->codecdata_len);
memcpy(sh->codecdata, sh->wf+1, sh->codecdata_len);
mp_msg(MSGT_DECAUDIO,MSGL_DBG2,"FAAD: codecdata extracted from WAVEFORMATEX\n");
}
if(!sh->codecdata_len || sh->format == mmioFOURCC('M', 'P', '4', 'L')) {
faacDecConfigurationPtr faac_conf;
/* Set the default object type and samplerate */
/* This is useful for RAW AAC files */
faac_conf = faacDecGetCurrentConfiguration(faac_hdec);
if(sh->samplerate)
faac_conf->defSampleRate = sh->samplerate;
/* XXX: FAAD support FLOAT output, how do we handle
* that (FAAD_FMT_FLOAT)? ::atmos
*/
if (audio_output_channels <= 2) faac_conf->downMatrix = 1;
switch(sh->samplesize){
case 1: // 8Bit
mp_msg(MSGT_DECAUDIO,MSGL_WARN,"FAAD: 8Bit samplesize not supported by FAAD, assuming 16Bit!\n");
default:
sh->samplesize=2;
case 2: // 16Bit
faac_conf->outputFormat = FAAD_FMT_16BIT;
break;
case 3: // 24Bit
faac_conf->outputFormat = FAAD_FMT_24BIT;
break;
case 4: // 32Bit
faac_conf->outputFormat = FAAD_FMT_32BIT;
break;
}
//faac_conf->defObjectType = LTP; // => MAIN, LC, SSR, LTP available.
faacDecSetConfiguration(faac_hdec, faac_conf);
sh->a_in_buffer_len = demux_read_data(sh->ds, sh->a_in_buffer, sh->a_in_buffer_size);
if (!sh->a_in_buffer_len) {
// faad init will crash with 0 buffer length
mp_msg(MSGT_DECAUDIO, MSGL_FATAL, "Could not get audio data!\n");
return 0;
}
/* external faad does not have latm lookup support */
faac_init = faacDecInit(faac_hdec, sh->a_in_buffer,
sh->a_in_buffer_len, &faac_samplerate, &faac_channels);
if (faac_init < 0) {
pos = aac_probe(sh->a_in_buffer, sh->a_in_buffer_len);
if(pos) {
sh->a_in_buffer_len -= pos;
memmove(sh->a_in_buffer, &(sh->a_in_buffer[pos]), sh->a_in_buffer_len);
sh->a_in_buffer_len +=
demux_read_data(sh->ds,&(sh->a_in_buffer[sh->a_in_buffer_len]),
sh->a_in_buffer_size - sh->a_in_buffer_len);
pos = 0;
}
/* init the codec */
faac_init = faacDecInit(faac_hdec, sh->a_in_buffer,
sh->a_in_buffer_len, &faac_samplerate, &faac_channels);
}
sh->a_in_buffer_len -= (faac_init > 0)?faac_init:0; // how many bytes init consumed
// XXX FIXME: shouldn't we memcpy() here in a_in_buffer ?? --A'rpi
} else { // We have ES DS in codecdata
faacDecConfigurationPtr faac_conf = faacDecGetCurrentConfiguration(faac_hdec);
if (audio_output_channels <= 2) {
faac_conf->downMatrix = 1;
faacDecSetConfiguration(faac_hdec, faac_conf);
}
/*int i;
for(i = 0; i < sh_audio->codecdata_len; i++)
printf("codecdata_dump %d: 0x%02X\n", i, sh_audio->codecdata[i]);*/
faac_init = faacDecInit2(faac_hdec, sh->codecdata,
sh->codecdata_len, &faac_samplerate, &faac_channels);
}
if(faac_init < 0) {
mp_msg(MSGT_DECAUDIO,MSGL_WARN,"FAAD: Failed to initialize the decoder!\n"); // XXX: deal with cleanup!
faacDecClose(faac_hdec);
// XXX: free a_in_buffer here or in uninit?
return 0;
} else {
mp_msg(MSGT_DECAUDIO,MSGL_V,"FAAD: Decoder init done (%dBytes)!\n", sh->a_in_buffer_len); // XXX: remove or move to debug!
mp_msg(MSGT_DECAUDIO,MSGL_V,"FAAD: Negotiated samplerate: %ldHz channels: %d\n", faac_samplerate, faac_channels);
// 8 channels is aac channel order #7.
sh->channels = faac_channels == 7 ? 8 : faac_channels;
if (audio_output_channels <= 2) sh->channels = faac_channels > 1 ? 2 : 1;
sh->samplerate = faac_samplerate;
sh->samplesize=2;
//sh->o_bps = sh->samplesize*faac_channels*faac_samplerate;
if(!sh->i_bps) {
mp_msg(MSGT_DECAUDIO,MSGL_WARN,"FAAD: compressed input bitrate missing, assuming 128kbit/s!\n");
sh->i_bps = 128*1000/8; // XXX: HACK!!! ::atmos
} else
mp_msg(MSGT_DECAUDIO,MSGL_V,"FAAD: got %dkbit/s bitrate from MP4 header!\n",sh->i_bps*8/1000);
}
return 1;
}
static void uninit(sh_audio_t *sh)
{
mp_msg(MSGT_DECAUDIO,MSGL_V,"FAAD: Closing decoder!\n");
faacDecClose(faac_hdec);
}
static int aac_sync(sh_audio_t *sh)
{
int pos = 0;
// do not probe LATM, faad does that
if(!sh->codecdata_len && sh->format != mmioFOURCC('M', 'P', '4', 'L')) {
if(sh->a_in_buffer_len < sh->a_in_buffer_size){
sh->a_in_buffer_len +=
demux_read_data(sh->ds,&sh->a_in_buffer[sh->a_in_buffer_len],
sh->a_in_buffer_size - sh->a_in_buffer_len);
}
pos = aac_probe(sh->a_in_buffer, sh->a_in_buffer_len);
if(pos) {
sh->a_in_buffer_len -= pos;
memmove(sh->a_in_buffer, &(sh->a_in_buffer[pos]), sh->a_in_buffer_len);
mp_msg(MSGT_DECAUDIO,MSGL_V, "\nAAC SYNC AFTER %d bytes\n", pos);
}
}
return pos;
}
static int control(sh_audio_t *sh,int cmd,void* arg, ...)
{
switch(cmd)
{
case ADCTRL_RESYNC_STREAM:
aac_sync(sh);
return CONTROL_TRUE;
#if 0
case ADCTRL_SKIP_FRAME:
return CONTROL_TRUE;
#endif
}
return CONTROL_UNKNOWN;
}
#define MAX_FAAD_ERRORS 10
static int decode_audio(sh_audio_t *sh,unsigned char *buf,int minlen,int maxlen)
{
int len = 0, last_dec_len = 1, errors = 0;
// int j = 0;
void *faac_sample_buffer;
while(len < minlen && last_dec_len > 0 && errors < MAX_FAAD_ERRORS) {
/* update buffer for raw aac streams: */
if(!sh->codecdata_len)
if(sh->a_in_buffer_len < sh->a_in_buffer_size){
sh->a_in_buffer_len +=
demux_read_data(sh->ds,&sh->a_in_buffer[sh->a_in_buffer_len],
sh->a_in_buffer_size - sh->a_in_buffer_len);
}
#ifdef DUMP_AAC_COMPRESSED
{int i;
for (i = 0; i < 16; i++)
printf ("%02X ", sh->a_in_buffer[i]);
printf ("\n");}
#endif
if(!sh->codecdata_len){
// raw aac stream:
do {
faac_sample_buffer = faacDecDecode(faac_hdec, &faac_finfo, sh->a_in_buffer, sh->a_in_buffer_len);
/* update buffer index after faacDecDecode */
if(faac_finfo.bytesconsumed >= sh->a_in_buffer_len) {
sh->a_in_buffer_len=0;
} else {
sh->a_in_buffer_len-=faac_finfo.bytesconsumed;
memmove(sh->a_in_buffer,&sh->a_in_buffer[faac_finfo.bytesconsumed],sh->a_in_buffer_len);
}
if(faac_finfo.error > 0) {
mp_msg(MSGT_DECAUDIO,MSGL_WARN,"FAAD: error: %s, trying to resync!\n",
faacDecGetErrorMessage(faac_finfo.error));
if (sh->a_in_buffer_len <= 0) {
errors = MAX_FAAD_ERRORS;
break;
}
sh->a_in_buffer_len--;
memmove(sh->a_in_buffer,&sh->a_in_buffer[1],sh->a_in_buffer_len);
aac_sync(sh);
errors++;
} else
break;
} while(errors < MAX_FAAD_ERRORS);
} else {
// packetized (.mp4) aac stream:
unsigned char* bufptr=NULL;
double pts;
int buflen=ds_get_packet_pts(sh->ds, &bufptr, &pts);
if(buflen<=0) break;
if (pts != MP_NOPTS_VALUE) {
sh->pts = pts;
sh->pts_bytes = 0;
}
faac_sample_buffer = faacDecDecode(faac_hdec, &faac_finfo, bufptr, buflen);
}
//for (j=0;j<faac_finfo.channels;j++) printf("%d:%d\n", j, faac_finfo.channel_position[j]);
if(faac_finfo.error > 0) {
mp_msg(MSGT_DECAUDIO,MSGL_WARN,"FAAD: Failed to decode frame: %s \n",
faacDecGetErrorMessage(faac_finfo.error));
} else if (faac_finfo.samples == 0) {
mp_msg(MSGT_DECAUDIO,MSGL_DBG2,"FAAD: Decoded zero samples!\n");
} else {
/* XXX: samples already multiplied by channels! */
mp_msg(MSGT_DECAUDIO,MSGL_DBG2,"FAAD: Successfully decoded frame (%ld Bytes)!\n",
sh->samplesize*faac_finfo.samples);
if (sh->channels >= 5)
reorder_channel_copy_nch(faac_sample_buffer,
AF_CHANNEL_LAYOUT_AAC_DEFAULT,
buf+len, AF_CHANNEL_LAYOUT_MPLAYER_DEFAULT,
sh->channels,
faac_finfo.samples, sh->samplesize);
else
memcpy(buf+len,faac_sample_buffer, sh->samplesize*faac_finfo.samples);
last_dec_len = sh->samplesize*faac_finfo.samples;
len += last_dec_len;
sh->pts_bytes += last_dec_len;
//printf("FAAD: buffer: %d bytes consumed: %d \n", k, faac_finfo.bytesconsumed);
}
}
return len;
}
|
{
"pile_set_name": "Github"
}
|
//Types of elements found in the DOM
module.exports = {
Text: "text", //Text
Directive: "directive", //<? ... ?>
Comment: "comment", //<!-- ... -->
Script: "script", //<script> tags
Style: "style", //<style> tags
Tag: "tag", //Any tag
CDATA: "cdata", //<![CDATA[ ... ]]>
isTag: function(elem){
return elem.type === "tag" || elem.type === "script" || elem.type === "style";
}
};
|
{
"pile_set_name": "Github"
}
|
module.exports={
"all": {
"100000": "四川",
"100100": "成都",
"100200": "资阳",
"100300": "阿坝",
"100400": "凉山",
"100500": "南充",
"100600": "乐山",
"100700": "达州",
"100800": "德阳",
"100900": "内江",
"101000": "攀枝花",
"101100": "广安",
"101200": "雅安",
"101300": "宜宾",
"101400": "绵阳",
"101500": "自贡",
"101600": "遂宁",
"101700": "广元",
"101800": "泸州",
"101900": "甘孜",
"102000": "巴中",
"102100": "眉山",
"110000": "贵州",
"110100": "贵阳",
"110200": "铜仁",
"110300": "黔东南",
"110400": "黔南",
"110500": "安顺",
"110600": "黔西",
"110700": "遵义",
"110800": "毕节",
"110900": "六盘水",
"120000": "河北",
"120100": "石家庄",
"120200": "唐山",
"120300": "衡水",
"120400": "承德",
"120500": "保定",
"120600": "邢台",
"120700": "沧州",
"120800": "张家口",
"120900": "邯郸",
"121000": "廊坊",
"121100": "秦皇岛",
"130000": "河南",
"130100": "郑州",
"130200": "周口",
"130300": "安阳",
"130400": "焦作",
"130500": "洛阳",
"130600": "濮阳",
"130700": "南阳",
"130800": "鹤壁",
"130900": "漯河",
"131000": "商丘",
"131100": "许昌",
"131200": "开封",
"131300": "信阳",
"131400": "新乡",
"131500": "三门峡",
"131600": "驻马店",
"131700": "平顶山",
"131800": "济源",
"140000": "吉林",
"140100": "长春",
"140200": "白城",
"140300": "吉林",
"140400": "四平",
"140500": "辽源",
"140600": "白山",
"140700": "通化",
"140800": "松原",
"140900": "延边",
"140903": "延吉",
"150000": "江西",
"150100": "南昌",
"150200": "萍乡",
"150300": "景德镇",
"150400": "吉安",
"150500": "鹰潭",
"150600": "九江",
"150700": "抚州",
"150800": "新余",
"150900": "上饶",
"151000": "赣州",
"151100": "宜春",
"160000": "辽宁",
"160100": "沈阳",
"160200": "本溪",
"160300": "辽阳",
"160400": "丹东",
"160500": "铁岭",
"160600": "锦州",
"160700": "抚顺",
"160800": "葫芦岛",
"160900": "鞍山",
"161000": "朝阳",
"161100": "营口",
"161200": "阜新",
"161300": "大连",
"161400": "盘锦",
"170000": "青海",
"170100": "西宁",
"170200": "海东",
"170300": "黄南",
"170400": "海南",
"170500": "果洛",
"170600": "玉树",
"170700": "海西",
"170800": "海北",
"180000": "山东",
"180100": "济南",
"180200": "烟台",
"180300": "日照",
"180400": "潍坊",
"180500": "青岛",
"180600": "临沂",
"180700": "淄博",
"180800": "莱芜",
"180900": "聊城",
"181000": "威海",
"181100": "枣庄",
"181200": "济宁",
"181300": "德州",
"181400": "泰安",
"181500": "菏泽",
"181600": "滨州",
"181700": "东营",
"181800": "东昌府",
"181900": "阳谷",
"182000": "莘县",
"182100": "茌平",
"182200": "东阿",
"182300": "冠县",
"182400": "高唐",
"190000": "山西",
"190100": "太原",
"190200": "晋城",
"190300": "晋中",
"190400": "忻州",
"190500": "大同",
"190600": "临汾",
"190700": "运城",
"190800": "阳泉",
"190900": "长治",
"191000": "吕梁",
"191100": "朔州",
"200000": "陕西",
"200100": "西安",
"200200": "咸阳",
"200300": "延安",
"200400": "渭南",
"200500": "榆林",
"200600": "安康",
"200700": "宝鸡",
"200800": "汉中",
"200900": "铜川",
"201000": "商洛",
"210000": "云南",
"210100": "昆明",
"210200": "文山",
"210300": "昭通",
"210400": "德宏",
"210500": "曲靖",
"210600": "西双版纳",
"210700": "普洱",
"210800": "迪庆",
"210900": "保山",
"211000": "玉溪",
"211100": "临沧",
"211200": "大理",
"211300": "丽江",
"211400": "楚雄",
"211500": "中甸",
"211600": "红河",
"211700": "怒江",
"220000": "广西",
"220100": "南宁",
"220200": "河池",
"220300": "来宾",
"220400": "百色",
"220500": "崇左",
"220600": "钦州",
"220700": "北海",
"220800": "桂林",
"220900": "玉林",
"221000": "柳州",
"221100": "梧州",
"221200": "防城港",
"221300": "贺州",
"221400": "贵港",
"230000": "海南",
"230100": "海口",
"230200": "陵水",
"230300": "三亚",
"230400": "儋州",
"230500": "琼海",
"230600": "保亭",
"230700": "万宁",
"230800": "五指山",
"230900": "文昌",
"231000": "东方",
"231100": "定安",
"231200": "屯昌",
"231300": "澄迈",
"231400": "临高",
"231500": "三沙",
"231600": "白沙",
"231700": "昌江",
"231800": "乐东",
"231900": "琼中",
"240000": "黑龙江",
"240100": "伊春",
"240200": "哈尔滨",
"240300": "牡丹江",
"240400": "佳木斯",
"240500": "七台河",
"240600": "绥化",
"240700": "齐齐哈尔",
"240800": "鸡西",
"240900": "大兴安岭",
"241000": "大庆",
"241100": "鹤岗",
"241200": "黑河",
"241300": "双鸭山",
"250000": "宁夏",
"250100": "银川",
"250200": "固原",
"250300": "石嘴山",
"250400": "吴忠",
"250500": "中卫",
"260000": "新疆",
"260100": "乌鲁木齐",
"260200": "哈密",
"260300": "克拉玛依",
"260400": "和田",
"260500": "石河子",
"260600": "阿克苏",
"260700": "伊犁哈萨克",
"260800": "博尔塔拉蒙古",
"260900": "克孜勒苏柯尔克孜",
"261000": "吐鲁番",
"261100": "塔城",
"261200": "昌吉",
"261300": "巴音郭楞蒙古",
"261400": "阿勒泰",
"261500": "阿拉尔",
"261600": "喀什",
"261700": "图木舒克",
"261800": "五家渠",
"270000": "西藏",
"270100": "拉萨",
"270200": "林芝",
"270300": "山南",
"270400": "那曲",
"270500": "昌都",
"270600": "阿里",
"270700": "日喀则",
"280000": "内蒙古",
"280100": "呼和浩特",
"280200": "赤峰",
"280300": "乌海",
"280400": "兴安",
"280500": "巴彦淖尔",
"280600": "阿拉善",
"280700": "呼伦贝尔",
"280703": "满洲里",
"280800": "乌兰察布",
"280900": "锡林郭勒",
"281000": "包头",
"281100": "通辽",
"281200": "鄂尔多斯",
"290000": "香港",
"290100": "香港",
"300000": "湖北",
"300100": "武汉",
"300200": "荆门",
"300300": "十堰",
"300400": "黄冈",
"300500": "恩施",
"300600": "天门",
"300700": "鄂州",
"300800": "神农架",
"300900": "襄阳",
"301000": "咸宁",
"301100": "随州",
"301200": "仙桃",
"301300": "潜江",
"301400": "孝感",
"301500": "黄石",
"301600": "宜昌",
"301700": "荆州",
"310000": "澳门",
"310100": "澳门",
"320000": "国外",
"320100": "国外",
"330000": "台湾",
"330100": "台北",
"330200": "高雄",
"330300": "基隆",
"330400": "嘉义",
"330500": "台南",
"330600": "台中",
"330700": "新竹",
"350000": "安徽",
"350100": "合肥",
"350200": "蚌埠",
"350300": "淮北",
"350400": "亳州",
"350500": "黄山",
"350600": "铜陵",
"350700": "安庆",
"350800": "淮南",
"350900": "宿州",
"351000": "阜阳",
"351100": "六安",
"351200": "滁州",
"351300": "宣城",
"351400": "马鞍山",
"351500": "芜湖",
"351600": "巢湖",
"351700": "池州",
"360000": "甘肃",
"360100": "兰州",
"360200": "平凉",
"360300": "天水",
"360400": "临夏",
"360500": "白银",
"360600": "庆阳",
"360700": "张掖",
"360800": "武威",
"360900": "嘉峪关",
"361000": "酒泉",
"361100": "金昌",
"361200": "陇南",
"361300": "定西",
"361400": "甘南",
"370000": "全国",
"370100": "全国",
"010000": "北京",
"010100": "东城",
"010200": "西城",
"010300": "崇文",
"010400": "宣武",
"010500": "朝阳",
"010600": "海淀",
"010700": "丰台",
"010800": "石景山",
"010900": "门头沟",
"011000": "房山",
"011100": "通州",
"011200": "顺义",
"011300": "昌平",
"011400": "大兴",
"011500": "平谷",
"011600": "怀柔",
"011700": "延庆",
"011800": "密云",
"020000": "天津",
"020100": "和平",
"020200": "河东",
"020300": "河西",
"020400": "南开",
"020500": "河北",
"020600": "红桥",
"020700": "塘沽",
"020800": "汉沽",
"020900": "大港",
"021000": "东丽",
"021100": "西青",
"021200": "津南",
"021300": "北辰",
"021400": "武清",
"021500": "宁和",
"021600": "静海",
"021700": "蓟县",
"021800": "宝坻",
"030000": "上海",
"030100": "黄浦",
"030200": "卢湾",
"030300": "徐汇",
"030400": "杨浦",
"030500": "长宁",
"030600": "静安",
"030700": "普陀",
"030800": "闸北",
"030900": "虹口",
"031000": "浦东",
"031100": "宝山",
"031200": "嘉定",
"031300": "闵行",
"031400": "金山",
"031500": "松江",
"031600": "青浦",
"031700": "奉贤",
"031800": "南汇",
"031900": "崇明",
"040000": "重庆",
"040100": "渝北",
"040200": "巴南",
"040300": "永川",
"040400": "南川",
"040500": "江津",
"040600": "合川",
"040700": "渝中",
"040800": "九龙坡",
"040900": "沙坪坝",
"041000": "南岸",
"041100": "江北",
"041200": "大渡口",
"041300": "北碚",
"041400": "长寿",
"041500": "万盛",
"041600": "双桥",
"041700": "涪陵",
"041800": "万州",
"041900": "黔江",
"042000": "綦江",
"042100": "潼南",
"042200": "铜梁",
"042300": "大足",
"042400": "荣昌",
"042500": "璧山",
"042600": "梁平",
"042700": "城口",
"042800": "丰都",
"042900": "垫江",
"043000": "武隆",
"043100": "忠县",
"043200": "开县",
"043300": "云阳",
"043400": "奉节",
"043500": "巫山",
"043600": "巫溪",
"043700": "石柱",
"043800": "秀山",
"043900": "酉江",
"044000": "彭水",
"050000": "浙江",
"050100": "杭州",
"050200": "宁波",
"050300": "温州",
"050400": "嘉兴",
"050500": "台州",
"050600": "金华",
"050700": "绍兴",
"050800": "湖州",
"050900": "丽水",
"051000": "衢州",
"051100": "舟山",
"060000": "江苏",
"060100": "南京",
"060200": "徐州",
"060300": "南通",
"060400": "镇江",
"060500": "连云港",
"060600": "常州",
"060700": "宿迁",
"060800": "淮安",
"060900": "无锡",
"061000": "盐城",
"061100": "苏州",
"061200": "泰州",
"061300": "扬州",
"070000": "广东",
"070100": "广州",
"070200": "深圳",
"070300": "韶关",
"070400": "肇庆",
"070500": "东莞",
"070600": "茂名",
"070700": "汕头",
"070800": "中山",
"070900": "梅州",
"071000": "佛山",
"071100": "惠州",
"071200": "阳江",
"071300": "潮州",
"071400": "江门",
"071500": "河源",
"071600": "汕尾",
"071700": "清远",
"071800": "湛江",
"071900": "珠海",
"072000": "揭阳",
"072100": "云浮",
"080000": "湖南",
"080100": "长沙",
"080200": "张家界",
"080300": "永州",
"080400": "郴州",
"080500": "湘西",
"080600": "湘潭",
"080700": "娄底",
"080800": "益阳",
"080900": "怀化",
"081000": "株洲",
"081100": "衡阳",
"081200": "岳阳",
"081300": "邵阳",
"081400": "常德",
"090000": "福建",
"090100": "福州",
"090200": "三明",
"090300": "南平",
"090400": "莆田",
"090500": "宁德",
"090600": "厦门",
"090700": "泉州",
"090800": "龙岩",
"090900": "漳州"
},
"province": [
"01","02","03","04","05","06","07","08","09","10","11","12","13","14","15","16","17","18","19","20","21","22","23","24","25","26","27","28","29","30","31","32","33","35","36","37"
],
"hot": [
"010000","070200","070100","230100","030000","050100","100100","061100","020000","300100"
]
}
|
{
"pile_set_name": "Github"
}
|
== Welcome to Rails
Rails is a web-application framework that includes everything needed to create
database-backed web applications according to the Model-View-Control pattern.
This pattern splits the view (also called the presentation) into "dumb" templates
that are primarily responsible for inserting pre-built data in between HTML tags.
The model contains the "smart" domain objects (such as Account, Product, Person,
Post) that holds all the business logic and knows how to persist themselves to
a database. The controller handles the incoming requests (such as Save New Account,
Update Product, Show Post) by manipulating the model and directing data to the view.
In Rails, the model is handled by what's called an object-relational mapping
layer entitled Active Record. This layer allows you to present the data from
database rows as objects and embellish these data objects with business logic
methods. You can read more about Active Record in
link:files/vendor/rails/activerecord/README.html.
The controller and view are handled by the Action Pack, which handles both
layers by its two parts: Action View and Action Controller. These two layers
are bundled in a single package due to their heavy interdependence. This is
unlike the relationship between the Active Record and Action Pack that is much
more separate. Each of these packages can be used independently outside of
Rails. You can read more about Action Pack in
link:files/vendor/rails/actionpack/README.html.
== Getting Started
1. At the command prompt, start a new Rails application using the <tt>rails</tt> command
and your application name. Ex: rails myapp
2. Change directory into myapp and start the web server: <tt>script/server</tt> (run with --help for options)
3. Go to http://localhost:3000/ and get "Welcome aboard: You're riding the Rails!"
4. Follow the guidelines to start developing your application
== Web Servers
By default, Rails will try to use Mongrel if it's are installed when started with script/server, otherwise Rails will use WEBrick, the webserver that ships with Ruby. But you can also use Rails
with a variety of other web servers.
Mongrel is a Ruby-based webserver with a C component (which requires compilation) that is
suitable for development and deployment of Rails applications. If you have Ruby Gems installed,
getting up and running with mongrel is as easy as: <tt>gem install mongrel</tt>.
More info at: http://mongrel.rubyforge.org
Say other Ruby web servers like Thin and Ebb or regular web servers like Apache or LiteSpeed or
Lighttpd or IIS. The Ruby web servers are run through Rack and the latter can either be setup to use
FCGI or proxy to a pack of Mongrels/Thin/Ebb servers.
== Apache .htaccess example for FCGI/CGI
# General Apache options
AddHandler fastcgi-script .fcgi
AddHandler cgi-script .cgi
Options +FollowSymLinks +ExecCGI
# If you don't want Rails to look in certain directories,
# use the following rewrite rules so that Apache won't rewrite certain requests
#
# Example:
# RewriteCond %{REQUEST_URI} ^/notrails.*
# RewriteRule .* - [L]
# Redirect all requests not available on the filesystem to Rails
# By default the cgi dispatcher is used which is very slow
#
# For better performance replace the dispatcher with the fastcgi one
#
# Example:
# RewriteRule ^(.*)$ dispatch.fcgi [QSA,L]
RewriteEngine On
# If your Rails application is accessed via an Alias directive,
# then you MUST also set the RewriteBase in this htaccess file.
#
# Example:
# Alias /myrailsapp /path/to/myrailsapp/public
# RewriteBase /myrailsapp
RewriteRule ^$ index.html [QSA]
RewriteRule ^([^.]+)$ $1.html [QSA]
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^(.*)$ dispatch.cgi [QSA,L]
# In case Rails experiences terminal errors
# Instead of displaying this message you can supply a file here which will be rendered instead
#
# Example:
# ErrorDocument 500 /500.html
ErrorDocument 500 "<h2>Application error</h2>Rails application failed to start properly"
== Debugging Rails
Sometimes your application goes wrong. Fortunately there are a lot of tools that
will help you debug it and get it back on the rails.
First area to check is the application log files. Have "tail -f" commands running
on the server.log and development.log. Rails will automatically display debugging
and runtime information to these files. Debugging info will also be shown in the
browser on requests from 127.0.0.1.
You can also log your own messages directly into the log file from your code using
the Ruby logger class from inside your controllers. Example:
class WeblogController < ActionController::Base
def destroy
@weblog = Weblog.find(params[:id])
@weblog.destroy
logger.info("#{Time.now} Destroyed Weblog ID ##{@weblog.id}!")
end
end
The result will be a message in your log file along the lines of:
Mon Oct 08 14:22:29 +1000 2007 Destroyed Weblog ID #1
More information on how to use the logger is at http://www.ruby-doc.org/core/
Also, Ruby documentation can be found at http://www.ruby-lang.org/ including:
* The Learning Ruby (Pickaxe) Book: http://www.ruby-doc.org/docs/ProgrammingRuby/
* Learn to Program: http://pine.fm/LearnToProgram/ (a beginners guide)
These two online (and free) books will bring you up to speed on the Ruby language
and also on programming in general.
== Debugger
Debugger support is available through the debugger command when you start your Mongrel or
Webrick server with --debugger. This means that you can break out of execution at any point
in the code, investigate and change the model, AND then resume execution!
You need to install ruby-debug to run the server in debugging mode. With gems, use 'gem install ruby-debug'
Example:
class WeblogController < ActionController::Base
def index
@posts = Post.find(:all)
debugger
end
end
So the controller will accept the action, run the first line, then present you
with a IRB prompt in the server window. Here you can do things like:
>> @posts.inspect
=> "[#<Post:0x14a6be8 @attributes={\"title\"=>nil, \"body\"=>nil, \"id\"=>\"1\"}>,
#<Post:0x14a6620 @attributes={\"title\"=>\"Rails you know!\", \"body\"=>\"Only ten..\", \"id\"=>\"2\"}>]"
>> @posts.first.title = "hello from a debugger"
=> "hello from a debugger"
...and even better is that you can examine how your runtime objects actually work:
>> f = @posts.first
=> #<Post:0x13630c4 @attributes={"title"=>nil, "body"=>nil, "id"=>"1"}>
>> f.
Display all 152 possibilities? (y or n)
Finally, when you're ready to resume execution, you enter "cont"
== Console
You can interact with the domain model by starting the console through <tt>script/console</tt>.
Here you'll have all parts of the application configured, just like it is when the
application is running. You can inspect domain models, change values, and save to the
database. Starting the script without arguments will launch it in the development environment.
Passing an argument will specify a different environment, like <tt>script/console production</tt>.
To reload your controllers and models after launching the console run <tt>reload!</tt>
== dbconsole
You can go to the command line of your database directly through <tt>script/dbconsole</tt>.
You would be connected to the database with the credentials defined in database.yml.
Starting the script without arguments will connect you to the development database. Passing an
argument will connect you to a different database, like <tt>script/dbconsole production</tt>.
Currently works for mysql, postgresql and sqlite.
== Description of Contents
app
Holds all the code that's specific to this particular application.
app/controllers
Holds controllers that should be named like weblogs_controller.rb for
automated URL mapping. All controllers should descend from ApplicationController
which itself descends from ActionController::Base.
app/models
Holds models that should be named like post.rb.
Most models will descend from ActiveRecord::Base.
app/views
Holds the template files for the view that should be named like
weblogs/index.html.erb for the WeblogsController#index action. All views use eRuby
syntax.
app/views/layouts
Holds the template files for layouts to be used with views. This models the common
header/footer method of wrapping views. In your views, define a layout using the
<tt>layout :default</tt> and create a file named default.html.erb. Inside default.html.erb,
call <% yield %> to render the view using this layout.
app/helpers
Holds view helpers that should be named like weblogs_helper.rb. These are generated
for you automatically when using script/generate for controllers. Helpers can be used to
wrap functionality for your views into methods.
config
Configuration files for the Rails environment, the routing map, the database, and other dependencies.
db
Contains the database schema in schema.rb. db/migrate contains all
the sequence of Migrations for your schema.
doc
This directory is where your application documentation will be stored when generated
using <tt>rake doc:app</tt>
lib
Application specific libraries. Basically, any kind of custom code that doesn't
belong under controllers, models, or helpers. This directory is in the load path.
public
The directory available for the web server. Contains subdirectories for images, stylesheets,
and javascripts. Also contains the dispatchers and the default HTML files. This should be
set as the DOCUMENT_ROOT of your web server.
script
Helper scripts for automation and generation.
test
Unit and functional tests along with fixtures. When using the script/generate scripts, template
test files will be generated for you and placed in this directory.
vendor
External libraries that the application depends on. Also includes the plugins subdirectory.
If the app has frozen rails, those gems also go here, under vendor/rails/.
This directory is in the load path.
|
{
"pile_set_name": "Github"
}
|
<?php
// +----------------------------------------------------------------------
// | framework
// +----------------------------------------------------------------------
// | 版权所有 2014~2018 广州楚才信息科技有限公司 [ http://www.cuci.cc ]
// +----------------------------------------------------------------------
// | 官方网站: http://framework.thinkadmin.top
// +----------------------------------------------------------------------
// | 开源协议 ( https://mit-license.org )
// +----------------------------------------------------------------------
// | github开源项目:https://github.com/zoujingli/framework
// +----------------------------------------------------------------------
namespace app\wechat\controller\api;
use app\wechat\service\WechatService;
use library\Controller;
/**
* 微信测试工具
* Class Tools
* @package app\wechat\controller\api
*/
class Tools extends Controller
{
/**
* 网页授权测试
* @return string
* @throws \WeChat\Exceptions\InvalidResponseException
* @throws \WeChat\Exceptions\LocalCacheException
* @throws \think\Exception
* @throws \think\exception\PDOException
*/
public function oauth()
{
$this->url = $this->request->url(true);
$this->fans = WechatService::getWebOauthInfo($this->url, 1);
$this->fetch();
}
/**
* 显示网页授权二维码
* @return \think\Response
* @throws \Endroid\QrCode\Exceptions\ImageFunctionFailedException
* @throws \Endroid\QrCode\Exceptions\ImageFunctionUnknownException
* @throws \Endroid\QrCode\Exceptions\ImageTypeInvalidException
*/
public function oauth_qrc()
{
$url = url('@wechat/api.tools/oauth', '', true, true);
return $this->showQrc($url);
}
/**
* JSSDK测试
* @return string
* @throws \WeChat\Exceptions\InvalidResponseException
* @throws \WeChat\Exceptions\LocalCacheException
* @throws \think\Exception
* @throws \think\exception\PDOException
*/
public function jssdk()
{
$this->options = WechatService::getWebJssdkSign();
$this->fetch();
}
/**
* 显示网页授权二维码
* @throws \Endroid\QrCode\Exceptions\ImageFunctionFailedException
* @throws \Endroid\QrCode\Exceptions\ImageFunctionUnknownException
* @throws \Endroid\QrCode\Exceptions\ImageTypeInvalidException
*/
public function jssdk_qrc()
{
$this->url = url('@wechat/api.tools/jssdk', '', true, true);
return $this->showQrc($this->url);
}
/**
* 微信扫码支付模式一二维码显示
* @throws \Endroid\QrCode\Exceptions\ImageFunctionFailedException
* @throws \Endroid\QrCode\Exceptions\ImageFunctionUnknownException
* @throws \Endroid\QrCode\Exceptions\ImageTypeInvalidException
*/
public function scanOneQrc()
{
$pay = WechatService::WePayOrder();
$result = $pay->qrcParams('8888888');
$this->showQrc($result);
}
/**
* 微信扫码支付模式一通知处理
* @return string
* @throws \WeChat\Exceptions\InvalidResponseException
* @throws \WeChat\Exceptions\LocalCacheException
*/
public function scanOneNotify()
{
$pay = WechatService::WePayOrder();
$notify = $pay->getNotify();
p('======= 来自扫码支付1的数据 ======');
p($notify);
// 产品ID 你的业务代码,并实现下面的统一下单操作
$product_id = $notify['product_id'];
// 微信统一下单处理
$options = [
'body' => '测试商品,产品ID:' . $product_id,
'out_trade_no' => time(),
'total_fee' => '1',
'trade_type' => 'NATIVE',
'notify_url' => url('@wechat/api.tools/notify', '', true, true),
'spbill_create_ip' => request()->ip(),
];
$order = $pay->create($options);
p('======= 来自扫码支付1统一下单结果 ======');
p($order);
// 回复XML文本
$result = [
'return_code' => 'SUCCESS',
'return_msg' => '处理成功',
'appid' => $notify['appid'],
'mch_id' => $notify['mch_id'],
'nonce_str' => \WeChat\Contracts\Tools::createNoncestr(),
'prepay_id' => $order['prepay_id'],
'result_code' => 'SUCCESS',
];
$result['sign'] = $pay->getPaySign($result);
p('======= 来自扫码支付1返回的结果 ======');
p($result);
return \WeChat\Contracts\Tools::arr2xml($result);
}
/**
* 扫码支付模式二测试二维码
* @throws \Endroid\QrCode\Exceptions\ImageFunctionFailedException
* @throws \Endroid\QrCode\Exceptions\ImageFunctionUnknownException
* @throws \Endroid\QrCode\Exceptions\ImageTypeInvalidException
* @throws \WeChat\Exceptions\InvalidResponseException
* @throws \WeChat\Exceptions\LocalCacheException
*/
public function scanQrc()
{
$pay = WechatService::WePayOrder();
$result = $pay->create([
'body' => '测试商品',
'out_trade_no' => time(),
'total_fee' => '1',
'trade_type' => 'NATIVE',
'notify_url' => url('@wechat/api.tools/notify', '', true, true),
'spbill_create_ip' => request()->ip(),
]);
$this->showQrc($result['code_url']);
}
/**
* 微信JSAPI支付二维码
* @return \think\Response
* @throws \Endroid\QrCode\Exceptions\ImageFunctionFailedException
* @throws \Endroid\QrCode\Exceptions\ImageFunctionUnknownException
* @throws \Endroid\QrCode\Exceptions\ImageTypeInvalidException
*/
public function jsapiQrc()
{
$this->url = url('@wechat/api.tools/jsapi', '', true, true);
return $this->showQrc($this->url);
}
/**
* 微信JSAPI支付测试
* @throws \WeChat\Exceptions\InvalidResponseException
* @throws \WeChat\Exceptions\LocalCacheException
* @throws \think\Exception
* @throws \think\exception\PDOException
* @link wx-demo-jsapi
*/
public function jsapi()
{
$pay = WechatService::WePayOrder();
$openid = WechatService::getWebOauthInfo(request()->url(true), 0)['openid'];
$options = [
'body' => '测试商品',
'out_trade_no' => time(),
'total_fee' => '1',
'openid' => $openid,
'trade_type' => 'JSAPI',
'notify_url' => url('@wechat/api.tools/notify', '', true, true),
'spbill_create_ip' => request()->ip(),
];
// 生成预支付码
$result = $pay->create($options);
// 创建JSAPI参数签名
$options = $pay->jsapiParams($result['prepay_id']);
$optionJSON = json_encode($options, JSON_UNESCAPED_UNICODE);
// JSSDK 签名配置
$configJSON = json_encode(WechatService::getWebJssdkSign(), JSON_UNESCAPED_UNICODE);
echo '<pre>';
echo "当前用户OPENID: {$openid}";
echo "\n--- 创建预支付码 ---\n";
var_export($result);
echo '</pre>';
echo '<pre>';
echo "\n\n--- JSAPI 及 H5 参数 ---\n";
var_export($options);
echo '</pre>';
echo "<button id='paytest' type='button'>JSAPI支付测试</button>";
echo "
<script src='//res.wx.qq.com/open/js/jweixin-1.2.0.js'></script>
<script>
wx.config($configJSON);
document.getElementById('paytest').onclick = function(){
var options = $optionJSON;
options.success = function(){
alert('支付成功');
}
wx.chooseWXPay(options);
}
</script>";
}
/**
* 支付通知接收处理
* @return string
* @throws \WeChat\Exceptions\InvalidResponseException
*/
public function notify()
{
$wechat = WechatService::WePayOrder();
p($wechat->getNotify());
return 'SUCCESS';
}
/**
* 创建二维码响应对应
* @param string $url 二维码内容
* @throws \Endroid\QrCode\Exceptions\ImageFunctionFailedException
* @throws \Endroid\QrCode\Exceptions\ImageFunctionUnknownException
* @throws \Endroid\QrCode\Exceptions\ImageTypeInvalidException
*/
protected function showQrc($url)
{
$qrCode = new \Endroid\QrCode\QrCode();
$qrCode->setText($url)->setSize(300)->setPadding(20)->setImageType('png');
response($qrCode->get(), 200, ['Content-Type' => 'image/png'])->send();
}
}
|
{
"pile_set_name": "Github"
}
|
@extends('layouts.app')
@section('content')
<div class="container">
<div class="row">
<div class="col-md-8 col-md-offset-2">
<div class="panel panel-default">
<div class="panel-heading">Login</div>
<div class="panel-body">
<form class="form-horizontal" method="POST" action="{{ route('login') }}">
{{ csrf_field() }}
<div class="form-group{{ $errors->has('email') ? ' has-error' : '' }}">
<label for="email" class="col-md-4 control-label">E-Mail Address</label>
<div class="col-md-6">
<input id="email" type="email" class="form-control" name="email" value="{{ old('email') }}" required autofocus>
@if ($errors->has('email'))
<span class="help-block">
<strong>{{ $errors->first('email') }}</strong>
</span>
@endif
</div>
</div>
<div class="form-group{{ $errors->has('password') ? ' has-error' : '' }}">
<label for="password" class="col-md-4 control-label">Password</label>
<div class="col-md-6">
<input id="password" type="password" class="form-control" name="password" required>
@if ($errors->has('password'))
<span class="help-block">
<strong>{{ $errors->first('password') }}</strong>
</span>
@endif
</div>
</div>
<div class="form-group">
<div class="col-md-6 col-md-offset-4">
<div class="checkbox">
<label>
<input type="checkbox" name="remember" {{ old('remember') ? 'checked' : '' }}> Remember Me
</label>
</div>
</div>
</div>
<div class="form-group">
<div class="col-md-8 col-md-offset-4">
<button type="submit" class="btn btn-primary">
Login
</button>
<a class="btn btn-link" href="{{ route('password.request') }}">
Forgot Your Password?
</a>
</div>
</div>
</form>
</div>
</div>
</div>
</div>
</div>
@endsection
|
{
"pile_set_name": "Github"
}
|
import unittest
from checkov.cloudformation.checks.resource.registry import cfn_registry as registry
class TestScannerRegistry(unittest.TestCase):
def test_num_of_scanners(self):
scanners_counter = 0
for key in list(registry.checks.keys()):
scanners_counter += len(registry.checks[key])
self.assertGreater(scanners_counter, 1)
def test_non_colliding_check_ids(self):
check_id_check_class_map = {}
for (resource_type, checks) in registry.checks.items():
for check in checks:
check_id_check_class_map.setdefault(check.id, []).append(check)
for check_id, check_classes in check_id_check_class_map.items():
self.assertEqual(len(set(check_classes)), 1)
if __name__ == '__main__':
unittest.main()
|
{
"pile_set_name": "Github"
}
|
# wcsdup.m4 serial 3
dnl Copyright (C) 2011-2020 Free Software Foundation, Inc.
dnl This file is free software; the Free Software Foundation
dnl gives unlimited permission to copy and/or distribute it,
dnl with or without modifications, as long as this notice is preserved.
AC_DEFUN([gl_FUNC_WCSDUP],
[
AC_REQUIRE([gl_WCHAR_H_DEFAULTS])
AC_CACHE_CHECK([for wcsdup],
[gl_cv_func_wcsdup],
[AC_LINK_IFELSE(
[AC_LANG_PROGRAM(
[[
/* Tru64 with Desktop Toolkit C has a bug: <stdio.h> must be included before
<wchar.h>.
BSD/OS 4.0.1 has a bug: <stddef.h>, <stdio.h> and <time.h> must be included
before <wchar.h>. */
#include <stddef.h>
#include <stdio.h>
#include <time.h>
#include <wchar.h>
]GL_MDA_DEFINES],
[[return wcsdup (L"hello") != NULL;]])
],
[gl_cv_func_wcsdup=yes],
[gl_cv_func_wcsdup=no])
])
if test $gl_cv_func_wcsdup = no; then
HAVE_WCSDUP=0
fi
])
|
{
"pile_set_name": "Github"
}
|
using Rebus.Config;
using Rebus.Logging;
using Rebus.Pipeline;
using Rebus.Pipeline.Receive;
using Rebus.Pipeline.Send;
using Rebus.Transport;
namespace Rebus.Sagas.Idempotent
{
/// <summary>
/// Configuration extension for the idempotent sagas feature (allows for guaranteeing that a saga instance does not handle the same
/// message twice, even in the face of at-least-once delivery guarantees and retries due to transport layer failures)
/// </summary>
public static class IdempotentSagaConfigurationExtensions
{
/// <summary>
/// Enables idempotent sagas. When enabled, sagas derived from <see cref="IdempotentSaga{TSagaData}"/> can be truly idempotent.
/// This means that the saga instance stores the IDs of all handled messages, including all outgoing messages send when handling
/// each incoming message - this way, the saga instance can guard itself against handling the same message twice, while still
/// preserving externally visible behavior even when a message gets handled more than once.
/// </summary>
public static void EnableIdempotentSagas(this OptionsConfigurer configurer)
{
configurer.Decorate<IPipeline>(c =>
{
var transport = c.Get<ITransport>();
var pipeline = c.Get<IPipeline>();
var rebusLoggerFactory = c.Get<IRebusLoggerFactory>();
var incomingStep = new IdempotentSagaIncomingStep(transport, rebusLoggerFactory);
var outgoingStep = new IdempotentSagaOutgoingStep();
var injector = new PipelineStepInjector(pipeline)
.OnReceive(incomingStep, PipelineRelativePosition.Before, typeof (DispatchIncomingMessageStep))
.OnSend(outgoingStep, PipelineRelativePosition.After, typeof (SendOutgoingMessageStep));
return injector;
});
}
}
}
|
{
"pile_set_name": "Github"
}
|
#unittest {
name: "Simple closure.";
error: NONE;
result: 30;
};
func f1(a) {
return func(b) {
return a + b;
}
}
func main() {
var addTen = f1(10);
return addTen(20);
}
|
{
"pile_set_name": "Github"
}
|
/*
* Copyright 2014 Google Inc. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.recipe_app.client;
import android.app.Activity;
import android.app.Fragment;
import android.app.FragmentManager;
import android.app.FragmentTransaction;
import android.content.Intent;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.support.v13.app.FragmentPagerAdapter;
import android.support.v4.view.ViewPager;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.ProgressBar;
import android.widget.TableLayout;
import android.widget.TableRow;
import android.widget.TextView;
import android.widget.Toast;
import com.google.android.gms.appindexing.AppIndex;
import com.google.android.gms.common.api.GoogleApiClient;
import com.google.android.gms.common.api.PendingResult;
import com.google.android.gms.common.api.ResultCallback;
import com.google.android.gms.common.api.Status;
import com.recipe_app.R;
import com.recipe_app.client.content_provider.RecipeContentProvider;
import com.recipe_app.client.database.RecipeTable;
import com.squareup.picasso.Callback;
import com.squareup.picasso.Picasso;
/**
* This Activity class is used to display a {@link com.recipe_app.client.Recipe} object
*/
public class RecipeActivity extends Activity {
private static final String TAG = RecipeActivity.class.getName();
private static final Uri BASE_APP_URI = Uri.parse("android-app://com.recipe_app/http/recipe-app.com/recipe/");
private GoogleApiClient mClient;
/**
* The {@link android.support.v4.view.PagerAdapter} that will provide
* fragments for each of the sections. We use a
* {@link FragmentPagerAdapter} derivative, which will keep every
* loaded fragment in memory. If this becomes too memory intensive, it
* may be best to switch to a
* {@link android.support.v13.app.FragmentStatePagerAdapter}.
*/
private SectionsPagerAdapter mSectionsPagerAdapter;
/**
* The {@link ViewPager} that will host the section contents.
*/
private ViewPager mViewPager;
private Recipe recipe;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_recipe);
mClient = new GoogleApiClient.Builder(this).addApi(AppIndex.APP_INDEX_API).build();
onNewIntent(getIntent());
}
protected void onNewIntent(Intent intent) {
String action = intent.getAction();
String data = intent.getDataString();
if (Intent.ACTION_VIEW.equals(action) && data != null) {
String recipeId = data.substring(data.lastIndexOf("/") + 1);
Uri contentUri = RecipeContentProvider.CONTENT_URI.buildUpon()
.appendPath(recipeId).build();
showRecipe(contentUri);
}
}
@Override
public void onStart(){
super.onStart();
if (recipe != null) {
// Connect your client
mClient.connect();
// Define a title for your current page, shown in autocompletion UI
final String TITLE = recipe.getTitle();
final Uri APP_URI = BASE_APP_URI.buildUpon().appendPath(recipe.getId()).build();
final Uri WEB_URL = Uri.parse(recipe.getUrl());
// Call the App Indexing API view method
PendingResult<Status> result = AppIndex.AppIndexApi.view(mClient, this,
APP_URI, TITLE, WEB_URL, null);
result.setResultCallback(new ResultCallback<Status>() {
@Override
public void onResult(Status status) {
if (status.isSuccess()) {
Log.d(TAG, "App Indexing API: Recorded recipe "
+ recipe.getTitle() + " view successfully.");
} else {
Log.e(TAG, "App Indexing API: There was an error recording the recipe view."
+ status.toString());
}
}
});
}
}
@Override
public void onStop(){
super.onStop();
if (recipe != null) {
final Uri APP_URI = BASE_APP_URI.buildUpon().appendPath(recipe.getId()).build();
PendingResult<Status> result = AppIndex.AppIndexApi.viewEnd(mClient, this, APP_URI);
result.setResultCallback(new ResultCallback<Status>() {
@Override
public void onResult(Status status) {
if (status.isSuccess()) {
Log.d(TAG, "App Indexing API: Recorded recipe "
+ recipe.getTitle() + " view end successfully.");
} else {
Log.e(TAG, "App Indexing API: There was an error recording the recipe view."
+ status.toString());
}
}
});
mClient.disconnect();
}
}
private void showRecipe(Uri recipeUri) {
Log.d("Recipe Uri", recipeUri.toString());
String[] projection = { RecipeTable.ID, RecipeTable.TITLE,
RecipeTable.DESCRIPTION, RecipeTable.PHOTO,
RecipeTable.PREP_TIME};
Cursor cursor = getContentResolver().query(recipeUri, projection, null, null, null);
if (cursor != null && cursor.moveToFirst()) {
recipe = Recipe.fromCursor(cursor);
Uri ingredientsUri = RecipeContentProvider.CONTENT_URI.buildUpon().appendPath("ingredients").appendPath(recipe.getId()).build();
Cursor ingredientsCursor = getContentResolver().query(ingredientsUri, projection, null, null, null);
if (ingredientsCursor != null && ingredientsCursor.moveToFirst()) {
do {
Recipe.Ingredient ingredient = new Recipe.Ingredient();
ingredient.setAmount(ingredientsCursor.getString(0));
ingredient.setDescription(ingredientsCursor.getString(1));
recipe.addIngredient(ingredient);
ingredientsCursor.moveToNext();
} while (!ingredientsCursor.isAfterLast());
ingredientsCursor.close();
}
Uri instructionsUri = RecipeContentProvider.CONTENT_URI.buildUpon().appendPath("instructions").appendPath(recipe.getId()).build();
Cursor instructionsCursor = getContentResolver().query(instructionsUri, projection, null, null, null);
if (instructionsCursor != null && instructionsCursor.moveToFirst()) {
do {
Recipe.Step step = new Recipe.Step();
step.setDescription(instructionsCursor.getString(1));
step.setPhoto(instructionsCursor.getString(2));
recipe.addStep(step);
instructionsCursor.moveToNext();
} while (!instructionsCursor.isAfterLast());
instructionsCursor.close();
}
// always close the cursor
cursor.close();
} else {
Toast toast = Toast.makeText(getApplicationContext(),
"No match for deep link " + recipeUri.toString(),
Toast.LENGTH_SHORT);
toast.show();
}
if (recipe != null) {
// Create the adapter that will return a fragment for each of the steps of the recipe.
mSectionsPagerAdapter = new SectionsPagerAdapter(getFragmentManager());
// Set up the ViewPager with the sections adapter.
mViewPager = (ViewPager) findViewById(R.id.pager);
mViewPager.setAdapter(mSectionsPagerAdapter);
// Set the recipe title
TextView recipeTitle = (TextView) findViewById(R.id.recipeTitle);
recipeTitle.setText(recipe.getTitle());
// Set the recipe prep time
TextView recipeTime = (TextView) findViewById(R.id.recipeTime);
recipeTime.setText(" " + recipe.getPrepTime());
}
}
/**
* A {@link FragmentPagerAdapter} that returns a fragment corresponding to
* one of the sections/tabs/pages.
*/
public class SectionsPagerAdapter extends FragmentPagerAdapter {
public SectionsPagerAdapter(FragmentManager fm) {
super(fm);
}
@Override
public Fragment getItem(int position) {
// getItem is called to instantiate the fragment for the given page.
// Return a PlaceholderFragment (defined as a static inner class below).
return RecipeFragment.newInstance(recipe, position + 1);
}
@Override
public int getCount() {
if (recipe != null) {
return recipe.getInstructions().size() + 1;
} else {
return 0;
}
}
@Override
public CharSequence getPageTitle(int position) {
return null;
}
}
/**
* A placeholder fragment containing a simple view.
*/
public static class RecipeFragment extends Fragment {
/**
* The fragment argument representing the section number for this
* fragment.
*/
private static final String ARG_SECTION_NUMBER = "section_number";
private Recipe recipe;
private ProgressBar progressBar;
private ImageView recipeImage;
/**
* Returns a new instance of this fragment for the given section
* number.
*/
public static RecipeFragment newInstance(Recipe recipe, int sectionNumber) {
RecipeFragment fragment = new RecipeFragment();
fragment.recipe = recipe;
Bundle args = new Bundle();
args.putInt(ARG_SECTION_NUMBER, sectionNumber);
fragment.setArguments(args);
return fragment;
}
public RecipeFragment() {
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_recipe, container, false);
this.recipe = ((RecipeActivity)getActivity()).recipe;
progressBar = (ProgressBar) rootView.findViewById(R.id.loading);
recipeImage = (ImageView)rootView.findViewById(R.id.recipe_image);
String photoUrl = recipe.getPhoto();
int sectionNumber = this.getArguments().getInt(ARG_SECTION_NUMBER);
if (sectionNumber > 1) {
Recipe.Step step = recipe.getInstructions().get(sectionNumber - 2);
if (step.getPhoto() != null) {
photoUrl = step.getPhoto();
}
}
Picasso.with(rootView.getContext())
.load(photoUrl)
.into(recipeImage, new Callback.EmptyCallback() {
@Override
public void onSuccess() {
progressBar.setVisibility(View.GONE);
Log.d("Picasso", "Image loaded successfully");
}
@Override
public void onError() {
progressBar.setVisibility(View.GONE);
Log.d("Picasso", "Failed to load image");
}
});
FragmentTransaction transaction = getChildFragmentManager().beginTransaction();
if (sectionNumber == 1) {
Fragment ingredientsFragment = IngredientsFragment.newInstance(recipe, sectionNumber);
transaction.replace(R.id.ingredients_fragment, ingredientsFragment).commit();
} else {
Fragment instructionFragment = InstructionFragment.newInstance(recipe, sectionNumber);
transaction.replace(R.id.instruction_fragment, instructionFragment).commit();
}
return rootView;
}
}
/**
* A placeholder fragment containing a simple view.
*/
public static class IngredientsFragment extends Fragment {
/**
* The fragment argument representing the section number for this
* fragment.
*/
private static final String ARG_SECTION_NUMBER = "section_number";
private Recipe recipe;
/**
* Returns a new instance of this fragment for the given section
* number.
*/
public static IngredientsFragment newInstance(Recipe recipe, int sectionNumber) {
IngredientsFragment fragment = new IngredientsFragment();
fragment.recipe = recipe;
Bundle args = new Bundle();
args.putInt(ARG_SECTION_NUMBER, sectionNumber);
fragment.setArguments(args);
return fragment;
}
public IngredientsFragment() {
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.ingredients_fragment, container, false);
this.recipe = ((RecipeActivity)getActivity()).recipe;
TableLayout table = (TableLayout)rootView.findViewById(R.id.ingredientsTable);
for (Recipe.Ingredient ingredient : recipe.getIngredients()) {
TableRow row = (TableRow)inflater.inflate(R.layout.ingredients_row, null);
((TextView)row.findViewById(R.id.attrib_name)).setText(ingredient.getAmount());
((TextView)row.findViewById(R.id.attrib_value)).setText(ingredient.getDescription());
table.addView(row);
}
return rootView;
}
}
/**
* A placeholder fragment containing a simple view.
*/
public static class InstructionFragment extends Fragment {
/**
* The fragment argument representing the section number for this
* fragment.
*/
private static final String ARG_SECTION_NUMBER = "section_number";
private Recipe recipe;
/**
* Returns a new instance of this fragment for the given section
* number.
*/
public static InstructionFragment newInstance(Recipe recipe, int sectionNumber) {
InstructionFragment fragment = new InstructionFragment();
fragment.recipe = recipe;
Bundle args = new Bundle();
args.putInt(ARG_SECTION_NUMBER, sectionNumber);
fragment.setArguments(args);
return fragment;
}
public InstructionFragment() {
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.instructions_fragment, container, false);
int sectionNumber = this.getArguments().getInt(ARG_SECTION_NUMBER);
this.recipe = ((RecipeActivity)getActivity()).recipe;
TextView instructionTitle = (TextView)rootView.findViewById(R.id.instructionTitle);
instructionTitle.setText("Step " + Integer.toString(sectionNumber - 1));
Recipe.Step step = recipe.getInstructions().get(sectionNumber - 2);
TextView instructionBody = (TextView)rootView.findViewById(R.id.instructionBody);
instructionBody.setText(step.getDescription());
return rootView;
}
}
}
|
{
"pile_set_name": "Github"
}
|
using System;
using System.Reflection;
namespace iSpyApplication.Controls
{
public class Reflector
{
#region variables
readonly string _mNs;
readonly Assembly _mAsmb;
#endregion
#region Constructors
/// <summary>
/// Constructor
/// </summary>
/// <param name="ns">The namespace containing types to be used</param>
public Reflector(string ns)
: this(ns, ns)
{ }
/// <summary>
/// Constructor
/// </summary>
/// <param name="an">A specific assembly name (used if the assembly name does not tie exactly with the namespace)</param>
/// <param name="ns">The namespace containing types to be used</param>
public Reflector(string an, string ns)
{
_mNs = ns;
_mAsmb = null;
foreach (AssemblyName aN in Assembly.GetExecutingAssembly().GetReferencedAssemblies())
{
if (aN.FullName.StartsWith(an))
{
_mAsmb = Assembly.Load(aN);
break;
}
}
}
#endregion
#region Methods
/// <summary>
/// Return a Type instance for a type 'typeName'
/// </summary>
/// <param name="typeName">The name of the type</param>
/// <returns>A type instance</returns>
public Type GetType(string typeName)
{
Type type = null;
string[] names = typeName.Split('.');
if (names.Length > 0)
type = _mAsmb.GetType(_mNs + "." + names[0]);
for (int i = 1; i < names.Length; ++i)
{
type = type?.GetNestedType(names[i], BindingFlags.NonPublic);
}
return type;
}
/// <summary>
/// Create a new object of a named type passing along any params
/// </summary>
/// <param name="name">The name of the type to create</param>
/// <param name="parameters"></param>
/// <returns>An instantiated type</returns>
public object New(string name, params object[] parameters)
{
Type type = GetType(name);
ConstructorInfo[] ctorInfos = type.GetConstructors();
foreach (ConstructorInfo ci in ctorInfos) {
try {
return ci.Invoke(parameters);
}
catch
{
// ignored
}
}
return null;
}
/// <summary>
/// Calls method 'func' on object 'obj' passing parameters 'parameters'
/// </summary>
/// <param name="obj">The object on which to excute function 'func'</param>
/// <param name="func">The function to execute</param>
/// <param name="parameters">The parameters to pass to function 'func'</param>
/// <returns>The result of the function invocation</returns>
public object Call(object obj, string func, params object[] parameters)
{
return Call2(obj, func, parameters);
}
/// <summary>
/// Calls method 'func' on object 'obj' passing parameters 'parameters'
/// </summary>
/// <param name="obj">The object on which to excute function 'func'</param>
/// <param name="func">The function to execute</param>
/// <param name="parameters">The parameters to pass to function 'func'</param>
/// <returns>The result of the function invocation</returns>
public object Call2(object obj, string func, object[] parameters)
{
return CallAs2(obj.GetType(), obj, func, parameters);
}
/// <summary>
/// Calls method 'func' on object 'obj' which is of type 'type' passing parameters 'parameters'
/// </summary>
/// <param name="type">The type of 'obj'</param>
/// <param name="obj">The object on which to excute function 'func'</param>
/// <param name="func">The function to execute</param>
/// <param name="parameters">The parameters to pass to function 'func'</param>
/// <returns>The result of the function invocation</returns>
public object CallAs(Type type, object obj, string func, params object[] parameters)
{
return CallAs2(type, obj, func, parameters);
}
/// <summary>
/// Calls method 'func' on object 'obj' which is of type 'type' passing parameters 'parameters'
/// </summary>
/// <param name="type">The type of 'obj'</param>
/// <param name="obj">The object on which to excute function 'func'</param>
/// <param name="func">The function to execute</param>
/// <param name="parameters">The parameters to pass to function 'func'</param>
/// <returns>The result of the function invocation</returns>
public object CallAs2(Type type, object obj, string func, object[] parameters) {
MethodInfo methInfo = type.GetMethod(func, BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic);
return methInfo.Invoke(obj, parameters);
}
/// <summary>
/// Returns the value of property 'prop' of object 'obj'
/// </summary>
/// <param name="obj">The object containing 'prop'</param>
/// <param name="prop">The property name</param>
/// <returns>The property value</returns>
public object Get(object obj, string prop)
{
return GetAs(obj.GetType(), obj, prop);
}
/// <summary>
/// Returns the value of property 'prop' of object 'obj' which has type 'type'
/// </summary>
/// <param name="type">The type of 'obj'</param>
/// <param name="obj">The object containing 'prop'</param>
/// <param name="prop">The property name</param>
/// <returns>The property value</returns>
public object GetAs(Type type, object obj, string prop) {
PropertyInfo propInfo = type.GetProperty(prop, BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic);
return propInfo.GetValue(obj, null);
}
/// <summary>
/// Returns an enum value
/// </summary>
/// <param name="typeName">The name of enum type</param>
/// <param name="name">The name of the value</param>
/// <returns>The enum value</returns>
public object GetEnum(string typeName, string name) {
Type type = GetType(typeName);
FieldInfo fieldInfo = type.GetField(name);
return fieldInfo.GetValue(null);
}
#endregion
}
}
|
{
"pile_set_name": "Github"
}
|
/**
* Copyright 2007-2016, Kaazing Corporation. 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 org.apache.mina.filter.ssl;
import java.security.KeyStore;
import java.security.SecureRandom;
import javax.net.ssl.KeyManager;
import javax.net.ssl.KeyManagerFactory;
import javax.net.ssl.ManagerFactoryParameters;
import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLSessionContext;
import javax.net.ssl.TrustManager;
import javax.net.ssl.TrustManagerFactory;
/**
* A factory that creates and configures a new {@link SSLContext}.
* <p>
* If no properties are set the returned {@link SSLContext} will
* be equivalent to what the following creates:
* <pre>
* SSLContext c = SSLContext.getInstance( "TLS" );
* c.init(null, null, null);
* </pre>
* </p>
* <p>
* Use the properties prefixed with <code>keyManagerFactory</code> to control
* the creation of the {@link KeyManager} to be used.
* </p>
* <p>
* Use the properties prefixed with <code>trustManagerFactory</code> to control
* the creation of the {@link TrustManagerFactory} to be used.
* </p>
*
* @author <a href="http://mina.apache.org">Apache MINA Project</a>
*/
public class SslContextFactory {
private String provider = null;
private String protocol = "TLS";
private SecureRandom secureRandom = null;
private KeyStore keyManagerFactoryKeyStore = null;
private char[] keyManagerFactoryKeyStorePassword = null;
private KeyManagerFactory keyManagerFactory = null;
private String keyManagerFactoryAlgorithm = null;
private String keyManagerFactoryProvider = null;
private boolean keyManagerFactoryAlgorithmUseDefault = true;
private KeyStore trustManagerFactoryKeyStore = null;
private TrustManagerFactory trustManagerFactory = null;
private String trustManagerFactoryAlgorithm = null;
private String trustManagerFactoryProvider = null;
private boolean trustManagerFactoryAlgorithmUseDefault = true;
private ManagerFactoryParameters trustManagerFactoryParameters = null;
private int clientSessionCacheSize = -1;
private int clientSessionTimeout = -1;
private int serverSessionCacheSize = -1;
private int serverSessionTimeout = -1;
public SSLContext newInstance() throws Exception {
KeyManagerFactory kmf = this.keyManagerFactory;
TrustManagerFactory tmf = this.trustManagerFactory;
if (kmf == null) {
String algorithm = keyManagerFactoryAlgorithm;
if (algorithm == null && keyManagerFactoryAlgorithmUseDefault) {
algorithm = KeyManagerFactory.getDefaultAlgorithm();
}
if (algorithm != null) {
if (keyManagerFactoryProvider == null) {
kmf = KeyManagerFactory.getInstance(algorithm);
} else {
kmf = KeyManagerFactory.getInstance(algorithm,
keyManagerFactoryProvider);
}
}
}
if (tmf == null) {
String algorithm = trustManagerFactoryAlgorithm;
if (algorithm == null && trustManagerFactoryAlgorithmUseDefault) {
algorithm = TrustManagerFactory.getDefaultAlgorithm();
}
if (algorithm != null) {
if (trustManagerFactoryProvider == null) {
tmf = TrustManagerFactory.getInstance(algorithm);
} else {
tmf = TrustManagerFactory.getInstance(algorithm,
trustManagerFactoryProvider);
}
}
}
KeyManager[] keyManagers = null;
if (kmf != null) {
kmf.init(keyManagerFactoryKeyStore,
keyManagerFactoryKeyStorePassword);
keyManagers = kmf.getKeyManagers();
}
TrustManager[] trustManagers = null;
if (tmf != null) {
if (trustManagerFactoryParameters != null) {
tmf.init(trustManagerFactoryParameters);
} else {
tmf.init(trustManagerFactoryKeyStore);
}
trustManagers = tmf.getTrustManagers();
}
SSLContext context;
if (provider == null) {
context = SSLContext.getInstance(protocol);
} else {
context = SSLContext.getInstance(protocol, provider);
}
context.init(keyManagers, trustManagers, secureRandom);
if (clientSessionCacheSize >= 0) {
context.getClientSessionContext().setSessionCacheSize(
clientSessionCacheSize);
}
if (clientSessionTimeout >= 0) {
context.getClientSessionContext().setSessionTimeout(
clientSessionTimeout);
}
if (serverSessionCacheSize >= 0) {
context.getServerSessionContext().setSessionCacheSize(
serverSessionCacheSize);
}
if (serverSessionTimeout >= 0) {
context.getServerSessionContext().setSessionTimeout(
serverSessionTimeout);
}
return context;
}
/**
* Sets the provider of the new {@link SSLContext}. The default value is
* <tt>null</tt>, which means the default provider will be used.
*
* @param provider the name of the {@link SSLContext} provider
*/
public void setProvider(String provider) {
this.provider = provider;
}
/**
* Sets the protocol to use when creating the {@link SSLContext}. The
* default is <code>TLS</code>.
*
* @param protocol the name of the protocol.
*/
public void setProtocol(String protocol) {
if (protocol == null) {
throw new NullPointerException("protocol");
}
this.protocol = protocol;
}
/**
* If this is set to <code>true</code> while no {@link KeyManagerFactory}
* has been set using {@link #setKeyManagerFactory(KeyManagerFactory)} and
* no algorithm has been set using
* {@link #setKeyManagerFactoryAlgorithm(String)} the default algorithm
* return by {@link KeyManagerFactory#getDefaultAlgorithm()} will be used.
* The default value of this property is <tt>true<tt/>.
*
* @param useDefault
* <code>true</code> or <code>false</code>.
*/
public void setKeyManagerFactoryAlgorithmUseDefault(boolean useDefault) {
this.keyManagerFactoryAlgorithmUseDefault = useDefault;
}
/**
* If this is set to <code>true</code> while no {@link TrustManagerFactory}
* has been set using {@link #setTrustManagerFactory(TrustManagerFactory)} and
* no algorithm has been set using
* {@link #setTrustManagerFactoryAlgorithm(String)} the default algorithm
* return by {@link TrustManagerFactory#getDefaultAlgorithm()} will be used.
* The default value of this property is <tt>true<tt/>.
*
* @param useDefault <code>true</code> or <code>false</code>.
*/
public void setTrustManagerFactoryAlgorithmUseDefault(boolean useDefault) {
this.trustManagerFactoryAlgorithmUseDefault = useDefault;
}
/**
* Sets the {@link KeyManagerFactory} to use. If this is set the properties
* which are used by this factory bean to create a {@link KeyManagerFactory}
* will all be ignored.
*
* @param factory the factory.
*/
public void setKeyManagerFactory(KeyManagerFactory factory) {
this.keyManagerFactory = factory;
}
/**
* Sets the algorithm to use when creating the {@link KeyManagerFactory}
* using {@link KeyManagerFactory#getInstance(java.lang.String)} or
* {@link KeyManagerFactory#getInstance(java.lang.String, java.lang.String)}.
* <p>
* This property will be ignored if a {@link KeyManagerFactory} has been
* set directly using {@link #setKeyManagerFactory(KeyManagerFactory)}.
* </p>
* <p>
* If this property isn't set while no {@link KeyManagerFactory} has been
* set using {@link #setKeyManagerFactory(KeyManagerFactory)} and
* {@link #setKeyManagerFactoryAlgorithmUseDefault(boolean)} has been set to
* <code>true</code> the value returned
* by {@link KeyManagerFactory#getDefaultAlgorithm()} will be used instead.
* </p>
*
* @param algorithm the algorithm to use.
*/
public void setKeyManagerFactoryAlgorithm(String algorithm) {
this.keyManagerFactoryAlgorithm = algorithm;
}
/**
* Sets the provider to use when creating the {@link KeyManagerFactory}
* using
* {@link KeyManagerFactory#getInstance(java.lang.String, java.lang.String)}.
* <p>
* This property will be ignored if a {@link KeyManagerFactory} has been
* set directly using {@link #setKeyManagerFactory(KeyManagerFactory)}.
* </p>
* <p>
* If this property isn't set and no {@link KeyManagerFactory} has been set
* using {@link #setKeyManagerFactory(KeyManagerFactory)}
* {@link KeyManagerFactory#getInstance(java.lang.String)} will be used
* to create the {@link KeyManagerFactory}.
* </p>
*
* @param provider the name of the provider.
*/
public void setKeyManagerFactoryProvider(String provider) {
this.keyManagerFactoryProvider = provider;
}
/**
* Sets the {@link KeyStore} which will be used in the call to
* {@link KeyManagerFactory#init(java.security.KeyStore, char[])} when
* the {@link SSLContext} is created.
*
* @param keyStore the key store.
*/
public void setKeyManagerFactoryKeyStore(KeyStore keyStore) {
this.keyManagerFactoryKeyStore = keyStore;
}
/**
* Sets the password which will be used in the call to
* {@link KeyManagerFactory#init(java.security.KeyStore, char[])} when
* the {@link SSLContext} is created.
*
* @param password the password. Use <code>null</code> to disable password.
*/
public void setKeyManagerFactoryKeyStorePassword(String password) {
if (password != null) {
this.keyManagerFactoryKeyStorePassword = password.toCharArray();
} else {
this.keyManagerFactoryKeyStorePassword = null;
}
}
/**
* Sets the {@link TrustManagerFactory} to use. If this is set the
* properties which are used by this factory bean to create a
* {@link TrustManagerFactory} will all be ignored.
*
* @param factory
* the factory.
*/
public void setTrustManagerFactory(TrustManagerFactory factory) {
this.trustManagerFactory = factory;
}
/**
* Sets the algorithm to use when creating the {@link TrustManagerFactory}
* using {@link TrustManagerFactory#getInstance(java.lang.String)} or
* {@link TrustManagerFactory#getInstance(java.lang.String, java.lang.String)}.
* <p>
* This property will be ignored if a {@link TrustManagerFactory} has been
* set directly using {@link #setTrustManagerFactory(TrustManagerFactory)}.
* </p>
* <p>
* If this property isn't set while no {@link TrustManagerFactory} has been
* set using {@link #setTrustManagerFactory(TrustManagerFactory)} and
* {@link #setTrustManagerFactoryAlgorithmUseDefault(boolean)} has been set to
* <code>true</code> the value returned
* by {@link TrustManagerFactory#getDefaultAlgorithm()} will be used instead.
* </p>
*
* @param algorithm the algorithm to use.
*/
public void setTrustManagerFactoryAlgorithm(String algorithm) {
this.trustManagerFactoryAlgorithm = algorithm;
}
/**
* Sets the {@link KeyStore} which will be used in the call to
* {@link TrustManagerFactory#init(java.security.KeyStore)} when
* the {@link SSLContext} is created.
* <p>
* This property will be ignored if {@link ManagerFactoryParameters} has been
* set directly using {@link #setTrustManagerFactoryParameters(ManagerFactoryParameters)}.
* </p>
*
* @param keyStore the key store.
*/
public void setTrustManagerFactoryKeyStore(KeyStore keyStore) {
this.trustManagerFactoryKeyStore = keyStore;
}
/**
* Sets the {@link ManagerFactoryParameters} which will be used in the call to
* {@link TrustManagerFactory#init(javax.net.ssl.ManagerFactoryParameters)} when
* the {@link SSLContext} is created.
*
* @param parameters describing provider-specific trust material.
*/
public void setTrustManagerFactoryParameters(
ManagerFactoryParameters parameters) {
this.trustManagerFactoryParameters = parameters;
}
/**
* Sets the provider to use when creating the {@link TrustManagerFactory}
* using
* {@link TrustManagerFactory#getInstance(java.lang.String, java.lang.String)}.
* <p>
* This property will be ignored if a {@link TrustManagerFactory} has been
* set directly using {@link #setTrustManagerFactory(TrustManagerFactory)}.
* </p>
* <p>
* If this property isn't set and no {@link TrustManagerFactory} has been set
* using {@link #setTrustManagerFactory(TrustManagerFactory)}
* {@link TrustManagerFactory#getInstance(java.lang.String)} will be used
* to create the {@link TrustManagerFactory}.
* </p>
*
* @param provider the name of the provider.
*/
public void setTrustManagerFactoryProvider(String provider) {
this.trustManagerFactoryProvider = provider;
}
/**
* Sets the {@link SecureRandom} to use when initializing the
* {@link SSLContext}. The JVM's default will be used if this isn't set.
*
* @param secureRandom the {@link SecureRandom} or <code>null</code> if the
* JVM's default should be used.
* @see SSLContext#init(javax.net.ssl.KeyManager[], javax.net.ssl.TrustManager[], java.security.SecureRandom)
*/
public void setSecureRandom(SecureRandom secureRandom) {
this.secureRandom = secureRandom;
}
/**
* Sets the SSLSession cache size for the {@link SSLSessionContext} for use in client mode.
*
* @param size the new session cache size limit; zero means there is no limit.
* @see SSLSessionContext#setSessionCacheSize(int size)
*/
public void setClientSessionCacheSize(int size) {
this.clientSessionCacheSize = size;
}
/**
* Set the SSLSession timeout limit for the {@link SSLSessionContext} for use in client mode.
*
* @param seconds the new session timeout limit in seconds; zero means there is no limit.
* @see SSLSessionContext#setSessionTimeout(int seconds)
*/
public void setClientSessionTimeout(int seconds) {
this.clientSessionTimeout = seconds;
}
/**
* Sets the SSLSession cache size for the {@link SSLSessionContext} for use in server mode.
*
* @param serverSessionCacheSize the new session cache size limit; zero means there is no limit.
* @see SSLSessionContext#setSessionCacheSize(int)
*/
public void setServerSessionCacheSize(int serverSessionCacheSize) {
this.serverSessionCacheSize = serverSessionCacheSize;
}
/**
* Set the SSLSession timeout limit for the {@link SSLSessionContext} for use in server mode.
*
* @param serverSessionTimeout the new session timeout limit in seconds; zero means there is no limit.
* @see SSLSessionContext#setSessionTimeout(int)
*/
public void setServerSessionTimeout(int serverSessionTimeout) {
this.serverSessionTimeout = serverSessionTimeout;
}
}
|
{
"pile_set_name": "Github"
}
|
package cn.anline.annzone.ui.intro
import android.content.Context
import android.net.Uri
import android.os.Bundle
import androidx.fragment.app.Fragment
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import cn.anline.annzone.R
/**
* 引导页第二页
*/
class Intro2Fragment : androidx.fragment.app.Fragment() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
}
override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?,
savedInstanceState: Bundle?): View? {
// Inflate the layout for this fragment
return inflater.inflate(R.layout.fragment_intro2, container, false)
}
}
|
{
"pile_set_name": "Github"
}
|
$NetBSD: distinfo,v 1.3 2015/11/03 20:45:08 agc Exp $
SHA1 (tex-lm-math-36915/lm-math.tar.xz) = 8f44a9ec25368700576df88ea92aa7f3ac564af2
RMD160 (tex-lm-math-36915/lm-math.tar.xz) = 62d72a43a961ecffc72443ae5c1f963931db6b9f
SHA512 (tex-lm-math-36915/lm-math.tar.xz) = 3e2d05712b0a401d7b5f181f811983594331f112340d53a8e9ece491eca10989a2a0aa8871787bd884e3adb31a2a58672516b3c8d2f5a0aa25d9882663746b77
Size (tex-lm-math-36915/lm-math.tar.xz) = 377748 bytes
|
{
"pile_set_name": "Github"
}
|
/**********
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 3 of the License, or (at your
option) any later version. (See <http://www.gnu.org/copyleft/lesser.html>.)
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
**********/
// "liveMedia"
// Copyright (c) 1996-2019 Live Networks, Inc. All rights reserved.
// RTP sink for GSM audio
// C++ header
#ifndef _GSM_AUDIO_RTP_SINK_HH
#define _GSM_AUDIO_RTP_SINK_HH
#ifndef _AUDIO_RTP_SINK_HH
#include "AudioRTPSink.hh"
#endif
class GSMAudioRTPSink: public AudioRTPSink {
public:
static GSMAudioRTPSink* createNew(UsageEnvironment& env, Groupsock* RTPgs);
protected:
GSMAudioRTPSink(UsageEnvironment& env, Groupsock* RTPgs);
// called only by createNew()
virtual ~GSMAudioRTPSink();
private: // redefined virtual functions:
virtual
Boolean frameCanAppearAfterPacketStart(unsigned char const* frameStart,
unsigned numBytesInFrame) const;
};
#endif
|
{
"pile_set_name": "Github"
}
|
/*
* BitMEX API
* ## REST API for the BitMEX Trading Platform [View Changelog](/app/apiChangelog) - #### Getting Started Base URI: [https://www.bitmex.com/api/v1](/api/v1) ##### Fetching Data All REST endpoints are documented below. You can try out any query right from this interface. Most table queries accept `count`, `start`, and `reverse` params. Set `reverse=true` to get rows newest-first. Additional documentation regarding filters, timestamps, and authentication is available in [the main API documentation](/app/restAPI). _All_ table data is available via the [Websocket](/app/wsAPI). We highly recommend using the socket if you want to have the quickest possible data without being subject to ratelimits. ##### Return Types By default, all data is returned as JSON. Send `?_format=csv` to get CSV data or `?_format=xml` to get XML data. ##### Trade Data Queries _This is only a small subset of what is available, to get you started._ Fill in the parameters and click the `Try it out!` button to try any of these queries. - [Pricing Data](#!/Quote/Quote_get) - [Trade Data](#!/Trade/Trade_get) - [OrderBook Data](#!/OrderBook/OrderBook_getL2) - [Settlement Data](#!/Settlement/Settlement_get) - [Exchange Statistics](#!/Stats/Stats_history) Every function of the BitMEX.com platform is exposed here and documented. Many more functions are available. ##### Swagger Specification [⇩ Download Swagger JSON](swagger.json) - ## All API Endpoints Click to expand a section.
*
* OpenAPI spec version: 1.2.0
* Contact: [email protected]
*
* NOTE: This class is auto generated by the swagger code generator program.
* https://github.com/swagger-api/swagger-codegen.git
*
* Swagger Codegen version: 2.4.11-SNAPSHOT
*
* Do not edit the class manually.
*
*/
(function(root, factory) {
if (typeof define === 'function' && define.amd) {
// AMD.
define(['expect.js', '../../src/index'], factory);
} else if (typeof module === 'object' && module.exports) {
// CommonJS-like environments that support module.exports, like Node.
factory(require('expect.js'), require('../../src/index'));
} else {
// Browser globals (root is window)
factory(root.expect, root.BitMexApi);
}
}(this, function(expect, BitMexApi) {
'use strict';
var instance;
describe('(package)', function() {
describe('Announcement', function() {
beforeEach(function() {
instance = new BitMexApi.Announcement();
});
it('should create an instance of Announcement', function() {
// TODO: update the code to test Announcement
expect(instance).to.be.a(BitMexApi.Announcement);
});
it('should have the property id (base name: "id")', function() {
// TODO: update the code to test the property id
expect(instance).to.have.property('id');
// expect(instance.id).to.be(expectedValueLiteral);
});
it('should have the property link (base name: "link")', function() {
// TODO: update the code to test the property link
expect(instance).to.have.property('link');
// expect(instance.link).to.be(expectedValueLiteral);
});
it('should have the property title (base name: "title")', function() {
// TODO: update the code to test the property title
expect(instance).to.have.property('title');
// expect(instance.title).to.be(expectedValueLiteral);
});
it('should have the property content (base name: "content")', function() {
// TODO: update the code to test the property content
expect(instance).to.have.property('content');
// expect(instance.content).to.be(expectedValueLiteral);
});
it('should have the property _date (base name: "date")', function() {
// TODO: update the code to test the property _date
expect(instance).to.have.property('_date');
// expect(instance._date).to.be(expectedValueLiteral);
});
});
});
}));
|
{
"pile_set_name": "Github"
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.