text
stringlengths 2
100k
| meta
dict |
---|---|
package com.frameworkset.common.ecs;
import java.util.ArrayList;
public class TD extends BaseElement{
private Integer colSpan;
private Integer rowSpan;
private String align;
private boolean noWrap;
private Object width;
protected boolean tdtype = true;
public TD() {
subelements = new ArrayList<BaseElement>();
}
protected String getTD()
{
return this.tdtype?"td":"th";
}
public void toString(StringBuilder a) {
a.append("<").append(getTD());
if(width != null)
a.append(" width=\"").append(width).append("\"");
if(colSpan != null)
a.append(" colspan=\"").append(colSpan).append("\"");
if(noWrap)
a.append(" nowrap ");
if(rowSpan != null)
a.append(" rowspan=\"").append(rowSpan).append("\"");
if(align != null)
a.append(" align=\"").append(align).append("\"");
if(style != null)
a.append(" style=\"").append(style).append("\"");
if(clazz != null)
a.append(" class=\"").append(clazz).append("\"");
if(this.extend != null)
a.append(" ").append(extend);
a.append(">");
if(tagText != null)
a.append(tagText);
else
super.buildElements(a);
a.append("</").append(getTD()).append(">");
// return a.toString();
}
public Integer getColSpan() {
return colSpan;
}
public void setColSpan(Integer colSpan) {
this.colSpan = colSpan;
}
public Integer getRowSpan() {
return rowSpan;
}
public void setRowSpan(Integer rowSpan) {
this.rowSpan = rowSpan;
}
public String getAlign() {
return align;
}
public void setAlign(String align) {
this.align = align;
}
public boolean isTdtype() {
return tdtype;
}
public void setTdtype(boolean tdtype) {
this.tdtype = tdtype;
}
public Object getWidth() {
return width;
}
public void setWidth(Object width) {
this.width = width;
}
public boolean isNoWrap() {
return noWrap;
}
public void setNoWrap(boolean noWrap) {
this.noWrap = noWrap;
}
}
| {
"pile_set_name": "Github"
} |
"""Natural Policy Gradient Optimization."""
# pylint: disable=wrong-import-order
# yapf: disable
import collections
from dowel import logger, tabular
import numpy as np
import tensorflow as tf
from garage import EpisodeBatch, log_performance, make_optimizer, StepType
from garage.np import explained_variance_1d, pad_tensor_n
from garage.np.algos import RLAlgorithm
from garage.sampler import RaySampler
from garage.tf import (center_advs,
compile_function,
compute_advantages,
discounted_returns,
flatten_inputs,
graph_inputs,
paths_to_tensors,
positive_advs)
from garage.tf.optimizers import LBFGSOptimizer
# yapf: enable
class NPO(RLAlgorithm):
"""Natural Policy Gradient Optimization.
Args:
env_spec (EnvSpec): Environment specification.
policy (garage.tf.policies.StochasticPolicy): Policy.
baseline (garage.tf.baselines.Baseline): The baseline.
scope (str): Scope for identifying the algorithm.
Must be specified if running multiple algorithms
simultaneously, each using different environments
and policies.
discount (float): Discount.
gae_lambda (float): Lambda used for generalized advantage
estimation.
center_adv (bool): Whether to rescale the advantages
so that they have mean 0 and standard deviation 1.
positive_adv (bool): Whether to shift the advantages
so that they are always positive. When used in
conjunction with center_adv the advantages will be
standardized before shifting.
fixed_horizon (bool): Whether to fix horizon.
pg_loss (str): A string from: 'vanilla', 'surrogate',
'surrogate_clip'. The type of loss functions to use.
lr_clip_range (float): The limit on the likelihood ratio between
policies, as in PPO.
max_kl_step (float): The maximum KL divergence between old and new
policies, as in TRPO.
optimizer (object): The optimizer of the algorithm. Should be the
optimizers in garage.tf.optimizers.
optimizer_args (dict): The arguments of the optimizer.
policy_ent_coeff (float): The coefficient of the policy entropy.
Setting it to zero would mean no entropy regularization.
use_softplus_entropy (bool): Whether to estimate the softmax
distribution of the entropy to prevent the entropy from being
negative.
use_neg_logli_entropy (bool): Whether to estimate the entropy as the
negative log likelihood of the action.
stop_entropy_gradient (bool): Whether to stop the entropy gradient.
entropy_method (str): A string from: 'max', 'regularized',
'no_entropy'. The type of entropy method to use. 'max' adds the
dense entropy to the reward for each time step. 'regularized' adds
the mean entropy to the surrogate objective. See
https://arxiv.org/abs/1805.00909 for more details.
name (str): The name of the algorithm.
Note:
sane defaults for entropy configuration:
- entropy_method='max', center_adv=False, stop_gradient=True
(center_adv normalizes the advantages tensor, which will
significantly alleviate the effect of entropy. It is also
recommended to turn off entropy gradient so that the agent
will focus on high-entropy actions instead of increasing the
variance of the distribution.)
- entropy_method='regularized', stop_gradient=False,
use_neg_logli_entropy=False
"""
def __init__(self,
env_spec,
policy,
baseline,
scope=None,
discount=0.99,
gae_lambda=1,
center_adv=True,
positive_adv=False,
fixed_horizon=False,
pg_loss='surrogate',
lr_clip_range=0.01,
max_kl_step=0.01,
optimizer=None,
optimizer_args=None,
policy_ent_coeff=0.0,
use_softplus_entropy=False,
use_neg_logli_entropy=False,
stop_entropy_gradient=False,
entropy_method='no_entropy',
name='NPO'):
self.policy = policy
self._scope = scope
self.max_episode_length = env_spec.max_episode_length
self._env_spec = env_spec
self._baseline = baseline
self._discount = discount
self._gae_lambda = gae_lambda
self._center_adv = center_adv
self._positive_adv = positive_adv
self._fixed_horizon = fixed_horizon
self._name = name
self._name_scope = tf.name_scope(self._name)
self._old_policy = policy.clone('old_policy')
self._use_softplus_entropy = use_softplus_entropy
self._use_neg_logli_entropy = use_neg_logli_entropy
self._stop_entropy_gradient = stop_entropy_gradient
self._pg_loss = pg_loss
if optimizer is None:
if optimizer_args is None:
optimizer_args = dict()
optimizer = LBFGSOptimizer
self._check_entropy_configuration(entropy_method, center_adv,
stop_entropy_gradient,
use_neg_logli_entropy,
policy_ent_coeff)
if pg_loss not in ['vanilla', 'surrogate', 'surrogate_clip']:
raise ValueError('Invalid pg_loss')
self._optimizer = make_optimizer(optimizer, **optimizer_args)
self._lr_clip_range = float(lr_clip_range)
self._max_kl_step = float(max_kl_step)
self._policy_ent_coeff = float(policy_ent_coeff)
self._f_rewards = None
self._f_returns = None
self._f_policy_kl = None
self._f_policy_entropy = None
self._policy_network = None
self._old_policy_network = None
self._episode_reward_mean = collections.deque(maxlen=100)
self.sampler_cls = RaySampler
self._init_opt()
def _init_opt(self):
"""Initialize optimizater."""
pol_loss_inputs, pol_opt_inputs = self._build_inputs()
self._policy_opt_inputs = pol_opt_inputs
pol_loss, pol_kl = self._build_policy_loss(pol_loss_inputs)
self._optimizer.update_opt(loss=pol_loss,
target=self.policy,
leq_constraint=(pol_kl, self._max_kl_step),
inputs=flatten_inputs(
self._policy_opt_inputs),
constraint_name='mean_kl')
def train(self, trainer):
"""Obtain samplers and start actual training for each epoch.
Args:
trainer (Trainer): Experiment trainer, which rovides services
such as snapshotting and sampler control.
Returns:
float: The average return in last epoch cycle.
"""
last_return = None
for _ in trainer.step_epochs():
trainer.step_path = trainer.obtain_samples(trainer.step_itr)
last_return = self._train_once(trainer.step_itr, trainer.step_path)
trainer.step_itr += 1
return last_return
def _train_once(self, itr, paths):
"""Perform one step of policy optimization given one batch of samples.
Args:
itr (int): Iteration number.
paths (list[dict]): A list of collected paths.
Returns:
numpy.float64: Average return.
"""
# -- Stage: Calculate baseline
paths = [
dict(
observations=path['observations'],
actions=(
self._env_spec.action_space.flatten_n( # noqa: E126
path['actions'])),
rewards=path['rewards'],
env_infos=path['env_infos'],
agent_infos=path['agent_infos'],
dones=np.array([
step_type == StepType.TERMINAL
for step_type in path['step_types']
])) for path in paths
]
if hasattr(self._baseline, 'predict_n'):
baseline_predictions = self._baseline.predict_n(paths)
else:
baseline_predictions = [
self._baseline.predict(path) for path in paths
]
# -- Stage: Pre-process samples based on collected paths
samples_data = paths_to_tensors(paths, self.max_episode_length,
baseline_predictions, self._discount,
self._gae_lambda)
# -- Stage: Run and calculate performance of the algorithm
undiscounted_returns = log_performance(itr,
EpisodeBatch.from_list(
self._env_spec, paths),
discount=self._discount)
self._episode_reward_mean.extend(undiscounted_returns)
tabular.record('Extras/EpisodeRewardMean',
np.mean(self._episode_reward_mean))
samples_data['average_return'] = np.mean(undiscounted_returns)
logger.log('Optimizing policy...')
self._optimize_policy(samples_data)
return samples_data['average_return']
def _optimize_policy(self, samples_data):
"""Optimize policy.
Args:
samples_data (dict): Processed sample data.
See garage.tf.paths_to_tensors() for details.
"""
policy_opt_input_values = self._policy_opt_input_values(samples_data)
logger.log('Computing loss before')
loss_before = self._optimizer.loss(policy_opt_input_values)
logger.log('Computing KL before')
policy_kl_before = self._f_policy_kl(*policy_opt_input_values)
logger.log('Optimizing')
self._optimizer.optimize(policy_opt_input_values)
logger.log('Computing KL after')
policy_kl = self._f_policy_kl(*policy_opt_input_values)
logger.log('Computing loss after')
loss_after = self._optimizer.loss(policy_opt_input_values)
tabular.record('{}/LossBefore'.format(self.policy.name), loss_before)
tabular.record('{}/LossAfter'.format(self.policy.name), loss_after)
tabular.record('{}/dLoss'.format(self.policy.name),
loss_before - loss_after)
tabular.record('{}/KLBefore'.format(self.policy.name),
policy_kl_before)
tabular.record('{}/KL'.format(self.policy.name), policy_kl)
pol_ent = self._f_policy_entropy(*policy_opt_input_values)
ent = np.sum(pol_ent) / np.sum(samples_data['valids'])
tabular.record('{}/Entropy'.format(self.policy.name), ent)
tabular.record('{}/Perplexity'.format(self.policy.name), np.exp(ent))
self._fit_baseline_with_data(samples_data)
ev = explained_variance_1d(samples_data['baselines'],
samples_data['returns'],
samples_data['valids'])
tabular.record('{}/ExplainedVariance'.format(self._baseline.name), ev)
self._old_policy.parameters = self.policy.parameters
def _build_inputs(self):
"""Build input variables.
Returns:
namedtuple: Collection of variables to compute policy loss.
namedtuple: Collection of variables to do policy optimization.
"""
observation_space = self.policy.observation_space
action_space = self.policy.action_space
with tf.name_scope('inputs'):
obs_var = observation_space.to_tf_placeholder(name='obs',
batch_dims=2)
action_var = action_space.to_tf_placeholder(name='action',
batch_dims=2)
reward_var = tf.compat.v1.placeholder(tf.float32,
shape=[None, None],
name='reward')
valid_var = tf.compat.v1.placeholder(tf.float32,
shape=[None, None],
name='valid')
baseline_var = tf.compat.v1.placeholder(tf.float32,
shape=[None, None],
name='baseline')
policy_state_info_vars = {
k: tf.compat.v1.placeholder(tf.float32,
shape=[None] * 2 + list(shape),
name=k)
for k, shape in self.policy.state_info_specs
}
policy_state_info_vars_list = [
policy_state_info_vars[k] for k in self.policy.state_info_keys
]
augmented_obs_var = obs_var
for k in self.policy.state_info_keys:
extra_state_var = policy_state_info_vars[k]
extra_state_var = tf.cast(extra_state_var, tf.float32)
augmented_obs_var = tf.concat([augmented_obs_var, extra_state_var],
-1)
self._policy_network = self.policy.build(augmented_obs_var,
name='policy')
self._old_policy_network = self._old_policy.build(augmented_obs_var,
name='policy')
policy_loss_inputs = graph_inputs(
'PolicyLossInputs',
action_var=action_var,
reward_var=reward_var,
baseline_var=baseline_var,
valid_var=valid_var,
policy_state_info_vars=policy_state_info_vars,
)
policy_opt_inputs = graph_inputs(
'PolicyOptInputs',
obs_var=obs_var,
action_var=action_var,
reward_var=reward_var,
baseline_var=baseline_var,
valid_var=valid_var,
policy_state_info_vars_list=policy_state_info_vars_list,
)
return policy_loss_inputs, policy_opt_inputs
# pylint: disable=too-many-branches, too-many-statements
def _build_policy_loss(self, i):
"""Build policy loss and other output tensors.
Args:
i (namedtuple): Collection of variables to compute policy loss.
Returns:
tf.Tensor: Policy loss.
tf.Tensor: Mean policy KL divergence.
"""
policy_entropy = self._build_entropy_term(i)
rewards = i.reward_var
if self._maximum_entropy:
with tf.name_scope('augmented_rewards'):
rewards = i.reward_var + (self._policy_ent_coeff *
policy_entropy)
with tf.name_scope('policy_loss'):
adv = compute_advantages(self._discount,
self._gae_lambda,
self.max_episode_length,
i.baseline_var,
rewards,
name='adv')
adv = tf.reshape(adv, [-1, self.max_episode_length])
# Optionally normalize advantages
eps = tf.constant(1e-8, dtype=tf.float32)
if self._center_adv:
adv = center_advs(adv, axes=[0], eps=eps)
if self._positive_adv:
adv = positive_advs(adv, eps)
old_policy_dist = self._old_policy_network.dist
policy_dist = self._policy_network.dist
with tf.name_scope('kl'):
kl = old_policy_dist.kl_divergence(policy_dist)
pol_mean_kl = tf.reduce_mean(kl)
# Calculate vanilla loss
with tf.name_scope('vanilla_loss'):
ll = policy_dist.log_prob(i.action_var, name='log_likelihood')
vanilla = ll * adv
# Calculate surrogate loss
with tf.name_scope('surrogate_loss'):
lr = tf.exp(ll - old_policy_dist.log_prob(i.action_var))
surrogate = lr * adv
# Finalize objective function
with tf.name_scope('loss'):
if self._pg_loss == 'vanilla':
# VPG uses the vanilla objective
obj = tf.identity(vanilla, name='vanilla_obj')
elif self._pg_loss == 'surrogate':
# TRPO uses the standard surrogate objective
obj = tf.identity(surrogate, name='surr_obj')
elif self._pg_loss == 'surrogate_clip':
lr_clip = tf.clip_by_value(lr,
1 - self._lr_clip_range,
1 + self._lr_clip_range,
name='lr_clip')
surr_clip = lr_clip * adv
obj = tf.minimum(surrogate, surr_clip, name='surr_obj')
if self._entropy_regularzied:
obj += self._policy_ent_coeff * policy_entropy
# filter only the valid values
obj = tf.boolean_mask(obj, i.valid_var)
# Maximize E[surrogate objective] by minimizing
# -E_t[surrogate objective]
loss = -tf.reduce_mean(obj)
# Diagnostic functions
self._f_policy_kl = tf.compat.v1.get_default_session(
).make_callable(pol_mean_kl,
feed_list=flatten_inputs(self._policy_opt_inputs))
self._f_rewards = tf.compat.v1.get_default_session().make_callable(
rewards, feed_list=flatten_inputs(self._policy_opt_inputs))
returns = discounted_returns(self._discount,
self.max_episode_length, rewards)
self._f_returns = tf.compat.v1.get_default_session().make_callable(
returns, feed_list=flatten_inputs(self._policy_opt_inputs))
return loss, pol_mean_kl
def _build_entropy_term(self, i):
"""Build policy entropy tensor.
Args:
i (namedtuple): Collection of variables to compute policy loss.
Returns:
tf.Tensor: Policy entropy.
"""
pol_dist = self._policy_network.dist
with tf.name_scope('policy_entropy'):
if self._use_neg_logli_entropy:
policy_entropy = -pol_dist.log_prob(i.action_var,
name='policy_log_likeli')
else:
policy_entropy = pol_dist.entropy()
# This prevents entropy from becoming negative for small policy std
if self._use_softplus_entropy:
policy_entropy = tf.nn.softplus(policy_entropy)
if self._stop_entropy_gradient:
policy_entropy = tf.stop_gradient(policy_entropy)
# dense form, match the shape of advantage
policy_entropy = tf.reshape(policy_entropy,
[-1, self.max_episode_length])
self._f_policy_entropy = compile_function(
flatten_inputs(self._policy_opt_inputs), policy_entropy)
return policy_entropy
def _fit_baseline_with_data(self, samples_data):
"""Update baselines from samples.
Args:
samples_data (dict): Processed sample data.
See garage.tf.paths_to_tensors() for details.
"""
policy_opt_input_values = self._policy_opt_input_values(samples_data)
# Augment reward from baselines
rewards_tensor = self._f_rewards(*policy_opt_input_values)
returns_tensor = self._f_returns(*policy_opt_input_values)
returns_tensor = np.squeeze(returns_tensor, -1)
paths = samples_data['paths']
valids = samples_data['valids']
# Recompute parts of samples_data
aug_rewards = []
aug_returns = []
for rew, ret, val, path in zip(rewards_tensor, returns_tensor, valids,
paths):
path['rewards'] = rew[val.astype(np.bool)]
path['returns'] = ret[val.astype(np.bool)]
aug_rewards.append(path['rewards'])
aug_returns.append(path['returns'])
samples_data['rewards'] = pad_tensor_n(aug_rewards,
self.max_episode_length)
samples_data['returns'] = pad_tensor_n(aug_returns,
self.max_episode_length)
# Fit baseline
logger.log('Fitting baseline...')
self._baseline.fit(paths)
def _policy_opt_input_values(self, samples_data):
"""Map episode samples to the policy optimizer inputs.
Args:
samples_data (dict): Processed sample data.
See garage.tf.paths_to_tensors() for details.
Returns:
list(np.ndarray): Flatten policy optimization input values.
"""
policy_state_info_list = [
samples_data['agent_infos'][k] for k in self.policy.state_info_keys
]
# pylint: disable=unexpected-keyword-arg
policy_opt_input_values = self._policy_opt_inputs._replace(
obs_var=samples_data['observations'],
action_var=samples_data['actions'],
reward_var=samples_data['rewards'],
baseline_var=samples_data['baselines'],
valid_var=samples_data['valids'],
policy_state_info_vars_list=policy_state_info_list,
)
return flatten_inputs(policy_opt_input_values)
def _check_entropy_configuration(self, entropy_method, center_adv,
stop_entropy_gradient,
use_neg_logli_entropy, policy_ent_coeff):
"""Check entropy configuration.
Args:
entropy_method (str): A string from: 'max', 'regularized',
'no_entropy'. The type of entropy method to use. 'max' adds the
dense entropy to the reward for each time step. 'regularized'
adds the mean entropy to the surrogate objective. See
https://arxiv.org/abs/1805.00909 for more details.
center_adv (bool): Whether to rescale the advantages
so that they have mean 0 and standard deviation 1.
stop_entropy_gradient (bool): Whether to stop the entropy gradient.
use_neg_logli_entropy (bool): Whether to estimate the entropy as
the negative log likelihood of the action.
policy_ent_coeff (float): The coefficient of the policy entropy.
Setting it to zero would mean no entropy regularization.
Raises:
ValueError: If center_adv is True when entropy_method is max.
ValueError: If stop_gradient is False when entropy_method is max.
ValueError: If policy_ent_coeff is non-zero when there is
no entropy method.
ValueError: If entropy_method is not one of 'max', 'regularized',
'no_entropy'.
"""
del use_neg_logli_entropy
if entropy_method == 'max':
if center_adv:
raise ValueError('center_adv should be False when '
'entropy_method is max')
if not stop_entropy_gradient:
raise ValueError('stop_gradient should be True when '
'entropy_method is max')
self._maximum_entropy = True
self._entropy_regularzied = False
elif entropy_method == 'regularized':
self._maximum_entropy = False
self._entropy_regularzied = True
elif entropy_method == 'no_entropy':
if policy_ent_coeff != 0.0:
raise ValueError('policy_ent_coeff should be zero '
'when there is no entropy method')
self._maximum_entropy = False
self._entropy_regularzied = False
else:
raise ValueError('Invalid entropy_method')
def __getstate__(self):
"""Parameters to save in snapshot.
Returns:
dict: Parameters to save.
"""
data = self.__dict__.copy()
del data['_name_scope']
del data['_policy_opt_inputs']
del data['_f_policy_entropy']
del data['_f_policy_kl']
del data['_f_rewards']
del data['_f_returns']
del data['_policy_network']
del data['_old_policy_network']
return data
def __setstate__(self, state):
"""Parameters to restore from snapshot.
Args:
state (dict): Parameters to restore from.
"""
self.__dict__ = state
self._name_scope = tf.name_scope(self._name)
self._init_opt()
| {
"pile_set_name": "Github"
} |
/*==LICENSE==*
CyanWorlds.com Engine - MMOG client, server and tools
Copyright (C) 2011 Cyan Worlds, Inc.
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
Additional permissions under GNU GPL version 3 section 7
If you modify this Program, or any covered work, by linking or
combining it with any of RAD Game Tools Bink SDK, Autodesk 3ds Max SDK,
NVIDIA PhysX SDK, Microsoft DirectX SDK, OpenSSL library, Independent
JPEG Group JPEG library, Microsoft Windows Media SDK, or Apple QuickTime SDK
(or a modified version of those libraries),
containing parts covered by the terms of the Bink SDK EULA, 3ds Max EULA,
PhysX SDK EULA, DirectX SDK EULA, OpenSSL and SSLeay licenses, IJG
JPEG Library README, Windows Media SDK EULA, or QuickTime SDK EULA, the
licensors of this Program grant you additional
permission to convey the resulting work. Corresponding Source for a
non-source form of such a combination shall include the source code for
the parts of OpenSSL and IJG JPEG Library used as well as that of the covered
work.
You can contact Cyan Worlds, Inc. by email [email protected]
or by snail mail at:
Cyan Worlds, Inc.
14617 N Newport Hwy
Mead, WA 99021
*==LICENSE==*/
#include "HeadSpin.h"
#include "hsFastMath.h"
#include "hsStream.h"
#pragma hdrstop
#include "plBulletMsg.h"
void plBulletMsg::Read(hsStream* stream, hsResMgr* mgr)
{
IMsgRead(stream, mgr);
fCmd = Cmd(stream->ReadByte());
fFrom.Read(stream);
fDir.Read(stream);
fRange = stream->ReadLEScalar();
fRadius = stream->ReadLEScalar();
fPartyTime = stream->ReadLEScalar();
}
void plBulletMsg::Write(hsStream* stream, hsResMgr* mgr)
{
IMsgWrite(stream, mgr);
stream->WriteByte(uint8_t(fCmd));
fFrom.Write(stream);
fDir.Write(stream);
stream->WriteLEScalar(fRange);
stream->WriteLEScalar(fRadius);
stream->WriteLEScalar(fPartyTime);
}
void plBulletMsg::FireShot(const hsPoint3& from, const hsVector3& dir, float radius, float range, float psecs)
{
fFrom = from;
fDir = dir;
fRange = range;
fRadius = radius;
fPartyTime = psecs;
fCmd = kShot;
}
void plBulletMsg::FireShot(const hsPoint3& from, const hsPoint3& at, float radius, float psecs)
{
hsVector3 dir(&at, &from);
float invLen = hsFastMath::InvSqrt(dir.MagnitudeSquared());
hsAssert(invLen > 0, "degenerate from and at to fire bullet");
dir *= invLen;
float range = 1.f / invLen;
FireShot(from, dir, radius, range, psecs);
}
| {
"pile_set_name": "Github"
} |
<?xml version="1.0" encoding="utf-8"?>
<navigation xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/nav_graph"
app:startDestination="@id/WelcomeFragment">
<fragment
android:id="@+id/WelcomeFragment"
android:name="io.homeassistant.companion.android.nfc.NfcWelcomeFragment"
android:label="@string/nfc_welcome_fragment_label"
tools:layout="@layout/fragment_nfc_welcome">
<action
android:id="@+id/action_NFC_READ"
app:destination="@id/ReadFragment" />
<action
android:id="@+id/action_NFC_WRITE"
app:destination="@id/WriteFragment" />
</fragment>
<fragment
android:id="@+id/WriteFragment"
android:name="io.homeassistant.companion.android.nfc.NfcWriteFragment"
android:label="@string/nfc_write_fragment_label"
tools:layout="@layout/fragment_nfc_write">
<action
android:id="@+id/action_NFC_EDIT"
app:destination="@id/EditFragment" />
</fragment>
<fragment
android:id="@+id/ReadFragment"
android:name="io.homeassistant.companion.android.nfc.NfcReadFragment"
android:label="@string/nfc_read_fragment_label"
tools:layout="@layout/fragment_nfc_read">
<action
android:id="@+id/action_NFC_EDIT"
app:destination="@id/EditFragment" />
</fragment>
<fragment
android:id="@+id/EditFragment"
android:name="io.homeassistant.companion.android.nfc.NfcEditFragment"
android:label="@string/nfc_edit_fragment_label"
tools:layout="@layout/fragment_nfc_edit">
<action
android:id="@+id/action_NFC_WRITE"
app:destination="@id/WriteFragment" />
</fragment>
</navigation> | {
"pile_set_name": "Github"
} |
#language "lang/plush/0"
var vm = import "core/vm/0";
var roundTrip = function (val)
{
// Test with minification enabled
var s1 = vm.serialize(val, true);
//print(s1);
var v1 = vm.parse(s1);
var s2 = vm.serialize(v1, true);
//print(s2);
assert (
s1 == s2,
"serializing twice does not produce the same string"
);
// Test again with minification disabled
var s1 = vm.serialize(val, false);
//print(s1);
var v1 = vm.parse(s1);
var s2 = vm.serialize(v1, false);
//print(s2);
assert (
s1 == s2,
"serializing twice does not produce the same string with minification disabled"
);
};
assert (vm.parse("3;") == 3);
assert (vm.serialize(3, true) == "3;");
assert (vm.serialize(true, true) == "$true;");
assert (vm.serialize([1,2,3], true) == "[1,2,3];");
roundTrip(true);
roundTrip(false);
roundTrip(undef);
roundTrip(1.5f);
roundTrip(3.706f);
roundTrip(777);
roundTrip([1,2,3]);
roundTrip([1,2,[3,4]]);
roundTrip({ a:1, b:2 });
roundTrip({ a:1, b:2, c:[3,4] });
roundTrip("foobar");
roundTrip("foo\nbar");
roundTrip("foo\"bar");
roundTrip("\"");
roundTrip("\'");
roundTrip("\n");
roundTrip("\\");
roundTrip("\xF0");
// Object with non-identifier field name
obj = {};
obj["a b"] = true;
roundTrip(obj);
// Referencing a value twice
a1 = [1,2];
a2 = [a1, a1];
roundTrip(a2);
// Cycle
a1 = [];
a2 = [];
a1:push(a2);
a2:push(a1);
roundTrip(a2);
// Reference to cycle
a1 = [];
a2 = [];
a1:push(a2);
a2:push(a1);
roundTrip([a2]);
// Serializing, parsing and then calling a function
var fibPkg = import "./tests/vm/ex_fibonacci.zim";
var fib = fibPkg.fib;
var str = vm.serialize(fib, false);
//print(str);
var fib2 = vm.parse(str);
assert (fib(10) == fib2(10));
roundTrip(fib);
// Object with a method (parsed by the Plush package)
var obj = {
count: 0,
incr: function (self) { self.count += 1; }
};
obj:incr();
var str = vm.serialize(obj, false);
//print(str);
//print(str.length);
var obj2 = vm.parse(str);
obj2:incr();
assert (obj2.count == 2);
| {
"pile_set_name": "Github"
} |
// Copyright (c) 2015 Western Digital Corporation or its affiliates. All rights reserved.
// SPDX-License-Identifier: MIT
package blb
import (
"context"
"math/rand"
"strings"
"sync"
"time"
log "github.com/golang/glog"
"github.com/prometheus/client_golang/prometheus"
"github.com/prometheus/client_golang/prometheus/promauto"
"github.com/westerndigitalcorporation/blb/pkg/retry"
"github.com/westerndigitalcorporation/blb/internal/core"
"github.com/westerndigitalcorporation/blb/internal/server"
"github.com/westerndigitalcorporation/blb/platform/clustersniff"
)
var (
clientOpLatenciesSet = promauto.NewSummaryVec(prometheus.SummaryOpts{
Subsystem: "blb_client",
Name: "latencies",
}, []string{"op", "instance"})
clientOpSizesSet = promauto.NewSummaryVec(prometheus.SummaryOpts{
Subsystem: "blb_client",
Name: "sizes",
}, []string{"op", "instance"})
clientOpBytesSet = promauto.NewCounterVec(prometheus.CounterOpts{
Subsystem: "blb_client",
Name: "bytes",
}, []string{"op", "instance"})
)
const (
// ParallelRPCs is the number of read/write rpcs to issue in parallel per
// call to blob.Read or Write. (Note that this is not a global limit. Each
// call may issue up to this many RPCs in parallel.)
ParallelRPCs = 12
// LookupCacheSize is the number of partitions for which we cache the
// current curator. We don't expect that many partitions so we might as well
// cache them all.
LookupCacheSize = 100
// TractCacheSize is the number of _blobs_ for which we cache tract
// locations. (Large blobs may use more space in the cache, there's no
// weight tracking.)
TractCacheSize = 100
// TractLength defines the size of a full tract.
TractLength = core.TractLength
)
// Options contains configurations of a client.
type Options struct {
// The cluster this client will connect to. Most users can use a simple
// cluster name here. This may also be a cluster/user/service string, to
// fully specify a service discovery record, or a comma-separated list of
// master hostnames. If empty, we will try to connect to the default cluster
// (but this is not recommended; try to use an explicit cluster name if
// possible).
Cluster string
// Whether client will retry operations failed due to "retriable" erorr.
DisableRetry bool
// RetryTimeout bounds the total time of retries if it's greater than zero.
RetryTimeout time.Duration
// Whether client will use cache.
DisableCache bool
// An optional label to diffrentiate metrics from differen client instances.
// It will be "default" if it's not specified.
Instance string
// How the client decides whether to attempt client-side RS reconstruction.
ReconstructBehavior ReconstructBehavior
}
// Client exposes a simple interface to Blb users for requesting services and
// handles communications with master, curator and tractservers under the hood.
type Client struct {
// which cluster this client is connecting to
cluster string
// Connection to the primary master.
master MasterConnection
// How we talk to curators
curators CuratorTalker
// How we talk to tractservers
tractservers TractserverTalker
// Cache of partition->curator mapping.
lookupCache *lookupCache
// Cache of tract metadata.
tractCache *tractCache
// Whether to use cache or not.
cacheDisabled bool
// Lock for curators, tractservers, cacheDisabled.
lock sync.Mutex
// Retrier for retrying client's operations once they failed.
retrier retry.Retrier
// Reconstruct behavior.
reconstructState reconstructState
// Metrics we collect.
metricOpen prometheus.Observer
metricCreate prometheus.Observer
metricReadDurations prometheus.Observer
metricReadSizes prometheus.Observer
metricReadBytes prometheus.Counter
metricWriteDurations prometheus.Observer
metricWriteSizes prometheus.Observer
metricWriteBytes prometheus.Counter
metricDelete prometheus.Observer
metricUndelete prometheus.Observer
metricReconDuration prometheus.Observer
metricReconBytes prometheus.Counter
}
// newBaseClient returns a new Client with common fields initialized, but that isn't
// actually useful yet.
func newBaseClient(options *Options) *Client {
var retrier retry.Retrier
// Create a retrier.
if options.DisableRetry {
retrier = retry.Retrier{MaxNumRetries: 1}
} else {
if options.RetryTimeout == 0 {
// Give it a default timeout: 30 seconds.
options.RetryTimeout = 30 * time.Second
}
retrier = retry.Retrier{
MinSleep: 500 * time.Millisecond,
MaxSleep: options.RetryTimeout,
MaxRetry: options.RetryTimeout,
}
}
if options.Instance == "" {
options.Instance = "default"
}
if options.Cluster == "" {
options.Cluster = clustersniff.Cluster()
}
return &Client{
lookupCache: lookupCacheNew(LookupCacheSize),
tractCache: tractCacheNew(TractCacheSize),
cacheDisabled: options.DisableCache,
cluster: options.Cluster,
retrier: retrier,
reconstructState: makeReconstructState(options.ReconstructBehavior),
metricOpen: clientOpLatenciesSet.WithLabelValues("open", options.Instance),
metricCreate: clientOpLatenciesSet.WithLabelValues("create", options.Instance),
metricReadDurations: clientOpLatenciesSet.WithLabelValues("read", options.Instance),
metricWriteDurations: clientOpLatenciesSet.WithLabelValues("write", options.Instance),
metricDelete: clientOpLatenciesSet.WithLabelValues("delete", options.Instance),
metricUndelete: clientOpLatenciesSet.WithLabelValues("undelete", options.Instance),
metricReconDuration: clientOpLatenciesSet.WithLabelValues("reconstruct", options.Instance),
metricReadSizes: clientOpSizesSet.WithLabelValues("read", options.Instance),
metricWriteSizes: clientOpSizesSet.WithLabelValues("write", options.Instance),
metricReadBytes: clientOpBytesSet.WithLabelValues("read", options.Instance),
metricWriteBytes: clientOpBytesSet.WithLabelValues("write", options.Instance),
metricReconBytes: clientOpBytesSet.WithLabelValues("reconstruct", options.Instance),
}
}
// NewClient returns a new Client that can be used to interact with a Blob cell.
// You must pass an Option object that contains the configuration of the client.
func NewClient(options Options) *Client {
cli := newBaseClient(&options)
cli.master = NewRPCMasterConnection(options.Cluster)
cli.curators = NewRPCCuratorTalker()
cli.tractservers = NewRPCTractserverTalker()
return cli
}
// NewMockClient returns a new in-memory mock client that can only be used for
// testing.
func NewMockClient() *Client {
options := Options{
DisableRetry: true,
DisableCache: true,
}
cli := newBaseClient(&options)
cli.master = newMemMasterConnection([]string{"1", "2", "3"})
cli.curators = newMemCuratorTalker()
cli.tractservers = newMemTractserverTalker(nil)
return cli
}
//----------------------------
// Mechanism for serving user
//----------------------------
const (
dialTimeout = 5 * time.Second // timeout for dial to a server
rpcTimeout = 10 * time.Second // timeout for a rpc invocation
)
// Create creates a blob with the given options. It will retry the operation internally
// according to the retry policy specified by users if the operation failed due to
// "retriable" errors.
func (cli *Client) Create(opts ...createOpt) (*Blob, error) {
// Construct options from arguments.
options := defaultCreateOptions
options.ctx = context.Background()
for _, o := range opts {
o(&options)
}
options.ctx = context.WithValue(options.ctx, priorityKey, options.pri)
var blob *Blob
var berr core.Error
st := time.Now()
cli.retrier.Do(options.ctx, func(seq int) bool {
log.Infof("create blob with opts %v, attempt #%d", options, seq)
blob, berr = cli.createOnce(options)
return !core.IsRetriableError(berr)
})
cli.metricCreate.Observe(float64(time.Since(st)) / 1e9)
return blob, berr.Error()
}
// createOnce creates a blob with the given options.
func (cli *Client) createOnce(options createOptions) (*Blob, core.Error) {
// Contact master for a proper curator.
addr, err := cli.master.MasterCreateBlob(options.ctx)
if core.NoError != err {
return nil, err
}
// Contact the curator for creating a BlobID.
metadata := core.BlobInfo{
Repl: options.repl,
Hint: options.hint,
Expires: options.expires,
}
id, err := cli.curators.CreateBlob(options.ctx, addr, metadata)
if core.NoError != err {
return nil, err
}
if cli.useCache() {
// A write will usually follow a successful create, we should cache
// partition->curator mapping so a subsequent write doesn't have to
// contact master again.
cli.lookupCache.put(id.Partition(), addr)
}
// Create and return a Blob.
return &Blob{
cli: cli,
id: id,
// Both reading and writing are allowed on a new blob (it wouldn't be
// very useful otherwise).
allowRead: true,
allowWrite: true,
ctx: options.ctx,
}, core.NoError
}
// ClusterID returns the cluster this client is connecting to
func (cli *Client) ClusterID() string {
return cli.cluster
}
// EnableCache turns on/off caching.
func (cli *Client) EnableCache(cacheEnabled bool) {
cli.lock.Lock()
defer cli.lock.Unlock()
cli.cacheDisabled = !cacheEnabled
}
// useCache checks whethe we should use cache or not.
func (cli *Client) useCache() bool {
cli.lock.Lock()
defer cli.lock.Unlock()
return !cli.cacheDisabled
}
// Open opens a blob referenced by 'id'. It will retry the operation internally
// according to the retry policy specified by users if the operation failed due
// to "retriable" errors.
// 'mode' should be a combination of "r" for reading, "w" for writing, and "s"
// for statting.
func (cli *Client) Open(id BlobID, mode string, opts ...openOpt) (*Blob, error) {
// Construct options from arguments.
options := defaultOpenOptions
options.ctx = context.Background()
for _, o := range opts {
o(&options)
}
options.ctx = context.WithValue(options.ctx, priorityKey, options.pri)
// Check mode.
if strings.Trim(mode, "rws") != "" {
return nil, core.ErrInvalidArgument.Error()
}
var blob *Blob
var berr core.Error
st := time.Now()
cli.retrier.Do(options.ctx, func(seq int) bool {
log.Infof("open blob %v, attempt #%d", id, seq)
blob, berr = cli.openOnce(options.ctx, core.BlobID(id), mode)
// Return false if we want to retry this operation, true otherwise.
// Ditto for all the code below.
return !core.IsRetriableError(berr)
})
cli.metricOpen.Observe(float64(time.Since(st)) / 1e9)
return blob, berr.Error()
}
// openOnce opens a blob referenced by 'id'.
func (cli *Client) openOnce(ctx context.Context, id core.BlobID, mode string) (*Blob, core.Error) {
allowRead := strings.Contains(mode, "r")
allowWrite := strings.Contains(mode, "w")
addr, lookupWasCached, err := cli.lookup(ctx, id.Partition())
if core.NoError != err {
return nil, err
}
// Do a non-cached read on tract metadata. This isn't technically necessary,
// but it ensures that we contact the curator directly in the next step so
// that we really do return an error here if the blob has been deleted or
// is unreachable.
tracts, err := cli.curators.GetTracts(ctx, addr, id, 0, 0, allowRead, allowWrite)
if err != core.NoError {
if lookupWasCached {
// Maybe we're talking to the wrong curator.
cli.lookupCache.invalidate(id.Partition())
return cli.openOnce(ctx, id, mode)
}
return nil, err
}
if cli.useCache() {
// We still want to cache the first tract so a subsequent access on the
// first tract of the blob doesn't need to talk to curator.
cli.tractCache.put(id, tracts)
}
// Create and return a Blob.
return &Blob{
cli: cli,
id: id,
allowRead: allowRead,
allowWrite: allowWrite,
ctx: ctx,
}, core.NoError
}
// Delete deletes 'blob'. It will retry the operation internally according to
// the retry policy specified by users if the operation failed due to
// "retriable" errors.
func (cli *Client) Delete(ctx context.Context, id BlobID) error {
var berr core.Error
st := time.Now()
cli.retrier.Do(ctx, func(seq int) bool {
log.Infof("delete blob %v, attempt #%d", id, seq)
berr = cli.deleteOnce(ctx, core.BlobID(id))
return !core.IsRetriableError(berr)
})
cli.metricDelete.Observe(float64(time.Since(st)) / 1e9)
return berr.Error()
}
// deleteOnce deletes 'blob'.
func (cli *Client) deleteOnce(ctx context.Context, blob core.BlobID) core.Error {
log.V(1).Infof("delete blob %d", blob)
addr, lookupWasCached, err := cli.lookup(ctx, blob.Partition())
if core.NoError != err {
return err
}
err = cli.curators.DeleteBlob(ctx, addr, blob)
if err != core.NoError && lookupWasCached {
// Maybe we're talking to the wrong curator.
cli.lookupCache.invalidate(blob.Partition())
return cli.deleteOnce(ctx, blob)
}
return err
}
// Undelete undeletes 'blob'.
func (cli *Client) Undelete(ctx context.Context, id BlobID) error {
var berr core.Error
st := time.Now()
cli.retrier.Do(ctx, func(seq int) bool {
log.Infof("undelete blob %v, attempt #%d", id, seq)
berr = cli.undeleteOnce(ctx, core.BlobID(id))
return !core.IsRetriableError(berr)
})
cli.metricUndelete.Observe(float64(time.Since(st)) / 1e9)
return berr.Error()
}
// undeleteOnce undeletes 'blob'.
func (cli *Client) undeleteOnce(ctx context.Context, blob core.BlobID) core.Error {
log.V(1).Infof("undelete blob %d", blob)
addr, lookupWasCached, err := cli.lookup(ctx, blob.Partition())
if core.NoError != err {
return err
}
err = cli.curators.UndeleteBlob(ctx, addr, blob)
if err != core.NoError && lookupWasCached {
// Maybe we're talking to the wrong curator.
cli.lookupCache.invalidate(blob.Partition())
return cli.undeleteOnce(ctx, blob)
}
return err
}
// GetTracts returns a subset of the tracts for the blob. It will retry the
// operation internally according to the retry policy specified by users if the
// operation failed due to "retriable" errors.
func (cli *Client) GetTracts(ctx context.Context, id BlobID, start, end int) ([]core.TractInfo, error) {
var tracts []core.TractInfo
var berr core.Error
cli.retrier.Do(ctx, func(seq int) bool {
log.Infof("get tracts [%d, %d) on blob %v, attempt #%d", start, end, id, seq)
tracts, berr = cli.getTractsOnce(ctx, core.BlobID(id), start, end)
return !core.IsRetriableError(berr)
})
return tracts, berr.Error()
}
// getTractsOnce returns a subset of the tracts for the blob.
func (cli *Client) getTractsOnce(ctx context.Context, id core.BlobID, start, end int) ([]core.TractInfo, core.Error) {
log.V(1).Infof("get tracts on blob %d from %d to %d", id, start, end)
addr, lookupWasCached, err := cli.lookup(ctx, id.Partition())
if core.NoError != err {
return nil, err
}
tracts, tractsWereCached, err := cli.getTracts(ctx, addr, id, start, end)
if core.NoError != err {
if lookupWasCached || tractsWereCached {
// Maybe we're talking to the wrong curator.
cli.lookupCache.invalidate(id.Partition())
// This shouldn't be cached, but it could theoretically happen if
// two threads call GetTracts at the same time. Invalidate again just to
// be sure.
cli.tractCache.invalidate(id)
return cli.getTractsOnce(ctx, id, start, end)
}
return nil, err
}
return tracts, err
}
// SetMetadata allows changing various fields of blob metadata. Currently
// changing the storage hint, mtime, atime are supported.
func (cli *Client) SetMetadata(ctx context.Context, id BlobID, metadata core.BlobInfo) error {
var berr core.Error
cli.retrier.Do(ctx, func(seq int) bool {
log.Infof("set metadata on %s: %+v, attempt #%d", id, metadata, seq)
berr = cli.setMetadataOnce(ctx, core.BlobID(id), metadata)
return !core.IsRetriableError(berr)
})
return berr.Error()
}
func (cli *Client) setMetadataOnce(ctx context.Context, blob core.BlobID, metadata core.BlobInfo) core.Error {
log.V(1).Infof("setmetadata on %s: %v", blob, metadata)
addr, lookupWasCached, err := cli.lookup(ctx, blob.Partition())
if core.NoError != err {
return err
}
err = cli.curators.SetMetadata(ctx, addr, blob, metadata)
if err != core.NoError && lookupWasCached {
// Maybe we're talking to the wrong curator.
cli.lookupCache.invalidate(blob.Partition())
return cli.setMetadataOnce(ctx, blob, metadata)
}
return err
}
// ListBlobs returns an iterator that lists all existing blobs, in batches.
// Clients should keep calling the iterator until it return nil, or an error.
// The iterator should be used in a single-threaded manner.
//
// ListBlobs is not guaranteed to return all blobs if cluster membership or raft
// leadership changes during iteration. It's intended for informative and
// diagnostic use only.
func (cli *Client) ListBlobs(ctx context.Context) BlobIterator {
bi := &blobIterator{cli: cli, ctx: ctx}
return bi.next
}
// BlobIterator is a function that returns BlobIDs in batches.
type BlobIterator func() ([]BlobID, error)
//----------------
// Helper methods
//----------------
// getNextRange is a helper function to split a byte slice, conceptually
// positioned at a given offset in a blob, that may cross tract boundaries, into
// ranges that do not cross tract boundaries.
//
// Call it repeatedly with the whole range and offset, and a pointer to an int
// representing the number of bytes returned so far (initialized to zero).
func (cli *Client) getNextRange(b []byte, offset int64, position *int) (thisB []byte, thisOffset int64) {
pos := *position
thisOffset = (offset + int64(pos)) % core.TractLength
thisLen := int(core.TractLength - thisOffset)
if thisLen > (len(b) - pos) {
thisLen = (len(b) - pos)
}
thisB = b[pos : pos+thisLen]
*position += thisLen
return
}
// extendTo extends the given blob, by possibly creating empty tracts, to
// accomodate futher writes upto 'offset'.
//
// NOTE: This can be possibly used to pre-allocate empty tracts so that multiple
// clients can write to different tracts in the same blob simultaneously w/o
// conflicts. A single client should use 'writeAt' which will create empty
// tracts on demand.
func (cli *Client) extendTo(ctx context.Context, id core.BlobID, offset int64) core.Error {
if offset < 0 {
return core.ErrInvalidArgument
}
// We want to cover tracts in [0, end).
end := int((offset + core.TractLength - 1) / core.TractLength)
// Contact the curator for the blob stat. Extend the blob if there are
// not enough existing tracts.
curatorAddr, info, err := cli.statBlob(ctx, id)
if core.NoError != err {
return err
}
if info.NumTracts >= end {
return core.NoError
}
return cli.createEmptyTracts(ctx, id, info.NumTracts, end, curatorAddr)
}
// writeAt writes 'len(b)' bytes from 'b' to 'blob' at 'offset'. It returns the
// number of bytes written from 'b' and any error encountered that caused the
// write to stop early.
func (cli *Client) writeAt(ctx context.Context, id core.BlobID, b []byte, offset int64) (int, core.Error) {
if offset < 0 {
return 0, core.ErrInvalidArgument
}
if len(b) == 0 {
return 0, core.NoError
}
// We want to write tracts in [start, end).
start := int(offset / core.TractLength)
end := int((offset + int64(len(b)) + core.TractLength - 1) / core.TractLength)
// Contact the curator for the blob stat. Extend the blob if there are
// not enough existing tracts for the write.
// TODO: we shouldn't stat every time here: cache info.NumTracts
curatorAddr, info, err := cli.statBlob(ctx, id)
if core.NoError != err {
return 0, err
}
// Can only write to replicated blobs. We shouldn't get here, since the
// curator should return an error to the initial GetTracts call, but this is
// here for defense in depth.
if info.Class != core.StorageClassREPLICATED {
return 0, core.ErrReadOnlyStorageClass
}
// For existing tracts, write directly.
var writePos int
if start < info.NumTracts {
if writePos, err = cli.writeExistingTracts(ctx, id, start, min(end, info.NumTracts), b, offset, curatorAddr); err != core.NoError {
return 0, err
}
start = info.NumTracts
b = b[writePos:]
offset += int64(writePos)
}
// Create new tracts if necessary.
var createPos int
if end > info.NumTracts {
// Might need to create empty tracts (hole) in [info.NumTracts, start).
if start > info.NumTracts {
if err = cli.createEmptyTracts(ctx, id, info.NumTracts, start, curatorAddr); err != core.NoError {
return 0, err
}
}
// Create and write tracts in [start, end).
createPos, err = cli.createWriteTracts(ctx, id, start, end, b, offset, curatorAddr)
}
return writePos + createPos, err
}
// Write bytes to existing tracts in the range [start, end) from the give blob.
// The caller needs to make sure that these tracts exist in curator's durable
// state and thus can be returned by getTracts call; otherwise error will be
// returned.
func (cli *Client) writeExistingTracts(
ctx context.Context,
id core.BlobID,
start int,
end int,
b []byte,
offset int64,
curatorAddr string) (int, core.Error) {
// Contact the curator for the TractInfo's.
tracts, tractsWereCached, err := cli.getTracts(ctx, curatorAddr, id, start, end)
if core.NoError != err {
return 0, err
}
// Check that we got as many tracts as we asked for.
if len(tracts) < end-start {
log.Errorf("curator didn't return enough tracts: %d < %d", len(tracts), end-start)
return 0, core.ErrNoSuchTract
}
// Check for the same replication factor across all tracts.
repl := len(tracts[0].Hosts)
for _, tract := range tracts {
if len(tract.Hosts) != repl {
log.Errorf("host set length mismatch for tract %s", tract.Tract)
return 0, core.ErrInvalidState
}
// We also need them all to be present.
for j, host := range tract.Hosts {
if host == "" {
log.Errorf("missing host for tsid %d writing tract %s", tract.TSIDs[j], tract.Tract)
return 0, core.ErrHostNotExist
}
}
}
// We set up an array of Errors for results and each goroutine writes into
// its own slot. This is simpler than using a channel and is closer to how
// readAt works. The WaitGroup is used to block the caller on the completion
// of all goroutines and the Semaphore is used to limit the concurrency.
sem := server.NewSemaphore(ParallelRPCs)
results := make([]core.Error, repl*len(tracts))
var wg sync.WaitGroup
// Fire off a bunch of rpcs in parallel.
var position, idx int
for _, tract := range tracts {
thisB, thisOffset := cli.getNextRange(b, offset, &position)
for _, host := range tract.Hosts {
wg.Add(1)
go cli.writeOneTract(ctx, &results[idx], &wg, sem, tract, host, thisB, thisOffset)
idx++
}
}
wg.Wait()
// The write only succeeds if every tract write succeeded.
for i := 0; i < len(results); i++ {
// This tract is OK.
if results[i] == core.NoError {
continue
}
// Something went wrong. We can take steps to recover.
// Maybe we got older cached tracts.
// PL-1153: This will retry the whole write operation after talking to
// the curator again. Ideally we would only retry the tracts that
// failed.
if tractsWereCached {
cli.tractCache.invalidate(id)
return cli.writeExistingTracts(ctx, id, start, end, b, offset, curatorAddr)
}
// We couldn't talk to one of the tractservers, and we're pretty sure that the
// metadata was fresh as it wasn't cached. We can ask the curator to consider
// re-replicating data.
// PL-1154: We should collect all these ReportBadTS and FixVersion calls
// and put them in a queue and send them in batches, at a throttled rate.
if results[i] == core.ErrRPC {
tractNo := i / repl
replicaNo := i % repl
id := tracts[tractNo].Tract
host := tracts[tractNo].Hosts[replicaNo]
log.Errorf("rpc error writing tract %s to replica on tractserver at address %s", id, host)
cli.curators.ReportBadTS(context.Background(), curatorAddr, id, host, "write", results[i], false)
} else if results[i] == core.ErrVersionMismatch {
tract := tracts[i/repl]
host := tract.Hosts[i%repl]
log.Errorf("version mismatch when writing tract %v to tractserver at %s", tract, host)
cli.curators.FixVersion(context.Background(), curatorAddr, tract, host)
}
// For now, just assume nothing written if anything failed.
// PL-1153: Return partial writes if a nonzero prefix succeeded.
return 0, results[i]
}
return position, core.NoError
}
// Create empty tracts in the range [start, end) from the given blob . The
// caller needs to make sure that these tracts don't already exist in curator's
// durable state yet; otherwise error will be returned.
func (cli *Client) createEmptyTracts(
ctx context.Context,
id core.BlobID,
start int,
end int,
curatorAddr string) core.Error {
// Contact curator to allocate tractservers.
var newTracts []core.TractInfo
var err core.Error
if newTracts, err = cli.curators.ExtendBlob(ctx, curatorAddr, id, end); core.NoError != err {
return err
}
// Check that we got as many tracts as we asked for.
if len(newTracts) < end-start {
log.Errorf("curator didn't return enough tracts: %d < %d", len(newTracts), end-start)
return core.ErrNoSuchTract
}
// Check for the same replication factor across all tracts.
repl := len(newTracts[0].Hosts)
for _, tract := range newTracts {
if len(tract.Hosts) != repl {
log.Fatalf("host set length mismatch for tract %s", tract.Tract)
return core.ErrInvalidState
}
}
// We set up an array of Errors for results and each goroutine writes into
// its own slot. This is simpler than using a channel and is closer to how
// readAt works. The WaitGroup is used to block the caller on the completion
// of all goroutines and the Semaphore is used to limit the concurrency.
sem := server.NewSemaphore(ParallelRPCs)
results := make([]core.Error, repl*len(newTracts))
var wg sync.WaitGroup
var idx int
for _, tract := range newTracts {
for i, host := range tract.Hosts {
wg.Add(1)
go cli.createOneTract(ctx, &results[idx], &wg, sem, tract, host, tract.TSIDs[i], nil, 0)
idx++
}
}
wg.Wait()
// The creation only succeeds if every tract creation succeeded.
for _, err := range results {
if err != core.NoError {
return err
}
}
// Ack the success of extend to curator.
if err = cli.curators.AckExtendBlob(ctx, curatorAddr, id, newTracts); core.NoError != err {
log.Errorf("failed to ack extending blob %s with new tracts %+v: %s", id, newTracts, err)
}
return err
}
// Create new tracts in the range [start, end) from the given blob and write
// bytes to them. The caller needs to make sure that these tracts don't already
// exist in curator's durable state yet; otherwise error will be returned.
func (cli *Client) createWriteTracts(
ctx context.Context,
id core.BlobID,
start int,
end int,
b []byte,
offset int64,
curatorAddr string) (int, core.Error) {
// Contact curator to allocate tractservers.
var newTracts []core.TractInfo
var err core.Error
if newTracts, err = cli.curators.ExtendBlob(ctx, curatorAddr, id, end); core.NoError != err {
return 0, err
}
// Check that we got as many tracts as we asked for.
if len(newTracts) < end-start {
log.Errorf("curator didn't return enough tracts: %d < %d", len(newTracts), end-start)
return 0, core.ErrNoSuchTract
}
// Check for the same replication factor across all tracts.
repl := len(newTracts[0].Hosts)
for _, tract := range newTracts {
if len(tract.Hosts) != repl {
log.Fatalf("host set length mismatch for tract %s", tract.Tract)
return 0, core.ErrInvalidState
}
}
// We set up an array of Errors for results and each goroutine writes into
// its own slot. This is simpler than using a channel and is closer to how
// readAt works. The WaitGroup is used to block the caller on the completion
// of all goroutines and the Semaphore is used to limit the concurrency.
sem := server.NewSemaphore(ParallelRPCs)
results := make([]core.Error, repl*len(newTracts))
var wg sync.WaitGroup
// Fire off a bunch of rpcs in parallel.
var position, idx int
for _, tract := range newTracts {
thisB, thisOffset := cli.getNextRange(b, offset, &position)
for i, host := range tract.Hosts {
wg.Add(1)
go cli.createOneTract(ctx, &results[idx], &wg, sem, tract, host, tract.TSIDs[i], thisB, thisOffset)
idx++
}
}
wg.Wait()
// The write only succeeds if every tract write succeeded.
for _, err := range results {
if err != core.NoError {
return 0, err
}
}
// Ack the success of extend to curator.
if err := cli.curators.AckExtendBlob(ctx, curatorAddr, id, newTracts); core.NoError != err {
log.Errorf("failed to ack extending blob %s with new tracts %+v: %s", id, newTracts, err)
return 0, err
}
return position, core.NoError
}
func (cli *Client) writeOneTract(
ctx context.Context,
result *core.Error,
wg *sync.WaitGroup,
sem server.Semaphore,
tract core.TractInfo,
host string,
thisB []byte,
thisOffset int64) {
defer wg.Done()
sem.Acquire()
defer sem.Release()
*result = cli.tractservers.Write(ctx, host, tract.Tract, tract.Version, thisB, thisOffset)
log.V(1).Infof("write %s to %s: %s", tract.Tract, host, *result)
}
func (cli *Client) createOneTract(
ctx context.Context,
result *core.Error,
wg *sync.WaitGroup,
sem server.Semaphore,
tract core.TractInfo,
host string,
tsid core.TractserverID,
thisB []byte,
thisOffset int64) {
defer wg.Done()
sem.Acquire()
defer sem.Release()
*result = cli.tractservers.Create(ctx, host, tsid, tract.Tract, thisB, thisOffset)
log.V(1).Infof("create %s to %s: %s", tract.Tract, host, *result)
}
type tractResult struct {
wanted int // how much wanted to read
read int // how much was read
err core.Error // any error
badVersionHost string // last host that we got an ErrVersionMismatch from
// Note that we can set a badVersionHost for some host even if we return no
// overall error because another host succeeded.
}
// readAt reads up to 'len(b)' bytes from 'blob' into 'b' at 'offset'. It
// returns the number of bytes read and any error encountered.
func (cli *Client) readAt(ctx context.Context, id core.BlobID, b []byte, offset int64) (int, core.Error) {
if offset < 0 {
return 0, core.ErrInvalidArgument
} else if len(b) == 0 {
return 0, core.NoError
}
// We want to read tracts in [start, end).
start := int(offset / core.TractLength)
end := int((offset + int64(len(b)) + core.TractLength - 1) / core.TractLength)
// Get the curator address.
addr, curatorWasCached, err := cli.lookup(ctx, id.Partition())
if core.NoError != err {
return 0, err
}
// Contact the curator for the blob stat.
// We will try to get tracts in [start, end+1). The extra tract is used
// to check if tracts in [start, end) include the last one in the blob.
tracts, tractsWereCached, err := cli.getTracts(ctx, addr, id, start, end+1)
if core.NoError != err {
if err == core.ErrNoSuchTract {
// This means the blob exists but the required tracts don't exist
// in curator's state. Because we don't allow tracts truncation, this
// means we must have read past the last tract, return EOF error
// directly.
return 0, core.ErrEOF
}
if curatorWasCached {
// Maybe we're talking to the wrong curator.
cli.lookupCache.invalidate(id.Partition())
return cli.readAt(ctx, id, b, offset)
}
return 0, err
}
// If the blob has no tracts in this range, we're at the end.
if len(tracts) == 0 {
return 0, core.ErrEOF
}
var padAll bool // If we need to pad all short-read tracts.
// If the number of returned tracts is equal to what we asked for,
// end+1-start (including the extra tract), it means that all tracts in
// the range [start, end) are not the last tract in the blob. Therefore,
// we will need to pad the read results if short read happens to any of
// them.
//
// We will remove the extra tract before actually pulling data from them.
if len(tracts) == end+1-start {
padAll = true
tracts = tracts[:len(tracts)-1]
} else {
// The number of returned tract is less than what we asked for
// (cannot be more than that). It means that the range [start,
// end) includes the last tract in the blob. We should not pad
// the last tract in case of short read (still need to pad
// others in case of short read).
//
// The extra tract is not included so we don't need to remove
// anything from the returned slice.
padAll = false
}
// We create an array of results and let each goroutine write into one of
// them, in addition to writing directly into the slice of b that it's
// responsible for. The result here includes the length as well as the error
// code. We use an array instead of passing the results on a channel because
// we need to examine them in order to handle EOFs and short reads.
sem := server.NewSemaphore(ParallelRPCs)
results := make([]tractResult, len(tracts))
var wg sync.WaitGroup
position := 0
// Fire off a goroutine to position each tract.
for idx := range tracts {
thisB, thisOffset := cli.getNextRange(b, offset, &position)
wg.Add(1)
go cli.readOneTract(ctx, addr, &results[idx], &wg, sem, &tracts[idx], thisB, thisOffset)
}
wg.Wait()
// Figure out how much succeeded.
read := 0
for i, res := range results {
err = res.err
if err == core.NoError {
read += res.read
} else if err == core.ErrEOF {
// Any tract can be a short read at the tractserver end.
// However, the client will pad those that are not the last
// tract in the blob.
//
// For the last tract, the lengths of the bytes returned
// by the client is equal to that from the tractserver.
if i == len(results)-1 && !padAll {
read += res.read
break
}
// For previous tracts, short read means there is a hole
// in the tract. As the client pads them with 0's (see
// 'readOneTract'), the lengths of the bytes returned by
// the client is equal to how much we wanted to read
// from the tractserver. This is not EOF so we will
// reset the error here.
read += res.wanted
err = core.NoError
} else {
break
}
}
if err != core.NoError && err != core.ErrEOF && tractsWereCached {
// Maybe we got older cached tracts.
cli.tractCache.invalidate(id)
return cli.readAt(ctx, id, b, offset)
}
// Maybe kick off FixVersion rpcs. Do this after the cache invalidate/retry
// since we don't want to do extra work if the only reason for version
// mismatches is that we have out of date cached data.
wg = sync.WaitGroup{}
for i, res := range results {
tract := tracts[i]
// For replicated tracts, we might want to do a FixVersion if someone reported a wrong version.
if res.badVersionHost == "" {
continue
}
log.Infof("got version mismatch when reading tract %s from host %s, requesting FixVersion",
tract.Tract, res.badVersionHost)
var doneWg *sync.WaitGroup
if res.err == core.ErrVersionMismatch {
// If we failed to read this tract because none of the
// tractservers had the right version, then we should wait on
// this FixVersion call. Otherwise we can kick it off and forget
// about it.
doneWg = &wg
doneWg.Add(1)
}
go func(badHost string, tract core.TractInfo) {
cli.curators.FixVersion(context.Background(), addr, tract, badHost)
if doneWg != nil {
doneWg.Done()
}
}(res.badVersionHost, tract)
}
wg.Wait()
return read, err
}
func (cli *Client) readOneTract(
ctx context.Context,
curAddr string,
result *tractResult,
wg *sync.WaitGroup,
sem server.Semaphore,
tract *core.TractInfo,
thisB []byte,
thisOffset int64) {
defer wg.Done()
sem.Acquire()
defer sem.Release()
if len(tract.Hosts) > 0 {
cli.readOneTractReplicated(ctx, curAddr, result, tract, thisB, thisOffset)
} else if tract.RS.Present() {
cli.readOneTractRS(ctx, curAddr, result, tract, thisB, thisOffset)
} else {
*result = tractResult{err: core.ErrInvalidState}
}
}
func (cli *Client) readOneTractReplicated(
ctx context.Context,
curAddr string,
result *tractResult,
tract *core.TractInfo,
thisB []byte,
thisOffset int64) {
var badVersionHost string
order := rand.Perm(len(tract.Hosts))
err := core.ErrAllocHost // default error if none present
for _, n := range order {
host := tract.Hosts[n]
if host == "" {
log.V(1).Infof("read %s from tsid %d: no host", tract.Tract, tract.TSIDs[n])
continue
}
var read int
read, err = cli.tractservers.ReadInto(ctx, host, tract.Tract, tract.Version, thisB, thisOffset)
if err == core.ErrVersionMismatch {
badVersionHost = host
}
if err != core.NoError && err != core.ErrEOF {
log.V(1).Infof("read %s from tractserver at address %s: %s", tract.Tract, host, err)
// If we failed to read from a TS, report that to the curator. Defer so we can examine
// result.err at the end, to see if we succeeded on another or not.
defer func(host string, err core.Error) {
couldRecover := result.err == core.NoError || result.err == core.ErrEOF
go cli.curators.ReportBadTS(context.Background(), curAddr, tract.Tract, host, "read", err, couldRecover)
}(host, err)
continue // try another host
}
log.V(1).Infof("read %s from tractserver at address %s: %s", tract.Tract, host, err)
// In case of short read, i.e., read < len(thisB), we should
// pad the result with 0's. This doesn't need to be done
// explicitly if 'thisB' given to us starts to be empty.
// However, just in case it's not, we will ensure that by
// overwritting untouched bytes with 0's.
for i := read; i < len(thisB); i++ {
thisB[i] = 0
}
*result = tractResult{len(thisB), read, err, badVersionHost}
return
}
log.V(1).Infof("read %s all hosts failed", tract.Tract)
*result = tractResult{0, 0, err, badVersionHost}
}
func (cli *Client) readOneTractRS(
ctx context.Context,
curAddr string,
result *tractResult,
tract *core.TractInfo,
thisB []byte,
thisOffset int64) {
rsTract := tract.RS.Chunk.ToTractID()
length := min(len(thisB), int(tract.RS.Length))
offset := int64(tract.RS.Offset) + thisOffset
read, err := cli.tractservers.ReadInto(ctx, tract.RS.Host, rsTract, core.RSChunkVersion, thisB[:length], offset)
if err != core.NoError && err != core.ErrEOF {
log.V(1).Infof("rs read %s from tractserver at address %s: %s", tract.Tract, tract.RS.Host, err)
// If we failed to read from a TS, report that to the curator. Defer so
// we can examine result.err at the end, to see if we recovered or not.
defer func(err core.Error) {
couldRecover := result.err == core.NoError || result.err == core.ErrEOF
go cli.curators.ReportBadTS(context.Background(), curAddr, rsTract, tract.RS.Host, "read", err, couldRecover)
}(err)
if !cli.shouldReconstruct(tract) {
*result = tractResult{len(thisB), 0, err, ""}
return
}
// Let's try reconstruction. We're already recording metrics for this as a read, but we
// should keep separate metrics for client-side recovery, since it's a heavyweight process.
st := time.Now()
cli.reconstructOneTract(ctx, result, tract, thisB, offset, length)
cli.metricReconDuration.Observe(float64(time.Since(st)) / 1e9)
cli.metricReconBytes.Add(float64(result.read))
return
}
log.V(1).Infof("rs read %s from tractserver at address %s: %s", tract.Tract, tract.RS.Host, err)
for i := read; i < len(thisB); i++ {
thisB[i] = 0 // Pad with zeros. See comment in readOneTractReplicated.
}
// Even if the tractserver doesn't think this was an EOF (because it was
// packed with other data), we might have requested less than the caller
// asked for. That counts as an EOF too.
if int(tract.RS.Length) < len(thisB) {
err = core.ErrEOF
}
*result = tractResult{len(thisB), read, err, ""}
}
// statBlob returns the corresponding curator and number of tracts for a given blob.
// Error is returned if any.
func (cli *Client) statBlob(ctx context.Context, id core.BlobID) (addr string, info core.BlobInfo, err core.Error) {
var wasCached bool
addr, wasCached, err = cli.lookup(ctx, id.Partition())
if err != core.NoError {
return
}
info, err = cli.curators.StatBlob(ctx, addr, id)
if err != core.NoError && wasCached {
// Maybe we're talking to the wrong curator.
cli.lookupCache.invalidate(id.Partition())
return cli.statBlob(ctx, id)
}
return
}
// statTract returns the length of the given tract. tract should be the result
// of a GetTracts call. Error is returned if any.
func (cli *Client) statTract(ctx context.Context, tract core.TractInfo) (int64, core.Error) {
if tract.RS.Present() {
return int64(tract.RS.Length), core.NoError
}
order := rand.Perm(len(tract.Hosts))
err := core.ErrAllocHost // default error if none present
for _, n := range order {
host := tract.Hosts[n]
if host == "" {
continue
}
var res int64
res, err = cli.tractservers.StatTract(ctx, host, tract.Tract, tract.Version)
if err != core.NoError {
log.V(1).Infof("stat %s from %s: %s", tract.Tract, host, err)
continue // try another host
}
return res, core.NoError
}
log.V(1).Infof("stat %s: all hosts failed", tract.Tract)
return 0, err // return last error
}
// ByteLength returns the length of the blob in bytes.
func (cli *Client) byteLength(ctx context.Context, id core.BlobID) (int64, core.Error) {
curator, info, err := cli.statBlob(ctx, id)
if err != core.NoError {
return 0, err
}
if info.NumTracts == 0 {
return 0, core.NoError
}
tracts, tractsWereCached, err := cli.getTracts(ctx, curator, id, info.NumTracts-1, info.NumTracts)
if err != core.NoError || len(tracts) != 1 {
return 0, err
}
lastLen, err := cli.statTract(ctx, tracts[0])
if err != core.NoError {
if tractsWereCached {
// Maybe we're talking to the wrong tractserver.
cli.tractCache.invalidate(id)
return cli.byteLength(ctx, id)
}
return 0, err
}
return int64(info.NumTracts-1)*core.TractLength + lastLen, core.NoError
}
// lookup returns a curator address for the given partition. The blob->curator
// mapping may be cached, and that will be indicated in the return value. If the
// result was cached and the caller gets an error talking to the returned
// curator, the caller should call invalidate and try again.
func (cli *Client) lookup(ctx context.Context, id core.PartitionID) (addr string, wasCached bool, err core.Error) {
useCache := cli.useCache()
if useCache {
// Check cache if allowed.
addr, wasCached = cli.lookupCache.get(id)
}
if !wasCached {
// Do the rpc.
addr, err = cli.master.LookupPartition(ctx, id)
if err != core.NoError {
return "", false, err
}
if useCache {
// Insert into cache.
cli.lookupCache.put(id, addr)
}
}
return
}
// getTracts returns tract info for the given tracts. It may return data from a cache.
func (cli *Client) getTracts(ctx context.Context, addr string, id core.BlobID, start, end int) (tracts []core.TractInfo, wasCached bool, err core.Error) {
useCache := cli.useCache()
if useCache {
// Check cache if allowed.
tracts, wasCached = cli.tractCache.get(id, start, end)
}
if !wasCached {
// Do the rpc.
// We can use `false, false` here because Open does an uncached
// GetTracts call with the correct read/write intention.
tracts, err = cli.curators.GetTracts(ctx, addr, id, start, end, false, false)
if err != core.NoError {
return nil, false, err
}
if useCache {
// Insert into cache.
cli.tractCache.put(id, tracts)
}
}
return
}
type blobIterator struct {
cli *Client
thisPartition core.PartitionID
partitions []core.PartitionID
curator string
start core.BlobKey
// Conceptually, an iteration is a single "request", so we use one context throughout.
ctx context.Context
}
func (bi *blobIterator) next() (ids []BlobID, err error) {
var berr core.Error
if bi.partitions == nil {
// Need to get partitions from master.
bi.cli.retrier.Do(bi.ctx, func(seq int) bool {
log.Infof("ListPartitions, attempt #%d", seq)
bi.partitions, berr = bi.cli.master.ListPartitions(bi.ctx)
return !core.IsRetriableError(berr)
})
if berr != core.NoError {
return nil, berr.Error()
}
}
if len(bi.partitions) == 0 && bi.thisPartition == 0 {
// No more partitions, return nil to signal end.
return nil, nil
}
curatorWasCached := false
doLookup := false
if bi.thisPartition == 0 {
// Check next partition.
bi.thisPartition = bi.partitions[0]
bi.partitions = bi.partitions[1:]
bi.start = 0
doLookup = true
}
RetryLookup:
if doLookup {
bi.cli.retrier.Do(bi.ctx, func(seq int) bool {
log.Infof("LookupPartition(%x), attempt #%d", bi.thisPartition, seq)
bi.curator, curatorWasCached, berr = bi.cli.lookup(bi.ctx, bi.thisPartition)
return !core.IsRetriableError(berr)
})
if berr != core.NoError {
return nil, berr.Error()
}
}
// Ask curator for blobs.
var keys []core.BlobKey
bi.cli.retrier.Do(bi.ctx, func(seq int) bool {
log.Infof("ListBlobs(%x), attempt #%d", bi.thisPartition, seq)
keys, berr = bi.cli.curators.ListBlobs(bi.ctx, bi.curator, bi.thisPartition, bi.start)
return !core.IsRetriableError(berr)
})
if berr != core.NoError {
if curatorWasCached {
// Maybe we got the wrong curator from the cache.
bi.cli.lookupCache.invalidate(bi.thisPartition)
goto RetryLookup
}
return nil, berr.Error()
}
if len(keys) == 0 {
// We're done with this partition.
bi.thisPartition = 0
return bi.next()
}
// Return some ids.
ids = make([]BlobID, len(keys))
for i, key := range keys {
ids[i] = BlobID(core.BlobIDFromParts(bi.thisPartition, key))
}
// start here next time
bi.start = keys[len(keys)-1] + 1
return ids, nil
}
func min(a, b int) int {
if a < b {
return a
}
return b
}
// Priorities in contexts:
type contextKey int
const priorityKey contextKey = iota
func priorityFromContext(ctx context.Context) core.Priority {
if pri, ok := ctx.Value(priorityKey).(core.Priority); ok {
return pri
}
return core.PriorityTSDEFAULT
}
| {
"pile_set_name": "Github"
} |
---
-api-id: M:Windows.UI.Xaml.Controls.ListViewBase.SelectAll
-api-type: winrt method
---
<!-- Method syntax
public void SelectAll()
-->
# Windows.UI.Xaml.Controls.ListViewBase.SelectAll
## -description
Selects all the items in a view.
## -remarks
> [!WARNING]
> Call the SelectAll method only when the [SelectionMode](listviewbase_selectionmode.md) property is set to [Multiple](listviewselectionmode.md) or [Extended](listviewselectionmode.md). If you call SelectAll when the [SelectionMode](listviewbase_selectionmode.md) is **Single** or **None**, an exception is thrown.
Starting in Windows 10, you can use the [SelectRange](listviewbase_selectrange_1824826911.md) and [DeselectRange](listviewbase_deselectrange_1629963900.md) methods with the [SelectedRanges](listviewbase_selectedranges.md) property to make selections using ranges of indexes. This is a more efficient way to describe item selection than using [SelectedItems](listviewbase_selecteditems.md), which requires the actual item object to be created for each selected item. To select all items using index ranges, use [SelectRange](listviewbase_selectrange_1824826911.md).
## -examples
```xaml
<GridView x:Name="itemGridView"/>
```
```csharp
if (itemGridView.SelectionMode == ListViewSelectionMode.Multiple ||
itemGridView.SelectionMode == ListViewSelectionMode.Extended)
{
itemGridView.SelectAll();
}
```
```cppwinrt
if (itemGridView().SelectionMode() == Windows::UI::Xaml::Controls::ListViewSelectionMode::Multiple ||
itemGridView().SelectionMode() == Windows::UI::Xaml::Controls::ListViewSelectionMode::Extended)
{
itemGridView().SelectAll();
}
```
```cppcx
if (itemGridView->SelectionMode == ListViewSelectionMode::Multiple ||
itemGridView->SelectionMode == ListViewSelectionMode::Extended)
{
itemGridView->SelectAll();
}
```
```vbnet
If itemGridView.SelectionMode = ListViewSelectionMode.Multiple OrElse
itemGridView.SelectionMode = ListViewSelectionMode.Extended Then
itemGridView.SelectAll()
End If
```
## -see-also
[SelectedRanges](listviewbase_selectedranges.md), [SelectRange](listviewbase_selectrange_1824826911.md), [DeselectRange](listviewbase_deselectrange_1629963900.md), [ItemIndexRange](../windows.ui.xaml.data/itemindexrange.md)
| {
"pile_set_name": "Github"
} |
/*
* Copyright 2008-2020 Async-IO.org
*
* 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.atmosphere.nettosphere;
import io.netty.channel.Channel;
import io.netty.channel.ChannelId;
import io.netty.channel.group.ChannelGroup;
import org.atmosphere.websocket.WebSocket;
import java.util.HashSet;
import java.util.Set;
import static org.atmosphere.nettosphere.BridgeRuntime.NETTY_41_PLUS;
import static org.atmosphere.nettosphere.HttpStaticFileServerHandler.ATTACHMENT;
/**
* This class expose some runtime properties of the Netty implementation
*
* @author Jeanfrancois Arcand
*/
public class RuntimeEngine {
private final BridgeRuntime runtime;
private final ChannelGroup httpChannels;
private final ChannelGroup websocketChannels;
public RuntimeEngine(BridgeRuntime runtime) {
this.runtime = runtime;
this.httpChannels = runtime.httpChannels();
this.websocketChannels = runtime.websocketChannels();
}
/**
* Return the underlying {@link Channel}.
*
* @param id the unique {@link Channel} ID.
* @return the underlying {@link Channel}.
*/
public <U> Channel find(U id) {
Channel c = null;
if (NETTY_41_PLUS) {
c = websocketChannels.find((ChannelId) id);
if (c == null) {
c = httpChannels.find((ChannelId) id);
}
} else {
throw new UnsupportedOperationException("You need to use Netty 4.1+ to use this feature");
}
return c;
}
/**
* Retrieve the associated {@link WebSocket} attached to the {@link Channel}
*
* @param id the unique {@link Channel} ID.
* @return the associated {@link WebSocket} attached to the {@link Channel}
*/
public <U> WebSocket findWebSocket(U id) {
if (NETTY_41_PLUS) {
Channel c = websocketChannels.find((ChannelId) id);
if (c != null) {
Object o = c.attr(ATTACHMENT).get();
if (o != null && WebSocket.class.isAssignableFrom(o.getClass())) {
return WebSocket.class.cast(o);
}
}
} else {
throw new UnsupportedOperationException("You need to use Netty 4.1+ to use this feature");
}
return null;
}
/**
* Return all connected {@link WebSocket}.
*
* @return all connected {@link WebSocket}.
*/
public Set<WebSocket> findAllWebSockets() {
Set<WebSocket> s = new HashSet<WebSocket>();
for (Channel c : websocketChannels) {
if (c != null) {
Object o = c.attr(ATTACHMENT).get();
if (o != null && WebSocket.class.isAssignableFrom(o.getClass())) {
s.add(WebSocket.class.cast(o));
}
}
}
return s;
}
/**
* Return the {@link ChannelGroup} associated with HTTP requests.
*
* @return the {@link ChannelGroup} associated with HTTP requests.
*/
public ChannelGroup httpChannels() {
return runtime.httpChannels();
}
/**
* Return the {@link ChannelGroup} associated with websocket requests.
*
* @return the {@link ChannelGroup} associated with websocket requests.
*/
public ChannelGroup websocketChannels() {
return runtime.websocketChannels();
}
}
| {
"pile_set_name": "Github"
} |
package shi_Latn
import (
"math"
"strconv"
"time"
"github.com/go-playground/locales"
"github.com/go-playground/locales/currency"
)
type shi_Latn struct {
locale string
pluralsCardinal []locales.PluralRule
pluralsOrdinal []locales.PluralRule
pluralsRange []locales.PluralRule
decimal string
group string
minus string
percent string
perMille string
timeSeparator string
inifinity string
currencies []string // idx = enum of currency code
monthsAbbreviated []string
monthsNarrow []string
monthsWide []string
daysAbbreviated []string
daysNarrow []string
daysShort []string
daysWide []string
periodsAbbreviated []string
periodsNarrow []string
periodsShort []string
periodsWide []string
erasAbbreviated []string
erasNarrow []string
erasWide []string
timezones map[string]string
}
// New returns a new instance of translator for the 'shi_Latn' locale
func New() locales.Translator {
return &shi_Latn{
locale: "shi_Latn",
pluralsCardinal: []locales.PluralRule{2, 4, 6},
pluralsOrdinal: nil,
pluralsRange: nil,
decimal: ",",
group: " ",
minus: "-",
percent: "%",
perMille: "‰",
timeSeparator: ":",
inifinity: "∞",
currencies: []string{"ADP", "AED", "AFA", "AFN", "ALK", "ALL", "AMD", "ANG", "AOA", "AOK", "AON", "AOR", "ARA", "ARL", "ARM", "ARP", "ARS", "ATS", "AUD", "AWG", "AZM", "AZN", "BAD", "BAM", "BAN", "BBD", "BDT", "BEC", "BEF", "BEL", "BGL", "BGM", "BGN", "BGO", "BHD", "BIF", "BMD", "BND", "BOB", "BOL", "BOP", "BOV", "BRB", "BRC", "BRE", "BRL", "BRN", "BRR", "BRZ", "BSD", "BTN", "BUK", "BWP", "BYB", "BYN", "BYR", "BZD", "CAD", "CDF", "CHE", "CHF", "CHW", "CLE", "CLF", "CLP", "CNH", "CNX", "CNY", "COP", "COU", "CRC", "CSD", "CSK", "CUC", "CUP", "CVE", "CYP", "CZK", "DDM", "DEM", "DJF", "DKK", "DOP", "DZD", "ECS", "ECV", "EEK", "EGP", "ERN", "ESA", "ESB", "ESP", "ETB", "EUR", "FIM", "FJD", "FKP", "FRF", "GBP", "GEK", "GEL", "GHC", "GHS", "GIP", "GMD", "GNF", "GNS", "GQE", "GRD", "GTQ", "GWE", "GWP", "GYD", "HKD", "HNL", "HRD", "HRK", "HTG", "HUF", "IDR", "IEP", "ILP", "ILR", "ILS", "INR", "IQD", "IRR", "ISJ", "ISK", "ITL", "JMD", "JOD", "JPY", "KES", "KGS", "KHR", "KMF", "KPW", "KRH", "KRO", "KRW", "KWD", "KYD", "KZT", "LAK", "LBP", "LKR", "LRD", "LSL", "LTL", "LTT", "LUC", "LUF", "LUL", "LVL", "LVR", "LYD", "MAD", "MAF", "MCF", "MDC", "MDL", "MGA", "MGF", "MKD", "MKN", "MLF", "MMK", "MNT", "MOP", "MRO", "MTL", "MTP", "MUR", "MVP", "MVR", "MWK", "MXN", "MXP", "MXV", "MYR", "MZE", "MZM", "MZN", "NAD", "NGN", "NIC", "NIO", "NLG", "NOK", "NPR", "NZD", "OMR", "PAB", "PEI", "PEN", "PES", "PGK", "PHP", "PKR", "PLN", "PLZ", "PTE", "PYG", "QAR", "RHD", "ROL", "RON", "RSD", "RUB", "RUR", "RWF", "SAR", "SBD", "SCR", "SDD", "SDG", "SDP", "SEK", "SGD", "SHP", "SIT", "SKK", "SLL", "SOS", "SRD", "SRG", "SSP", "STD", "STN", "SUR", "SVC", "SYP", "SZL", "THB", "TJR", "TJS", "TMM", "TMT", "TND", "TOP", "TPE", "TRL", "TRY", "TTD", "TWD", "TZS", "UAH", "UAK", "UGS", "UGX", "USD", "USN", "USS", "UYI", "UYP", "UYU", "UZS", "VEB", "VEF", "VND", "VNN", "VUV", "WST", "XAF", "XAG", "XAU", "XBA", "XBB", "XBC", "XBD", "XCD", "XDR", "XEU", "XFO", "XFU", "XOF", "XPD", "XPF", "XPT", "XRE", "XSU", "XTS", "XUA", "XXX", "YDD", "YER", "YUD", "YUM", "YUN", "YUR", "ZAL", "ZAR", "ZMK", "ZMW", "ZRN", "ZRZ", "ZWD", "ZWL", "ZWR"},
monthsAbbreviated: []string{"", "inn", "bṛa", "maṛ", "ibr", "may", "yun", "yul", "ɣuc", "cut", "ktu", "nuw", "duj"},
monthsNarrow: []string{"", "i", "b", "m", "i", "m", "y", "y", "ɣ", "c", "k", "n", "d"},
monthsWide: []string{"", "innayr", "bṛayṛ", "maṛṣ", "ibrir", "mayyu", "yunyu", "yulyuz", "ɣuct", "cutanbir", "ktubr", "nuwanbir", "dujanbir"},
daysAbbreviated: []string{"asa", "ayn", "asi", "akṛ", "akw", "asim", "asiḍ"},
daysNarrow: []string{"S", "M", "T", "W", "T", "F", "S"},
daysWide: []string{"asamas", "aynas", "asinas", "akṛas", "akwas", "asimwas", "asiḍyas"},
periodsAbbreviated: []string{"tifawt", "tadggʷat"},
periodsNarrow: []string{"", ""},
periodsWide: []string{"tifawt", "tadggʷat"},
erasAbbreviated: []string{"daɛ", "dfɛ"},
erasNarrow: []string{"", ""},
erasWide: []string{"dat n ɛisa", "dffir n ɛisa"},
timezones: map[string]string{"WEZ": "WEZ", "MESZ": "MESZ", "HKT": "HKT", "LHST": "LHST", "CLT": "CLT", "AEDT": "AEDT", "MYT": "MYT", "SGT": "SGT", "COST": "COST", "SRT": "SRT", "CAT": "CAT", "CHAST": "CHAST", "CHADT": "CHADT", "WESZ": "WESZ", "NZDT": "NZDT", "MDT": "MDT", "HECU": "HECU", "AEST": "AEST", "BT": "BT", "AKST": "AKST", "IST": "IST", "VET": "VET", "HAST": "HAST", "PST": "PST", "EST": "EST", "ACST": "ACST", "HNOG": "HNOG", "WITA": "WITA", "UYST": "UYST", "PDT": "PDT", "HNEG": "HNEG", "HEEG": "HEEG", "WART": "WART", "OESZ": "OESZ", "ART": "ART", "AWDT": "AWDT", "NZST": "NZST", "TMST": "TMST", "JST": "JST", "AKDT": "AKDT", "ACWDT": "ACWDT", "HEPM": "HEPM", "ADT": "ADT", "ChST": "ChST", "ECT": "ECT", "CLST": "CLST", "HAT": "HAT", "HNPM": "HNPM", "HNPMX": "HNPMX", "HEPMX": "HEPMX", "JDT": "JDT", "HEOG": "HEOG", "HKST": "HKST", "LHDT": "LHDT", "HENOMX": "HENOMX", "WIT": "WIT", "WAT": "WAT", "WIB": "WIB", "WARST": "WARST", "SAST": "SAST", "∅∅∅": "∅∅∅", "GMT": "GMT", "CST": "CST", "CDT": "CDT", "ACDT": "ACDT", "HNT": "HNT", "HNNOMX": "HNNOMX", "HADT": "HADT", "COT": "COT", "HNCU": "HNCU", "EAT": "EAT", "ARST": "ARST", "GYT": "GYT", "AWST": "AWST", "WAST": "WAST", "GFT": "GFT", "EDT": "EDT", "ACWST": "ACWST", "TMT": "TMT", "MEZ": "MEZ", "OEZ": "OEZ", "UYT": "UYT", "AST": "AST", "BOT": "BOT", "MST": "MST"},
}
}
// Locale returns the current translators string locale
func (shi *shi_Latn) Locale() string {
return shi.locale
}
// PluralsCardinal returns the list of cardinal plural rules associated with 'shi_Latn'
func (shi *shi_Latn) PluralsCardinal() []locales.PluralRule {
return shi.pluralsCardinal
}
// PluralsOrdinal returns the list of ordinal plural rules associated with 'shi_Latn'
func (shi *shi_Latn) PluralsOrdinal() []locales.PluralRule {
return shi.pluralsOrdinal
}
// PluralsRange returns the list of range plural rules associated with 'shi_Latn'
func (shi *shi_Latn) PluralsRange() []locales.PluralRule {
return shi.pluralsRange
}
// CardinalPluralRule returns the cardinal PluralRule given 'num' and digits/precision of 'v' for 'shi_Latn'
func (shi *shi_Latn) CardinalPluralRule(num float64, v uint64) locales.PluralRule {
n := math.Abs(num)
i := int64(n)
if (i == 0) || (n == 1) {
return locales.PluralRuleOne
} else if n >= 2 && n <= 10 {
return locales.PluralRuleFew
}
return locales.PluralRuleOther
}
// OrdinalPluralRule returns the ordinal PluralRule given 'num' and digits/precision of 'v' for 'shi_Latn'
func (shi *shi_Latn) OrdinalPluralRule(num float64, v uint64) locales.PluralRule {
return locales.PluralRuleUnknown
}
// RangePluralRule returns the ordinal PluralRule given 'num1', 'num2' and digits/precision of 'v1' and 'v2' for 'shi_Latn'
func (shi *shi_Latn) RangePluralRule(num1 float64, v1 uint64, num2 float64, v2 uint64) locales.PluralRule {
return locales.PluralRuleUnknown
}
// MonthAbbreviated returns the locales abbreviated month given the 'month' provided
func (shi *shi_Latn) MonthAbbreviated(month time.Month) string {
return shi.monthsAbbreviated[month]
}
// MonthsAbbreviated returns the locales abbreviated months
func (shi *shi_Latn) MonthsAbbreviated() []string {
return shi.monthsAbbreviated[1:]
}
// MonthNarrow returns the locales narrow month given the 'month' provided
func (shi *shi_Latn) MonthNarrow(month time.Month) string {
return shi.monthsNarrow[month]
}
// MonthsNarrow returns the locales narrow months
func (shi *shi_Latn) MonthsNarrow() []string {
return shi.monthsNarrow[1:]
}
// MonthWide returns the locales wide month given the 'month' provided
func (shi *shi_Latn) MonthWide(month time.Month) string {
return shi.monthsWide[month]
}
// MonthsWide returns the locales wide months
func (shi *shi_Latn) MonthsWide() []string {
return shi.monthsWide[1:]
}
// WeekdayAbbreviated returns the locales abbreviated weekday given the 'weekday' provided
func (shi *shi_Latn) WeekdayAbbreviated(weekday time.Weekday) string {
return shi.daysAbbreviated[weekday]
}
// WeekdaysAbbreviated returns the locales abbreviated weekdays
func (shi *shi_Latn) WeekdaysAbbreviated() []string {
return shi.daysAbbreviated
}
// WeekdayNarrow returns the locales narrow weekday given the 'weekday' provided
func (shi *shi_Latn) WeekdayNarrow(weekday time.Weekday) string {
return shi.daysNarrow[weekday]
}
// WeekdaysNarrow returns the locales narrow weekdays
func (shi *shi_Latn) WeekdaysNarrow() []string {
return shi.daysNarrow
}
// WeekdayShort returns the locales short weekday given the 'weekday' provided
func (shi *shi_Latn) WeekdayShort(weekday time.Weekday) string {
return shi.daysShort[weekday]
}
// WeekdaysShort returns the locales short weekdays
func (shi *shi_Latn) WeekdaysShort() []string {
return shi.daysShort
}
// WeekdayWide returns the locales wide weekday given the 'weekday' provided
func (shi *shi_Latn) WeekdayWide(weekday time.Weekday) string {
return shi.daysWide[weekday]
}
// WeekdaysWide returns the locales wide weekdays
func (shi *shi_Latn) WeekdaysWide() []string {
return shi.daysWide
}
// Decimal returns the decimal point of number
func (shi *shi_Latn) Decimal() string {
return shi.decimal
}
// Group returns the group of number
func (shi *shi_Latn) Group() string {
return shi.group
}
// Group returns the minus sign of number
func (shi *shi_Latn) Minus() string {
return shi.minus
}
// FmtNumber returns 'num' with digits/precision of 'v' for 'shi_Latn' and handles both Whole and Real numbers based on 'v'
func (shi *shi_Latn) FmtNumber(num float64, v uint64) string {
return strconv.FormatFloat(math.Abs(num), 'f', int(v), 64)
}
// FmtPercent returns 'num' with digits/precision of 'v' for 'shi_Latn' and handles both Whole and Real numbers based on 'v'
// NOTE: 'num' passed into FmtPercent is assumed to be in percent already
func (shi *shi_Latn) FmtPercent(num float64, v uint64) string {
return strconv.FormatFloat(math.Abs(num), 'f', int(v), 64)
}
// FmtCurrency returns the currency representation of 'num' with digits/precision of 'v' for 'shi_Latn'
func (shi *shi_Latn) FmtCurrency(num float64, v uint64, currency currency.Type) string {
s := strconv.FormatFloat(math.Abs(num), 'f', int(v), 64)
symbol := shi.currencies[currency]
l := len(s) + len(symbol) + 2 + 2*len(s[:len(s)-int(v)-1])/3
count := 0
inWhole := v == 0
b := make([]byte, 0, l)
for i := len(s) - 1; i >= 0; i-- {
if s[i] == '.' {
b = append(b, shi.decimal[0])
inWhole = true
continue
}
if inWhole {
if count == 3 {
for j := len(shi.group) - 1; j >= 0; j-- {
b = append(b, shi.group[j])
}
count = 1
} else {
count++
}
}
b = append(b, s[i])
}
if num < 0 {
b = append(b, shi.minus[0])
}
// reverse
for i, j := 0, len(b)-1; i < j; i, j = i+1, j-1 {
b[i], b[j] = b[j], b[i]
}
if int(v) < 2 {
if v == 0 {
b = append(b, shi.decimal...)
}
for i := 0; i < 2-int(v); i++ {
b = append(b, '0')
}
}
b = append(b, symbol...)
return string(b)
}
// FmtAccounting returns the currency representation of 'num' with digits/precision of 'v' for 'shi_Latn'
// in accounting notation.
func (shi *shi_Latn) FmtAccounting(num float64, v uint64, currency currency.Type) string {
s := strconv.FormatFloat(math.Abs(num), 'f', int(v), 64)
symbol := shi.currencies[currency]
l := len(s) + len(symbol) + 2 + 2*len(s[:len(s)-int(v)-1])/3
count := 0
inWhole := v == 0
b := make([]byte, 0, l)
for i := len(s) - 1; i >= 0; i-- {
if s[i] == '.' {
b = append(b, shi.decimal[0])
inWhole = true
continue
}
if inWhole {
if count == 3 {
for j := len(shi.group) - 1; j >= 0; j-- {
b = append(b, shi.group[j])
}
count = 1
} else {
count++
}
}
b = append(b, s[i])
}
if num < 0 {
b = append(b, shi.minus[0])
}
// reverse
for i, j := 0, len(b)-1; i < j; i, j = i+1, j-1 {
b[i], b[j] = b[j], b[i]
}
if int(v) < 2 {
if v == 0 {
b = append(b, shi.decimal...)
}
for i := 0; i < 2-int(v); i++ {
b = append(b, '0')
}
}
if num < 0 {
b = append(b, symbol...)
} else {
b = append(b, symbol...)
}
return string(b)
}
// FmtDateShort returns the short date representation of 't' for 'shi_Latn'
func (shi *shi_Latn) FmtDateShort(t time.Time) string {
b := make([]byte, 0, 32)
b = strconv.AppendInt(b, int64(t.Day()), 10)
b = append(b, []byte{0x2f}...)
b = strconv.AppendInt(b, int64(t.Month()), 10)
b = append(b, []byte{0x2f}...)
if t.Year() > 0 {
b = strconv.AppendInt(b, int64(t.Year()), 10)
} else {
b = strconv.AppendInt(b, int64(-t.Year()), 10)
}
return string(b)
}
// FmtDateMedium returns the medium date representation of 't' for 'shi_Latn'
func (shi *shi_Latn) FmtDateMedium(t time.Time) string {
b := make([]byte, 0, 32)
b = strconv.AppendInt(b, int64(t.Day()), 10)
b = append(b, []byte{0x20}...)
b = append(b, shi.monthsAbbreviated[t.Month()]...)
b = append(b, []byte{0x2c, 0x20}...)
if t.Year() > 0 {
b = strconv.AppendInt(b, int64(t.Year()), 10)
} else {
b = strconv.AppendInt(b, int64(-t.Year()), 10)
}
return string(b)
}
// FmtDateLong returns the long date representation of 't' for 'shi_Latn'
func (shi *shi_Latn) FmtDateLong(t time.Time) string {
b := make([]byte, 0, 32)
b = strconv.AppendInt(b, int64(t.Day()), 10)
b = append(b, []byte{0x20}...)
b = append(b, shi.monthsWide[t.Month()]...)
b = append(b, []byte{0x20}...)
if t.Year() > 0 {
b = strconv.AppendInt(b, int64(t.Year()), 10)
} else {
b = strconv.AppendInt(b, int64(-t.Year()), 10)
}
return string(b)
}
// FmtDateFull returns the full date representation of 't' for 'shi_Latn'
func (shi *shi_Latn) FmtDateFull(t time.Time) string {
b := make([]byte, 0, 32)
b = append(b, shi.daysWide[t.Weekday()]...)
b = append(b, []byte{0x20}...)
b = strconv.AppendInt(b, int64(t.Day()), 10)
b = append(b, []byte{0x20}...)
b = append(b, shi.monthsWide[t.Month()]...)
b = append(b, []byte{0x20}...)
if t.Year() > 0 {
b = strconv.AppendInt(b, int64(t.Year()), 10)
} else {
b = strconv.AppendInt(b, int64(-t.Year()), 10)
}
return string(b)
}
// FmtTimeShort returns the short time representation of 't' for 'shi_Latn'
func (shi *shi_Latn) FmtTimeShort(t time.Time) string {
b := make([]byte, 0, 32)
if t.Hour() < 10 {
b = append(b, '0')
}
b = strconv.AppendInt(b, int64(t.Hour()), 10)
b = append(b, shi.timeSeparator...)
if t.Minute() < 10 {
b = append(b, '0')
}
b = strconv.AppendInt(b, int64(t.Minute()), 10)
return string(b)
}
// FmtTimeMedium returns the medium time representation of 't' for 'shi_Latn'
func (shi *shi_Latn) FmtTimeMedium(t time.Time) string {
b := make([]byte, 0, 32)
if t.Hour() < 10 {
b = append(b, '0')
}
b = strconv.AppendInt(b, int64(t.Hour()), 10)
b = append(b, shi.timeSeparator...)
if t.Minute() < 10 {
b = append(b, '0')
}
b = strconv.AppendInt(b, int64(t.Minute()), 10)
b = append(b, shi.timeSeparator...)
if t.Second() < 10 {
b = append(b, '0')
}
b = strconv.AppendInt(b, int64(t.Second()), 10)
return string(b)
}
// FmtTimeLong returns the long time representation of 't' for 'shi_Latn'
func (shi *shi_Latn) FmtTimeLong(t time.Time) string {
b := make([]byte, 0, 32)
if t.Hour() < 10 {
b = append(b, '0')
}
b = strconv.AppendInt(b, int64(t.Hour()), 10)
b = append(b, shi.timeSeparator...)
if t.Minute() < 10 {
b = append(b, '0')
}
b = strconv.AppendInt(b, int64(t.Minute()), 10)
b = append(b, shi.timeSeparator...)
if t.Second() < 10 {
b = append(b, '0')
}
b = strconv.AppendInt(b, int64(t.Second()), 10)
b = append(b, []byte{0x20}...)
tz, _ := t.Zone()
b = append(b, tz...)
return string(b)
}
// FmtTimeFull returns the full time representation of 't' for 'shi_Latn'
func (shi *shi_Latn) FmtTimeFull(t time.Time) string {
b := make([]byte, 0, 32)
if t.Hour() < 10 {
b = append(b, '0')
}
b = strconv.AppendInt(b, int64(t.Hour()), 10)
b = append(b, shi.timeSeparator...)
if t.Minute() < 10 {
b = append(b, '0')
}
b = strconv.AppendInt(b, int64(t.Minute()), 10)
b = append(b, shi.timeSeparator...)
if t.Second() < 10 {
b = append(b, '0')
}
b = strconv.AppendInt(b, int64(t.Second()), 10)
b = append(b, []byte{0x20}...)
tz, _ := t.Zone()
if btz, ok := shi.timezones[tz]; ok {
b = append(b, btz...)
} else {
b = append(b, tz...)
}
return string(b)
}
| {
"pile_set_name": "Github"
} |
.TH "SCRIPTS" "7" "March 2020" "" ""
.SH "NAME"
\fBscripts\fR \- How npm handles the "scripts" field
.SS Description
.P
The \fB"scripts"\fP property of of your \fBpackage\.json\fP file supports a number of built\-in scripts and their preset life cycle events as well as arbitrary scripts\. These all can be executed by running \fBnpm run\-script <stage>\fP or \fBnpm run <stage>\fP for short\. \fIPre\fR and \fIpost\fR commands with matching names will be run for those as well (e\.g\. \fBpremyscript\fP, \fBmyscript\fP, \fBpostmyscript\fP)\. Scripts from dependencies can be run with \fBnpm explore <pkg> \-\- npm run <stage>\fP\|\.
.SS Pre & Post Scripts
.P
To create "pre" or "post" scripts for any scripts defined in the \fB"scripts"\fP section of the \fBpackage\.json\fP, simply create another script \fIwith a matching name\fR and add "pre" or "post" to the beginning of them\.
.P
.RS 2
.nf
{
"scripts": {
"precompress": "{{ executes BEFORE the `compress` script }}",
"compress": "{{ run command to compress files }}",
"postcompress": "{{ executes AFTER `compress` script }}"
}
}
.fi
.RE
.SS Life Cycle Scripts
.P
There are some special life cycle scripts that happen only in certain situations\. These scripts happen in addtion to the "pre" and "post" script\.
.RS 0
.IP \(bu 2
\fBprepare\fP, \fBprepublish\fP, \fBprepublishOnly\fP, \fBprepack\fP, \fBpostpack\fP
.RE
.P
\fBprepare\fR (since \fBnpm@4\.0\.0\fP)
.RS 0
.IP \(bu 2
Runs BEFORE the package is packed
.IP \(bu 2
Runs BEFORE the package is published
.IP \(bu 2
Runs on local \fBnpm install\fP without any arguments
.IP \(bu 2
Run AFTER \fBprepublish\fP, but BEFORE \fBprepublishOnly\fP
.IP \(bu 2
NOTE: If a package being installed through git contains a \fBprepare\fP script, its \fBdependencies\fP and \fBdevDependencies\fP will be installed, and the prepare script will be run, before the package is packaged and installed\.
.RE
.P
\fBprepublish\fR (DEPRECATED)
.RS 0
.IP \(bu 2
Same as \fBprepare\fP
.RE
.P
\fBprepublishOnly\fR
.RS 0
.IP \(bu 2
Runs BEFORE the package is prepared and packed, ONLY on \fBnpm publish\fP\|\.
.RE
.P
\fBprepack\fR
.RS 0
.IP \(bu 2
Runs BEFORE a tarball is packed (on "\fBnpm pack\fP", "\fBnpm publish\fP", and when installing a git dependencies)\.
.IP \(bu 2
NOTE: "\fBnpm run pack\fP" is NOT the same as "\fBnpm pack\fP"\. "\fBnpm run pack\fP" is an arbitrary user defined script name, where as, "\fBnpm pack\fP" is a CLI defined command\.
.RE
.P
\fBpostpack\fR
.RS 0
.IP \(bu 2
Runs AFTER the tarball has been generated and moved to its final destination\.
.RE
.SS Prepare and Prepublish
.P
\fBDeprecation Note: prepublish\fR
.P
Since \fBnpm@1\.1\.71\fP, the npm CLI has run the \fBprepublish\fP script for both \fBnpm publish\fP and \fBnpm install\fP, because it's a convenient way to prepare a package for use (some common use cases are described in the section below)\. It has also turned out to be, in practice, very confusing \fIhttps://github\.com/npm/npm/issues/10074\fR\|\. As of \fBnpm@4\.0\.0\fP, a new event has been introduced, \fBprepare\fP, that preserves this existing behavior\. A \fInew\fR event, \fBprepublishOnly\fP has been added as a transitional strategy to allow users to avoid the confusing behavior of existing npm versions and only run on \fBnpm publish\fP (for instance, running the tests one last time to ensure they're in good shape)\.
.P
See https://github\.com/npm/npm/issues/10074 for a much lengthier justification, with further reading, for this change\.
.P
\fBUse Cases\fR
.P
If you need to perform operations on your package before it is used, in a way that is not dependent on the operating system or architecture of the target system, use a \fBprepublish\fP script\. This includes tasks such as:
.RS 0
.IP \(bu 2
Compiling CoffeeScript source code into JavaScript\.
.IP \(bu 2
Creating minified versions of JavaScript source code\.
.IP \(bu 2
Fetching remote resources that your package will use\.
.RE
.P
The advantage of doing these things at \fBprepublish\fP time is that they can be done once, in a single place, thus reducing complexity and variability\. Additionally, this means that:
.RS 0
.IP \(bu 2
You can depend on \fBcoffee\-script\fP as a \fBdevDependency\fP, and thus
your users don't need to have it installed\.
.IP \(bu 2
You don't need to include minifiers in your package, reducing
the size for your users\.
.IP \(bu 2
You don't need to rely on your users having \fBcurl\fP or \fBwget\fP or
other system tools on the target machines\.
.RE
.SS Life Cycle Operation Order
.SS npm help \fBpublish\fP
.RS 0
.IP \(bu 2
\fBprepublishOnly\fP
.IP \(bu 2
\fBprepare\fP
.IP \(bu 2
\fBprepublish\fP
.IP \(bu 2
\fBpublish\fP
.IP \(bu 2
\fBpostpublish\fP
.RE
.SS npm help \fBpack\fP
.RS 0
.IP \(bu 2
\fBprepack\fP
.IP \(bu 2
\fBpostpack\fP
.RE
.SS npm help \fBinstall\fP
.RS 0
.IP \(bu 2
\fBpreinstall\fP
.IP \(bu 2
\fBinstall\fP
.IP \(bu 2
\fBpostinstall\fP
.RE
.P
Also triggers
.RS 0
.IP \(bu 2
\fBprepublish\fP (when on local)
.IP \(bu 2
\fBprepare\fP (when on local)
.RE
.SS npm help \fBstart\fP
.P
\fBnpm run start\fP has an \fBnpm start\fP shorthand\.
.RS 0
.IP \(bu 2
\fBprestart\fP
.IP \(bu 2
\fBstart\fP
.IP \(bu 2
\fBpoststart\fP
.RE
.SS Default Values
.P
npm will default some script values based on package contents\.
.RS 0
.IP \(bu 2
\fB"start": "node server\.js"\fP:
If there is a \fBserver\.js\fP file in the root of your package, then npm
will default the \fBstart\fP command to \fBnode server\.js\fP\|\.
.IP \(bu 2
\fB"install": "node\-gyp rebuild"\fP:
If there is a \fBbinding\.gyp\fP file in the root of your package and you
haven't defined your own \fBinstall\fP or \fBpreinstall\fP scripts, npm will
default the \fBinstall\fP command to compile using node\-gyp\.
.RE
.SS User
.P
If npm was invoked with root privileges, then it will change the uid
to the user account or uid specified by the \fBuser\fP config, which
defaults to \fBnobody\fP\|\. Set the \fBunsafe\-perm\fP flag to run scripts with
root privileges\.
.SS Environment
.P
Package scripts run in an environment where many pieces of information
are made available regarding the setup of npm and the current state of
the process\.
.SS path
.P
If you depend on modules that define executable scripts, like test
suites, then those executables will be added to the \fBPATH\fP for
executing the scripts\. So, if your package\.json has this:
.P
.RS 2
.nf
{ "name" : "foo"
, "dependencies" : { "bar" : "0\.1\.x" }
, "scripts": { "start" : "bar \./test" } }
.fi
.RE
.P
then you could run \fBnpm start\fP to execute the \fBbar\fP script, which is
exported into the \fBnode_modules/\.bin\fP directory on \fBnpm install\fP\|\.
.SS package\.json vars
.P
The package\.json fields are tacked onto the \fBnpm_package_\fP prefix\. So,
for instance, if you had \fB{"name":"foo", "version":"1\.2\.5"}\fP in your
package\.json file, then your package scripts would have the
\fBnpm_package_name\fP environment variable set to "foo", and the
\fBnpm_package_version\fP set to "1\.2\.5"\. You can access these variables
in your code with \fBprocess\.env\.npm_package_name\fP and
\fBprocess\.env\.npm_package_version\fP, and so on for other fields\.
.SS configuration
.P
Configuration parameters are put in the environment with the
\fBnpm_config_\fP prefix\. For instance, you can view the effective \fBroot\fP
config by checking the \fBnpm_config_root\fP environment variable\.
.SS Special: package\.json "config" object
.P
The package\.json "config" keys are overwritten in the environment if
there is a config param of \fB<name>[@<version>]:<key>\fP\|\. For example,
if the package\.json has this:
.P
.RS 2
.nf
{ "name" : "foo"
, "config" : { "port" : "8080" }
, "scripts" : { "start" : "node server\.js" } }
.fi
.RE
.P
and the server\.js is this:
.P
.RS 2
.nf
http\.createServer(\.\.\.)\.listen(process\.env\.npm_package_config_port)
.fi
.RE
.P
then the user could change the behavior by doing:
.P
.RS 2
.nf
npm config set foo:port 80
.fi
.RE
.SS current lifecycle event
.P
Lastly, the \fBnpm_lifecycle_event\fP environment variable is set to
whichever stage of the cycle is being executed\. So, you could have a
single script used for different parts of the process which switches
based on what's currently happening\.
.P
Objects are flattened following this format, so if you had
\fB{"scripts":{"install":"foo\.js"}}\fP in your package\.json, then you'd
see this in the script:
.P
.RS 2
.nf
process\.env\.npm_package_scripts_install === "foo\.js"
.fi
.RE
.SS Examples
.P
For example, if your package\.json contains this:
.P
.RS 2
.nf
{ "scripts" :
{ "install" : "scripts/install\.js"
, "postinstall" : "scripts/postinstall\.js"
, "uninstall" : "scripts/uninstall\.js"
}
}
.fi
.RE
.P
then \fBscripts/install\.js\fP will be called for the install
and post\-install stages of the lifecycle, and \fBscripts/uninstall\.js\fP
will be called when the package is uninstalled\. Since
\fBscripts/install\.js\fP is running for two different phases, it would
be wise in this case to look at the \fBnpm_lifecycle_event\fP environment
variable\.
.P
If you want to run a make command, you can do so\. This works just
fine:
.P
.RS 2
.nf
{ "scripts" :
{ "preinstall" : "\./configure"
, "install" : "make && make install"
, "test" : "make test"
}
}
.fi
.RE
.SS Exiting
.P
Scripts are run by passing the line as a script argument to \fBsh\fP\|\.
.P
If the script exits with a code other than 0, then this will abort the
process\.
.P
Note that these script files don't have to be nodejs or even
javascript programs\. They just have to be some kind of executable
file\.
.SS Hook Scripts
.P
If you want to run a specific script at a specific lifecycle event for
ALL packages, then you can use a hook script\.
.P
Place an executable file at \fBnode_modules/\.hooks/{eventname}\fP, and
it'll get run for all packages when they are going through that point
in the package lifecycle for any packages installed in that root\.
.P
Hook scripts are run exactly the same way as package\.json scripts\.
That is, they are in a separate child process, with the env described
above\.
.SS Best Practices
.RS 0
.IP \(bu 2
Don't exit with a non\-zero error code unless you \fIreally\fR mean it\.
Except for uninstall scripts, this will cause the npm action to
fail, and potentially be rolled back\. If the failure is minor or
only will prevent some optional features, then it's better to just
print a warning and exit successfully\.
.IP \(bu 2
Try not to use scripts to do what npm can do for you\. Read through
npm help \fBpackage\.json\fP to see all the things that you can specify and enable
by simply describing your package appropriately\. In general, this
will lead to a more robust and consistent state\.
.IP \(bu 2
Inspect the env to determine where to put things\. For instance, if
the \fBnpm_config_binroot\fP environment variable is set to \fB/home/user/bin\fP, then
don't try to install executables into \fB/usr/local/bin\fP\|\. The user
probably set it up that way for a reason\.
.IP \(bu 2
Don't prefix your script commands with "sudo"\. If root permissions
are required for some reason, then it'll fail with that error, and
the user will sudo the npm command in question\.
.IP \(bu 2
Don't use \fBinstall\fP\|\. Use a \fB\|\.gyp\fP file for compilation, and \fBprepublish\fP
for anything else\. You should almost never have to explicitly set a
preinstall or install script\. If you are doing this, please consider if
there is another option\. The only valid use of \fBinstall\fP or \fBpreinstall\fP
scripts is for compilation which must be done on the target architecture\.
.RE
.SS See Also
.RS 0
.IP \(bu 2
npm help run\-script
.IP \(bu 2
npm help package\.json
.IP \(bu 2
npm help developers
.IP \(bu 2
npm help install
.RE
| {
"pile_set_name": "Github"
} |
package org.magnum.mobilecloud.video;
import java.util.UUID;
import org.magnum.mobilecloud.video.repository.Video;
import com.fasterxml.jackson.databind.ObjectMapper;
/**
* This is a utility class to aid in the construction of
* Video objects with random names, urls, and durations.
* The class also provides a facility to convert objects
* into JSON using Jackson, which is the format that the
* VideoSvc controller is going to expect data in for
* integration testing.
*
* @author jules
*
*/
public class TestData {
private static final ObjectMapper objectMapper = new ObjectMapper();
/**
* Construct and return a Video object with a
* rnadom name, url, and duration.
*
* @return
*/
public static Video randomVideo() {
// Information about the video
// Construct a random identifier using Java's UUID class
String id = UUID.randomUUID().toString();
String title = "Video-"+id;
String url = "http://coursera.org/some/video-"+id;
long duration = 60 * (int)Math.rint(Math.random() * 60) * 1000; // random time up to 1hr
return new Video(title, url, duration);
}
/**
* Convert an object to JSON using Jackson's ObjectMapper
*
* @param o
* @return
* @throws Exception
*/
public static String toJson(Object o) throws Exception{
return objectMapper.writeValueAsString(o);
}
}
| {
"pile_set_name": "Github"
} |
using System.IO;
namespace Ryujinx.HLE.HOS.Diagnostics.Demangler.Ast
{
public class ArraySubscriptingExpression : BaseNode
{
private BaseNode _leftNode;
private BaseNode _subscript;
public ArraySubscriptingExpression(BaseNode leftNode, BaseNode subscript) : base(NodeType.ArraySubscriptingExpression)
{
_leftNode = leftNode;
_subscript = subscript;
}
public override void PrintLeft(TextWriter writer)
{
writer.Write("(");
_leftNode.Print(writer);
writer.Write(")[");
_subscript.Print(writer);
writer.Write("]");
}
}
} | {
"pile_set_name": "Github"
} |
/*
* 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 java.io;
import java.security.BasicPermission;
import java.security.Permission;
/**
* Legacy security code; do not use.
*/
public final class SerializablePermission extends BasicPermission {
public SerializablePermission(String permissionName) { super(""); }
public SerializablePermission(String name, String actions) { super("", ""); }
@Override public String getActions() { return null; }
@Override public boolean implies(Permission permission) { return true; }
}
| {
"pile_set_name": "Github"
} |
// META: global=window,dedicatedworker,jsshell
// META: script=/wasm/jsapi/wasm-module-builder.js
// META: script=/wasm/jsapi/assertions.js
// META: script=/wasm/jsapi/instanceTestFactory.js
let emptyModuleBinary;
setup(() => {
emptyModuleBinary = new WasmModuleBuilder().toBuffer();
});
promise_test(t => {
return promise_rejects_js(t, TypeError, WebAssembly.instantiate());
}, "Missing arguments");
promise_test(() => {
const fn = WebAssembly.instantiate;
const thisValues = [
undefined,
null,
true,
"",
Symbol(),
1,
{},
WebAssembly,
];
return Promise.all(thisValues.map(thisValue => {
return fn.call(thisValue, emptyModuleBinary).then(assert_WebAssemblyInstantiatedSource);
}));
}, "Branding");
promise_test(t => {
const invalidArguments = [
undefined,
null,
true,
"",
Symbol(),
1,
{},
WebAssembly.Module,
WebAssembly.Module.prototype,
ArrayBuffer,
ArrayBuffer.prototype,
Array.from(emptyModuleBinary),
];
return Promise.all(invalidArguments.map(argument => {
return promise_rejects_js(t, TypeError, WebAssembly.instantiate(argument),
`instantiate(${format_value(argument)})`);
}));
}, "Invalid arguments");
test(() => {
const promise = WebAssembly.instantiate(emptyModuleBinary);
assert_equals(Object.getPrototypeOf(promise), Promise.prototype, "prototype");
assert_true(Object.isExtensible(promise), "extensibility");
}, "Promise type");
for (const [name, fn] of instanceTestFactory) {
promise_test(() => {
const { buffer, args, exports, verify } = fn();
return WebAssembly.instantiate(buffer, ...args).then(result => {
assert_WebAssemblyInstantiatedSource(result, exports);
verify(result.instance);
});
}, `${name}: BufferSource argument`);
promise_test(() => {
const { buffer, args, exports, verify } = fn();
const module = new WebAssembly.Module(buffer);
return WebAssembly.instantiate(module, ...args).then(instance => {
assert_Instance(instance, exports);
verify(instance);
});
}, `${name}: Module argument`);
}
promise_test(() => {
const builder = new WasmModuleBuilder();
builder.addImportedGlobal("module", "global", kWasmI32);
const buffer = builder.toBuffer();
const order = [];
const imports = {
get module() {
order.push("module getter");
return {
get global() {
order.push("global getter");
return 0;
},
}
},
};
const expected = [
"module getter",
"global getter",
];
const p = WebAssembly.instantiate(buffer, imports);
assert_array_equals(order, []);
return p.then(result => {
assert_WebAssemblyInstantiatedSource(result);
assert_array_equals(order, expected);
});
}, "Synchronous options handling: Buffer argument");
promise_test(() => {
const builder = new WasmModuleBuilder();
builder.addImportedGlobal("module", "global", kWasmI32);
const buffer = builder.toBuffer();
const module = new WebAssembly.Module(buffer);
const order = [];
const imports = {
get module() {
order.push("module getter");
return {
get global() {
order.push("global getter");
return 0;
},
}
},
};
const expected = [
"module getter",
"global getter",
];
const p = WebAssembly.instantiate(module, imports);
assert_array_equals(order, expected);
return p.then(instance => assert_Instance(instance, {}));
}, "Synchronous options handling: Module argument");
promise_test(t => {
const buffer = new Uint8Array();
return promise_rejects_js(t, WebAssembly.CompileError, WebAssembly.instantiate(buffer));
}, "Empty buffer");
promise_test(t => {
const buffer = new Uint8Array(Array.from(emptyModuleBinary).concat([0, 0]));
return promise_rejects_js(t, WebAssembly.CompileError, WebAssembly.instantiate(buffer));
}, "Invalid code");
promise_test(() => {
const buffer = new WasmModuleBuilder().toBuffer();
assert_equals(buffer[0], 0);
const promise = WebAssembly.instantiate(buffer);
buffer[0] = 1;
return promise.then(assert_WebAssemblyInstantiatedSource);
}, "Changing the buffer");
| {
"pile_set_name": "Github"
} |
<!DOCTYPE html>
<html lang="en">
<head>
<link rel='shortcut icon' href='../img/favicon.ico' type='image/x-icon'/ >
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Data Sketches</title>
<meta name="author" content="Nadieh Bremer">
<meta name="description" content="Data Sketches - December - Music">
<meta name="keywords" content="data, visualization, visualisation, data visualization, data visualisation, information, information visualization, information visualisation, dataviz, datavis, infoviz, infovis, collaboration, data art">
<!-- Google fonts -->
<link href="https://fonts.googleapis.com/css?family=Tinos:400,400i|Sacramento|Quicksand|Playfair+Display:400i" rel="stylesheet">
<!-- jQuery -->
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<!-- Moment -->
<script src="https://momentjs.com/downloads/moment.min.js"></script>
<script src="https://momentjs.com/downloads/moment-timezone-with-data.min.js"></script>
<!-- Bootstrap -->
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.2/css/bootstrap.min.css">
<!-- <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.2/js/bootstrap.min.js"></script> -->
<!-- fancyBox -->
<link rel="stylesheet" href="../plugins/fancybox/jquery.fancybox.css" type="text/css" media="screen" />
<script type="text/javascript" src="../plugins/fancybox/jquery.fancybox.pack.js"></script>
<!-- Stylesheet -->
<link rel="stylesheet" href="../css/style.css">
<!-- HTML5 shim and Respond.js for IE8 support of HTML5 elements and media queries -->
<!-- WARNING: Respond.js doesn't work if you view the page via file:// -->
<!--[if lt IE 9]>
<script src="https://oss.maxcdn.com/html5shiv/3.7.2/html5shiv.min.js"></script>
<script src="https://oss.maxcdn.com/respond/1.4.2/respond.min.js"></script>
<![endif]-->
</head>
<body>
<header>
<!-- Logo and name -->
<div>
<a class="hide-mobile peach kingBasil no-border" href="../november"><div class="top-links other-month-link textRight">go to November</div></a>
<div class="month-logo"><a class="no-border" href=".."><img class="paddingTop20" src="../img/logo.png" width="120" /></a></div>
<a class="hide-mobile peach kingBasil no-border" href="../january"><div class="top-links other-month-link textLeft">go to January</div></a>
</div>
<div>
<a class="quicksand no-border" href=".."><div class="top-links datasketch-top-link"><span class="dark-grey">data sketch<span class="dark-pink">|</span>es</span></div></a>
</div>
<!-- Title above -->
<div class="row">
<div class="col-xs-12 month-page-title">
<h2 class="kingBasil peach">December</h2>
<h1 class="quicksand">Music</h1>
</div>
</div>
</header>
<section id="december" class="month-page">
<div class="nadieh background col-xs-12 col-sm-12 col-md-6 col-lg-6"></div>
<div class="shirley background col-xs-12 col-sm-12 col-md-6 col-lg-6"></div>
<div class="container">
<!-- Write-ups -->
<div class="row">
<!-- Nadieh -->
<div class="col-xs-12 col-md-6 write-up">
<div class="nadieh">
<div class="name paddingBelow kingBasil">Nadieh</div>
<div class="time kingBasil"></div>
<div class="location quicksand">amsterdam</div>
<a href="code/nadieh/img/Top2000PosterEnglish.png"><img src="code/nadieh/img/top2000_header.jpg" class="img-responsive img-month-top" alt="Top 2000 loves the 70's & 80's"></a>
<h3 class="margin-top-10">week 1 <span class="light-grey">|</span> data</h3>
<p>When you're saying "music in December" to somebody from the Netherlands, there's a very likely chance that they'll think of the <a href="http://www.nporadio2.nl/top2000" target="_new">Top 2000</a>. A yearly chosen list of songs that is played between Christmas and midnight December 31st. I've actually played with this data before. It was perhaps <a href="http://nbremer.github.io/top2000/" target="_new">my 2nd serious personal project</a> and I was still very new to d3. Since I sometimes see artists revisiting artwork they've done in the past to see how their style evolved (which I always love to see), I thought it would be fitting to try and to the same myself (in the sketch section you'll see I've had this idea for a few months already). So, 2 years since my previous attempt, I'm going to look at the Top 2000 again and visualize the insights.</p>
<p>Not to worry if you're not Dutch, the Top 2000 is probably 90% English songs, with Queen often on 1st place, and many Beatles, U2 and Michael Jackson songs, so the list should seem familiar to most of you.</p>
<p><a href="http://www.nporadio2.nl/top2000" target="_new">The Top 2000 website</a> thankfully shares an Excel file of the 2000 songs containing the name, artist and year of release. This year it was released on December 19th. However, I needed another important variable; the highest rank ever reached in the normal weekly charts. There are a few of these in the Netherlands, but I chose to go with the Top 40, since this has been going non-stop since 1965. But also because <a href="https://www.top40.nl/" target="_new">the Top 40 website</a> seemed scrape-able. So I wrote a small scraper that would go through 50 years of charts lists and save the artist's name, song title, URL to the song's page and position. This data was then aggregated to make it unique per song (the URL of the song was the unique key) and save some extra info, such as the highest position ever reached and number of weeks in the Top 40.</p>
<p>Next came the tricky bit, matching those artists and songs to those in the Top 2000 list. Of course I first tried a merge on an exact match of artist and title. That connected about 60% of the songs. Browsing through the remaining songs I saw that sometimes one of the two lists was using more words than the other, such as <i>John Lennon-Plastic Ono Band</i> versus just <i>John Lennon</i>. So I also searched for partial matches between the lists, as long as all the words of one song and artist were contained in the other list. That helped match 10% more.</p>
<p>Then came the fuzzy part. Sometimes words are written slightly different, such as <i>Don't stop 'til you get enough</i> versus <i>Don't stop 'till you get enough</i>. Using R's <a href="https://cran.r-project.org/web/packages/stringdist/index.html" target="_new">stringdist</a> package, I applied the "Full Damerau-Levenshtein" distance to compare titles and artists (it counts the number of deletions, insertions, substitutions, and transposition of adjacent characters necessary to turn b into a). However, I was quite strict and said that only 2 changes are allowed on both the title and artist to create a match (otherwise the song <i>Bad</i> from <i>U2</i> could be turned into any other 3-letter song and 2-3 letter artist). Sadly, that only gave me 2.5% more matches. As a side note, I did have to quickly check all the matched songs after each step to take out a few wrong matches.</p>
<p>Almost 600 songs were still not matched. However, that's is not necessarily a bad thing, since not all songs made the Top 40. Number 3, <i>Led Zeppelin</i> with <i>Stairway to Heaven</i> for example, since he never released singles, only albums. But how to know which "unmatched" songs were meant to be unmatched, and which songs had actually appeared in the Top 40, but had failed to match? One final idea I applied had to do with the <a href="https://www.top40.nl/tipparade/2016/week-50" target="_new">Tips of the week</a>. Since ±1970 the music station airing the Top 40 also keeps a list of 20/30 tips; songs that aren't in the Top 40, but that the DJ's think will or should be. I therefore scraped that list as well for all available years and performed exactly the same steps as with the Top 40 list. This gave me 8% more matched songs for which I new for certain that they were never in the Top 40 (but they were tipped for it once).</p>
<p>For the remaining ±430 songs I just manually went through the list to look at artists or song titles that have long or odd names for which I thought the matching probably didn't work and therefore could be a Top 40 song, such as <i>Andrea Bocelli & Sarah Brightman</i> in the Top 2000 list versus <i>Sarah Brightman & Andrea Bocelli</i> in the Top 40. I still can't say for the remaining 380 songs how many of those did actually appear in the Top 40, but to be honest, after all the data processing and things I've learned and checked about the data along the way, I think it's less than 10%.</p>
<h3>week 2 <span class="light-grey">|</span> sketches</h3>
<p>This spring I was in <a href="https://twitter.com/juanvelasco" target="_new">Juan Velasco's</a> excellent workshop <a href="http://graphichunters.nl/information-graphics-for-print-and-online/", target="_new">Information Graphics for Print and Online</a>. Part of the workshop was to work out an infographic. And although my small team of 3 had written down about 40 possible ideas we were all intrigued by the Top 2000 songs. From experience with my previous attempt of visualizing this data I already knew that there was a very interesting shift happening in the most loved decade (of release) over the past years. Therefore, we choose to make that the general concept around which to base the different parts of the infographic.</p>
<p>The most recent list of 2000 songs would take center stage, visualized with a <i>beeswarm</i> plot idea which would group them around their year of release. Each circle (i.e. a song) would be sized according to their highest position in the Top 40 and colored according to their rank in the Top 2000. Some of these songs would then be highlighted with annotations, such as highest newcomer.</p>
<a class="fancybox" href="sketches/nadieh/Top_2000_Poster_idea.jpg"> <img src="sketches/nadieh/Top_2000_Poster_idea_small.jpg" class="img-responsive img-month" alt="The general idea for the Top 2000 poster"></a>
<p>Finally, in the bottom section there would be a few mini charts that would highlight the distribution of the chosen songs on year of release between the 1999, 2008 & 2016 editions of the Top 2000. This would highlight the fact that in 1999 the bulk of the songs were released in the 70's, but that this has slowly been moving to newer decades.</p>
<p>On the 2nd day of the workshop we also made a mobile version of this concept. This time resulting in a long scrollable Beeswarm plot where you could theoretically listen to bits of each song and see extra information.</p>
<a class="fancybox" href="sketches/nadieh/Top_2000_Mobile_idea.jpg"> <img src="sketches/nadieh/Top_2000_Mobile_idea_small.jpg" class="img-responsive img-month" alt="The general idea for the Top 2000 mobile version"></a>
<p>Although I won't have time to build the mobile version I still wanted to show our concept ^_^</p>
<h3>week 3 & 4 <span class="light-grey">|</span> code</h3>
<p>So! This month I'm finally going to focus on making a static poster. Nevertheless, I'm still going to use d3 to build the center piece (the beeswarm). Afterwards I'll pull it into Illustrator. The smaller histograms at the bottom I'll take straight from R into Illustrator, so a whole combination of tools :)</p>
<p>Especially with d3v4 it's become much easier to create <i>beeswarm</i> like plots, since we can now define forces that run across an <i>x</i> and/or <i>y</i> axis. In this case I needed a force along the horizontal axis that would cluster the songs based on their year of release. It still took me several iterations to figure out the right balance of forces in the <i>x</i> and <i>y</i> direction (plus an offset by the collision detection preventing circle overlap) so it filled the region nicely around the year axis, without the songs being moved away too far from their actual release year.</p>
<p>In my first attempts I had sized the circles according to their highest position reached in the Top 40 and colored them according to their position in the Top 2000. However, that created a lot of light grey circles of about the same size (see the image below). It just didn't look appealing.</p>
<a class="fancybox" href="code/nadieh/img/beeswarm_initial_scales.png"> <img src="code/nadieh/img/beeswarm_initial_scales_small.jpg" class="img-responsive img-month" alt="Using Top 40 for size and Top 2000 for color didn't create an appealing image"></a>
<p>So I switched those two scales (thus size was determined by the Top 2000 position and color was the Top 40 position) and that immediately gave a great improvement. I then started to mark out the circles (songs) that I wanted to annotate later. I wanted to keep the visual very black and white, inspired by the intense blackness of vinyl records, and only use red to mark songs that had something interesting about them and blue for the artist / band with most songs in the list. However, with David Bowie and Prince passing away this year I just had to make a note of that as well, so I added yellow and purple.</p>
<p>Since the top 10 songs from the list were the biggest circles, I thought it would look nice to mark these as small vinyl records (which is nothing more than a very small white circle on top of a small red circle).</p>
<a class="fancybox" href="code/nadieh/img/vinyl_records.png"> <img src="code/nadieh/img/vinyl_records.png" class="img-responsive img-month" alt="Tiny vinyl records for the Top 10 songs"></a>
<p>Also, a small simple tip: you cannot do an <i>outside</i> stroke on SVGs. Thus when you stroke an element, the width of that stroke is centered on the outline of the element. However, in this case I wanted the grey circles to be visible for their entire radius, not having some part taken away by the stroke (which was very apparent in the small circles). So instead I plotted colored circles behind the grey circles that would be a few pixels bigger and thus mimicking a colored <i>outside</i> stroke. In the animated gif below the version with the "bigger" looking circles is using the background circles so that the grey circles keep their true radius)</p>
<a class="fancybox" href="code/nadieh/img/circle_stroke_animated.gif"> <img src="code/nadieh/img/circle_stroke_animated_small.gif" class="img-responsive img-month" alt="Comparing the impact of strokes on background circles"></a>
<p>With those relatively simple elements done and being sure I wouldn't change anything anymore, I used <a href="http://nytimes.github.io/svg-crowbar/" target="_new">SVG Crowbar</a> to save the beeswarm SVG and opened it up in Adobe Illustrator. There I turned it 25 degrees, just for a bit more interesting effect, and started placing annotations around it (based on an underlying grid to keep things nicely aligned in columns and rows). I used the data and the Top 2000 website to figure out some interesting facts, like Justin Timberlake having the highest ranking song from 2016.</p>
<a class="fancybox" href="code/nadieh/img/underlying_grid.png"> <img src="code/nadieh/img/underlying_grid_small.jpg" class="img-responsive img-month" alt="The underlying grid that I used in Illustrator"></a>
<p>After finishing the beeswarm / top part of the infographic I thought that maybe it would be nice to have <a href="code/nadieh" target="_new">a small interactive version</a> as well, so you could hover over all the circles and see which song it was. So I put in 2-3 hours to getting the beeswarm in a decent state, with a tooltip and legend.</p>
<a class="fancybox" href="code/nadieh/img/top2000_tooltip.gif"> <img src="code/nadieh/img/top2000_tooltip_small.gif" class="img-responsive img-month" alt="In the interactive version you can see the info of all songs"></a>
<p>I also wanted to touch on the fact that the distribution of the songs across release year has been changing towards the 90's & 00's. Since this was an added detail, a deeper insight into the data, I placed it below the main graphic. But it wasn't quite clear what visual form would convey the idea best. I already had the historic Top 2000 data from my previous visual on the topic from 2 years ago, so I appended the 2015 & 2016 data and started making some plots. That it should convey a histogram like approach was clear to me from the start, but should I smooth it down? How many years to show? Overlapping or in a small multiple fashion?</p>
<a class="fancybox" href="code/nadieh/img/Top2000_all_editions_histogram.png"> <img src="code/nadieh/img/Top2000_all_editions_histogram_small.jpg" class="img-responsive img-month" alt="Comparing the trend across all 18 editions of the Top 2000"></a>
<p>In the end I choose to go with a simple small multiple histogram of 4 editions across the past 18 years, but overplotted a smoothed density curve to make the general shape more easily comparable between the 4 charts. Below you can see what I took straight from R, created with the <a href="https://cran.r-project.org/web/packages/ggplot2/index.html" target="_new">ggplot2</a> package (where I played with the color to also encode the height. Although eventually I made them all the same grey, since I didn't want the histograms to draw too much attention).</p>
<a class="fancybox" href="code/nadieh/img/histograms_from_R.png"> <img src="code/nadieh/img/histograms_from_R_small.jpg" class="img-responsive img-month" alt="The chart straight from R"></a>
<p>The <a href="code/nadieh/img/Top2000PosterEnglish.png" target="_new">final infographic</a> can be found below, and the interactive version is <a href="code/nadieh" target="_new">here</a>. Besides an English version I also made a <a href="code/nadieh/img/Top2000PosterDutch.png" target="_new">Dutch</a> one, since the data is so related to Dutch pop culture.</p>
<a href="code/nadieh/img/Top2000PosterEnglish.png" target="_new"> <img src="code/nadieh/img/Top2000PosterEnglish.png" class="img-responsive img-month" alt="The final infographic about how the Top 2000 lives the 70s and 80s"></a>
<p>Another reason why I decided to create an infographic is because I just didn't have that much time this month; I only finished the November visual for data sketches on December 7th, I had a small vacation to London planned (where I met Shirley again after 8 months YAY!) and we have the holidays at the end of December of course. And making a static visualization is always much much faster for me, even if it is partly based on something that I started in d3.</p>
<p>I think preparing and doing the data scraping & cleaning took about 20 hours, the ideation & sketching about 3 and the coding/creating about 20 - 30 hours (I keep telling myself to actually start keeping track, haha). After doing these static things I always remember how much I like making "printable" things :)</p>
</div>
</div>
<!-- Shirley -->
<div class="col-xs-12 col-md-6 write-up">
<div class="shirley">
<div class="name paddingBelow kingBasil">Shirley</div>
<div class="time kingBasil"></div>
<div class="location quicksand">san francisco</div>
<a href="http://sxywu.com/ddr" target='_new'><img src="code/shirley/header.jpg" class="img-responsive img-month-top" alt=""></a>
<h3 class="margin-top-10">week 1 <span class="light-grey">|</span> data</h3>
<p>
When we first agreed on Music for December, I felt quite lost; I didn't know what I wanted to do, other than perhaps something about K-pop. It wasn't until I was lamenting this lack of angle with <a href='https://twitter.com/kennethormandy' target='_new'>Kenneth Ormandy</a> that something he said stuck and I suddenly remembered DDR.
</p>
<p>
DDR was a huge part of my teenage life. I first saw it in 2001, at a friend of a friend's house. Since there were no arcades with DDR anywhere near where I grew up, I begged my parents to buy me a set. Easier said then done; there were absolutely no video games in our house at the time, so a DDR set meant not only the game itself, but the PS2 and the mat that came along with it. It took me two years to convince my parents, and the summer I got it, I was on it every day for hours. I was the type of kid that played the same song on the same difficulty over and over until I mastered it (with mastery defined as being able to clear the song at least twice in a row). I played it regularly until I left for college 5 years later.
</p>
<p>
(I should say though that I was never <em>that great</em>, and the highest I was ever able to clear was an 8/10 difficulty, and I most comfortably played songs that were 6 or 7/10.)
</p>
<p>
When I first went out looking, I was excited for the data out there; with hundreds of songs (thousands?), each with at least three difficulty levels and BPMs and maybe even the values in the Groove Radar (Stream, Voltage, Air, Freeze, and Chaos), that's potentially a lot of data. (By the way, never knew that pentagon was called a Groove Radar, I just learned it - thanks Google.) Never in my wildest dreams though, did I imagine <em>all the steps from 645 songs</em> just there, available. But then I came across the amazingness of <a href='http://www.ddrfreak.com/' target='_new'>DDR Freak</a> and their <a href='http://www.ddrfreak.com/stepcharts/stepcharts.php' target='_new'>step charts</a>:
<a class="fancybox" href="data/shirley/midnight.png"> <img src="data/shirley/midnight.png" class="img-responsive img-month"></a>
And I started talking to my Computer Vision friend about how I (he) would go about getting the data out of that image. But Kenneth suggested I just email DDR Freak and ask if they had the raw data. And I was skeptical (the site had been largely inactive for at least the last five years) but I found an email (Jason Ko, founder of DDR Freak) and was like, hey why not? Never expecting a response.
</p>
<p>
And then Jason responds 18 (read: 18!!) minutes later with a zip of all the songs he had on hand. <em>How awesome is he??</em>
</p>
<p>
His zip had several different data formats, including .dwi (Dance with Intensity) and .stp (their own proprietary format). The .dwi files looked like this:
<a class="fancybox" href="data/shirley/midnite_dwi.png"> <img src="data/shirley/midnite_dwi.png" class="img-responsive img-month"></a>
The file format is <a href='http://dwi.ddruk.com/readme.php#4' target='_new'>explained here</a>, but at the very basic: 0 indicates no arrow, 2 is Down, 4 Left, 6 Right, and 8 Up. Each character defaults to 1/8 of a beat, but <code>(...)</code> indicates a 1/16 step, <code>[...]</code> a 1/24 step, and so on.
</p>
<p>
With that information, I was able to quickly reverse-engineer the .stp files (which I found to be a bit more reader-friendly, and ended up using):
<a class="fancybox" href="data/shirley/midnite_stp.png"> <img src="data/shirley/midnite_stp.png" class="img-responsive img-month"></a>
The only difference I found here is that instead of <code>(...)</code>, <code>{...}</code> indicates 1/16, <code>{{...}}</code> indicates 1/24 (though I think in my code I assumed 1/32...), and so on.
</p>
<p>
Here is my (super straightforward) <a href='https://github.com/sxywu/ddr/blob/master/data/parse.js' target='_new'>parsing code</a>, and the resulting <a href='https://raw.githubusercontent.com/sxywu/ddr/master/data/songs.json' target='_new'>JSON file</a> if you ever want to play with the data 😁✌️
</p>
<h3>week 2 <span class="light-grey">|</span> sketches</h3>
<p>
Because I was traveling for majority of December, I wanted to do something relatively simple. I had seen <a href='https://www.team-lab.net/' target='_new'>teamLAB</a>'s <a href='https://www.team-lab.net/w/crystaluniverse/' target='_new'>Crystal Universe</a> a few weeks earlier, and was incredibly inspired by its beauty:
<a class="fancybox" href="sketches/shirley/crystal_universe.png"> <img src="sketches/shirley/crystal_universe.png" class="img-responsive img-month"></a>
I wanted to do something similar for my December, where each step was a light, and I could animate it light up based on its position in the song. It started out promisingly, where I mapped the steps for each song's 2 modes (Single and Double) and 3 difficulty levels (Basic, Trick, Maniac) over time:
<a class="fancybox" href="sketches/shirley/attempt1.png"> <img src="sketches/shirley/attempt1.png" class="img-responsive img-month"></a>
To distinguish different modes/difficulties from the next row of music, I went back to the music sheet/staff idea from November (you might have to click and expand the image to see the lines since they're so faint):
<a class="fancybox" href="sketches/shirley/attempt2.jpg"> <img src="sketches/shirley/attempt2.jpg" class="img-responsive img-month"></a>
But then I got really stuck. Yes, with the staff lines I can now distinguish rows of modes/difficulties from the next row of steps over time. But it didn't seem to do me much good, and the steps were so spread apart that I couldn't seem to see the whole song on one screen and see if there were any interesting patterns. I also couldn't figure out how the rest of the interface would fit in, where people would browse and select songs to bring up this song view.
</p>
<h3>week 3 & 4 <span class="light-grey">|</span> code</h3>
<p>
While still stuck, I went to sleep with only two goals for an interface in mind: I wanted each song to be compact, and I wanted the visual analogy for a song to be continuous. I woke up the next day with spirals on my mind, and I was convinced that it was the answer to my problems; spirals like circles were very compact, and a spiral was basically one long continuous line that I could map my steps to.
</p>
<p>
I giddily set about looking into the math behind spirals, and was super happy to find that for an Archimedean spiral (a spiral where the distance between each spiral branch is the same) the radius was simply the angle:
<a class="fancybox" href="code/shirley/spiral_math.png"> <img src="code/shirley/spiral_math.png" class="img-responsive img-month"></a>
Until I realized that...if I used that formula, I would end up with something like this:
<a class="fancybox" href="code/shirley/not_equidistant.jpg"> <img src="code/shirley/not_equidistant.jpg" class="img-responsive img-month"></a>
When instead I wanted the points (the beats) to be equidistant along the length of the spiral, and realized that the problem wasn't as simple as I thought:
<a class="fancybox" href="code/shirley/math.png"> <img src="code/shirley/math.png" class="img-responsive img-month"></a>
(<em><a href='http://math.stackexchange.com/questions/1371668/equation-to-place-points-equidistantly-on-an-archimedian-spiral-using-arc-length' target='_new'>StackExchange: Equation to place points equidistantly on an Archimedian Spiral using arc-length</a></em>)
</p>
<p>
And bashed my head because it's been about a decade since I last touched an integral. I spent an hour scribbling in my notebook trying to figure out all the steps in between the equations, so that I could understand how the final equation was derived. No luck.
</p>
<p>
Then two miraculous things happened:
<ol>
<li>I posted <a href='https://twitter.com/datasketches/status/822244700925018113' target='_new'>my plight</a> on Twitter, and <a href='https://twitter.com/aknauft' target='_new'>Andrew Knauft</a> <a href='https://twitter.com/aknauft/status/822408607828348928' target='_new'>came back</a> with his own <a href='https://www.desmos.com/calculator/xjmovaguu5' target='_new'>step-by-step derivation</a></li>.
<li>I was <a href='https://twitter.com/visualisingdata/status/819637580086046724' target='_new'>waiting at a bar</a> at the time, and someone had sat down in the empty seat across from me. I took the chance to ask how his math was (<a href='https://www.issackelly.com/blog/2017/01/20/mark-equidistant-points-on-a-spiral' target='_new'>here's the full story</a>), and after a few emails, he (<a href='https://twitter.com/issackelly' target='_new'>Issac Kelly</a>) had <a href='http://jsfiddle.net/issackelly/r679xfrk/12/' target='_new'>brute-forced</a> the <a href='http://jsfiddle.net/issackelly/qptnsL46/2/' target='_new'>answer</a>.</li>
</ol>
Because I was already far far behind on my month and completely out of time, I took Issac's brute-force approach and adopted it for the DDR steps:
<a class="fancybox" href="code/shirley/spiral1.png"> <img src="code/shirley/spiral1.png" class="img-responsive img-month"></a>
(<em><a href='https://github.com/sxywu/ddr/blob/master/src/Visualization.js#L60-L103' target='_new'>Adapted spiral code</a></em>)
</p>
<p>
I then added legends for each song that also doubled as the filter (I originally had the legends up top that acted as a filter for ALL the songs, but found it completely unperformant, so switched to filters for EACH song):
<a class="fancybox" href="code/shirley/ddr_filter.gif"> <img src="code/shirley/ddr_filter.gif" class="img-responsive img-month"></a>
Here is the final:
<a href="http://sxywu.com/ddr" target='_new'> <img src="code/shirley/final.png" class="img-responsive img-month"></a>
Overall, I'm happy with where I ended up given where I started. With the spiral, I can now compare multiple songs, so both the big spirals (long songs) and teeny spirals stand out. I can also see from a glance that some songs I used to love indeed had a lot of steps close together throughout the whole song with few breaks, so no wonder I was out of breadth all the time. Having said that, I'm not 100% satisfied; for the sake of compactness, I sacrificed being able to see at a glance patterns <em>within</em> a song. One of the funnest things about DDR is that a song will have many sets of steps that repeat throughout; with this viz, it's hard to find those. I'm not sure if, given enough time, I would have been able to find a visualization that could show both trends between songs, as well as patterns within songs.
</p>
<p>
Either way, my favorite part about this month isn't at all the process or what I ended up with, but rather the kindness of (almost) perfect strangers willing to give a helping hand proving that (some) people are <em>awesome</em> ✌️
</p>
</div>
</div>
</div>
<!-- Our names and website below -->
<div class="row">
<div class="nadieh col-xs-6">
<div class="name kingBasil">Nadieh</div>
<div class="quicksand"><a href="http://www.visualcinnamon.com/">VisualCinnamon.com</a></div>
</div>
<div class="shirley col-xs-6">
<div class="name kingBasil">Shirley</div>
<div class="quicksand"><a href="http://sxywu.com/">sxywu.com</a></div>
</div>
</div>
</div>
</section>
<footer>
<div class="container">
<div>
<span>a monthly collaboration between </span>
<span class="kingBasil">Nadieh Bremer & Shirley Wu</span>
</div>
<div class="quicksand">
<a href="https://twitter.com/datasketches">@datasketches</a><span class="pipe-divider"> | </span>#datasketches
</div>
<div class="about-link quicksand">
<a href="../about">about</a><span class="pipe-divider"> | </span><a href="../feed.xml">rss</a><span class="pipe-divider"> | </span><a href="https://tinyletter.com/datasketches">newsletter</a>
</div>
</div>
</footer>
<script>
function setTime() {
var format = 'h:mm a';
var time = new Date();
var nadieh = moment(time, format).tz("Europe/Amsterdam");
var shirley = moment(time, format).tz("America/Los_Angeles");
$('.nadieh .time').text(nadieh.format(format));
$('.shirley .time').text(shirley.format(format));
var nadiehColor = nadieh.hour();
nadiehColor = nadiehColor >= 18 || nadiehColor <= 6 ? 'dark' : 'light';
var shirleyColor = shirley.hour();
shirleyColor = shirleyColor >= 18 || shirleyColor <= 6 ? 'dark' : 'light';
$('.nadieh').removeClass('light dark').addClass(nadiehColor);
$('.shirley').removeClass('light dark').addClass(shirleyColor);
}
$( document ).ready( function() {
setTime();
setInterval(setTime, 60000);
$(".fancybox").fancybox({
openEffect : 'fade',
closeEffect : 'fade',
padding: 0,
helpers: {
overlay: {
locked: false
}
}
});
});
</script>
<!-- Google analytics -->
<script>
(function(i,s,o,g,r,a,m){i['GoogleAnalyticsObject']=r;i[r]=i[r]||function(){
(i[r].q=i[r].q||[]).push(arguments)},i[r].l=1*new Date();a=s.createElement(o),
m=s.getElementsByTagName(o)[0];a.async=1;a.src=g;m.parentNode.insertBefore(a,m)
})(window,document,'script','https://www.google-analytics.com/analytics.js','ga');
ga('create', 'UA-43942889-3', 'auto');
ga('set', 'anonymizeIp', true);
ga('send', 'pageview');
</script>
</body>
</html>
| {
"pile_set_name": "Github"
} |
<?php
require dirname(__FILE__) . '/../vendor/autoload.php';
$secretId = "COS_SECRETID"; //"云 API 密钥 SecretId";
$secretKey = "COS_SECRETKEY"; //"云 API 密钥 SecretKey";
$region = "ap-beijing"; //设置一个默认的存储桶地域
$cosClient = new Qcloud\Cos\Client(
array(
'region' => $region,
'schema' => 'https', //协议头部,默认为http
'credentials'=> array(
'secretId' => $secretId ,
'secretKey' => $secretKey)));
try {
$result = $cosClient->deleteBucketLifecycle(array(
'Bucket' => 'examplebucket-125000000' //格式:BucketName-APPID
));
// 请求成功
print_r($result);
} catch (\Exception $e) {
// 请求失败
echo($e);
}
| {
"pile_set_name": "Github"
} |
#include <fc/fc.hpp>
namespace higan::Famicom {
FDS fds;
#include "drive.cpp"
#include "timer.cpp"
#include "audio.cpp"
#include "serialization.cpp"
auto FDS::load(Node::Object parent) -> void {
port = parent->append<Node::Port>("Disk Slot");
port->setFamily("Famicom Disk");
port->setType("Floppy Disk");
port->setHotSwappable(true);
port->setAllocate([&](auto name) { return allocate(port); });
port->setConnect([&] { return connect(); });
port->setDisconnect([&] { return disconnect(); });
audio.load(parent);
power();
}
auto FDS::unload() -> void {
audio.unload();
disconnect();
port = {};
disk1.sideA.reset();
disk1.sideB.reset();
disk2.sideA.reset();
disk2.sideB.reset();
inserted.reset();
inserting.reset();
changed = 0;
}
auto FDS::allocate(Node::Port parent) -> Node::Peripheral {
return node = parent->append<Node::Peripheral>("Famicom Disk");
}
auto FDS::connect() -> void {
node->setManifest([&] { return information.manifest; });
state = node->append<Node::String>("State", "Ejected", [&](auto value) {
change(value);
});
vector<string> states = {"Ejected"};
information = {};
if(auto fp = platform->open(node, "manifest.bml", File::Read, File::Required)) {
information.manifest = fp->reads();
}
auto document = BML::unserialize(information.manifest);
information.name = document["game/label"].text();
if(auto fp = platform->open(node, "disk1.sideA", File::Read, File::Required)) {
disk1.sideA.allocate(fp->size());
disk1.sideA.load(fp);
states.append("Disk 1: Side A");
}
if(auto fp = platform->open(node, "disk1.sideB", File::Read)) {
disk1.sideB.allocate(fp->size());
disk1.sideB.load(fp);
states.append("Disk 1: Side B");
}
if(auto fp = platform->open(node, "disk2.sideA", File::Read)) {
disk2.sideA.allocate(fp->size());
disk2.sideA.load(fp);
states.append("Disk 2: Side A");
}
if(auto fp = platform->open(node, "disk2.sideB", File::Read)) {
disk2.sideB.allocate(fp->size());
disk2.sideB.load(fp);
states.append("Disk 2: Side B");
}
state->setAllowedValues(states);
state->setDynamic(true);
change(state->value());
}
auto FDS::disconnect() -> void {
if(!node) return;
if(disk1.sideA)
if(auto fp = platform->open(node, "disk1.sideA", File::Write)) {
disk1.sideA.save(fp);
}
if(disk1.sideB)
if(auto fp = platform->open(node, "disk1.sideB", File::Write)) {
disk1.sideB.save(fp);
}
if(disk2.sideA)
if(auto fp = platform->open(node, "disk2.sideA", File::Write)) {
disk2.sideA.save(fp);
}
if(disk2.sideB)
if(auto fp = platform->open(node, "disk2.sideB", File::Write)) {
disk2.sideB.save(fp);
}
node = {};
}
auto FDS::change(string value) -> void {
//this setting can be changed even when the system is not powered on
if(state) state->setLatch();
inserting.reset();
if(value == "Disk 1: Side A") inserting = disk1.sideA;
if(value == "Disk 1: Side B") inserting = disk1.sideB;
if(value == "Disk 2: Side A") inserting = disk2.sideA;
if(value == "Disk 2: Side B") inserting = disk2.sideB;
changed = 1;
}
auto FDS::change() -> void {
if(changed) {
changed = 0;
inserted = inserting;
inserting.reset();
drive.changing = 1;
}
}
auto FDS::poll() -> void {
cpu.irqLine((timer.irq && timer.pending) || (drive.irq && drive.pending));
}
auto FDS::main() -> void {
change();
drive.clock();
audio.clock();
timer.clock();
}
auto FDS::power() -> void {
change();
drive = {}; //clears drive.changing; no need to wait after power-on
timer = {};
audio.power();
}
auto FDS::read(uint16 address, uint8 data) -> uint8 {
data = drive.read(address, data);
data = timer.read(address, data);
data = audio.read(address, data);
return data;
}
auto FDS::write(uint16 address, uint8 data) -> void {
drive.write(address, data);
timer.write(address, data);
audio.write(address, data);
}
}
| {
"pile_set_name": "Github"
} |
<?xml version="1.0" encoding="utf-8"?>
<root>
<!--
Microsoft ResX Schema
Version 2.0
The primary goals of this format is to allow a simple XML format
that is mostly human readable. The generation and parsing of the
various data types are done through the TypeConverter classes
associated with the data types.
Example:
... ado.net/XML headers & schema ...
<resheader name="resmimetype">text/microsoft-resx</resheader>
<resheader name="version">2.0</resheader>
<resheader name="reader">System.Resources.ResXResourceReader, System.Windows.Forms, ...</resheader>
<resheader name="writer">System.Resources.ResXResourceWriter, System.Windows.Forms, ...</resheader>
<data name="Name1"><value>this is my long string</value><comment>this is a comment</comment></data>
<data name="Color1" type="System.Drawing.Color, System.Drawing">Blue</data>
<data name="Bitmap1" mimetype="application/x-microsoft.net.object.binary.base64">
<value>[base64 mime encoded serialized .NET Framework object]</value>
</data>
<data name="Icon1" type="System.Drawing.Icon, System.Drawing" mimetype="application/x-microsoft.net.object.bytearray.base64">
<value>[base64 mime encoded string representing a byte array form of the .NET Framework object]</value>
<comment>This is a comment</comment>
</data>
There are any number of "resheader" rows that contain simple
name/value pairs.
Each data row contains a name, and value. The row also contains a
type or mimetype. Type corresponds to a .NET class that support
text/value conversion through the TypeConverter architecture.
Classes that don't support this are serialized and stored with the
mimetype set.
The mimetype is used for serialized objects, and tells the
ResXResourceReader how to depersist the object. This is currently not
extensible. For a given mimetype the value must be set accordingly:
Note - application/x-microsoft.net.object.binary.base64 is the format
that the ResXResourceWriter will generate, however the reader can
read any of the formats listed below.
mimetype: application/x-microsoft.net.object.binary.base64
value : The object must be serialized with
: System.Runtime.Serialization.Formatters.Binary.BinaryFormatter
: and then encoded with base64 encoding.
mimetype: application/x-microsoft.net.object.soap.base64
value : The object must be serialized with
: System.Runtime.Serialization.Formatters.Soap.SoapFormatter
: and then encoded with base64 encoding.
mimetype: application/x-microsoft.net.object.bytearray.base64
value : The object must be serialized into a byte array
: using a System.ComponentModel.TypeConverter
: and then encoded with base64 encoding.
-->
<xsd:schema id="root" xmlns="" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:msdata="urn:schemas-microsoft-com:xml-msdata">
<xsd:import namespace="http://www.w3.org/XML/1998/namespace" />
<xsd:element name="root" msdata:IsDataSet="true">
<xsd:complexType>
<xsd:choice maxOccurs="unbounded">
<xsd:element name="metadata">
<xsd:complexType>
<xsd:sequence>
<xsd:element name="value" type="xsd:string" minOccurs="0" />
</xsd:sequence>
<xsd:attribute name="name" use="required" type="xsd:string" />
<xsd:attribute name="type" type="xsd:string" />
<xsd:attribute name="mimetype" type="xsd:string" />
<xsd:attribute ref="xml:space" />
</xsd:complexType>
</xsd:element>
<xsd:element name="assembly">
<xsd:complexType>
<xsd:attribute name="alias" type="xsd:string" />
<xsd:attribute name="name" type="xsd:string" />
</xsd:complexType>
</xsd:element>
<xsd:element name="data">
<xsd:complexType>
<xsd:sequence>
<xsd:element name="value" type="xsd:string" minOccurs="0" msdata:Ordinal="1" />
<xsd:element name="comment" type="xsd:string" minOccurs="0" msdata:Ordinal="2" />
</xsd:sequence>
<xsd:attribute name="name" type="xsd:string" use="required" msdata:Ordinal="1" />
<xsd:attribute name="type" type="xsd:string" msdata:Ordinal="3" />
<xsd:attribute name="mimetype" type="xsd:string" msdata:Ordinal="4" />
<xsd:attribute ref="xml:space" />
</xsd:complexType>
</xsd:element>
<xsd:element name="resheader">
<xsd:complexType>
<xsd:sequence>
<xsd:element name="value" type="xsd:string" minOccurs="0" msdata:Ordinal="1" />
</xsd:sequence>
<xsd:attribute name="name" type="xsd:string" use="required" />
</xsd:complexType>
</xsd:element>
</xsd:choice>
</xsd:complexType>
</xsd:element>
</xsd:schema>
<resheader name="resmimetype">
<value>text/microsoft-resx</value>
</resheader>
<resheader name="version">
<value>2.0</value>
</resheader>
<resheader name="reader">
<value>System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value>
</resheader>
<resheader name="writer">
<value>System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value>
</resheader>
<data name="ApplicationAccess" xml:space="preserve">
<value>دسترسی به برنامه</value>
</data>
<data name="No" xml:space="preserve">
<value>نه، اجازه نده</value>
</data>
<data name="PersonalInformation" xml:space="preserve">
<value>اطلاعات شخصی</value>
</data>
<data name="Remember" xml:space="preserve">
<value>تصمیم من را به یاد داشته باش</value>
</data>
<data name="SubTitle" xml:space="preserve">
<value>درخواست مجوز شما را می دهد</value>
</data>
<data name="UnCheckPermission" xml:space="preserve">
<value>مجوز هایی را که نمی خواهید واگذار کنید را بردارید.</value>
</data>
<data name="Yes" xml:space="preserve">
<value>بله، اجازه بدهید</value>
</data>
</root> | {
"pile_set_name": "Github"
} |
bl_info = {
"name": "B-SLAM-SIM",
"author": "Adam Kalisz",
"version": (0, 1),
"blender": (2, 80, 0),
"location": "View3D > Add > Mesh > New Object",
"description": "Helpful tools for creating synthetic ground truth data in order to test Visual SLAM algorithms",
"warning": "",
"wiki_url": "https://master.kalisz.co",
"category": "Import-Export",
}
"""
REFERENCES USED:
Lane widths are 3.0 - 3.3 meters for low speed traffic
https://www.driverknowledgetests.com/resources/road-widths/
(virtual lane width was 0.3 m on Feburary, 1st - fixed on Feburary, 7th)
GoPro Hero 4 Black Focal Length: Wide 17.2mm
https://gopro.com/help/articles/Question_Answer/HERO4-Field-of-View-FOV-Information
"""
import bpy
import os
import math
from bpy.types import Operator
from bpy.types import Panel
from bpy_extras.io_utils import ExportHelper
from mathutils import Vector, Euler, Quaternion, Matrix
import numpy as np
def VSLAMMappingFromBlender2DSO(translation, quaternion):
'''
Mapping from Blender to DSO world space:
Blender:
Up = Y-Axis
Right = X-Axis
Forward = -Z-Axis
DSO:
Up = -Y-Axis
Right = X-Axis
Forward = Z-Axis
x = x
y = -y
z = -z
Matrix:
1 0 0
0 -1 0
0 0 -1
'''
# Create space transformation matrix
Blender2DSO = Euler([math.pi/2.0, 0.0, 0.0], 'XYZ').to_matrix().to_4x4()
# Create matrix from translation and quaternion
mat_rot = quaternion.to_matrix().to_4x4()
mat_alignRotation = Euler([-math.pi, 0.0, 0.0], 'XYZ').to_matrix().to_4x4() # This is necessary, because I have decided to rotate Blenders camera such that it "lies" in
# the x-y-plane instead of x-z-plane (i.e. a rotation about 90 degrees around the x-axis) and thus is oriented with regards to the procedurally generated city.
mat_trans = Matrix.Translation(translation)
BlenderPoseCam2World = mat_trans @ mat_rot @ mat_alignRotation
# Transform from Blender world space to DSO world space
DSOPose = Blender2DSO @ BlenderPoseCam2World
# Mirror Quaternion along X-Axis is performed by flipping signs of the y and z component
# Source: Philipp Kurth -> https://stackoverflow.com/questions/32438252/efficient-way-to-apply-mirror-effect-on-quaternion-rotation
#newQuaternion = quaternion
#newQuaternion.y = -quaternion.y
#newQuaternion.z = -quaternion.z
return DSOPose.translation, DSOPose.to_quaternion()
def VSLAMMappingFromDSO2Blender(translation, quaternion):
'''
Mapping from DSO to Blender space:
x = -x
y = -z
z = y
Matrix:
-1 0 0
0 1 0
0 0 -1
'''
# Create space transformation matrix
DSO2Blender = Euler([-math.pi/2.0, 0.0, 0.0], 'XYZ').to_matrix().to_4x4()
# Create matrix from translation and quaternion
mat_rot = quaternion.to_matrix().to_4x4()
mat_alignRotation = Euler([math.pi, 0.0, 0.0], 'XYZ').to_matrix().to_4x4() # This is necessary, because I have decided to rotate Blenders camera such that it "lies" in
# the x-y-plane instead of x-z-plane (i.e. a rotation about 90 degrees around the x-axis) and thus is oriented with regards to the procedurally generated city.
mat_trans = Matrix.Translation(translation)
DSOPoseCam2World = mat_trans @ mat_rot @ mat_alignRotation # * mat_rotTurnAroundY
# Transform from DSO world space to Blender world space
BlenderPose = DSO2Blender @ DSOPoseCam2World
# Mirror Quaternion along X-Axis is performed by flipping signs of the y and z component
# Source: Philipp Kurth -> https://stackoverflow.com/questions/32438252/efficient-way-to-apply-mirror-effect-on-quaternion-rotation
#newQuaternion = quaternion
#newQuaternion.y = -quaternion.y
#newQuaternion.z = -quaternion.z
return BlenderPose.translation, BlenderPose.to_quaternion()
def VSLAMTestMappingBlenderDSO():
# Test Mapping:
translation = Vector([-1,21,22])
quaternion = Quaternion((1.0,0.0,0.0,0.0))
print("Blender (original): \t", translation, " - ", quaternion.to_euler('XYZ'))
dso_trans, dso_rot = VSLAMMappingFromBlender2DSO(translation, quaternion)
print("DSO: \t\t\t", dso_trans, " - ", dso_rot)
blender_trans, blender_rot = VSLAMMappingFromDSO2Blender(dso_trans, dso_rot)
print("Blender (retrieved): \t", blender_trans, " - ", blender_rot.to_euler('XYZ'))
if translation == blender_trans and quaternion == blender_rot:
print("Everything O.K.!")
else:
print("Mapping test failed... ... -.-")
class VSLAMImportDSO(Operator):
'''
This operator imports camera poses from the DSO.
'''
bl_idname = "vslam.import_dso"
bl_label = "Import DSO CSV File (camera_dso.csv)"
def execute(self, context):
scene = context.scene
camera_csv = "camera_dso.csv"
filepath = scene.vslam_output_directory + camera_csv
dso_camera = "Camera_DSO"
camera_object = scene.objects.get(dso_camera)
if(camera_object is None):
bpy.ops.object.camera_add(location=(0.0, 0.0, 0.0), rotation=(0.0, 0.0, 0.0))
camera_object = scene.objects.active
camera_object.name = dso_camera
with open(filepath) as poses:
line = poses.readline()
count = 1
while line:
line = line.strip()
line = line.split(",")
timestamp = int(line[0])
frame = round(timestamp / 1000.0 * scene.render.fps, 0)
location = [ float(line[1]),float(line[2]), float(line[3]) ]
orientation = [ float(line[4]),float(line[5]),float(line[6]),float(line[7]) ]
print("DSO-Importer: Now setting frame =", frame)
scene.frame_set(frame)
# Transformation from DSO to Blender
loc, quat = VSLAMMappingFromDSO2Blender( Vector( location ), Quaternion( orientation ) )
camera_object.location = loc
camera_object.rotation_quaternion = quat
# camera_object.location = Vector( location )
camera_object.keyframe_insert(data_path='location')
camera_object.keyframe_insert(data_path='rotation_quaternion')
#print("Line {}: {}".format(count, line.strip()))
line = poses.readline()
count += 1
camera_object.rotation_mode = 'QUATERNION'
return {"FINISHED"}
class VSLAMExportCamera(Operator):
'''
This operator exports ideal and noisy camera trajectories
'''
bl_idname = "vslam.export_camera"
bl_label = "Export noisy camera"
# ExportHelper mixin class uses this
# filename_ext = ".csv"
def execute(self, context):
scene = context.scene
camera = scene.objects[scene.vslam_camera]
camera.select_set(True)
context.view_layer.objects.active = camera
filepath_ideal_dso = scene.vslam_output_directory + camera.name + "_ideal_dso.csv"
filepath_ideal_blender = scene.vslam_output_directory + camera.name + "_ideal_blender.csv"
filepath_noisy_dso = scene.vslam_output_directory + camera.name + "_noisy_dso.csv"
filepath_noisy_blender = scene.vslam_output_directory + camera.name + "_noisy_blender.csv"
if(scene.vslam_bool_export_ideal):
FileIdealCameraDSO = open(filepath_ideal_dso, 'w', encoding='utf-8')
FileIdealCameraBlender = open(filepath_ideal_blender, 'w', encoding='utf-8')
if(scene.vslam_bool_export_noisy):
FileNoisyCameraDSO = open(filepath_noisy_dso, 'w', encoding='utf-8')
FileNoisyCameraBlender = open(filepath_noisy_blender, 'w', encoding='utf-8')
if(scene.objects.get(scene.vslam_altered_camera) is not None):
# deselect all
bpy.ops.object.select_all(action='DESELECT')
# select altered camera object
scene.objects[scene.vslam_altered_camera].select_set(True)
# remove it
bpy.ops.object.delete()
scene.frame_set(scene.frame_start)
bpy.ops.object.select_all(action='DESELECT')
scene.objects[scene.vslam_camera].select_set(True)
bpy.ops.object.duplicate(linked=False, mode="TRANSLATION")
print(context.view_layer.objects.active)
altered_camera = context.view_layer.objects.active
altered_camera.name = scene.vslam_altered_camera
for frame in range(scene.frame_start, scene.frame_end + 1):
scene.frame_set(frame)
timestamp = ( (scene.frame_current - scene.frame_start) * (1.0 / scene.render.fps) ) * 1000
# For every frame get camera transformation and write the ideal .csv file
translation = camera.matrix_world.translation
orientation = camera.matrix_world.to_quaternion()
dso_trans, dso_quat = VSLAMMappingFromBlender2DSO(translation, orientation)
if(scene.vslam_bool_export_ideal):
if(scene.vslam_bool_export_timestamp):
FileIdealCameraDSO.write("%d,%f,%f,%f,%f,%f,%f,%f\n" % (timestamp, dso_trans.x, dso_trans.y, dso_trans.z, dso_quat.w, dso_quat.x, dso_quat.y, dso_quat.z))
FileIdealCameraBlender.write("%d,%f,%f,%f,%f,%f,%f,%f\n" % (timestamp, translation.x, translation.y, translation.z, orientation.w, orientation.x, orientation.y, orientation.z))
else:
FileIdealCameraDSO.write("%f,%f,%f,%f,%f,%f,%f\n" % (dso_trans.x, dso_trans.y, dso_trans.z, dso_quat.w, dso_quat.x, dso_quat.y, dso_quat.z))
FileIdealCameraBlender.write("%f,%f,%f,%f,%f,%f,%f\n" % (translation.x, translation.y, translation.z, orientation.w, orientation.x, orientation.y, orientation.z))
# Calculate noise for translation (additive to position)
noise = np.random.normal(scene.vslam_noise_translation_mean, scene.vslam_noise_translation_std_deviation, size=3)
noise_translation = Vector( (noise[0], noise[1], noise[2]) )
'''
# ALTERNATIVE approach (not used here, only kept for reference):
# Idea: sample quaternion rotation randomly
# Based on: http://planning.cs.uiuc.edu/node198.html
u_1 = noise[3] * 0.5 + 0.5
u_2 = noise[4] * 0.5 + 0.5
u_3 = noise[5] * 0.5 + 0.5
q_w = math.sqrt(1-u_1) * math.sin(2*math.pi*u_2)
q_x = math.sqrt(1-u_1) * math.cos(2*math.pi*u_2)
q_y = math.sqrt(u_1) * math.sin(2*math.pi*u_3)
q_z = math.sqrt(u_1) * math.cos(2*math.pi*u_3)
noise_orientation = Quaternion( (q_w, q_x, q_y, q_z) )
noise_orientation = orientation
noise_orientation.x = noise[3]
noise_orientation.y = noise[4]
noise_orientation.z = noise[5]
noise_orientation.w = noise[6]
'''
# Generate noise for orientation (additive to Euler)
noise = np.random.normal(scene.vslam_noise_orientation_mean, scene.vslam_noise_orientation_std_deviation, size=3)
noise_orientation = orientation.to_euler()
noise_orientation.x += noise[0]
noise_orientation.y += noise[1]
noise_orientation.z += noise[2]
orientation = noise_orientation.to_quaternion()
translation = translation + noise_translation # Vector addition to translate objects
dso_trans, dso_quat = VSLAMMappingFromBlender2DSO(translation, orientation)
# And now export the noisy camera transformation for every frame and write the noisy .csv file
if(scene.vslam_bool_export_noisy):
if(scene.vslam_bool_export_timestamp):
FileNoisyCameraDSO.write("%d,%f,%f,%f,%f,%f,%f,%f\n" % (timestamp, dso_trans.x, dso_trans.y, dso_trans.z, dso_quat.w, dso_quat.x, dso_quat.y, dso_quat.z))
FileNoisyCameraBlender.write("%d,%f,%f,%f,%f,%f,%f,%f\n" % (timestamp, dso_trans.x, dso_trans.y, dso_trans.z, dso_quat.w, dso_quat.x, dso_quat.y, dso_quat.z))
else:
FileNoisyCameraDSO.write("%f,%f,%f,%f,%f,%f,%f\n" % (dso_trans.x, dso_trans.y, dso_trans.z, dso_quat.w, dso_quat.x, dso_quat.y, dso_quat.z))
FileNoisyCameraBlender.write("%f,%f,%f,%f,%f,%f,%f\n" % (dso_trans.x, dso_trans.y, dso_trans.z, dso_quat.w, dso_quat.x, dso_quat.y, dso_quat.z))
altered_camera.location = translation
altered_camera.rotation_euler = orientation.to_euler()
altered_camera.keyframe_insert(data_path='location')
altered_camera.keyframe_insert(data_path='rotation_euler')
if(scene.vslam_bool_export_ideal):
FileIdealCameraDSO.close()
FileIdealCameraBlender.close()
if(scene.vslam_bool_export_noisy):
FileNoisyCameraDSO.close()
FileNoisyCameraBlender.close()
if(scene.vslam_bool_export_dso):
"""
If set, export additional files (calibration and shell script) to run the dso directly.
### DSO camera.txt calibration configuration: ###
Pinhole fx fy cx cy 0
in_width in_height
"crop" / "full" / "none" / "fx fy cx cy 0"
out_width out_height
"""
image_width = scene.render.resolution_x * (scene.render.resolution_percentage * 0.01)
image_height = scene.render.resolution_y * (scene.render.resolution_percentage * 0.01)
cropped_image_width = image_width * scene.vslam_dso_scale_factor
cropped_image_height = image_height * scene.vslam_dso_scale_factor
# Calculate Focal length in Pixels:
# focal length in pixels = (image width in pixels) * (focal length in mm) / (CCD width in mm)
# Reference: http://phototour.cs.washington.edu/focal.html
fx = image_width * (1.0 * scene.camera.data.lens / scene.camera.data.sensor_width)
fy = image_height * (1.0 * scene.camera.data.lens / scene.camera.data.sensor_height)
cx = image_width / 2
cy = image_height / 2
dso_calib_file = "camera_" + camera.name + ".txt"
dso_image_folder = context.scene.vslam_camera + "/" + context.scene.vslam_camera + "_*"
filepath_dso_calib = scene.vslam_output_directory + dso_calib_file
FileDSO = open(filepath_dso_calib, 'w', encoding='utf-8')
FileDSO.write("Pinhole %f %f %f %f 0\n" % (fx, fy, cx, cy))
FileDSO.write("%d %d\n" % (image_width, image_height))
FileDSO.write("crop\n")
FileDSO.write("%d %d\n" % (cropped_image_width, cropped_image_height))
FileDSO.close()
"""
### DSO command line: ###
bin/dso_dataset \
files=XXXXX/sequence_XX/images.zip \
calib=XXXXX/sequence_XX/camera.txt \
gamma=XXXXX/sequence_XX/pcalib.txt \
vignette=XXXXX/sequence_XX/vignette.png \
preset=0 \
mode=0
"""
filepath_dso_shell = scene.vslam_output_directory + "run_dso_" + camera.name + ".sh"
FileDSO = open(filepath_dso_shell, 'w', encoding='utf-8')
FileDSO.write("bin/dso_dataset files=%s calib=%s" % (dso_image_folder, dso_calib_file))
FileDSO.close()
if(scene.vslam_bool_export_libmv):
# TODO: Add support for libMV as well (Blender's internal camera tracker)
filepath_libmv = scene.vslam_output_directory + ""
FileLibMVProject = open(filepath_libmv, 'w', encoding='utf-8')
FileLibMVProject.close()
return {"FINISHED"}
class VSLAMRenderSequence(Operator):
'''
This operator renders the animation as either opengl or via the selected render engine.
'''
bl_idname = "vslam.render"
bl_label = "Render image sequence"
def execute(self, context):
filepath = context.scene.vslam_output_directory + "/" + context.scene.vslam_camera + "/" + context.scene.vslam_camera + "_"
filepath = bpy.path.native_pathsep(filepath)
context.scene.render.filepath = filepath
if(context.scene.vslam_bool_render_opengl):
bpy.ops.render.opengl(animation=True)
else:
bpy.ops.render.render(animation=True)
return {"FINISHED"}
class VSLAMEffectAutomaticGainControl(Operator):
'''
This operator animates the exposure setting for cycles randomly
'''
bl_idname = "vslam.effect_auto_gain_control"
bl_label = "Activate Automatic Gain Control"
def execute(self, context):
print("Automatic Gain Control activated")
scene = context.scene
for frame in range(scene.frame_start, scene.frame_end + 1):
scene.frame_set(frame)
noise = np.random.normal(0.0, context.scene.vslam_automatic_gain_control_std_deviation)
scene.cycles.film_exposure = 1.0 + noise
scene.cycles.keyframe_insert("film_exposure")
return {"FINISHED"}
class VSLAMEffectRollingShutter(Operator):
'''
This operator sets the rolling shutter setting to the one provided by the user
'''
bl_idname = "vslam.effect_rolling_shutter"
bl_label = "Activate Rolling Shutter"
def execute(self, context):
print("Rolling Shutter (and Motion Blur) activated")
bpy.context.scene.render.use_motion_blur = True
bpy.context.scene.cycles.rolling_shutter_type = 'TOP'
bpy.context.scene.cycles.rolling_shutter_duration = context.scene.vslam_rolling_shutter_factor
return {"FINISHED"}
class VSLAMEffectMotionBlur(Operator):
'''
This operator activates the motion blur render effect
'''
bl_idname = "vslam.effect_motion_blur"
bl_label = "Activate Motion Blur"
def execute(self, context):
print("Motion Blur activated")
bpy.context.scene.render.use_motion_blur = True
bpy.context.scene.render.motion_blur_shutter = context.scene.vslam_motion_blur_duration
return {"FINISHED"}
class VSLAMToolPanel(Panel):
'''
This panel will be displayed in the toolbar and provides a simple ui for this addon
'''
bl_label = "B-SLAM-SIM: Create test data" # Name of the Panel
#bl_idname = "SCENE_PT_test11"
bl_space_type = "PROPERTIES" # show in 3D View
bl_region_type = "WINDOW" # more specifically: tool panel
bl_context = "scene"
bl_category = "VSLAM"
# Draw UI elements
def draw(self, context):
layout = self.layout
settings = layout.box()
settings.label(text="Settings:")
row = settings.row()
row.prop(context.scene, "vslam_output_directory", text="Output directory")
row = settings.row()
row.prop_search(context.scene, "vslam_camera", context.scene, "objects", text="Camera to use")
row = settings.row()
row.prop(context.scene, "vslam_altered_camera", text="Altered camera")
col = settings.row()
box = col.box()
box.label(text="Noise (Position):", icon="ANIM_DATA")
box.prop(context.scene, "vslam_noise_translation_mean", text="Mean", expand=True)
box.prop(context.scene, "vslam_noise_translation_std_deviation", text="Standard deviation", expand=True)
box = col.box()
box.label(text="Noise (Orientation):", icon="ANIM_DATA")
box.prop(context.scene, "vslam_noise_orientation_mean", text="Mean", expand=True)
box.prop(context.scene, "vslam_noise_orientation_std_deviation", text="Standard deviation", expand=True)
row = settings.row()
row.prop(context.scene, "vslam_bool_export_ideal", text="Export ideal camera poses")
row = settings.row()
row.prop(context.scene, "vslam_bool_export_noisy", text="Export noisy camera poses")
row = settings.row()
row.prop(context.scene, "vslam_bool_export_timestamp", text="Export timestamps")
row = settings.row()
row.prop(context.scene, "vslam_bool_export_dso", text="Create a DSO project")
row.prop(context.scene, "vslam_dso_scale_factor", text="Scale factor:")
row = settings.row()
row.enabled = False
row.prop(context.scene, "vslam_bool_export_libmv", text="Create a libMV project (N/A)", emboss=True)
row = settings.row()
row.prop(context.scene, "vslam_bool_render_opengl", text="Render as OpenGL")
row = settings.row()
box = row.box() # Box for Automatic Gain Control
box.label(text="Automatic Gain Control:", icon="ANIM_DATA")
box.prop(context.scene, "vslam_automatic_gain_control_std_deviation", text="Standard Deviation (image brightness scale)", expand=True)
row = settings.row()
box = row.box() # Box for Motion Blur
box.label(text="Motion Blur:", icon="ANIM_DATA")
box.prop(context.scene, "vslam_motion_blur_duration", text="Time in frames", expand=True)
row = settings.row()
box = row.box() # Box for Rolling Shutter
box.label(text="Rolling Shutter (0=no, 1=yes):", icon="ANIM_DATA")
box.prop(context.scene, "vslam_rolling_shutter_factor", text="Rolling Shutter factor", expand=True)
commands = layout.box()
commands.label(text="Commands:")
row = commands.row()
row.operator("vslam.effect_auto_gain_control", text="Simulate Automatic Gain Control (AGC)", icon="ANIM_DATA")
row = commands.row()
row.operator("vslam.effect_rolling_shutter", text="Simulate Rolling Shutter", icon="ANIM_DATA")
row = commands.row()
row.operator("vslam.effect_motion_blur", text="Simulate Motion Blur", icon="ANIM_DATA")
row = commands.row()
row.operator("vslam.render", text="Render image sequence", icon="IMAGE_DATA")
row = commands.row()
row.operator("vslam.import_dso", text="Import DSO (\"camera_dso.csv\")", icon="EMPTY_DATA")
row = commands.row()
row.operator("vslam.export_camera", text="Export camera poses and project files", icon="CAMERA_DATA")
sep = layout.separator()
# Register the new class within Blender
def register():
bpy.utils.register_class(VSLAMToolPanel)
bpy.utils.register_class(VSLAMRenderSequence)
bpy.utils.register_class(VSLAMEffectAutomaticGainControl)
bpy.utils.register_class(VSLAMEffectRollingShutter)
bpy.utils.register_class(VSLAMEffectMotionBlur)
bpy.utils.register_class(VSLAMImportDSO)
bpy.utils.register_class(VSLAMExportCamera)
bpy.types.Scene.vslam_output_directory = bpy.props.StringProperty(subtype='DIR_PATH', default=bpy.path.abspath("//"))
bpy.types.Scene.vslam_camera = bpy.props.StringProperty(default=bpy.context.scene.camera.name if bpy.context.scene.camera is not None else '') #TODO: Dont use string, but bpy.props.PointerProperty
bpy.types.Scene.vslam_altered_camera = bpy.props.StringProperty(default="Camera_altered")
bpy.types.Scene.vslam_noise_translation_mean = bpy.props.FloatVectorProperty(name="Mean", description="Enter the mean for gaussian noise", default=(0.0, 0.0, 0.0), unit="LENGTH", subtype="XYZ")
bpy.types.Scene.vslam_noise_translation_std_deviation = bpy.props.FloatVectorProperty(name="Standard deviation", description="Enter the standard deviation for gaussian noise", default=(0.01, 0.01, 0.01), unit="LENGTH", subtype="XYZ")
bpy.types.Scene.vslam_noise_orientation_mean = bpy.props.FloatVectorProperty(name="Mean", description="Enter the mean for gaussian noise", default=(0.0, 0.0, 0.0), unit="ROTATION", subtype="XYZ")
bpy.types.Scene.vslam_noise_orientation_std_deviation = bpy.props.FloatVectorProperty(name="Standard deviation", description="Enter the standard deviation for gaussian noise", default=(math.radians(1), math.radians(1), math.radians(1)), unit="ROTATION", subtype="XYZ")
# Simulated Camera Effects
bpy.types.Scene.vslam_automatic_gain_control_std_deviation = bpy.props.FloatProperty(name="AGC Standard deviation", description="Enter the standard deviation for gaussian noise being added to normal 1.0 exposure", default=0.02, unit="TIME")
bpy.types.Scene.vslam_motion_blur_duration = bpy.props.FloatProperty(name="Motion Blur Shutter duration in frames", description="Enter the time in frames between shutter open and close", default=0.1, min=0.01, max=2.0, subtype="FACTOR")
bpy.types.Scene.vslam_rolling_shutter_factor = bpy.props.FloatProperty(name="Rolling Shutter factor", description="Enter the percentage of how much rolling shutter there should be in relation to motion blur time (0 = no rolling shutter, 1 = only rolling shutter for the complete motion blur duration)", default=0.1, min=0.0, max=1.0, subtype="PERCENTAGE")
bpy.types.Scene.vslam_bool_export_ideal = bpy.props.BoolProperty(default=True)
bpy.types.Scene.vslam_bool_export_noisy = bpy.props.BoolProperty(default=True)
bpy.types.Scene.vslam_bool_export_timestamp = bpy.props.BoolProperty(default=True)
bpy.types.Scene.vslam_bool_export_dso = bpy.props.BoolProperty(default=True)
bpy.types.Scene.vslam_dso_scale_factor = bpy.props.FloatProperty(name="DSO: Scale down images", description="Scale images by factor", default=0.25)
bpy.types.Scene.vslam_bool_export_libmv = bpy.props.BoolProperty(default=False) # TODO!
bpy.types.Scene.vslam_bool_render_opengl = bpy.props.BoolProperty(default=True)
# Unregister the class when Blender is closed
def unregister():
bpy.utils.unregister_class(VSLAMToolPanel)
bpy.utils.unregister_class(VSLAMRenderSequence)
bpy.utils.unregister_class(VSLAMEffectAutomaticGainControl)
bpy.utils.unregister_class(VSLAMEffectRollingShutter)
bpy.utils.unregister_class(VSLAMEffectMotionBlur)
bpy.utils.unregister_class(VSLAMImportDSO)
bpy.utils.unregister_class(VSLAMExportCamera)
del bpy.types.Scene.vslam_output_directory
del bpy.types.Scene.vslam_camera
del bpy.types.Scene.vslam_altered_camera
del bpy.types.Scene.vslam_noise_translation_mean
del bpy.types.Scene.vslam_noise_translation_std_deviation
del bpy.types.Scene.vslam_noise_orientation_mean
del bpy.types.Scene.vslam_noise_orientation_std_deviation
del bpy.types.Scene.vslam_automatic_gain_control_std_deviation
del bpy.types.Scene.vslam_motion_blur_duration
del bpy.types.Scene.vslam_rolling_shutter_factor
del bpy.types.Scene.vslam_bool_export_ideal
del bpy.types.Scene.vslam_bool_export_noisy
del bpy.types.Scene.vslam_bool_export_timestamp
del bpy.types.Scene.vslam_bool_export_dso
del bpy.types.Scene.vslam_dso_scale_factor
del bpy.types.Scene.vslam_bool_export_libmv
del bpy.types.Scene.vslam_bool_render_opengl
# Needed to run script in Text Editor
if __name__ == "__main__":
register()
| {
"pile_set_name": "Github"
} |
# Modified by Princeton University on June 9th, 2015
# ========== Copyright Header Begin ==========================================
#
# OpenSPARC T1 Processor File: sjm_5.cmd
# Copyright (c) 2006 Sun Microsystems, Inc. All Rights Reserved.
# DO NOT ALTER OR REMOVE COPYRIGHT NOTICES.
#
# The above named 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.
#
# The above named program is distributed in the hope that it will be
# useful, but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
# General Public License for more details.
#
# You should have received a copy of the GNU General Public
# License along with this work; if not, write to the Free Software
# Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA.
#
# ========== Copyright Header End ============================================
CONFIG id=30 iosyncadr=0x7EF00BEEF00
TIMEOUT 100000
IOSYNC
WRITEBLK 0x1170010000 +
0x01234567 0x41234567 0x08234567 0xc1234567 +
0x11234567 0x51234567 0x09234567 0xd1234567 +
0x21234567 0x61234567 0x0a234567 0xe1234567 +
0x31234567 0x71234567 0x0b234567 0xf12345DE
WRITEBLK 0x1170010040 +
0x01034567 0x41334567 0x08734567 0xc1b34567 +
0x11134567 0x51434567 0x09834567 0xd1c34567 +
0x21234567 0x61534567 0x0a934567 0xe1d34567 +
0x31334567 0x71634567 0x0ba34567 0xf1e345DE
WRITEBLK 0x1170010080 +
0x01204567 0x41244567 0x08284567 0xc12c4567 +
0x11214567 0x51254567 0x09294567 0xd12d4567 +
0x21224567 0x61264567 0x0a2a4567 0xe12e4567 +
0x31234567 0x71274567 0x0b2b4567 0xf12f45de
WRITEBLK 0x11700100c0 +
0x01230567 0x41234567 0x0823b567 0xc123c567 +
0x11231567 0x51235567 0x0923a567 0xd123d567 +
0x21232567 0x61235567 0x0a239567 0xe123e567 +
0x31233567 0x71236567 0x0b238567 0xf123f5DE
WRITEBLK 0x1170010100 +
0x012345d7 0x412345d7 0x08234d67 0xc123d567 +
0x112345d7 0x512345d7 0x09234d67 0xd123d567 +
0x212345d7 0x612345d7 0x0a234d67 0xe123d567 +
0x312345d7 0x712345d7 0x0b234d67 0xf123d5DE
WRITEBLK 0x1170010140 +
0x012345d7 0x412345d7 0x082345d7 0xc12d4567 +
0x112345d7 0x512345d7 0x092345d7 0xd12d4567 +
0x212345d7 0x612345d7 0x0a2345d7 0xe12d4567 +
0x312345d7 0x712345d7 0x0b2345d7 0xf12d45DE
WRITEBLK 0x1170010180 +
0x012f4567 0x412f4567 0x08f34567 0xc1f34567 +
0x112f4567 0x512f4567 0x09f34567 0xd1f34567 +
0x212f4567 0x612f4567 0x0af34567 0xe1f34567 +
0x312f4567 0x712f4567 0x0bf34567 0xf1f345DE
WRITEBLK 0x11700101C0 +
0x01234f67 0x412345f7 0x08234f67 0xc1f34567 +
0x11234f67 0x512345f7 0x09234f67 0xd1f34567 +
0x21234f67 0x612345f7 0x0a234f67 0xe1f34567 +
0x31234f67 0x712345f7 0xDADADADA 0xDEDEDEF0
READBLK 0x1170010000 +
0x01234567 0x41234567 0x08234567 0xc1234567 +
0x11234567 0x51234567 0x09234567 0xd1234567 +
0x21234567 0x61234567 0x0a234567 0xe1234567 +
0x31234567 0x71234567 0x0b234567 0xf12345DE
READBLK 0x1170010040 +
0x01034567 0x41334567 0x08734567 0xc1b34567 +
0x11134567 0x51434567 0x09834567 0xd1c34567 +
0x21234567 0x61534567 0x0a934567 0xe1d34567 +
0x31334567 0x71634567 0x0ba34567 0xf1e345DE
READBLK 0x1170010080 +
0x01204567 0x41244567 0x08284567 0xc12c4567 +
0x11214567 0x51254567 0x09294567 0xd12d4567 +
0x21224567 0x61264567 0x0a2a4567 0xe12e4567 +
0x31234567 0x71274567 0x0b2b4567 0xf12f45DE
READBLK 0x11700100c0 +
0x01230567 0x41234567 0x0823b567 0xc123c567 +
0x11231567 0x51235567 0x0923a567 0xd123d567 +
0x21232567 0x61235567 0x0a239567 0xe123e567 +
0x31233567 0x71236567 0x0b238567 0xf123f5DE
READBLK 0x1170010100 +
0x012345d7 0x412345d7 0x08234d67 0xc123d567 +
0x112345d7 0x512345d7 0x09234d67 0xd123d567 +
0x212345d7 0x612345d7 0x0a234d67 0xe123d567 +
0x312345d7 0x712345d7 0x0b234d67 0xf123d5DE
READBLK 0x1170010140 +
0x012345d7 0x412345d7 0x082345d7 0xc12d4567 +
0x112345d7 0x512345d7 0x092345d7 0xd12d4567 +
0x212345d7 0x612345d7 0x0a2345d7 0xe12d4567 +
0x312345d7 0x712345d7 0x0b2345d7 0xf12d45DE
READBLK 0x1170010180 +
0x012f4567 0x412f4567 0x08f34567 0xc1f34567 +
0x112f4567 0x512f4567 0x09f34567 0xd1f34567 +
0x212f4567 0x612f4567 0x0af34567 0xe1f34567 +
0x312f4567 0x712f4567 0x0bf34567 0xf1f345DE
READBLK 0x11700101C0 +
0x01234f67 0x412345f7 0x08234f67 0xc1f34567 +
0x11234f67 0x512345f7 0x09234f67 0xd1f34567 +
0x21234f67 0x612345f7 0x0a234f67 0xe1f34567 +
0x31234f67 0x712345f7 0xDADADADA 0xDEDEDEF0
| {
"pile_set_name": "Github"
} |
<?xml version="1.0" encoding="utf-8"?>
<resources>
<color name="colorPrimary">#3F51B5</color>
<color name="colorPrimaryDark">#303F9F</color>
<color name="colorAccent">#FF4081</color>
<color name="transparent">#00000000</color>
<color name="first_layer">#d5b9c5</color>
<color name="second_layer">#b57d91</color>
<color name="third_layer">#a55c77</color>
</resources>
| {
"pile_set_name": "Github"
} |
Aaron Lehmann <[email protected]> (@aaronlehmann)
Brandon Philips <[email protected]> (@philips)
Brendan Burns <[email protected]> (@brendandburns)
Derek McGowan <[email protected]> (@dmcgowan)
Jason Bouzane <[email protected]> (@jbouzane)
John Starks <[email protected]> (@jstarks)
Jonathan Boulle <[email protected]> (@jonboulle)
Stephen Day <[email protected]> (@stevvooe)
Vincent Batts <[email protected]> (@vbatts)
| {
"pile_set_name": "Github"
} |
// Copyright 2011 the V8 project authors. 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.
// This is clang plugin used by gcmole tool. See README for more details.
#include "clang/AST/AST.h"
#include "clang/AST/ASTConsumer.h"
#include "clang/AST/Mangle.h"
#include "clang/AST/RecursiveASTVisitor.h"
#include "clang/AST/StmtVisitor.h"
#include "clang/Frontend/FrontendPluginRegistry.h"
#include "clang/Frontend/CompilerInstance.h"
#include "llvm/Support/raw_ostream.h"
#include <bitset>
#include <fstream>
#include <iostream>
#include <map>
#include <set>
#include <stack>
namespace {
bool g_tracing_enabled = false;
bool g_dead_vars_analysis = false;
#define TRACE(str) \
do { \
if (g_tracing_enabled) { \
std::cout << str << std::endl; \
} \
} while (false)
#define TRACE_LLVM_TYPE(str, type) \
do { \
if (g_tracing_enabled) { \
std::cout << str << " " << type.getAsString() << std::endl; \
} \
} while (false)
// Node: The following is used when tracing --dead-vars
// to provide extra info for the GC suspect.
#define TRACE_LLVM_DECL(str, decl) \
do { \
if (g_tracing_enabled && g_dead_vars_analysis) { \
std::cout << str << std::endl; \
decl->dump(); \
} \
} while (false)
typedef std::string MangledName;
typedef std::set<MangledName> CalleesSet;
typedef std::map<MangledName, MangledName> CalleesMap;
static bool GetMangledName(clang::MangleContext* ctx,
const clang::NamedDecl* decl,
MangledName* result) {
if (!llvm::isa<clang::CXXConstructorDecl>(decl) &&
!llvm::isa<clang::CXXDestructorDecl>(decl)) {
llvm::SmallVector<char, 512> output;
llvm::raw_svector_ostream out(output);
ctx->mangleName(decl, out);
*result = out.str().str();
return true;
}
return false;
}
static bool InV8Namespace(const clang::NamedDecl* decl) {
return decl->getQualifiedNameAsString().compare(0, 4, "v8::") == 0;
}
static std::string EXTERNAL("EXTERNAL");
static std::string STATE_TAG("enum v8::internal::StateTag");
static bool IsExternalVMState(const clang::ValueDecl* var) {
const clang::EnumConstantDecl* enum_constant =
llvm::dyn_cast<clang::EnumConstantDecl>(var);
if (enum_constant != NULL && enum_constant->getNameAsString() == EXTERNAL) {
clang::QualType type = enum_constant->getType();
return (type.getAsString() == STATE_TAG);
}
return false;
}
struct Resolver {
explicit Resolver(clang::ASTContext& ctx)
: ctx_(ctx), decl_ctx_(ctx.getTranslationUnitDecl()) {
}
Resolver(clang::ASTContext& ctx, clang::DeclContext* decl_ctx)
: ctx_(ctx), decl_ctx_(decl_ctx) {
}
clang::DeclarationName ResolveName(const char* n) {
clang::IdentifierInfo* ident = &ctx_.Idents.get(n);
return ctx_.DeclarationNames.getIdentifier(ident);
}
Resolver ResolveNamespace(const char* n) {
return Resolver(ctx_, Resolve<clang::NamespaceDecl>(n));
}
template<typename T>
T* Resolve(const char* n) {
if (decl_ctx_ == NULL) return NULL;
clang::DeclContext::lookup_result result =
decl_ctx_->lookup(ResolveName(n));
clang::DeclContext::lookup_iterator end = result.end();
for (clang::DeclContext::lookup_iterator i = result.begin(); i != end;
i++) {
if (llvm::isa<T>(*i)) {
return llvm::cast<T>(*i);
} else {
llvm::errs() << "Didn't match declaration template against "
<< (*i)->getNameAsString() << "\n";
}
}
return NULL;
}
clang::CXXRecordDecl* ResolveTemplate(const char* n) {
clang::NamedDecl* initial_template = Resolve<clang::NamedDecl>(n);
if (!initial_template) return NULL;
clang::NamedDecl* underlying_template =
initial_template->getUnderlyingDecl();
if (!underlying_template) {
llvm::errs() << "Couldn't resolve underlying template\n";
return NULL;
}
const clang::TypeAliasDecl* type_alias_decl =
llvm::dyn_cast_or_null<clang::TypeAliasDecl>(underlying_template);
if (!type_alias_decl) {
llvm::errs() << "Couldn't resolve TypeAliasDecl\n";
return NULL;
}
const clang::Type* type = type_alias_decl->getTypeForDecl();
if (!type) {
llvm::errs() << "Couldn't resolve TypeAliasDecl to Type\n";
return NULL;
}
const clang::TypedefType* typedef_type =
llvm::dyn_cast_or_null<clang::TypedefType>(type);
if (!typedef_type) {
llvm::errs() << "Couldn't resolve TypedefType\n";
return NULL;
}
const clang::TypedefNameDecl* typedef_name_decl = typedef_type->getDecl();
if (!typedef_name_decl) {
llvm::errs() << "Couldn't resolve TypedefType to TypedefNameDecl\n";
return NULL;
}
clang::QualType underlying_type = typedef_name_decl->getUnderlyingType();
if (!llvm::isa<clang::TemplateSpecializationType>(underlying_type)) {
llvm::errs() << "Couldn't resolve TemplateSpecializationType\n";
return NULL;
}
const clang::TemplateSpecializationType* templ_specialization_type =
llvm::cast<clang::TemplateSpecializationType>(underlying_type);
if (!llvm::isa<clang::RecordType>(templ_specialization_type->desugar())) {
llvm::errs() << "Couldn't resolve RecordType\n";
return NULL;
}
const clang::RecordType* record_type =
llvm::cast<clang::RecordType>(templ_specialization_type->desugar());
clang::CXXRecordDecl* record_decl =
llvm::dyn_cast_or_null<clang::CXXRecordDecl>(record_type->getDecl());
if (!record_decl) {
llvm::errs() << "Couldn't resolve CXXRecordDecl\n";
return NULL;
}
return record_decl;
}
private:
clang::ASTContext& ctx_;
clang::DeclContext* decl_ctx_;
};
class CalleesPrinter : public clang::RecursiveASTVisitor<CalleesPrinter> {
public:
explicit CalleesPrinter(clang::MangleContext* ctx) : ctx_(ctx) {
}
virtual bool VisitCallExpr(clang::CallExpr* expr) {
const clang::FunctionDecl* callee = expr->getDirectCallee();
if (callee != NULL) AnalyzeFunction(callee);
return true;
}
virtual bool VisitDeclRefExpr(clang::DeclRefExpr* expr) {
// If function mentions EXTERNAL VMState add artificial garbage collection
// mark.
if (IsExternalVMState(expr->getDecl()))
AddCallee("CollectGarbage", "CollectGarbage");
return true;
}
void AnalyzeFunction(const clang::FunctionDecl* f) {
MangledName name;
if (InV8Namespace(f) && GetMangledName(ctx_, f, &name)) {
const std::string& function = f->getNameAsString();
AddCallee(name, function);
const clang::FunctionDecl* body = NULL;
if (f->hasBody(body) && !Analyzed(name)) {
EnterScope(name);
TraverseStmt(body->getBody());
LeaveScope();
}
}
}
typedef std::map<MangledName, CalleesSet* > Callgraph;
bool Analyzed(const MangledName& name) {
return callgraph_[name] != NULL;
}
void EnterScope(const MangledName& name) {
CalleesSet* callees = callgraph_[name];
if (callees == NULL) {
callgraph_[name] = callees = new CalleesSet();
}
scopes_.push(callees);
}
void LeaveScope() {
scopes_.pop();
}
void AddCallee(const MangledName& name, const MangledName& function) {
if (!scopes_.empty()) scopes_.top()->insert(name);
mangled_to_function_[name] = function;
}
void PrintCallGraph() {
for (Callgraph::const_iterator i = callgraph_.begin(), e = callgraph_.end();
i != e;
++i) {
std::cout << i->first << "," << mangled_to_function_[i->first] << "\n";
CalleesSet* callees = i->second;
for (CalleesSet::const_iterator j = callees->begin(), e = callees->end();
j != e;
++j) {
std::cout << "\t" << *j << "," << mangled_to_function_[*j] << "\n";
}
}
}
private:
clang::MangleContext* ctx_;
std::stack<CalleesSet* > scopes_;
Callgraph callgraph_;
CalleesMap mangled_to_function_;
};
class FunctionDeclarationFinder
: public clang::ASTConsumer,
public clang::RecursiveASTVisitor<FunctionDeclarationFinder> {
public:
explicit FunctionDeclarationFinder(clang::DiagnosticsEngine& d,
clang::SourceManager& sm,
const std::vector<std::string>& args)
: d_(d), sm_(sm) {}
virtual void HandleTranslationUnit(clang::ASTContext &ctx) {
mangle_context_ = clang::ItaniumMangleContext::create(ctx, d_);
callees_printer_ = new CalleesPrinter(mangle_context_);
TraverseDecl(ctx.getTranslationUnitDecl());
callees_printer_->PrintCallGraph();
}
virtual bool VisitFunctionDecl(clang::FunctionDecl* decl) {
callees_printer_->AnalyzeFunction(decl);
return true;
}
private:
clang::DiagnosticsEngine& d_;
clang::SourceManager& sm_;
clang::MangleContext* mangle_context_;
CalleesPrinter* callees_printer_;
};
static bool gc_suspects_loaded = false;
static CalleesSet gc_suspects;
static CalleesSet gc_functions;
static bool whitelist_loaded = false;
static CalleesSet suspects_whitelist;
static void LoadGCSuspects() {
if (gc_suspects_loaded) return;
std::ifstream fin("gcsuspects");
std::string mangled, function;
while (!fin.eof()) {
std::getline(fin, mangled, ',');
gc_suspects.insert(mangled);
std::getline(fin, function);
gc_functions.insert(function);
}
gc_suspects_loaded = true;
}
static void LoadSuspectsWhitelist() {
if (whitelist_loaded) return;
std::ifstream fin("tools/gcmole/suspects.whitelist");
std::string s;
while (fin >> s) suspects_whitelist.insert(s);
whitelist_loaded = true;
}
// Looks for exact match of the mangled name.
static bool KnownToCauseGC(clang::MangleContext* ctx,
const clang::FunctionDecl* decl) {
LoadGCSuspects();
if (!InV8Namespace(decl)) return false;
if (suspects_whitelist.find(decl->getNameAsString()) !=
suspects_whitelist.end()) {
return false;
}
MangledName name;
if (GetMangledName(ctx, decl, &name)) {
return gc_suspects.find(name) != gc_suspects.end();
}
return false;
}
// Looks for partial match of only the function name.
static bool SuspectedToCauseGC(clang::MangleContext* ctx,
const clang::FunctionDecl* decl) {
LoadGCSuspects();
if (!InV8Namespace(decl)) return false;
LoadSuspectsWhitelist();
if (suspects_whitelist.find(decl->getNameAsString()) !=
suspects_whitelist.end()) {
return false;
}
if (gc_functions.find(decl->getNameAsString()) != gc_functions.end()) {
TRACE_LLVM_DECL("Suspected by ", decl);
return true;
}
return false;
}
static const int kNoEffect = 0;
static const int kCausesGC = 1;
static const int kRawDef = 2;
static const int kRawUse = 4;
static const int kAllEffects = kCausesGC | kRawDef | kRawUse;
class Environment;
class ExprEffect {
public:
bool hasGC() { return (effect_ & kCausesGC) != 0; }
void setGC() { effect_ |= kCausesGC; }
bool hasRawDef() { return (effect_ & kRawDef) != 0; }
void setRawDef() { effect_ |= kRawDef; }
bool hasRawUse() { return (effect_ & kRawUse) != 0; }
void setRawUse() { effect_ |= kRawUse; }
static ExprEffect None() { return ExprEffect(kNoEffect, NULL); }
static ExprEffect NoneWithEnv(Environment* env) {
return ExprEffect(kNoEffect, env);
}
static ExprEffect RawUse() { return ExprEffect(kRawUse, NULL); }
static ExprEffect Merge(ExprEffect a, ExprEffect b);
static ExprEffect MergeSeq(ExprEffect a, ExprEffect b);
ExprEffect Define(const std::string& name);
Environment* env() {
return reinterpret_cast<Environment*>(effect_ & ~kAllEffects);
}
static ExprEffect GC() {
return ExprEffect(kCausesGC, NULL);
}
private:
ExprEffect(int effect, Environment* env)
: effect_((effect & kAllEffects) |
reinterpret_cast<intptr_t>(env)) { }
intptr_t effect_;
};
const std::string BAD_EXPR_MSG("Possible problem with evaluation order.");
const std::string DEAD_VAR_MSG("Possibly dead variable.");
class Environment {
public:
Environment() = default;
static Environment Unreachable() {
Environment env;
env.unreachable_ = true;
return env;
}
static Environment Merge(const Environment& l,
const Environment& r) {
Environment out(l);
out &= r;
return out;
}
Environment ApplyEffect(ExprEffect effect) const {
Environment out = effect.hasGC() ? Environment() : Environment(*this);
if (effect.env()) out |= *effect.env();
return out;
}
typedef std::map<std::string, int> SymbolTable;
bool IsAlive(const std::string& name) const {
SymbolTable::iterator code = symbol_table_.find(name);
if (code == symbol_table_.end()) return false;
return is_live(code->second);
}
bool Equal(const Environment& env) {
if (unreachable_ && env.unreachable_) return true;
size_t size = std::max(live_.size(), env.live_.size());
for (size_t i = 0; i < size; ++i) {
if (is_live(i) != env.is_live(i)) return false;
}
return true;
}
Environment Define(const std::string& name) const {
return Environment(*this, SymbolToCode(name));
}
void MDefine(const std::string& name) { set_live(SymbolToCode(name)); }
static int SymbolToCode(const std::string& name) {
SymbolTable::iterator code = symbol_table_.find(name);
if (code == symbol_table_.end()) {
int new_code = symbol_table_.size();
symbol_table_.insert(std::make_pair(name, new_code));
return new_code;
}
return code->second;
}
static void ClearSymbolTable() {
for (Environment* e : envs_) delete e;
envs_.clear();
symbol_table_.clear();
}
void Print() const {
bool comma = false;
std::cout << "{";
for (auto& e : symbol_table_) {
if (!is_live(e.second)) continue;
if (comma) std::cout << ", ";
std::cout << e.first;
comma = true;
}
std::cout << "}" << std::endl;
}
static Environment* Allocate(const Environment& env) {
Environment* allocated_env = new Environment(env);
envs_.push_back(allocated_env);
return allocated_env;
}
private:
Environment(const Environment& l, int code)
: live_(l.live_) {
set_live(code);
}
void set_live(size_t pos) {
if (unreachable_) return;
if (pos >= live_.size()) live_.resize(pos + 1);
live_[pos] = true;
}
bool is_live(size_t pos) const {
return unreachable_ || (live_.size() > pos && live_[pos]);
}
Environment& operator|=(const Environment& o) {
if (o.unreachable_) {
unreachable_ = true;
live_.clear();
} else if (!unreachable_) {
for (size_t i = 0, e = o.live_.size(); i < e; ++i) {
if (o.live_[i]) set_live(i);
}
}
return *this;
}
Environment& operator&=(const Environment& o) {
if (o.unreachable_) return *this;
if (unreachable_) return *this = o;
// Carry over false bits from the tail of o.live_, and reset all bits that
// are not set in o.live_.
size_t size = std::max(live_.size(), o.live_.size());
if (size > live_.size()) live_.resize(size);
for (size_t i = 0; i < size; ++i) {
if (live_[i] && (i >= o.live_.size() || !o.live_[i])) live_[i] = false;
}
return *this;
}
static SymbolTable symbol_table_;
static std::vector<Environment*> envs_;
std::vector<bool> live_;
// unreachable_ == true implies live_.empty(), but still is_live(i) returns
// true for all i.
bool unreachable_ = false;
friend class ExprEffect;
friend class CallProps;
};
class CallProps {
public:
CallProps() : env_(NULL) { }
void SetEffect(int arg, ExprEffect in) {
if (in.hasGC()) {
gc_.set(arg);
}
if (in.hasRawDef()) raw_def_.set(arg);
if (in.hasRawUse()) raw_use_.set(arg);
if (in.env() != NULL) {
if (env_ == NULL) {
env_ = in.env();
} else {
*env_ |= *in.env();
}
}
}
ExprEffect ComputeCumulativeEffect(bool result_is_raw) {
ExprEffect out = ExprEffect::NoneWithEnv(env_);
if (gc_.any()) {
out.setGC();
}
if (raw_use_.any()) out.setRawUse();
if (result_is_raw) out.setRawDef();
return out;
}
bool IsSafe() {
if (!gc_.any()) {
return true;
}
std::bitset<kMaxNumberOfArguments> raw = (raw_def_ | raw_use_);
if (!raw.any()) {
return true;
}
bool result = gc_.count() == 1 && !((raw ^ gc_).any());
return result;
}
private:
static const int kMaxNumberOfArguments = 64;
std::bitset<kMaxNumberOfArguments> raw_def_;
std::bitset<kMaxNumberOfArguments> raw_use_;
std::bitset<kMaxNumberOfArguments> gc_;
Environment* env_;
};
Environment::SymbolTable Environment::symbol_table_;
std::vector<Environment*> Environment::envs_;
ExprEffect ExprEffect::Merge(ExprEffect a, ExprEffect b) {
Environment* a_env = a.env();
Environment* b_env = b.env();
Environment* out = NULL;
if (a_env != NULL && b_env != NULL) {
out = Environment::Allocate(*a_env);
*out &= *b_env;
}
return ExprEffect(a.effect_ | b.effect_, out);
}
ExprEffect ExprEffect::MergeSeq(ExprEffect a, ExprEffect b) {
Environment* a_env = b.hasGC() ? NULL : a.env();
Environment* b_env = b.env();
Environment* out = (b_env == NULL) ? a_env : b_env;
if (a_env != NULL && b_env != NULL) {
out = Environment::Allocate(*b_env);
*out |= *a_env;
}
return ExprEffect(a.effect_ | b.effect_, out);
}
ExprEffect ExprEffect::Define(const std::string& name) {
Environment* e = env();
if (e == NULL) {
e = Environment::Allocate(Environment());
}
e->MDefine(name);
return ExprEffect(effect_, e);
}
static std::string THIS ("this");
class FunctionAnalyzer {
public:
FunctionAnalyzer(clang::MangleContext* ctx, clang::CXXRecordDecl* object_decl,
clang::CXXRecordDecl* maybe_object_decl,
clang::CXXRecordDecl* smi_decl,
clang::CXXRecordDecl* no_gc_decl,
clang::CXXRecordDecl* no_gc_or_safepoint_decl,
clang::CXXRecordDecl* no_heap_access_decl,
clang::DiagnosticsEngine& d, clang::SourceManager& sm)
: ctx_(ctx),
object_decl_(object_decl),
maybe_object_decl_(maybe_object_decl),
smi_decl_(smi_decl),
no_gc_decl_(no_gc_decl),
no_gc_or_safepoint_decl_(no_gc_or_safepoint_decl),
no_heap_access_decl_(no_heap_access_decl),
d_(d),
sm_(sm),
block_(NULL) {}
// --------------------------------------------------------------------------
// Expressions
// --------------------------------------------------------------------------
ExprEffect VisitExpr(clang::Expr* expr, const Environment& env) {
#define VISIT(type) \
do { \
clang::type* concrete_expr = llvm::dyn_cast_or_null<clang::type>(expr); \
if (concrete_expr != NULL) { \
return Visit##type(concrete_expr, env); \
} \
} while (0);
VISIT(AbstractConditionalOperator);
VISIT(AddrLabelExpr);
VISIT(ArraySubscriptExpr);
VISIT(BinaryOperator);
VISIT(BlockExpr);
VISIT(CallExpr);
VISIT(CastExpr);
VISIT(CharacterLiteral);
VISIT(ChooseExpr);
VISIT(CompoundLiteralExpr);
VISIT(ConstantExpr);
VISIT(CXXBindTemporaryExpr);
VISIT(CXXBoolLiteralExpr);
VISIT(CXXConstructExpr);
VISIT(CXXDefaultArgExpr);
VISIT(CXXDeleteExpr);
VISIT(CXXDependentScopeMemberExpr);
VISIT(CXXNewExpr);
VISIT(CXXNoexceptExpr);
VISIT(CXXNullPtrLiteralExpr);
VISIT(CXXPseudoDestructorExpr);
VISIT(CXXScalarValueInitExpr);
VISIT(CXXThisExpr);
VISIT(CXXThrowExpr);
VISIT(CXXTypeidExpr);
VISIT(CXXUnresolvedConstructExpr);
VISIT(CXXUuidofExpr);
VISIT(DeclRefExpr);
VISIT(DependentScopeDeclRefExpr);
VISIT(DesignatedInitExpr);
VISIT(ExprWithCleanups);
VISIT(ExtVectorElementExpr);
VISIT(FloatingLiteral);
VISIT(GNUNullExpr);
VISIT(ImaginaryLiteral);
VISIT(ImplicitCastExpr);
VISIT(ImplicitValueInitExpr);
VISIT(InitListExpr);
VISIT(IntegerLiteral);
VISIT(MaterializeTemporaryExpr);
VISIT(MemberExpr);
VISIT(OffsetOfExpr);
VISIT(OpaqueValueExpr);
VISIT(OverloadExpr);
VISIT(PackExpansionExpr);
VISIT(ParenExpr);
VISIT(ParenListExpr);
VISIT(PredefinedExpr);
VISIT(ShuffleVectorExpr);
VISIT(SizeOfPackExpr);
VISIT(StmtExpr);
VISIT(StringLiteral);
VISIT(SubstNonTypeTemplateParmPackExpr);
VISIT(TypeTraitExpr);
VISIT(UnaryOperator);
VISIT(UnaryExprOrTypeTraitExpr);
VISIT(VAArgExpr);
#undef VISIT
return ExprEffect::None();
}
#define DECL_VISIT_EXPR(type) \
ExprEffect Visit##type (clang::type* expr, const Environment& env)
#define IGNORE_EXPR(type) \
ExprEffect Visit##type (clang::type* expr, const Environment& env) { \
return ExprEffect::None(); \
}
IGNORE_EXPR(AddrLabelExpr);
IGNORE_EXPR(BlockExpr);
IGNORE_EXPR(CharacterLiteral);
IGNORE_EXPR(ChooseExpr);
IGNORE_EXPR(CompoundLiteralExpr);
IGNORE_EXPR(CXXBoolLiteralExpr);
IGNORE_EXPR(CXXDependentScopeMemberExpr);
IGNORE_EXPR(CXXNullPtrLiteralExpr);
IGNORE_EXPR(CXXPseudoDestructorExpr);
IGNORE_EXPR(CXXScalarValueInitExpr);
IGNORE_EXPR(CXXNoexceptExpr);
IGNORE_EXPR(CXXTypeidExpr);
IGNORE_EXPR(CXXUnresolvedConstructExpr);
IGNORE_EXPR(CXXUuidofExpr);
IGNORE_EXPR(DependentScopeDeclRefExpr);
IGNORE_EXPR(DesignatedInitExpr);
IGNORE_EXPR(ExtVectorElementExpr);
IGNORE_EXPR(FloatingLiteral);
IGNORE_EXPR(ImaginaryLiteral);
IGNORE_EXPR(IntegerLiteral);
IGNORE_EXPR(OffsetOfExpr);
IGNORE_EXPR(ImplicitValueInitExpr);
IGNORE_EXPR(PackExpansionExpr);
IGNORE_EXPR(PredefinedExpr);
IGNORE_EXPR(ShuffleVectorExpr);
IGNORE_EXPR(SizeOfPackExpr);
IGNORE_EXPR(StmtExpr);
IGNORE_EXPR(StringLiteral);
IGNORE_EXPR(SubstNonTypeTemplateParmPackExpr);
IGNORE_EXPR(TypeTraitExpr);
IGNORE_EXPR(VAArgExpr);
IGNORE_EXPR(GNUNullExpr);
IGNORE_EXPR(OverloadExpr);
DECL_VISIT_EXPR(CXXThisExpr) {
return Use(expr, expr->getType(), THIS, env);
}
DECL_VISIT_EXPR(AbstractConditionalOperator) {
Environment after_cond = env.ApplyEffect(VisitExpr(expr->getCond(), env));
return ExprEffect::Merge(VisitExpr(expr->getTrueExpr(), after_cond),
VisitExpr(expr->getFalseExpr(), after_cond));
}
DECL_VISIT_EXPR(ArraySubscriptExpr) {
clang::Expr* exprs[2] = {expr->getBase(), expr->getIdx()};
return Parallel(expr, 2, exprs, env);
}
bool IsRawPointerVar(clang::Expr* expr, std::string* var_name) {
if (llvm::isa<clang::DeclRefExpr>(expr)) {
*var_name =
llvm::cast<clang::DeclRefExpr>(expr)->getDecl()->getNameAsString();
return true;
}
return false;
}
DECL_VISIT_EXPR(BinaryOperator) {
clang::Expr* lhs = expr->getLHS();
clang::Expr* rhs = expr->getRHS();
clang::Expr* exprs[2] = {lhs, rhs};
switch (expr->getOpcode()) {
case clang::BO_Comma:
return Sequential(expr, 2, exprs, env);
case clang::BO_LAnd:
case clang::BO_LOr:
return ExprEffect::Merge(VisitExpr(lhs, env), VisitExpr(rhs, env));
default:
return Parallel(expr, 2, exprs, env);
}
}
DECL_VISIT_EXPR(CXXBindTemporaryExpr) {
return VisitExpr(expr->getSubExpr(), env);
}
DECL_VISIT_EXPR(MaterializeTemporaryExpr) {
return VisitExpr(expr->GetTemporaryExpr(), env);
}
DECL_VISIT_EXPR(CXXConstructExpr) {
return VisitArguments<>(expr, env);
}
DECL_VISIT_EXPR(CXXDefaultArgExpr) {
return VisitExpr(expr->getExpr(), env);
}
DECL_VISIT_EXPR(CXXDeleteExpr) {
return VisitExpr(expr->getArgument(), env);
}
DECL_VISIT_EXPR(CXXNewExpr) { return VisitExpr(expr->getInitializer(), env); }
DECL_VISIT_EXPR(ExprWithCleanups) {
return VisitExpr(expr->getSubExpr(), env);
}
DECL_VISIT_EXPR(CXXThrowExpr) {
return VisitExpr(expr->getSubExpr(), env);
}
DECL_VISIT_EXPR(ImplicitCastExpr) {
return VisitExpr(expr->getSubExpr(), env);
}
DECL_VISIT_EXPR(ConstantExpr) { return VisitExpr(expr->getSubExpr(), env); }
DECL_VISIT_EXPR(InitListExpr) {
return Sequential(expr, expr->getNumInits(), expr->getInits(), env);
}
DECL_VISIT_EXPR(MemberExpr) {
return VisitExpr(expr->getBase(), env);
}
DECL_VISIT_EXPR(OpaqueValueExpr) {
return VisitExpr(expr->getSourceExpr(), env);
}
DECL_VISIT_EXPR(ParenExpr) {
return VisitExpr(expr->getSubExpr(), env);
}
DECL_VISIT_EXPR(ParenListExpr) {
return Parallel(expr, expr->getNumExprs(), expr->getExprs(), env);
}
DECL_VISIT_EXPR(UnaryOperator) {
// TODO(gcmole): We are treating all expressions that look like
// {&raw_pointer_var} as definitions of {raw_pointer_var}. This should be
// changed to recognize less generic pattern:
//
// if (maybe_object->ToObject(&obj)) return maybe_object;
//
if (expr->getOpcode() == clang::UO_AddrOf) {
std::string var_name;
if (IsRawPointerVar(expr->getSubExpr(), &var_name)) {
return ExprEffect::None().Define(var_name);
}
}
return VisitExpr(expr->getSubExpr(), env);
}
DECL_VISIT_EXPR(UnaryExprOrTypeTraitExpr) {
if (expr->isArgumentType()) {
return ExprEffect::None();
}
return VisitExpr(expr->getArgumentExpr(), env);
}
DECL_VISIT_EXPR(CastExpr) {
return VisitExpr(expr->getSubExpr(), env);
}
DECL_VISIT_EXPR(DeclRefExpr) {
return Use(expr, expr->getDecl(), env);
}
// Represents a node in the AST {parent} whose children {exprs} have
// undefined order of evaluation, e.g. array subscript or a binary operator.
ExprEffect Parallel(clang::Expr* parent, int n, clang::Expr** exprs,
const Environment& env) {
CallProps props;
for (int i = 0; i < n; ++i) {
props.SetEffect(i, VisitExpr(exprs[i], env));
}
if (!props.IsSafe()) ReportUnsafe(parent, BAD_EXPR_MSG);
return props.ComputeCumulativeEffect(
RepresentsRawPointerType(parent->getType()));
}
// Represents a node in the AST {parent} whose children {exprs} are
// executed in sequence, e.g. a switch statement or an initializer list.
ExprEffect Sequential(clang::Stmt* parent, int n, clang::Expr** exprs,
const Environment& env) {
ExprEffect out = ExprEffect::None();
Environment out_env = env;
for (int i = 0; i < n; ++i) {
out = ExprEffect::MergeSeq(out, VisitExpr(exprs[i], out_env));
out_env = out_env.ApplyEffect(out);
}
return out;
}
// Represents a node in the AST {parent} which uses the variable {var_name},
// e.g. this expression or operator&.
// Here we observe the type in {var_type} of a previously declared variable
// and if it's a raw heap object type, we do the following:
// 1. If it got stale due to GC since its declaration, we report it as such.
// 2. Mark its raw usage in the ExprEffect returned by this function.
ExprEffect Use(const clang::Expr* parent,
const clang::QualType& var_type,
const std::string& var_name,
const Environment& env) {
if (RepresentsRawPointerType(var_type)) {
// We currently care only about our internal pointer types and not about
// raw C++ pointers, because normally special care is taken when storing
// raw pointers to the managed heap. Furthermore, checking for raw
// pointers produces too many false positives in the dead variable
// analysis.
if (IsInternalPointerType(var_type) && !env.IsAlive(var_name) &&
!HasActiveGuard() && g_dead_vars_analysis) {
ReportUnsafe(parent, DEAD_VAR_MSG);
}
return ExprEffect::RawUse();
}
return ExprEffect::None();
}
ExprEffect Use(const clang::Expr* parent,
const clang::ValueDecl* var,
const Environment& env) {
if (IsExternalVMState(var)) {
return ExprEffect::GC();
}
return Use(parent, var->getType(), var->getNameAsString(), env);
}
template<typename ExprType>
ExprEffect VisitArguments(ExprType* call, const Environment& env) {
CallProps props;
VisitArguments<>(call, &props, env);
if (!props.IsSafe()) ReportUnsafe(call, BAD_EXPR_MSG);
return props.ComputeCumulativeEffect(
RepresentsRawPointerType(call->getType()));
}
template<typename ExprType>
void VisitArguments(ExprType* call,
CallProps* props,
const Environment& env) {
for (unsigned arg = 0; arg < call->getNumArgs(); arg++) {
props->SetEffect(arg + 1, VisitExpr(call->getArg(arg), env));
}
}
// After visiting the receiver and the arguments of the {call} node, this
// function might report a GC-unsafe usage (due to the undefined evaluation
// order of the receiver and the rest of the arguments).
ExprEffect VisitCallExpr(clang::CallExpr* call,
const Environment& env) {
CallProps props;
clang::CXXMemberCallExpr* memcall =
llvm::dyn_cast_or_null<clang::CXXMemberCallExpr>(call);
if (memcall != NULL) {
clang::Expr* receiver = memcall->getImplicitObjectArgument();
props.SetEffect(0, VisitExpr(receiver, env));
}
std::string var_name;
clang::CXXOperatorCallExpr* opcall =
llvm::dyn_cast_or_null<clang::CXXOperatorCallExpr>(call);
if (opcall != NULL && opcall->isAssignmentOp() &&
IsRawPointerVar(opcall->getArg(0), &var_name)) {
// TODO(gcmole): We are treating all assignment operator calls with
// the left hand side looking like {raw_pointer_var} as safe independent
// of the concrete assignment operator implementation. This should be
// changed to be more narrow only if the assignment operator of the base
// {Object} or {HeapObject} class was used, which we know to be safe.
props.SetEffect(1, VisitExpr(call->getArg(1), env).Define(var_name));
} else {
VisitArguments<>(call, &props, env);
}
if (!props.IsSafe()) ReportUnsafe(call, BAD_EXPR_MSG);
ExprEffect out = props.ComputeCumulativeEffect(
RepresentsRawPointerType(call->getType()));
clang::FunctionDecl* callee = call->getDirectCallee();
if (callee != NULL) {
if (KnownToCauseGC(ctx_, callee)) {
out.setGC();
}
// Support for virtual methods that might be GC suspects.
clang::CXXMethodDecl* method =
llvm::dyn_cast_or_null<clang::CXXMethodDecl>(callee);
if (method != NULL && method->isVirtual()) {
clang::CXXMemberCallExpr* memcall =
llvm::dyn_cast_or_null<clang::CXXMemberCallExpr>(call);
if (memcall != NULL) {
clang::CXXMethodDecl* target = method->getDevirtualizedMethod(
memcall->getImplicitObjectArgument(), false);
if (target != NULL) {
if (KnownToCauseGC(ctx_, target)) {
out.setGC();
}
} else {
// According to the documentation, {getDevirtualizedMethod} might
// return NULL, in which case we still want to use the partial
// match of the {method}'s name against the GC suspects in order
// to increase coverage.
if (SuspectedToCauseGC(ctx_, method)) {
out.setGC();
}
}
}
}
}
return out;
}
// --------------------------------------------------------------------------
// Statements
// --------------------------------------------------------------------------
Environment VisitStmt(clang::Stmt* stmt, const Environment& env) {
#define VISIT(type) \
do { \
clang::type* concrete_stmt = llvm::dyn_cast_or_null<clang::type>(stmt); \
if (concrete_stmt != NULL) { \
return Visit##type(concrete_stmt, env); \
} \
} while (0);
if (clang::Expr* expr = llvm::dyn_cast_or_null<clang::Expr>(stmt)) {
return env.ApplyEffect(VisitExpr(expr, env));
}
VISIT(AsmStmt);
VISIT(BreakStmt);
VISIT(CompoundStmt);
VISIT(ContinueStmt);
VISIT(CXXCatchStmt);
VISIT(CXXTryStmt);
VISIT(DeclStmt);
VISIT(DoStmt);
VISIT(ForStmt);
VISIT(GotoStmt);
VISIT(IfStmt);
VISIT(IndirectGotoStmt);
VISIT(LabelStmt);
VISIT(NullStmt);
VISIT(ReturnStmt);
VISIT(CaseStmt);
VISIT(DefaultStmt);
VISIT(SwitchStmt);
VISIT(WhileStmt);
#undef VISIT
return env;
}
#define DECL_VISIT_STMT(type) \
Environment Visit##type (clang::type* stmt, const Environment& env)
#define IGNORE_STMT(type) \
Environment Visit##type (clang::type* stmt, const Environment& env) { \
return env; \
}
IGNORE_STMT(IndirectGotoStmt);
IGNORE_STMT(NullStmt);
IGNORE_STMT(AsmStmt);
// We are ignoring control flow for simplicity.
IGNORE_STMT(GotoStmt);
IGNORE_STMT(LabelStmt);
// We are ignoring try/catch because V8 does not use them.
IGNORE_STMT(CXXCatchStmt);
IGNORE_STMT(CXXTryStmt);
class Block {
public:
Block(const Environment& in,
FunctionAnalyzer* owner)
: in_(in),
out_(Environment::Unreachable()),
changed_(false),
owner_(owner) {
parent_ = owner_->EnterBlock(this);
}
~Block() {
owner_->LeaveBlock(parent_);
}
void MergeIn(const Environment& env) {
Environment old_in = in_;
in_ = Environment::Merge(in_, env);
changed_ = !old_in.Equal(in_);
}
bool changed() {
if (changed_) {
changed_ = false;
return true;
}
return false;
}
const Environment& in() {
return in_;
}
const Environment& out() {
return out_;
}
void MergeOut(const Environment& env) {
out_ = Environment::Merge(out_, env);
}
void Sequential(clang::Stmt* a, clang::Stmt* b, clang::Stmt* c) {
Environment a_out = owner_->VisitStmt(a, in());
Environment b_out = owner_->VisitStmt(b, a_out);
Environment c_out = owner_->VisitStmt(c, b_out);
MergeOut(c_out);
}
void Sequential(clang::Stmt* a, clang::Stmt* b) {
Environment a_out = owner_->VisitStmt(a, in());
Environment b_out = owner_->VisitStmt(b, a_out);
MergeOut(b_out);
}
void Loop(clang::Stmt* a, clang::Stmt* b, clang::Stmt* c) {
Sequential(a, b, c);
MergeIn(out());
}
void Loop(clang::Stmt* a, clang::Stmt* b) {
Sequential(a, b);
MergeIn(out());
}
private:
Environment in_;
Environment out_;
bool changed_;
FunctionAnalyzer* owner_;
Block* parent_;
};
DECL_VISIT_STMT(BreakStmt) {
block_->MergeOut(env);
return Environment::Unreachable();
}
DECL_VISIT_STMT(ContinueStmt) {
block_->MergeIn(env);
return Environment::Unreachable();
}
DECL_VISIT_STMT(CompoundStmt) {
scopes_.push_back(GCGuard(stmt, false));
Environment out = env;
clang::CompoundStmt::body_iterator end = stmt->body_end();
for (clang::CompoundStmt::body_iterator s = stmt->body_begin();
s != end;
++s) {
out = VisitStmt(*s, out);
}
scopes_.pop_back();
return out;
}
DECL_VISIT_STMT(WhileStmt) {
Block block (env, this);
do {
block.Loop(stmt->getCond(), stmt->getBody());
} while (block.changed());
return block.out();
}
DECL_VISIT_STMT(DoStmt) {
Block block (env, this);
do {
block.Loop(stmt->getBody(), stmt->getCond());
} while (block.changed());
return block.out();
}
DECL_VISIT_STMT(ForStmt) {
Block block (VisitStmt(stmt->getInit(), env), this);
do {
block.Loop(stmt->getCond(),
stmt->getBody(),
stmt->getInc());
} while (block.changed());
return block.out();
}
DECL_VISIT_STMT(IfStmt) {
Environment cond_out = VisitStmt(stmt->getCond(), env);
Environment then_out = VisitStmt(stmt->getThen(), cond_out);
Environment else_out = VisitStmt(stmt->getElse(), cond_out);
return Environment::Merge(then_out, else_out);
}
DECL_VISIT_STMT(SwitchStmt) {
Block block (env, this);
block.Sequential(stmt->getCond(), stmt->getBody());
return block.out();
}
DECL_VISIT_STMT(CaseStmt) {
Environment in = Environment::Merge(env, block_->in());
Environment after_lhs = VisitStmt(stmt->getLHS(), in);
return VisitStmt(stmt->getSubStmt(), after_lhs);
}
DECL_VISIT_STMT(DefaultStmt) {
Environment in = Environment::Merge(env, block_->in());
return VisitStmt(stmt->getSubStmt(), in);
}
DECL_VISIT_STMT(ReturnStmt) {
VisitExpr(stmt->getRetValue(), env);
return Environment::Unreachable();
}
const clang::TagType* ToTagType(const clang::Type* t) {
if (t == NULL) {
return NULL;
} else if (llvm::isa<clang::TagType>(t)) {
return llvm::cast<clang::TagType>(t);
} else if (llvm::isa<clang::SubstTemplateTypeParmType>(t)) {
return ToTagType(llvm::cast<clang::SubstTemplateTypeParmType>(t)
->getReplacementType()
.getTypePtr());
} else {
return NULL;
}
}
bool IsDerivedFrom(const clang::CXXRecordDecl* record,
const clang::CXXRecordDecl* base) {
return (record == base) || record->isDerivedFrom(base);
}
const clang::CXXRecordDecl* GetDefinitionOrNull(
const clang::CXXRecordDecl* record) {
if (record == NULL) {
return NULL;
}
if (!InV8Namespace(record)) return NULL;
if (!record->hasDefinition()) {
return NULL;
}
return record->getDefinition();
}
bool IsDerivedFromInternalPointer(const clang::CXXRecordDecl* record) {
const clang::CXXRecordDecl* definition = GetDefinitionOrNull(record);
if (!definition) {
return false;
}
bool result = (IsDerivedFrom(record, object_decl_) &&
!IsDerivedFrom(record, smi_decl_)) ||
IsDerivedFrom(record, maybe_object_decl_);
return result;
}
bool IsRawPointerType(const clang::PointerType* type) {
const clang::CXXRecordDecl* record = type->getPointeeCXXRecordDecl();
bool result = IsDerivedFromInternalPointer(record);
TRACE("is raw " << result << " " << record->getNameAsString());
return result;
}
bool IsInternalPointerType(clang::QualType qtype) {
const clang::CXXRecordDecl* record = qtype->getAsCXXRecordDecl();
bool result = IsDerivedFromInternalPointer(record);
TRACE_LLVM_TYPE("is internal " << result, qtype);
return result;
}
// Returns weather the given type is a raw pointer or a wrapper around
// such. For V8 that means Object and MaybeObject instances.
bool RepresentsRawPointerType(clang::QualType qtype) {
// Not yet assigned pointers can't get moved by the GC.
if (qtype.isNull()) {
return false;
}
// nullptr can't get moved by the GC.
if (qtype->isNullPtrType()) {
return false;
}
const clang::PointerType* pointer_type =
llvm::dyn_cast_or_null<clang::PointerType>(qtype.getTypePtrOrNull());
if (pointer_type != NULL) {
return IsRawPointerType(pointer_type);
} else {
return IsInternalPointerType(qtype);
}
}
bool IsGCGuard(clang::QualType qtype) {
if (qtype.isNull()) {
return false;
}
if (qtype->isNullPtrType()) {
return false;
}
const clang::CXXRecordDecl* record = qtype->getAsCXXRecordDecl();
const clang::CXXRecordDecl* definition = GetDefinitionOrNull(record);
if (!definition) {
return false;
}
return (no_gc_decl_ && IsDerivedFrom(definition, no_gc_decl_)) ||
(no_gc_or_safepoint_decl_ &&
IsDerivedFrom(definition, no_gc_or_safepoint_decl_)) ||
(no_heap_access_decl_ &&
IsDerivedFrom(definition, no_heap_access_decl_));
}
Environment VisitDecl(clang::Decl* decl, Environment& env) {
if (clang::VarDecl* var = llvm::dyn_cast<clang::VarDecl>(decl)) {
Environment out = var->hasInit() ? VisitStmt(var->getInit(), env) : env;
if (RepresentsRawPointerType(var->getType())) {
out = out.Define(var->getNameAsString());
}
if (IsGCGuard(var->getType())) {
scopes_.back().has_guard = true;
}
return out;
}
// TODO(gcmole): handle other declarations?
return env;
}
DECL_VISIT_STMT(DeclStmt) {
Environment out = env;
clang::DeclStmt::decl_iterator end = stmt->decl_end();
for (clang::DeclStmt::decl_iterator decl = stmt->decl_begin();
decl != end;
++decl) {
out = VisitDecl(*decl, out);
}
return out;
}
void DefineParameters(const clang::FunctionDecl* f,
Environment* env) {
env->MDefine(THIS);
clang::FunctionDecl::param_const_iterator end = f->param_end();
for (clang::FunctionDecl::param_const_iterator p = f->param_begin();
p != end;
++p) {
env->MDefine((*p)->getNameAsString());
}
}
void AnalyzeFunction(const clang::FunctionDecl* f) {
const clang::FunctionDecl* body = NULL;
if (f->hasBody(body)) {
Environment env;
DefineParameters(body, &env);
VisitStmt(body->getBody(), env);
Environment::ClearSymbolTable();
}
}
Block* EnterBlock(Block* block) {
Block* parent = block_;
block_ = block;
return parent;
}
void LeaveBlock(Block* block) {
block_ = block;
}
bool HasActiveGuard() {
for (auto s : scopes_) {
if (s.has_guard) return true;
}
return false;
}
private:
void ReportUnsafe(const clang::Expr* expr, const std::string& msg) {
d_.Report(clang::FullSourceLoc(expr->getExprLoc(), sm_),
d_.getCustomDiagID(clang::DiagnosticsEngine::Warning, "%0"))
<< msg;
}
clang::MangleContext* ctx_;
clang::CXXRecordDecl* object_decl_;
clang::CXXRecordDecl* maybe_object_decl_;
clang::CXXRecordDecl* smi_decl_;
clang::CXXRecordDecl* no_gc_decl_;
clang::CXXRecordDecl* no_gc_or_safepoint_decl_;
clang::CXXRecordDecl* no_heap_access_decl_;
clang::DiagnosticsEngine& d_;
clang::SourceManager& sm_;
Block* block_;
struct GCGuard {
clang::CompoundStmt* stmt = NULL;
bool has_guard = false;
GCGuard(clang::CompoundStmt* stmt_, bool has_guard_)
: stmt(stmt_), has_guard(has_guard_) {}
};
std::vector<GCGuard> scopes_;
};
class ProblemsFinder : public clang::ASTConsumer,
public clang::RecursiveASTVisitor<ProblemsFinder> {
public:
ProblemsFinder(clang::DiagnosticsEngine& d, clang::SourceManager& sm,
const std::vector<std::string>& args)
: d_(d), sm_(sm) {
for (unsigned i = 0; i < args.size(); ++i) {
if (args[i] == "--dead-vars") {
g_dead_vars_analysis = true;
}
if (args[i] == "--verbose") {
g_tracing_enabled = true;
}
}
}
bool TranslationUnitIgnored() {
if (!ignored_files_loaded_) {
std::ifstream fin("tools/gcmole/ignored_files");
std::string s;
while (fin >> s) ignored_files_.insert(s);
ignored_files_loaded_ = true;
}
clang::FileID main_file_id = sm_.getMainFileID();
std::string filename = sm_.getFileEntryForID(main_file_id)->getName().str();
bool result = ignored_files_.find(filename) != ignored_files_.end();
if (result) {
llvm::outs() << "Ignoring file " << filename << "\n";
}
return result;
}
virtual void HandleTranslationUnit(clang::ASTContext &ctx) {
if (TranslationUnitIgnored()) {
return;
}
Resolver r(ctx);
// It is a valid situation that no_gc_decl == NULL when the
// DisallowHeapAllocation is not included and can't be resolved.
// This is gracefully handled in the FunctionAnalyzer later.
clang::CXXRecordDecl* no_gc_decl =
r.ResolveNamespace("v8")
.ResolveNamespace("internal")
.ResolveTemplate("DisallowHeapAllocation");
clang::CXXRecordDecl* no_gc_or_safepoint_decl =
r.ResolveNamespace("v8")
.ResolveNamespace("internal")
.ResolveTemplate("DisallowGarbageCollection");
clang::CXXRecordDecl* no_heap_access_decl =
r.ResolveNamespace("v8")
.ResolveNamespace("internal")
.Resolve<clang::CXXRecordDecl>("DisallowHeapAccess");
clang::CXXRecordDecl* object_decl =
r.ResolveNamespace("v8").ResolveNamespace("internal").
Resolve<clang::CXXRecordDecl>("Object");
clang::CXXRecordDecl* maybe_object_decl =
r.ResolveNamespace("v8")
.ResolveNamespace("internal")
.Resolve<clang::CXXRecordDecl>("MaybeObject");
clang::CXXRecordDecl* smi_decl =
r.ResolveNamespace("v8").ResolveNamespace("internal").
Resolve<clang::CXXRecordDecl>("Smi");
if (object_decl != NULL) object_decl = object_decl->getDefinition();
if (maybe_object_decl != NULL)
maybe_object_decl = maybe_object_decl->getDefinition();
if (smi_decl != NULL) smi_decl = smi_decl->getDefinition();
if (no_heap_access_decl != NULL)
no_heap_access_decl = no_heap_access_decl->getDefinition();
if (object_decl != NULL && smi_decl != NULL && maybe_object_decl != NULL) {
function_analyzer_ = new FunctionAnalyzer(
clang::ItaniumMangleContext::create(ctx, d_), object_decl,
maybe_object_decl, smi_decl, no_gc_decl, no_gc_or_safepoint_decl,
no_heap_access_decl, d_, sm_);
TraverseDecl(ctx.getTranslationUnitDecl());
} else {
if (object_decl == NULL) {
llvm::errs() << "Failed to resolve v8::internal::Object\n";
}
if (maybe_object_decl == NULL) {
llvm::errs() << "Failed to resolve v8::internal::MaybeObject\n";
}
if (smi_decl == NULL) {
llvm::errs() << "Failed to resolve v8::internal::Smi\n";
}
}
}
virtual bool VisitFunctionDecl(clang::FunctionDecl* decl) {
// Don't print tracing from includes, otherwise the output is too big.
bool tracing = g_tracing_enabled;
const auto& fileID = sm_.getFileID(decl->getLocation());
if (fileID != sm_.getMainFileID()) {
g_tracing_enabled = false;
}
TRACE("Visiting function " << decl->getNameAsString());
function_analyzer_->AnalyzeFunction(decl);
g_tracing_enabled = tracing;
return true;
}
private:
clang::DiagnosticsEngine& d_;
clang::SourceManager& sm_;
bool ignored_files_loaded_ = false;
std::set<std::string> ignored_files_;
FunctionAnalyzer* function_analyzer_;
};
template<typename ConsumerType>
class Action : public clang::PluginASTAction {
protected:
virtual std::unique_ptr<clang::ASTConsumer> CreateASTConsumer(
clang::CompilerInstance& CI, llvm::StringRef InFile) {
return std::unique_ptr<clang::ASTConsumer>(
new ConsumerType(CI.getDiagnostics(), CI.getSourceManager(), args_));
}
bool ParseArgs(const clang::CompilerInstance &CI,
const std::vector<std::string>& args) {
args_ = args;
return true;
}
void PrintHelp(llvm::raw_ostream& ros) {
}
private:
std::vector<std::string> args_;
};
}
static clang::FrontendPluginRegistry::Add<Action<ProblemsFinder> >
FindProblems("find-problems", "Find GC-unsafe places.");
static clang::FrontendPluginRegistry::Add<
Action<FunctionDeclarationFinder> >
DumpCallees("dump-callees", "Dump callees for each function.");
#undef TRACE
#undef TRACE_LLVM_TYPE
#undef TRACE_LLVM_DECL
#undef DECL_VISIT_EXPR
#undef IGNORE_EXPR
#undef DECL_VISIT_STMT
#undef IGNORE_STMT
| {
"pile_set_name": "Github"
} |
import { SummaryPosition } from './summary';
export interface Dimension {
offsetLeft: number;
offsetTop: number;
width: number;
autoWidth: boolean;
bodyHeight: number;
autoHeight: boolean;
minBodyHeight: number;
fitToParentHeight: boolean;
heightResizable: boolean;
rowHeight: number;
minRowHeight: number;
autoRowHeight: boolean;
headerHeight: number;
summaryPosition: SummaryPosition;
summaryHeight: number;
scrollbarWidth: number;
tableBorderWidth: number;
cellBorderWidth: number;
scrollX: boolean;
scrollY: boolean;
readonly contentsWidth: number;
readonly frozenBorderWidth: number;
readonly scrollXHeight: number;
readonly scrollYWidth: number;
}
| {
"pile_set_name": "Github"
} |
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
<component name="ProjectModuleManager">
<modules>
<module fileurl="file://$PROJECT_DIR$/.idea/less.js.iml" filepath="$PROJECT_DIR$/.idea/less.js.iml" />
</modules>
</component>
</project>
| {
"pile_set_name": "Github"
} |
/**
* Copyright (C) 2010-2014 Leon Blakey <lord.quackstar at gmail.com>
*
* This file is part of PircBotX.
*
* PircBotX is free software: you can redistribute it and/or modify it under the
* terms of the GNU General Public License as published by the Free Software
* Foundation, either version 3 of the License, or (at your option) any later
* version.
*
* PircBotX 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
* PircBotX. If not, see <http://www.gnu.org/licenses/>.
*/
package org.pircbotx.dcc;
import java.util.concurrent.TimeUnit;
import org.pircbotx.exception.DccException;
import lombok.Getter;
import lombok.extern.slf4j.Slf4j;
/**
* Information about a file transfer This is kept in sync by the instances of
* SendFileTransfer and ReceiveFileTransfer
*
* @author Rob
*/
@Slf4j
public class FileTransferStatus extends Thread {
@Getter
protected DccState dccState = DccState.INIT;
@Getter
protected long startPosition = 0;
@Getter
protected long fileSize = 0;
@Getter
protected long bytesTransfered = 0;
@Getter
protected long bytesAcknowledged = 0;
@Getter
protected long bytesPerSecond = 0;
@Getter
protected long averageBytesPerSecond = 0;
@Getter
protected DccException exception;
public FileTransferStatus(long fileSize, long startPosition) {
this.fileSize = fileSize;
this.startPosition = startPosition;
}
/**
* Is the transfer finished?
*
* @return True if its finished
*/
public boolean isFinished() {
return (dccState == DccState.DONE || dccState == DccState.ERROR);
}
/**
* Was the transfer successful
*
* @return True if done and bytes acknowledged match file size
*/
public boolean isSuccessful() {
return (dccState == DccState.DONE && bytesAcknowledged == fileSize);
}
/**
* Get percentage of file transfer. This is calculated based on the bytes
* received by the transfer requester
*
* @return integer
*/
public double getPercentageComplete() {
return (100 * ((double) bytesAcknowledged / fileSize));
}
@Override
public void run() {
int counter = 0;
long myBytesAcknowleged = startPosition;
long myBytesAveraged = 0;
long myBytesPerSecond = 0;
while (dccState == DccState.RUNNING) {
try {
TimeUnit.SECONDS.sleep(1);
} catch (InterruptedException e) {
log.error("Speed calculation has interrupted?", e);
}
bytesPerSecond = bytesAcknowledged - myBytesAcknowleged;
if (bytesPerSecond < 0) {
continue;
}
myBytesPerSecond = bytesPerSecond;
// Attempt to make this a smooth average. Is there some calculus way to do this?
myBytesAveraged = (myBytesPerSecond + myBytesAveraged) / 2;
counter++;
if (counter >= 3) {
averageBytesPerSecond = (myBytesAveraged + averageBytesPerSecond) / 2;
counter = 0;
}
myBytesAcknowleged = bytesAcknowledged;
}
}
}
| {
"pile_set_name": "Github"
} |
package io.noties.markwon.editor.handler;
import android.text.Editable;
import android.text.Spanned;
import androidx.annotation.NonNull;
import io.noties.markwon.core.spans.EmphasisSpan;
import io.noties.markwon.editor.AbstractEditHandler;
import io.noties.markwon.editor.MarkwonEditorUtils;
import io.noties.markwon.editor.PersistedSpans;
/**
* @since 4.2.0
*/
public class EmphasisEditHandler extends AbstractEditHandler<EmphasisSpan> {
@Override
public void configurePersistedSpans(@NonNull PersistedSpans.Builder builder) {
builder.persistSpan(EmphasisSpan.class, new PersistedSpans.SpanFactory<EmphasisSpan>() {
@NonNull
@Override
public EmphasisSpan create() {
return new EmphasisSpan();
}
});
}
@Override
public void handleMarkdownSpan(
@NonNull PersistedSpans persistedSpans,
@NonNull Editable editable,
@NonNull String input,
@NonNull EmphasisSpan span,
int spanStart,
int spanTextLength) {
final MarkwonEditorUtils.Match match =
MarkwonEditorUtils.findDelimited(input, spanStart, "*", "_");
if (match != null) {
editable.setSpan(
persistedSpans.get(EmphasisSpan.class),
match.start(),
match.end(),
Spanned.SPAN_EXCLUSIVE_EXCLUSIVE
);
}
}
@NonNull
@Override
public Class<EmphasisSpan> markdownSpanType() {
return EmphasisSpan.class;
}
}
| {
"pile_set_name": "Github"
} |
/**
* @ngdoc service
* @name ngCordovaMocks.cordovaCamera
*
* @description
* A service for testing camera features
* in an app build with ngCordova.
**/
ngCordovaMocks.factory('$cordovaCamera', ['$q', function ($q) {
var throwsError = false;
var imageData = '';
return {
/**
* @ngdoc property
* @name throwsError
* @propertyOf ngCordovaMocks.cordovaCamera
*
* @description
* A flag that signals whether a promise should be rejected or not.
* This property should only be used in automated tests.
**/
throwsError: throwsError,
/**
* @ngdoc property
* @name imageData
* @propertyOf ngCordovaMocks.cordovaCamera
*
* @description
* The imagedata (e.g. an url) which will be returned from the device.
* This property should only be used in automated tests.
**/
imageData: imageData,
getPicture: function (options) {
var defer = $q.defer();
if (this.throwsError) {
defer.reject('There was an error getting the picture.');
} else {
if (options) {
options = options; // This is just to get by JSHint.
}
defer.resolve(this.imageData);
}
return defer.promise;
}
};
}]);
| {
"pile_set_name": "Github"
} |
get_filename_component(_DIR "${CMAKE_CURRENT_LIST_FILE}" PATH)
if(NOT LIBGO_FIND_COMPONENTS)
set(LIBGO_FIND_COMPONENTS libgo libgo)
if(LIBGO_FIND_REQUIRED)
set(LIBGO_FIND_REQUIRED_libgo TRUE)
endif()
set(LIBGO_FOUND TRUE)
endif()
set(LIBGO_INCLUDE_DIRS ${_DIR}/../../include)
set(LIBGO_LIBRARIES)
if (EXISTS ${_DIR}/../../lib/liblibgo.a)
list(APPEND LIBGO_LIBRARIES optimized ${_DIR}/../../lib/liblibgo.a)
endif()
if (EXISTS ${_DIR}/../../debug/lib/liblibgo.a)
list(APPEND LIBGO_LIBRARIES debug ${_DIR}/../../debug/lib/liblibgo.a)
endif()
if (EXISTS ${_DIR}/../../lib/libgo.lib)
list(APPEND LIBGO_LIBRARIES optimized ${_DIR}/../../lib/libgo.lib)
endif()
if (EXISTS ${_DIR}/../../debug/lib/libgo.lib)
list(APPEND LIBGO_LIBRARIES debug ${_DIR}/../../debug/lib/libgo.lib)
endif()
| {
"pile_set_name": "Github"
} |
from __future__ import unicode_literals
import re
import frappe
import psycopg2
import psycopg2.extensions
from six import string_types
from frappe.utils import cstr
from psycopg2.extensions import ISOLATION_LEVEL_AUTOCOMMIT
from frappe.database.database import Database
from frappe.database.postgres.schema import PostgresTable
# cast decimals as floats
DEC2FLOAT = psycopg2.extensions.new_type(
psycopg2.extensions.DECIMAL.values,
'DEC2FLOAT',
lambda value, curs: float(value) if value is not None else None)
psycopg2.extensions.register_type(DEC2FLOAT)
class PostgresDatabase(Database):
ProgrammingError = psycopg2.ProgrammingError
TableMissingError = psycopg2.ProgrammingError
OperationalError = psycopg2.OperationalError
InternalError = psycopg2.InternalError
SQLError = psycopg2.ProgrammingError
DataError = psycopg2.DataError
InterfaceError = psycopg2.InterfaceError
REGEX_CHARACTER = '~'
def setup_type_map(self):
self.db_type = 'postgres'
self.type_map = {
'Currency': ('decimal', '18,6'),
'Int': ('bigint', None),
'Long Int': ('bigint', None),
'Float': ('decimal', '18,6'),
'Percent': ('decimal', '18,6'),
'Check': ('smallint', None),
'Small Text': ('text', ''),
'Long Text': ('text', ''),
'Code': ('text', ''),
'Text Editor': ('text', ''),
'Markdown Editor': ('text', ''),
'HTML Editor': ('text', ''),
'Date': ('date', ''),
'Datetime': ('timestamp', None),
'Time': ('time', '6'),
'Text': ('text', ''),
'Data': ('varchar', self.VARCHAR_LEN),
'Link': ('varchar', self.VARCHAR_LEN),
'Dynamic Link': ('varchar', self.VARCHAR_LEN),
'Password': ('text', ''),
'Select': ('varchar', self.VARCHAR_LEN),
'Rating': ('smallint', None),
'Read Only': ('varchar', self.VARCHAR_LEN),
'Attach': ('text', ''),
'Attach Image': ('text', ''),
'Signature': ('text', ''),
'Color': ('varchar', self.VARCHAR_LEN),
'Barcode': ('text', ''),
'Geolocation': ('text', ''),
'Duration': ('decimal', '18,6')
}
def get_connection(self):
# warnings.filterwarnings('ignore', category=psycopg2.Warning)
conn = psycopg2.connect("host='{}' dbname='{}' user='{}' password='{}' port={}".format(
self.host, self.user, self.user, self.password, self.port
))
conn.set_isolation_level(ISOLATION_LEVEL_AUTOCOMMIT) # TODO: Remove this
return conn
def escape(self, s, percent=True):
"""Excape quotes and percent in given string."""
if isinstance(s, bytes):
s = s.decode('utf-8')
if percent:
s = s.replace("%", "%%")
s = s.encode('utf-8')
return str(psycopg2.extensions.QuotedString(s))
def get_database_size(self):
''''Returns database size in MB'''
db_size = self.sql("SELECT (pg_database_size(%s) / 1024 / 1024) as database_size",
self.db_name, as_dict=True)
return db_size[0].get('database_size')
# pylint: disable=W0221
def sql(self, *args, **kwargs):
if args:
# since tuple is immutable
args = list(args)
args[0] = modify_query(args[0])
args = tuple(args)
elif kwargs.get('query'):
kwargs['query'] = modify_query(kwargs.get('query'))
return super(PostgresDatabase, self).sql(*args, **kwargs)
def get_tables(self):
return [d[0] for d in self.sql("""select table_name
from information_schema.tables
where table_catalog='{0}'
and table_type = 'BASE TABLE'
and table_schema='{1}'""".format(frappe.conf.db_name, frappe.conf.get("db_schema", "public")))]
def format_date(self, date):
if not date:
return '0001-01-01'
if not isinstance(date, frappe.string_types):
date = date.strftime('%Y-%m-%d')
return date
# column type
@staticmethod
def is_type_number(code):
return code == psycopg2.NUMBER
@staticmethod
def is_type_datetime(code):
return code == psycopg2.DATETIME
# exception type
@staticmethod
def is_deadlocked(e):
return e.pgcode == '40P01'
@staticmethod
def is_timedout(e):
# http://initd.org/psycopg/docs/extensions.html?highlight=datatype#psycopg2.extensions.QueryCanceledError
return isinstance(e, psycopg2.extensions.QueryCanceledError)
@staticmethod
def is_table_missing(e):
return e.pgcode == '42P01'
@staticmethod
def is_missing_column(e):
return e.pgcode == '42703'
@staticmethod
def is_access_denied(e):
return e.pgcode == '42501'
@staticmethod
def cant_drop_field_or_key(e):
return e.pgcode.startswith('23')
@staticmethod
def is_duplicate_entry(e):
return e.pgcode == '23505'
@staticmethod
def is_primary_key_violation(e):
return e.pgcode == '23505' and '_pkey' in cstr(e.args[0])
@staticmethod
def is_unique_key_violation(e):
return e.pgcode == '23505' and '_key' in cstr(e.args[0])
@staticmethod
def is_duplicate_fieldname(e):
return e.pgcode == '42701'
@staticmethod
def is_data_too_long(e):
return e.pgcode == '22001'
def create_auth_table(self):
self.sql_ddl("""create table if not exists "__Auth" (
"doctype" VARCHAR(140) NOT NULL,
"name" VARCHAR(255) NOT NULL,
"fieldname" VARCHAR(140) NOT NULL,
"password" TEXT NOT NULL,
"encrypted" INT NOT NULL DEFAULT 0,
PRIMARY KEY ("doctype", "name", "fieldname")
)""")
def create_global_search_table(self):
if not '__global_search' in self.get_tables():
self.sql('''create table "__global_search"(
doctype varchar(100),
name varchar({0}),
title varchar({0}),
content text,
route varchar({0}),
published int not null default 0,
unique (doctype, name))'''.format(self.VARCHAR_LEN))
def create_user_settings_table(self):
self.sql_ddl("""create table if not exists "__UserSettings" (
"user" VARCHAR(180) NOT NULL,
"doctype" VARCHAR(180) NOT NULL,
"data" TEXT,
UNIQUE ("user", "doctype")
)""")
def create_help_table(self):
self.sql('''CREATE TABLE "help"(
"path" varchar(255),
"content" text,
"title" text,
"intro" text,
"full_path" text)''')
self.sql('''CREATE INDEX IF NOT EXISTS "help_index" ON "help" ("path")''')
def updatedb(self, doctype, meta=None):
"""
Syncs a `DocType` to the table
* creates if required
* updates columns
* updates indices
"""
res = self.sql("select issingle from `tabDocType` where name='{}'".format(doctype))
if not res:
raise Exception('Wrong doctype {0} in updatedb'.format(doctype))
if not res[0][0]:
db_table = PostgresTable(doctype, meta)
db_table.validate()
self.commit()
db_table.sync()
self.begin()
@staticmethod
def get_on_duplicate_update(key='name'):
if isinstance(key, list):
key = '", "'.join(key)
return 'ON CONFLICT ("{key}") DO UPDATE SET '.format(
key=key
)
def check_transaction_status(self, query):
pass
def has_index(self, table_name, index_name):
return self.sql("""SELECT 1 FROM pg_indexes WHERE tablename='{table_name}'
and indexname='{index_name}' limit 1""".format(table_name=table_name, index_name=index_name))
def add_index(self, doctype, fields, index_name=None):
"""Creates an index with given fields if not already created.
Index name will be `fieldname1_fieldname2_index`"""
index_name = index_name or self.get_index_name(fields)
table_name = 'tab' + doctype
self.commit()
self.sql("""CREATE INDEX IF NOT EXISTS "{}" ON `{}`("{}")""".format(index_name, table_name, '", "'.join(fields)))
def add_unique(self, doctype, fields, constraint_name=None):
if isinstance(fields, string_types):
fields = [fields]
if not constraint_name:
constraint_name = "unique_" + "_".join(fields)
if not self.sql("""
SELECT CONSTRAINT_NAME
FROM information_schema.TABLE_CONSTRAINTS
WHERE table_name=%s
AND constraint_type='UNIQUE'
AND CONSTRAINT_NAME=%s""",
('tab' + doctype, constraint_name)):
self.commit()
self.sql("""ALTER TABLE `tab%s`
ADD CONSTRAINT %s UNIQUE (%s)""" % (doctype, constraint_name, ", ".join(fields)))
def get_table_columns_description(self, table_name):
"""Returns list of column and its description"""
# pylint: disable=W1401
return self.sql('''
SELECT a.column_name AS name,
CASE LOWER(a.data_type)
WHEN 'character varying' THEN CONCAT('varchar(', a.character_maximum_length ,')')
WHEN 'timestamp without time zone' THEN 'timestamp'
ELSE a.data_type
END AS type,
COUNT(b.indexdef) AS Index,
SPLIT_PART(COALESCE(a.column_default, NULL), '::', 1) AS default,
BOOL_OR(b.unique) AS unique
FROM information_schema.columns a
LEFT JOIN
(SELECT indexdef, tablename, indexdef LIKE '%UNIQUE INDEX%' AS unique
FROM pg_indexes
WHERE tablename='{table_name}') b
ON SUBSTRING(b.indexdef, '\(.*\)') LIKE CONCAT('%', a.column_name, '%')
WHERE a.table_name = '{table_name}'
GROUP BY a.column_name, a.data_type, a.column_default, a.character_maximum_length;'''
.format(table_name=table_name), as_dict=1)
def get_database_list(self, target):
return [d[0] for d in self.sql("SELECT datname FROM pg_database;")]
def modify_query(query):
""""Modifies query according to the requirements of postgres"""
# replace ` with " for definitions
query = query.replace('`', '"')
query = replace_locate_with_strpos(query)
# select from requires ""
if re.search('from tab', query, flags=re.IGNORECASE):
query = re.sub('from tab([a-zA-Z]*)', r'from "tab\1"', query, flags=re.IGNORECASE)
return query
def replace_locate_with_strpos(query):
# strpos is the locate equivalent in postgres
if re.search(r'locate\(', query, flags=re.IGNORECASE):
query = re.sub(r'locate\(([^,]+),([^)]+)\)', r'strpos(\2, \1)', query, flags=re.IGNORECASE)
return query
| {
"pile_set_name": "Github"
} |
/*
* Pixel Dungeon
* Copyright (C) 2012-2014 Oleg Dolya
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>
*/
package com.watabou.pixeldungeon.items.potions;
import com.nyrds.pixeldungeon.ml.R;
import com.watabou.noosa.Game;
import com.watabou.pixeldungeon.actors.Char;
import com.watabou.pixeldungeon.actors.buffs.Buff;
import com.watabou.pixeldungeon.actors.buffs.MindVision;
public class PotionOfMindVision extends UpgradablePotion {
{
labelIndex = 10;
}
@Override
protected void apply(Char hero ) {
setKnown();
Buff.affect( hero, MindVision.class, (float) (MindVision.DURATION * qualityFactor()));
MindVision.reportMindVisionEffect();
}
@Override
public String desc() {
return Game.getVar(R.string.PotionOfMindVision_Info);
}
@Override
public int basePrice() {
return 35;
}
}
| {
"pile_set_name": "Github"
} |
/***********************************************************************
*
* Copyright (c) 2012-2020 Barbara Geller
* Copyright (c) 2012-2020 Ansel Sermersheim
*
* Copyright (c) 2015 The Qt Company Ltd.
* Copyright (c) 2012-2016 Digia Plc and/or its subsidiary(-ies).
* Copyright (c) 2008-2012 Nokia Corporation and/or its subsidiary(-ies).
*
* This file is part of CopperSpice.
*
* CopperSpice is free software. You can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public License
* version 2.1 as published by the Free Software Foundation.
*
* CopperSpice 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.
*
* https://www.gnu.org/licenses/
*
***********************************************************************/
#include "qanyuri_p.h"
#include "qboolean_p.h"
#include "qbuiltintypes_p.h"
#include "qcommonvalues_p.h"
#include "qliteral_p.h"
#include "qitem_p.h"
#include "qqnamevalue_p.h"
#include "qatomicstring_p.h"
#include "qaccessorfns_p.h"
QT_BEGIN_NAMESPACE
using namespace QPatternist;
Item NodeNameFN::evaluateSingleton(const DynamicContext::Ptr &context) const
{
const Item item(m_operands.first()->evaluateSingleton(context));
if (item) {
const QXmlName name(item.asNode().name());
if (name.isNull()) {
return Item();
} else {
return toItem(QNameValue::fromValue(context->namePool(), name));
}
} else {
return Item();
}
}
Item NilledFN::evaluateSingleton(const DynamicContext::Ptr &context) const
{
const Item item(m_operands.first()->evaluateSingleton(context));
if (item && item.asNode().kind() == QXmlNodeModelIndex::Element) {
/* We have no access to the PSVI -- always return false. */
return CommonValues::BooleanFalse;
} else {
return Item();
}
}
Item StringFN::evaluateSingleton(const DynamicContext::Ptr &context) const
{
const Item item(m_operands.first()->evaluateSingleton(context));
if (item) {
return AtomicString::fromValue(item.stringValue());
} else {
return CommonValues::EmptyString;
}
}
Expression::Ptr StringFN::typeCheck(const StaticContext::Ptr &context, const SequenceType::Ptr &reqType)
{
const Expression::Ptr me(FunctionCall::typeCheck(context, reqType));
if (me != this) {
return me;
}
if (BuiltinTypes::xsString->xdtTypeMatches(m_operands.first()->staticType()->itemType())) {
return m_operands.first(); /* No need for string(), it's already a string. */
} else {
return me;
}
}
Item BaseURIFN::evaluateSingleton(const DynamicContext::Ptr &context) const
{
const Item node(m_operands.first()->evaluateSingleton(context));
if (node) {
const QUrl base(node.asNode().baseUri());
if (base.isEmpty()) {
return Item();
} else if (base.isValid()) {
Q_ASSERT_X(!base.isRelative(), Q_FUNC_INFO,
"The base URI must be absolute.");
return toItem(AnyURI::fromValue(base));
} else {
return Item();
}
} else {
return Item();
}
}
Item DocumentURIFN::evaluateSingleton(const DynamicContext::Ptr &context) const
{
const Item node(m_operands.first()->evaluateSingleton(context));
if (node) {
const QUrl documentURI(node.asNode().documentUri());
if (documentURI.isValid()) {
if (documentURI.isEmpty()) {
return Item();
} else {
Q_ASSERT_X(!documentURI.isRelative(), Q_FUNC_INFO,
"The document URI must be absolute.");
return toItem(AnyURI::fromValue(documentURI));
}
} else {
return Item();
}
} else {
return Item();
}
}
QT_END_NAMESPACE
| {
"pile_set_name": "Github"
} |
<?php
/*
* This file is part of PhpSpec, A php toolset to drive emergent
* design by specification.
*
* (c) Marcello Duarte <[email protected]>
* (c) Konstantin Kudryashov <[email protected]>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace PhpSpec\Formatter\Presenter\Value;
interface StringTypePresenter extends TypePresenter
{
}
| {
"pile_set_name": "Github"
} |
{
"loader": "forge:obj",
"model": "immersiveengineering:models/block/blastfurnace_advanced.obj",
"flip-v": true,
"transform": {
"thirdperson_righthand": {
"translation": [
0.0,
0.0,
0.0
],
"rotation": [
0.16043,
-0.37686962,
-0.06645229,
0.9098437
],
"scale": [
0.25,
0.25,
0.25
],
"post-rotation": [
0.0,
0.0,
0.0,
1.0
],
"origin": "corner"
},
"thirdperson_lefthand": {
"translation": [
0.0,
0.0,
0.0
],
"rotation": [
0.16043,
-0.37686962,
-0.06645229,
0.9098437
],
"scale": [
0.25,
0.25,
0.25
],
"post-rotation": [
0.0,
0.0,
0.0,
1.0
],
"origin": "corner"
},
"firstperson_righthand": {
"translation": [
0.0,
0.0,
0.0
],
"rotation": [
0.16043,
-0.37686962,
-0.06645229,
0.9098437
],
"scale": [
0.25,
0.25,
0.25
],
"post-rotation": [
0.0,
0.0,
0.0,
1.0
],
"origin": "corner"
},
"firstperson_lefthand": {
"translation": [
0.0,
0.0,
0.0
],
"rotation": [
0.16043,
-0.37686962,
-0.06645229,
0.9098437
],
"scale": [
0.25,
0.25,
0.25
],
"post-rotation": [
0.0,
0.0,
0.0,
1.0
],
"origin": "corner"
},
"head": {
"translation": [
0.0,
0.0,
0.0
],
"rotation": [
0.16043,
-0.37686962,
-0.06645229,
0.9098437
],
"scale": [
0.25,
0.25,
0.25
],
"post-rotation": [
0.0,
0.0,
0.0,
1.0
],
"origin": "corner"
},
"gui": {
"translation": [
0.0,
0.0,
0.0
],
"rotation": [
0.16043,
-0.37686962,
-0.06645229,
0.9098437
],
"scale": [
0.25,
0.25,
0.25
],
"post-rotation": [
0.0,
0.0,
0.0,
1.0
],
"origin": "corner"
},
"ground": {
"translation": [
0.0,
0.0,
0.0
],
"rotation": [
0.16043,
-0.37686962,
-0.06645229,
0.9098437
],
"scale": [
0.25,
0.25,
0.25
],
"post-rotation": [
0.0,
0.0,
0.0,
1.0
],
"origin": "corner"
},
"fixed": {
"translation": [
0.0,
0.0,
0.0
],
"rotation": [
0.16043,
-0.37686962,
-0.06645229,
0.9098437
],
"scale": [
0.25,
0.25,
0.25
],
"post-rotation": [
0.0,
0.0,
0.0,
1.0
],
"origin": "corner"
}
}
} | {
"pile_set_name": "Github"
} |
/**
* @author v.lugovsky
* created on 16.12.2015
*/
(function () {
'use strict';
angular.module('BlurAdmin.pages.ui.progressBars', [])
.config(routeConfig);
/** @ngInject */
function routeConfig($stateProvider) {
$stateProvider
.state('ui.progressBars', {
url: '/progressBars',
templateUrl: 'app/pages/ui/progressBars/progressBars.html',
title: 'Progress Bars',
sidebarMeta: {
order: 600,
},
});
}
})();
| {
"pile_set_name": "Github"
} |
/* This file is part of the ScriptDev2 Project. See AUTHORS file for Copyright information
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
/* ScriptData
SDName: Boss_Garr
SD%Complete: 80
SDComment: Firesworn erruption needs to be revisited
SDCategory: Molten Core
EndScriptData */
#include "precompiled.h"
#include "molten_core.h"
enum
{
// Garr spells
SPELL_ANTIMAGICPULSE = 19492,
SPELL_MAGMASHACKLES = 19496,
SPELL_ENRAGE = 19516,
// Add spells
SPELL_ERUPTION = 19497,
SPELL_MASSIVE_ERUPTION = 20483, // TODO possible on death
SPELL_IMMOLATE = 20294,
SPELL_SEPARATION_ANXIETY = 23492, // Used if separated too far from Garr
};
struct boss_garrAI : public ScriptedAI
{
boss_garrAI(Creature* pCreature) : ScriptedAI(pCreature)
{
m_pInstance = (ScriptedInstance*)pCreature->GetInstanceData();
Reset();
}
ScriptedInstance* m_pInstance;
uint32 m_uiAntiMagicPulseTimer;
uint32 m_uiMagmaShacklesTimer;
void Reset() override
{
m_uiAntiMagicPulseTimer = 25000;
m_uiMagmaShacklesTimer = 15000;
}
void Aggro(Unit* /*pWho*/) override
{
if (m_pInstance)
m_pInstance->SetData(TYPE_GARR, IN_PROGRESS);
}
void JustDied(Unit* /*pKiller*/) override
{
if (m_pInstance)
m_pInstance->SetData(TYPE_GARR, DONE);
}
void JustReachedHome() override
{
if (m_pInstance)
m_pInstance->SetData(TYPE_GARR, FAIL);
}
void UpdateAI(const uint32 uiDiff) override
{
if (!m_creature->SelectHostileTarget() || !m_creature->getVictim())
return;
// AntiMagicPulse_Timer
if (m_uiAntiMagicPulseTimer < uiDiff)
{
if (DoCastSpellIfCan(m_creature, SPELL_ANTIMAGICPULSE) == CAST_OK)
m_uiAntiMagicPulseTimer = urand(10000, 15000);
}
else
m_uiAntiMagicPulseTimer -= uiDiff;
// MagmaShackles_Timer
if (m_uiMagmaShacklesTimer < uiDiff)
{
if (DoCastSpellIfCan(m_creature, SPELL_MAGMASHACKLES) == CAST_OK)
m_uiMagmaShacklesTimer = urand(8000, 12000);
}
else
m_uiMagmaShacklesTimer -= uiDiff;
DoMeleeAttackIfReady();
}
};
struct mob_fireswornAI : public ScriptedAI
{
mob_fireswornAI(Creature* pCreature) : ScriptedAI(pCreature)
{
m_pInstance = (ScriptedInstance*)pCreature->GetInstanceData();
Reset();
}
ScriptedInstance* m_pInstance;
uint32 m_uiImmolateTimer;
uint32 m_uiSeparationCheckTimer;
void Reset() override
{
m_uiImmolateTimer = urand(4000, 8000); // These times are probably wrong
m_uiSeparationCheckTimer = 5000;
}
void JustDied(Unit* /*pKiller*/) override
{
if (m_pInstance)
{
if (Creature* pGarr = m_pInstance->GetSingleCreatureFromStorage(NPC_GARR))
pGarr->CastSpell(pGarr, SPELL_ENRAGE, true, NULL, NULL, m_creature->GetObjectGuid());
}
}
void UpdateAI(const uint32 uiDiff) override
{
if (!m_creature->SelectHostileTarget() || !m_creature->getVictim())
return;
// Immolate_Timer
if (m_uiImmolateTimer < uiDiff)
{
if (Unit* pTarget = m_creature->SelectAttackingTarget(ATTACKING_TARGET_RANDOM, 0))
{
if (DoCastSpellIfCan(pTarget, SPELL_IMMOLATE) == CAST_OK)
m_uiImmolateTimer = urand(5000, 10000);
}
}
else m_uiImmolateTimer -= uiDiff;
if (m_uiSeparationCheckTimer < uiDiff)
{
if (!m_pInstance)
return;
// Distance guesswork, but should be ok
Creature* pGarr = m_pInstance->GetSingleCreatureFromStorage(NPC_GARR);
if (pGarr && pGarr->isAlive() && !m_creature->IsWithinDist2d(pGarr->GetPositionX(), pGarr->GetPositionY(), 50.0f))
DoCastSpellIfCan(m_creature, SPELL_SEPARATION_ANXIETY, CAST_TRIGGERED);
m_uiSeparationCheckTimer = 5000;
}
else
m_uiSeparationCheckTimer -= uiDiff;
// Cast Erruption and let them die
if (m_creature->GetHealthPercent() <= 10.0f)
{
DoCastSpellIfCan(m_creature->getVictim(), SPELL_ERUPTION);
m_creature->SetDeathState(JUST_DIED);
m_creature->RemoveCorpse();
}
DoMeleeAttackIfReady();
}
};
CreatureAI* GetAI_boss_garr(Creature* pCreature)
{
return new boss_garrAI(pCreature);
}
CreatureAI* GetAI_mob_firesworn(Creature* pCreature)
{
return new mob_fireswornAI(pCreature);
}
void AddSC_boss_garr()
{
Script* pNewScript;
pNewScript = new Script;
pNewScript->Name = "boss_garr";
pNewScript->GetAI = &GetAI_boss_garr;
pNewScript->RegisterSelf();
pNewScript = new Script;
pNewScript->Name = "mob_firesworn";
pNewScript->GetAI = &GetAI_mob_firesworn;
pNewScript->RegisterSelf();
}
| {
"pile_set_name": "Github"
} |
#!/bin/ksh
#
# CDDL HEADER START
#
# The contents of this file are subject to the terms of the
# Common Development and Distribution License (the "License").
# You may not use this file except in compliance with the License.
#
# You can obtain a copy of the license at usr/src/OPENSOLARIS.LICENSE
# or http://www.opensolaris.org/os/licensing.
# See the License for the specific language governing permissions
# and limitations under the License.
#
# When distributing Covered Code, include this CDDL HEADER in each
# file and include the License file at usr/src/OPENSOLARIS.LICENSE.
# If applicable, add the following below this CDDL HEADER, with the
# fields enclosed by brackets "[]" replaced with your own identifying
# information: Portions Copyright [yyyy] [name of copyright owner]
#
# CDDL HEADER END
#
#
# Copyright 2007 Sun Microsystems, Inc. All rights reserved.
# Use is subject to license terms.
#
. $STF_SUITE/tests/functional/cli_root/zfs_copies/zfs_copies.kshlib
#
# DESCRIPTION:
# Verify that the volume space used by multiple copies is charged correctly
#
# STRATEGY:
# 1. Create volume;
# 2. Create ZFS filesystem based on the volume;
# 3. Set the copies property of volume to 1,2 or 3;
# 4. Copy specified size data into each filesystem;
# 5. Verify that the volume space is charged as expected.
#
verify_runnable "global"
function cleanup
{
destroy_pool -f $TESTPOOL1
destroy_dataset $vol
}
log_assert "Verify that ZFS volume space used by multiple copies is charged correctly."
log_onexit cleanup
vol=$TESTPOOL/$TESTVOL1
for val in 1 2 3; do
do_vol_test zfs $val
done
log_pass "The volume space used by multiple copies is charged correctly as expected. "
| {
"pile_set_name": "Github"
} |
<?php
/**
* Inherited Methods
* @method void wantToTest($text)
* @method void wantTo($text)
* @method void execute($callable)
* @method void expectTo($prediction)
* @method void expect($prediction)
* @method void amGoingTo($argumentation)
* @method void am($role)
* @method void lookForwardTo($achieveValue)
* @method void comment($description)
* @method \Codeception\Lib\Friend haveFriend($name, $actorClass = NULL)
*
* @SuppressWarnings(PHPMD)
*/
class UnitTester extends \Codeception\Actor
{
use _generated\UnitTesterActions;
/**
* Define custom actions here
*/
}
| {
"pile_set_name": "Github"
} |
// Copyright 2015 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package x509
import (
"bytes"
"crypto/md5"
"crypto/sha1"
"crypto/sha256"
"crypto/sha512"
"encoding/hex"
"encoding/json"
)
// CertificateFingerprint represents a digest/fingerprint of some data. It can
// easily be encoded to hex and JSON (as a hex string).
type CertificateFingerprint []byte
// MD5Fingerprint creates a fingerprint of data using the MD5 hash algorithm.
func MD5Fingerprint(data []byte) CertificateFingerprint {
sum := md5.Sum(data)
return sum[:]
}
// SHA1Fingerprint creates a fingerprint of data using the SHA1 hash algorithm.
func SHA1Fingerprint(data []byte) CertificateFingerprint {
sum := sha1.Sum(data)
return sum[:]
}
// SHA256Fingerprint creates a fingerprint of data using the SHA256 hash
// algorithm.
func SHA256Fingerprint(data []byte) CertificateFingerprint {
sum := sha256.Sum256(data)
return sum[:]
}
// SHA512Fingerprint creates a fingerprint of data using the SHA256 hash
// algorithm.
func SHA512Fingerprint(data []byte) CertificateFingerprint {
sum := sha512.Sum512(data)
return sum[:]
}
// Equal returns true if the fingerprints are bytewise-equal.
func (f CertificateFingerprint) Equal(other CertificateFingerprint) bool {
return bytes.Equal(f, other)
}
// Hex returns the given fingerprint encoded as a hex string.
func (f CertificateFingerprint) Hex() string {
return hex.EncodeToString(f)
}
// MarshalJSON implements the json.Marshaler interface, and marshals the
// fingerprint as a hex string.
func (f *CertificateFingerprint) MarshalJSON() ([]byte, error) {
return json.Marshal(f.Hex())
}
| {
"pile_set_name": "Github"
} |
*阅读本文的其他语言版本:[English](README.md) - [Español](README-es.md)。*
## 使用 Keras 和 Tensorflow 训练深度学习语言模型
此 Code Pattern 将指导您安装 Keras 和 Tensorflow、下载 Yelp 评论数据,并使用循环神经网络 (RNN) 训练语言模型以生成文本。
> 此 Code Pattern 的灵感来源于 [Hacknoon 博客帖子](https://hackernoon.com/how-to-generate-realistic-yelp-restaurant-reviews-with-keras-c1167c05e86d),并已整合到 Notebook 中。文本的生成方法类似于 [Keras 文本生成演示](https://github.com/keras-team/keras/blob/master/examples/lstm_text_generation.py),只需稍作更改便可适应此场景。
使用深度学习生成信息是一个热门的研究和试验领域。尤其值得注意的是,RNN 深度学习模型方法可适用于近乎无限数量的领域,无论是用来解决当前问题的方案还是孵化未来技术的应用。文本生成是这些应用领域之一,也是本 Code Pattern 介绍的内容。文本生成用于语言翻译、机器学习和拼写纠正。这些全部都是通过所谓的语言模型来创建的。本 Code Pattern 探讨的是:使用长短期记忆 (LSTM) RNN 的语言模型。对于部分上下文,RNN 通过带有隐藏记忆层的网络使用最高概率预测下一个步骤。与卷积神经网络 (CNNs) 使用正向传播(更确切地说,是沿其管道向前移动)不同的是,RNN 利用了反向传播或沿管道回转来使用上面提到的“记忆”。通过这种方式,RNNs 可以使用输入的文本来了解如何生成后续字母或字符作为其输出。输出随后会形成一个单词,最终会获得一个单词集合或句子和段落。通过模型的 LSTM 部分,您可以利用经过改进的长期依赖项学习或更好的记忆来构建更大的 RNN 模型。这意味着我们生成单词和句子的性能得到提升!
此模型的重要意义在于,在解决各行各业的翻译、拼写和评论问题时,人们对文本生成的需求正不断提升。尤其突出的是,抵制虚假评论在这一研究领域扮演着重要角色。虚假评论对于像 Amazon 和 Yelp 这样的公司是一个切实存在的问题,此类公司依赖于用户的真实评论为其站点上展示的特色产品和业务提供担保。对于编写此类评论而言,企业可以很轻松地付费购买虚假的正面评论,最终提升销售额和收入。为竞争企业生成负面评论同样也可轻而易举地实现。不幸的是,这会导致用户遭欺骗进入各种场所、购买各种产品,最终可能会导致产生负面体验,甚至更糟。为了打击此类滥用和非法活动,文本生成可用于检测评论生成时可能显示的内容,将其与真实用户撰写的真实评论进行对比。此 Code Pattern 会指导您完成在高级别创建此文本生成的步骤。我们将探讨如何通过少量 Yelp 评论数据来处理此问题,随后,您就可以将其应用于更大的集合,并检验得到的输出!
在 [Kaggle](https://www.kaggle.com/c/yelp-recruiting/data) 上可找到此 Code Pattern 中使用的原始 Yelp 数据,此数据在此存储库中以 [zip 文件](yelp_test_set.zip)形式提供。
### 什么是 Keras 和 Tensorflow?
如果您已单击此 Code Pattern,我猜想您可能是深度学习初级用户或中级用户,并且想要了解更多信息。无论您属于哪一个层面,都可能会认为机器学习和深度学习很棒(我对此表示认同),并且可能已经接触过各种示例和术语。您可能还对 Python 有所了解,并且也认识到深度学习属于机器学习的范畴(机器学习整体上属于人工智能的范畴)。有了这些假设,我就可以解释 Tensorflow 是一个用于机器学习的开源软件库,可用于跟踪所有模型并通过强大的可视化功能来查看这些模型。
Keras 是一个深度学习库,可与 Tensorflow 和其他几种深度学习库配合使用。Keras 对用户非常友好,因为它只需很少的几行代码即可完成一个模型(例如,使用 RNN),这使每个数据科学家(包括我自己)的工作都得到了显著的简化!此项目着重介绍了只需使用相对少量代码的功能。Keras 还支持根据要执行的操作在各种库之间进行切换,为您节省了大量时间,避免了种种麻烦。我们现在就进入正题吧。

## 操作流程
1. 安装必备软件、Keras 和 Tensorflow 之后,用户执行 Notebook。
1. 训练数据用于对语言模型进行训练。
1. 根据模型生成新文本并返回给用户。
## 包含的组件
* [Keras](https://keras.io/):Python 深度学习库。
* [Tensorflow](https://www.tensorflow.org/):用于机器智能的开源软件库。
## 特色技术
* [云](https://www.ibm.com/developerworks/learn/cloud/):通过互联网访问计算机和信息技术资源。
* [数据科学](https://medium.com/ibm-data-science-experience/):分析结构化和非结构化数据来提取知识和洞察的系统和科学方法。
* [Python](https://www.python.org/):Python 是一种支持更快速地工作并能更高效地集成系统的编程语言。
# 先决条件
1. 确保已安装 [Python](https://www.python.org/) 3.0 或更高版本。
2. 确保已安装以下系统库:
* [pip](https://pip.pypa.io/en/stable/installing/)(用于安装 Python 库)
* [gcc](https://gcc.gnu.org/)(用于编译 SciPy)
* 对于 Mac,安装 Python 时已安装 pip。示例:
```
brew install python
brew install gcc
```
* 对于其他操作系统,请试用以下命令:
```
sudo easy install pip
sudo easy install gfortran
```
3. 确保已安装以下 Python 库:
* [NumPy](http://www.numpy.org/)
* [SciPy](https://www.scipy.org/)
* [pandas](https://pandas.pydata.org/)
* [zipfile36](https://gitlab.com/takluyver/zipfile36)
* [h5py](http://www.h5py.org/)
```
pip install numpy
pip install scipy
pip install pandas
pip install zipfile36
pip install h5py
```
# 步骤
此模式通过以下步骤运行。查看 [Notebook](code/transfer_learn.ipynb) 以获取此代码!
1. [下载并安装 TensorFlow 和 Keras](#1-download-and-install-tensorflow-and-keras)
2. [克隆存储库](#2-clone-the-repository)
3. [训练模型](#3-train-a-model)
4. [分析结果](#4-analyze-the-results)
## 1. 下载并安装 TensorFlow 和 Keras
* 安装 TensorFlow。
请参阅 [TensorFlow 安装文档](https://www.tensorflow.org/install/),获取有关如何在所有受支持的操作系统上安装 TensorFlow 的指示信息。在大部分情况下,只需使用 `pip install tensorflow` 即可安装 TensorFlow Python 库。
* 安装 Keras。
请参阅 [Keras 安装文档](https://keras.io/#getting-started-30-seconds-to-keras),获取有关如何在所有受支持的操作系统上安装 Keras 的指示信息。在大部分情况下,只需使用 `pip install keras` 即可安装 Keras Python 库。

## 2. 克隆存储库
* 克隆此存储库并切换到新目录:
```
git clone https://github.com/IBM/deep-learning-language-model
cd deep-learning-language-model
```
对于存储库内容,须注意以下几点:
* [transfer_learn.ipynb](transfer_learn.ipynb):这是将运行的 Notebook。
* [yelp_test_set.zip](yelp_test_set.zip):包含 Yelp! 评论的完整数据集,此数据集来自 [Kaggle](https://www.kaggle.com/c/yelp-recruiting/data)
* [yelp_100_3.txt](data/yelp_100_3.txt):以上数据集的片段。
* [transfer weights](transfer_weights):用作此次练习基础的模型。
* [indices_char.txt](indices_char.txt) 和 [char_indices.txt](char_indices.txt):这两个文本文件用于定义字母和标点符号的相互对应关系。
*有关测试数据的简要说明:* 此数据允许我们使用真实的 Yelp 评论作为语言模型的输入。这意味着我们的模型将通过评论进行迭代,并生成类似的 Yelp 评论。如果使用其他数据集(例如,海明威的小说),那么将生成与海明威风格相似的文本。我们在 Notebook 中构建的模型将考虑某些功能及其与英语语言的相关性,以及这些功能如何帮助编写评论。当读者感觉对 Notebook 足够熟悉后,即可使用整个数据集。
*有关 `transfer weights` 模型的简要说明:* 权重使我们能够对模型进行微调,并随着模型学习的过程提高准确性。您此时无需担忧权重调整问题,因为模型运行后在保存至 `transfer_weights` 时会自动进行调整。现在,我们即开始对模型进行训练。
## 3. 训练模型
* 确保将下载的所有文件都收集到同一个文件夹中。
* 通过运行包含代码的单元来运行 [`transfer_learn.ipynb`](transfer_learn.ipynb)。
* 执行后,应可看到 TensorFlow 已启动,然后屏幕上会运行各种戳记,随后生成日益多样化的文本。

> 下图显示用户在本地运行 Notebook
为帮助了解其中发生的状况,在 [transfer_learn.ipynb](transfer_learn.ipynb) 文件中,我们使用了先前提到的 Keras 序列模型的 LSTM 变体。通过使用此变体,我们可以包含隐藏的记忆层以生成更准确的文本。此处的 maxlen 会自动设置为 none。maxlen 表示序列的最大长度,可为 none 或整数。随后,结合使用 Adam 优化器和 `categorical_crossentropy`,首先装入 `transfer_weights`。使用温度 0.6 定义样本。此处的温度是一个参数,可用于 softmax 函数中,该函数用于控制生成的新颖性级别,其中 1 表示限制采样并导致文本多样性降低/重复性提高,0 表示完全多样化的文本。在此情况下,我们略倾向于重复性,但在此特定模型中,我们采用浮动的多样性标度生成此模型的多个版本,这样就可通过相互比较来确定最适合的版本。您还将看到使用了枚举,这最终使我们能够创建自动的计数器以及循环遍历信息。随后,我们对模型进行训练,将权重保存到 `transfer_weights` 中。每次对模型进行训练时,都将保存所学到的权重,进而帮助提升文本生成的准确性。

正如您在上图中所见,输入的文本会通过 LSTM 模型的多个层进行发送(正向和反向),然后通过 dense 层发送,再通过 softmax 层发送。这将考量各种信息,并在字符级别通过数据进行迭代。这意味着它将考量先前采用的字符等上下文来确定后续字符,最终组成单词,然后组成句子,进而生成完整的评论。

## 4. 分析结果
正如您在下图中所见,您应该会看到以不同的多样性生成的文本,随后此类文本将重新保存至权重。通过此输出,您可以查看基于不同多样性的文本(多样性提高与多样性降低/重复性提高)可产生哪些不同的输出。

> 上图显示了 Notebook 的运行结果:生成了一条 Yelp! 评论。
祝贺您!现在,您已了解了如何基于提供的数据生成文本。您可以通过尝试完整的 Yelp 数据集或其他文本数据来挑战自己!您一定做得到!
# 链接
* [Watson Studio](https://www.ibm.com/cloud/watson-studio)
* [Jupyter Notebook](http://jupyter.org/):一种开源 Web 应用,可用来创建和共享包含实时代码、等式、可视化和解释性文本的文档。
* [Keras](https://keras.io/):Python 深度学习库。
* [Tensorflow](https://www.tensorflow.org/):用于机器智能的开源软件库。
# 了解更多信息
* **数据分析 Code Pattern**:喜欢本 Code Pattern 吗?了解我们其他的[数据分析 Code Pattern](https://developer.ibm.com/cn/technologies/data-science/)
* **AI 和数据 Code Pattern 播放清单**:收藏包含我们所有 Code Pattern 视频的[播放清单](http://i.youku.com/i/UNTI2NTA2NTAw/videos?spm=a2hzp.8244740.0.0)
* **Data Science Experience**:通过 IBM [Data Science Experience](https://datascience.ibm.com/) 掌握数据科学艺术
* **Watson Studio**:需要一个 Spark 集群?通过我们的 [Spark 服务](https://console.bluemix.net/catalog/services/apache-spark),在 IBM Cloud 上创建多达 30 个 Spark 执行程序。
# 许可证
[Apache 2.0](LICENSE)
| {
"pile_set_name": "Github"
} |
/*
* Copyright (c) 1997, 2013, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
/*
*/
/*
* (C) Copyright Taligent, Inc. 1996, 1997 - All Rights Reserved
* (C) Copyright IBM Corp. 1996 - 1998 - All Rights Reserved
*
* The original version of this source code and documentation
* is copyrighted and owned by Taligent, Inc., a wholly-owned
* subsidiary of IBM. These materials are provided under terms
* of a License Agreement between Taligent and Sun. This technology
* is protected by multiple US and International patents.
*
* This notice and attribution to Taligent may not be removed.
* Taligent is a registered trademark of Taligent, Inc.
*
*/
/*
* COPYRIGHT AND PERMISSION NOTICE
*
* Copyright (C) 1991-2012 Unicode, Inc. All rights reserved. Distributed under
* the Terms of Use in http://www.unicode.org/copyright.html.
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of the Unicode data files and any associated documentation (the "Data
* Files") or Unicode software and any associated documentation (the
* "Software") to deal in the Data Files or Software without restriction,
* including without limitation the rights to use, copy, modify, merge,
* publish, distribute, and/or sell copies of the Data Files or Software, and
* to permit persons to whom the Data Files or Software are furnished to do so,
* provided that (a) the above copyright notice(s) and this permission notice
* appear with all copies of the Data Files or Software, (b) both the above
* copyright notice(s) and this permission notice appear in associated
* documentation, and (c) there is clear notice in each modified Data File or
* in the Software as well as in the documentation associated with the Data
* File(s) or Software that the data or software has been modified.
*
* THE DATA FILES AND SOFTWARE ARE 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 OF
* THIRD PARTY RIGHTS. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR HOLDERS
* INCLUDED IN THIS NOTICE BE LIABLE FOR ANY CLAIM, OR ANY SPECIAL INDIRECT OR
* CONSEQUENTIAL DAMAGES, OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE,
* DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER
* TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE
* OF THE DATA FILES OR SOFTWARE.
*
* Except as contained in this notice, the name of a copyright holder shall not
* be used in advertising or otherwise to promote the sale, use or other
* dealings in these Data Files or Software without prior written authorization
* of the copyright holder.
*/
package sun.text.resources.ext;
import sun.util.resources.ParallelListResourceBundle;
public class FormatData_cs extends ParallelListResourceBundle {
/**
* Overrides ParallelListResourceBundle
*/
protected final Object[][] getContents() {
return new Object[][] {
{ "MonthNames",
new String[] {
"ledna",
"\u00fanora",
"b\u0159ezna",
"dubna",
"kv\u011btna",
"\u010dervna",
"\u010dervence",
"srpna",
"z\u00e1\u0159\u00ed",
"\u0159\u00edjna",
"listopadu",
"prosince",
"",
}
},
{ "standalone.MonthNames",
new String[] {
"leden", // january
"\u00fanor", // february
"b\u0159ezen", // march
"duben", // april
"kv\u011bten", // may
"\u010derven", // june
"\u010dervenec", // july
"srpen", // august
"z\u00e1\u0159\u00ed", // september
"\u0159\u00edjen", // october
"listopad", // november
"prosinec", // december
"" // month 13 if applicable
}
},
{ "MonthAbbreviations",
new String[] {
"Led",
"\u00dano",
"B\u0159e",
"Dub",
"Kv\u011b",
"\u010cer",
"\u010cvc",
"Srp",
"Z\u00e1\u0159",
"\u0158\u00edj",
"Lis",
"Pro",
"",
}
},
{ "standalone.MonthAbbreviations",
new String[] {
"I", // abb january
"II", // abb february
"III", // abb march
"IV", // abb april
"V", // abb may
"VI", // abb june
"VII", // abb july
"VIII", // abb august
"IX", // abb september
"X", // abb october
"XI", // abb november
"XII", // abb december
"" // abb month 13 if applicable
}
},
{ "MonthNarrows",
new String[] {
"l",
"\u00fa",
"b",
"d",
"k",
"\u010d",
"\u010d",
"s",
"z",
"\u0159",
"l",
"p",
"",
}
},
{ "standalone.MonthNarrows",
new String[] {
"l",
"\u00fa",
"b",
"d",
"k",
"\u010d",
"\u010d",
"s",
"z",
"\u0159",
"l",
"p",
"",
}
},
{ "DayNames",
new String[] {
"Ned\u011ble", // Sunday
"Pond\u011bl\u00ed", // Monday
"\u00dater\u00fd", // Tuesday
"St\u0159eda", // Wednesday
"\u010ctvrtek", // Thursday
"P\u00e1tek", // Friday
"Sobota" // Saturday
}
},
{ "standalone.DayNames",
new String[] {
"ned\u011ble",
"pond\u011bl\u00ed",
"\u00fater\u00fd",
"st\u0159eda",
"\u010dtvrtek",
"p\u00e1tek",
"sobota",
}
},
{ "DayAbbreviations",
new String[] {
"Ne", // abb Sunday
"Po", // abb Monday
"\u00dat", // abb Tuesday
"St", // abb Wednesday
"\u010ct", // abb Thursday
"P\u00e1", // abb Friday
"So" // abb Saturday
}
},
{ "standalone.DayAbbreviations",
new String[] {
"ne",
"po",
"\u00fat",
"st",
"\u010dt",
"p\u00e1",
"so",
}
},
{ "DayNarrows",
new String[] {
"N",
"P",
"\u00da",
"S",
"\u010c",
"P",
"S",
}
},
{ "standalone.DayNarrows",
new String[] {
"N",
"P",
"\u00da",
"S",
"\u010c",
"P",
"S",
}
},
{ "AmPmMarkers",
new String[] {
"dop.", // am marker
"odp." // pm marker
}
},
{ "Eras",
new String[] { // era strings
"p\u0159.Kr.",
"po Kr."
}
},
{ "short.Eras",
new String[] {
"p\u0159. n. l.",
"n. l.",
}
},
{ "narrow.Eras",
new String[] {
"p\u0159.n.l.",
"n. l.",
}
},
{ "NumberElements",
new String[] {
",", // decimal separator
"\u00a0", // group (thousands) separator
";", // list separator
"%", // percent sign
"0", // native 0 digit
"#", // pattern digit
"-", // minus sign
"E", // exponential
"\u2030", // per mille
"\u221e", // infinity
"\ufffd" // NaN
}
},
{ "TimePatterns",
new String[] {
"H:mm:ss z", // full time pattern
"H:mm:ss z", // long time pattern
"H:mm:ss", // medium time pattern
"H:mm", // short time pattern
}
},
{ "DatePatterns",
new String[] {
"EEEE, d. MMMM yyyy", // full date pattern
"d. MMMM yyyy", // long date pattern
"d.M.yyyy", // medium date pattern
"d.M.yy", // short date pattern
}
},
{ "DateTimePatterns",
new String[] {
"{1} {0}" // date-time pattern
}
},
{ "DateTimePatternChars", "GuMtkHmsSEDFwWahKzZ" },
};
}
}
| {
"pile_set_name": "Github"
} |
/* GIMP - The GNU Image Manipulation Program
* Copyright (C) 1995 Spencer Kimball and Peter Mattis
*
* gimpviewablebutton.h
* Copyright (C) 2003-2005 Michael Natterer <[email protected]>
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
#ifndef __GIMP_VIEWABLE_BUTTON_H__
#define __GIMP_VIEWABLE_BUTTON_H__
#define GIMP_TYPE_VIEWABLE_BUTTON (gimp_viewable_button_get_type ())
#define GIMP_VIEWABLE_BUTTON(obj) (G_TYPE_CHECK_INSTANCE_CAST ((obj), GIMP_TYPE_VIEWABLE_BUTTON, GimpViewableButton))
#define GIMP_VIEWABLE_BUTTON_CLASS(klass) (G_TYPE_CHECK_CLASS_CAST ((klass), GIMP_TYPE_VIEWABLE_BUTTON, GimpViewableButtonClass))
#define GIMP_IS_VIEWABLE_BUTTON(obj) (G_TYPE_CHECK_INSTANCE_TYPE ((obj), GIMP_TYPE_VIEWABLE_BUTTON))
#define GIMP_IS_VIEWABLE_BUTTON_CLASS(klass) (G_TYPE_CHECK_CLASS_TYPE ((klass), GIMP_TYPE_VIEWABLE_BUTTON))
#define GIMP_VIEWABLE_BUTTON_GET_CLASS(obj) (G_TYPE_INSTANCE_GET_CLASS ((obj), GIMP_TYPE_VIEWABLE_BUTTON, GimpViewableButtonClass))
typedef struct _GimpViewableButtonClass GimpViewableButtonClass;
struct _GimpViewableButton
{
GimpButton parent_instance;
GimpContainer *container;
GimpContext *context;
GimpViewType popup_view_type;
gint popup_view_size;
gint button_view_size;
gint view_border_width;
GimpDialogFactory *dialog_factory;
gchar *dialog_identifier;
gchar *dialog_icon_name;
gchar *dialog_tooltip;
GtkWidget *view;
};
struct _GimpViewableButtonClass
{
GimpButtonClass parent_class;
};
GType gimp_viewable_button_get_type (void) G_GNUC_CONST;
GtkWidget * gimp_viewable_button_new (GimpContainer *container,
GimpContext *context,
GimpViewType view_type,
gint button_view_size,
gint view_size,
gint view_border_width,
GimpDialogFactory *dialog_factory,
const gchar *dialog_identifier,
const gchar *dialog_icon_name,
const gchar *dialog_tooltip);
GimpViewType gimp_viewable_button_get_view_type (GimpViewableButton *button);
void gimp_viewable_button_set_view_type (GimpViewableButton *button,
GimpViewType view_type);
gint gimp_viewable_button_get_view_size (GimpViewableButton *button);
void gimp_viewable_button_set_view_size (GimpViewableButton *button,
gint view_size);
#endif /* __GIMP_VIEWABLE_BUTTON_H__ */
| {
"pile_set_name": "Github"
} |
--
-- Copyright (c) 2008--2015 Red Hat, Inc.
--
-- This software is licensed to you under the GNU General Public License,
-- version 2 (GPLv2). There is NO WARRANTY for this software, express or
-- implied, including the implied warranties of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
-- along with this software; if not, see
-- http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
--
-- Red Hat trademarks are not licensed under GPLv2. No permission is
-- granted to use or replicate Red Hat trademarks that are incorporated
-- in this software or its documentation.
--
--
--
--
create or replace function
does_user_have_role
(
user_id_in in numeric,
role_in in varchar
)
returns numeric
as $$
declare
org_admin numeric;
begin
select 1
into org_admin
from
rhnUserGroupType ugt,
rhnUserGroup ug,
rhnUserGroupMembers ugm
where 1=1
and ugm.user_id = user_id_in
and ugm.user_group_id = ug.id
and ugt.label = role_in
and ugt.id = ug.group_type;
if not found then
return 0;
end if;
return org_admin;
end; $$ language plpgsql;
| {
"pile_set_name": "Github"
} |
// A crate which builds the `backtrace` crate as-if it's included as a
// submodule into the standard library. We try to set this crate up similarly
// to the standard library itself to minimize the likelihood of issues when
// updating the `backtrace` crate.
#![no_std]
extern crate alloc;
// We want to `pub use std::*` in the root but we don't want `std` available in
// the root namespace, so do this in a funky inner module.
mod __internal {
extern crate std;
pub use std::*;
}
pub use __internal::*;
// This is the magical part which we hope works.
#[path = "../../../src/lib.rs"]
mod the_backtrace_crate;
| {
"pile_set_name": "Github"
} |
// (C) Copyright David Abrahams 2002.
// (C) Copyright Jeremy Siek 2002.
// (C) Copyright Thomas Witt 2002.
// 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_ENABLE_IF_23022003THW_HPP
#define BOOST_ENABLE_IF_23022003THW_HPP
#include <boost/detail/workaround.hpp>
#include <boost/mpl/identity.hpp>
#include <boost/iterator/detail/config_def.hpp>
//
// Boost iterators uses its own enable_if cause we need
// special semantics for deficient compilers.
// 23/02/03 thw
//
namespace boost
{
namespace iterators
{
//
// Base machinery for all kinds of enable if
//
template<bool>
struct enabled
{
template<typename T>
struct base
{
typedef T type;
};
};
//
// For compilers that don't support "Substitution Failure Is Not An Error"
// enable_if falls back to always enabled. See comments
// on operator implementation for consequences.
//
template<>
struct enabled<false>
{
template<typename T>
struct base
{
#ifdef BOOST_NO_SFINAE
typedef T type;
// This way to do it would give a nice error message containing
// invalid overload, but has the big disadvantage that
// there is no reference to user code in the error message.
//
// struct invalid_overload;
// typedef invalid_overload type;
//
#endif
};
};
template <class Cond,
class Return>
struct enable_if
# if !defined(BOOST_NO_SFINAE) && !defined(BOOST_NO_IS_CONVERTIBLE)
: enabled<(Cond::value)>::template base<Return>
# else
: mpl::identity<Return>
# endif
{
};
} // namespace iterators
} // namespace boost
#include <boost/iterator/detail/config_undef.hpp>
#endif // BOOST_ENABLE_IF_23022003THW_HPP
| {
"pile_set_name": "Github"
} |
/*! ColVis 1.1.2
* ©2010-2015 SpryMedia Ltd - datatables.net/license
*/
/**
* @summary ColVis
* @description Controls for column visibility in DataTables
* @version 1.1.2
* @file dataTables.colReorder.js
* @author SpryMedia Ltd (www.sprymedia.co.uk)
* @contact www.sprymedia.co.uk/contact
* @copyright Copyright 2010-2015 SpryMedia Ltd.
*
* This source file is free software, available under the following license:
* MIT license - http://datatables.net/license/mit
*
* This source file 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 license files for details.
*
* For details please refer to: http://www.datatables.net
*/
(function(window, document, undefined) {
var factory = function( $, DataTable ) {
"use strict";
/**
* ColVis provides column visibility control for DataTables
*
* @class ColVis
* @constructor
* @param {object} DataTables settings object. With DataTables 1.10 this can
* also be and API instance, table node, jQuery collection or jQuery selector.
* @param {object} ColVis configuration options
*/
var ColVis = function( oDTSettings, oInit )
{
/* Santiy check that we are a new instance */
if ( !this.CLASS || this.CLASS != "ColVis" )
{
alert( "Warning: ColVis must be initialised with the keyword 'new'" );
}
if ( typeof oInit == 'undefined' )
{
oInit = {};
}
var camelToHungarian = $.fn.dataTable.camelToHungarian;
if ( camelToHungarian ) {
camelToHungarian( ColVis.defaults, ColVis.defaults, true );
camelToHungarian( ColVis.defaults, oInit );
}
/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
* Public class variables
* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */
/**
* @namespace Settings object which contains customisable information for
* ColVis instance. Augmented by ColVis.defaults
*/
this.s = {
/**
* DataTables settings object
* @property dt
* @type Object
* @default null
*/
"dt": null,
/**
* Customisation object
* @property oInit
* @type Object
* @default passed in
*/
"oInit": oInit,
/**
* Flag to say if the collection is hidden
* @property hidden
* @type boolean
* @default true
*/
"hidden": true,
/**
* Store the original visibility settings so they could be restored
* @property abOriginal
* @type Array
* @default []
*/
"abOriginal": []
};
/**
* @namespace Common and useful DOM elements for the class instance
*/
this.dom = {
/**
* Wrapper for the button - given back to DataTables as the node to insert
* @property wrapper
* @type Node
* @default null
*/
"wrapper": null,
/**
* Activation button
* @property button
* @type Node
* @default null
*/
"button": null,
/**
* Collection list node
* @property collection
* @type Node
* @default null
*/
"collection": null,
/**
* Background node used for shading the display and event capturing
* @property background
* @type Node
* @default null
*/
"background": null,
/**
* Element to position over the activation button to catch mouse events when using mouseover
* @property catcher
* @type Node
* @default null
*/
"catcher": null,
/**
* List of button elements
* @property buttons
* @type Array
* @default []
*/
"buttons": [],
/**
* List of group button elements
* @property groupButtons
* @type Array
* @default []
*/
"groupButtons": [],
/**
* Restore button
* @property restore
* @type Node
* @default null
*/
"restore": null
};
/* Store global reference */
ColVis.aInstances.push( this );
/* Constructor logic */
this.s.dt = $.fn.dataTable.Api ?
new $.fn.dataTable.Api( oDTSettings ).settings()[0] :
oDTSettings;
this._fnConstruct( oInit );
return this;
};
ColVis.prototype = {
/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
* Public methods
* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */
/**
* Get the ColVis instance's control button so it can be injected into the
* DOM
* @method button
* @returns {node} ColVis button
*/
button: function ()
{
return this.dom.wrapper;
},
/**
* Alias of `rebuild` for backwards compatibility
* @method fnRebuild
*/
"fnRebuild": function ()
{
this.rebuild();
},
/**
* Rebuild the list of buttons for this instance (i.e. if there is a column
* header update)
* @method fnRebuild
*/
rebuild: function ()
{
/* Remove the old buttons */
for ( var i=this.dom.buttons.length-1 ; i>=0 ; i-- ) {
this.dom.collection.removeChild( this.dom.buttons[i] );
}
this.dom.buttons.splice( 0, this.dom.buttons.length );
this.dom.groupButtons.splice(0, this.dom.groupButtons.length);
if ( this.dom.restore ) {
this.dom.restore.parentNode( this.dom.restore );
}
/* Re-add them (this is not the optimal way of doing this, it is fast and effective) */
this._fnAddGroups();
this._fnAddButtons();
/* Update the checkboxes */
this._fnDrawCallback();
},
/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
* Private methods (they are of course public in JS, but recommended as private)
* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */
/**
* Constructor logic
* @method _fnConstruct
* @returns void
* @private
*/
"_fnConstruct": function ( init )
{
this._fnApplyCustomisation( init );
var that = this;
var i, iLen;
this.dom.wrapper = document.createElement('div');
this.dom.wrapper.className = "ColVis";
this.dom.button = $( '<button />', {
'class': !this.s.dt.bJUI ?
"ColVis_Button ColVis_MasterButton" :
"ColVis_Button ColVis_MasterButton ui-button ui-state-default"
} )
.append( '<span>'+this.s.buttonText+'</span>' )
.bind( this.s.activate=="mouseover" ? "mouseover" : "click", function (e) {
e.preventDefault();
that._fnCollectionShow();
} )
.appendTo( this.dom.wrapper )[0];
this.dom.catcher = this._fnDomCatcher();
this.dom.collection = this._fnDomCollection();
this.dom.background = this._fnDomBackground();
this._fnAddGroups();
this._fnAddButtons();
/* Store the original visibility information */
for ( i=0, iLen=this.s.dt.aoColumns.length ; i<iLen ; i++ )
{
this.s.abOriginal.push( this.s.dt.aoColumns[i].bVisible );
}
/* Update on each draw */
this.s.dt.aoDrawCallback.push( {
"fn": function () {
that._fnDrawCallback.call( that );
},
"sName": "ColVis"
} );
/* If columns are reordered, then we need to update our exclude list and
* rebuild the displayed list
*/
$(this.s.dt.oInstance).bind( 'column-reorder.dt', function ( e, oSettings, oReorder ) {
for ( i=0, iLen=that.s.aiExclude.length ; i<iLen ; i++ ) {
that.s.aiExclude[i] = oReorder.aiInvertMapping[ that.s.aiExclude[i] ];
}
var mStore = that.s.abOriginal.splice( oReorder.iFrom, 1 )[0];
that.s.abOriginal.splice( oReorder.iTo, 0, mStore );
that.fnRebuild();
} );
$(this.s.dt.oInstance).bind( 'destroy.dt', function () {
$(that.dom.wrapper).remove();
} );
// Set the initial state
this._fnDrawCallback();
},
/**
* Apply any customisation to the settings from the DataTables initialisation
* @method _fnApplyCustomisation
* @returns void
* @private
*/
"_fnApplyCustomisation": function ( init )
{
$.extend( true, this.s, ColVis.defaults, init );
// Slightly messy overlap for the camelCase notation
if ( ! this.s.showAll && this.s.bShowAll ) {
this.s.showAll = this.s.sShowAll;
}
if ( ! this.s.restore && this.s.bRestore ) {
this.s.restore = this.s.sRestore;
}
// CamelCase to Hungarian for the column groups
var groups = this.s.groups;
var hungarianGroups = this.s.aoGroups;
if ( groups ) {
for ( var i=0, ien=groups.length ; i<ien ; i++ ) {
if ( groups[i].title ) {
hungarianGroups[i].sTitle = groups[i].title;
}
if ( groups[i].columns ) {
hungarianGroups[i].aiColumns = groups[i].columns;
}
}
}
},
/**
* On each table draw, check the visibility checkboxes as needed. This allows any process to
* update the table's column visibility and ColVis will still be accurate.
* @method _fnDrawCallback
* @returns void
* @private
*/
"_fnDrawCallback": function ()
{
var columns = this.s.dt.aoColumns;
var buttons = this.dom.buttons;
var groups = this.s.aoGroups;
var button;
for ( var i=0, ien=buttons.length ; i<ien ; i++ ) {
button = buttons[i];
if ( button.__columnIdx !== undefined ) {
$('input', button).prop( 'checked', columns[ button.__columnIdx ].bVisible );
}
}
var allVisible = function ( columnIndeces ) {
for ( var k=0, kLen=columnIndeces.length ; k<kLen ; k++ )
{
if ( columns[columnIndeces[k]].bVisible === false ) { return false; }
}
return true;
};
var allHidden = function ( columnIndeces ) {
for ( var m=0 , mLen=columnIndeces.length ; m<mLen ; m++ )
{
if ( columns[columnIndeces[m]].bVisible === true ) { return false; }
}
return true;
};
for ( var j=0, jLen=groups.length ; j<jLen ; j++ )
{
if ( allVisible(groups[j].aiColumns) )
{
$('input', this.dom.groupButtons[j]).prop('checked', true);
$('input', this.dom.groupButtons[j]).prop('indeterminate', false);
}
else if ( allHidden(groups[j].aiColumns) )
{
$('input', this.dom.groupButtons[j]).prop('checked', false);
$('input', this.dom.groupButtons[j]).prop('indeterminate', false);
}
else
{
$('input', this.dom.groupButtons[j]).prop('indeterminate', true);
}
}
},
/**
* Loop through the groups (provided in the settings) and create a button for each.
* @method _fnAddgroups
* @returns void
* @private
*/
"_fnAddGroups": function ()
{
var nButton;
if ( typeof this.s.aoGroups != 'undefined' )
{
for ( var i=0, iLen=this.s.aoGroups.length ; i<iLen ; i++ )
{
nButton = this._fnDomGroupButton( i );
this.dom.groupButtons.push( nButton );
this.dom.buttons.push( nButton );
this.dom.collection.appendChild( nButton );
}
}
},
/**
* Loop through the columns in the table and as a new button for each one.
* @method _fnAddButtons
* @returns void
* @private
*/
"_fnAddButtons": function ()
{
var
nButton,
columns = this.s.dt.aoColumns;
if ( $.inArray( 'all', this.s.aiExclude ) === -1 ) {
for ( var i=0, iLen=columns.length ; i<iLen ; i++ )
{
if ( $.inArray( i, this.s.aiExclude ) === -1 )
{
nButton = this._fnDomColumnButton( i );
nButton.__columnIdx = i;
this.dom.buttons.push( nButton );
}
}
}
if ( this.s.order === 'alpha' ) {
this.dom.buttons.sort( function ( a, b ) {
var titleA = columns[ a.__columnIdx ].sTitle;
var titleB = columns[ b.__columnIdx ].sTitle;
return titleA === titleB ?
0 :
titleA < titleB ?
-1 :
1;
} );
}
if ( this.s.restore )
{
nButton = this._fnDomRestoreButton();
nButton.className += " ColVis_Restore";
this.dom.buttons.push( nButton );
}
if ( this.s.showAll )
{
nButton = this._fnDomShowXButton( this.s.showAll, true );
nButton.className += " ColVis_ShowAll";
this.dom.buttons.push( nButton );
}
if ( this.s.showNone )
{
nButton = this._fnDomShowXButton( this.s.showNone, false );
nButton.className += " ColVis_ShowNone";
this.dom.buttons.push( nButton );
}
$(this.dom.collection).append( this.dom.buttons );
},
/**
* Create a button which allows a "restore" action
* @method _fnDomRestoreButton
* @returns {Node} Created button
* @private
*/
"_fnDomRestoreButton": function ()
{
var
that = this,
dt = this.s.dt;
return $(
'<li class="ColVis_Special '+(dt.bJUI ? 'ui-button ui-state-default' : '')+'">'+
this.s.restore+
'</li>'
)
.click( function (e) {
for ( var i=0, iLen=that.s.abOriginal.length ; i<iLen ; i++ )
{
that.s.dt.oInstance.fnSetColumnVis( i, that.s.abOriginal[i], false );
}
that._fnAdjustOpenRows();
that.s.dt.oInstance.fnAdjustColumnSizing( false );
that.s.dt.oInstance.fnDraw( false );
} )[0];
},
/**
* Create a button which allows show all and show node actions
* @method _fnDomShowXButton
* @returns {Node} Created button
* @private
*/
"_fnDomShowXButton": function ( str, action )
{
var
that = this,
dt = this.s.dt;
return $(
'<li class="ColVis_Special '+(dt.bJUI ? 'ui-button ui-state-default' : '')+'">'+
str+
'</li>'
)
.click( function (e) {
for ( var i=0, iLen=that.s.abOriginal.length ; i<iLen ; i++ )
{
if (that.s.aiExclude.indexOf(i) === -1)
{
that.s.dt.oInstance.fnSetColumnVis( i, action, false );
}
}
that._fnAdjustOpenRows();
that.s.dt.oInstance.fnAdjustColumnSizing( false );
that.s.dt.oInstance.fnDraw( false );
} )[0];
},
/**
* Create the DOM for a show / hide group button
* @method _fnDomGroupButton
* @param {int} i Group in question, order based on that provided in settings
* @returns {Node} Created button
* @private
*/
"_fnDomGroupButton": function ( i )
{
var
that = this,
dt = this.s.dt,
oGroup = this.s.aoGroups[i];
return $(
'<li class="ColVis_Special '+(dt.bJUI ? 'ui-button ui-state-default' : '')+'">'+
'<label>'+
'<input type="checkbox" />'+
'<span>'+oGroup.sTitle+'</span>'+
'</label>'+
'</li>'
)
.click( function (e) {
var showHide = !$('input', this).is(":checked");
if ( e.target.nodeName.toLowerCase() !== "li" )
{
showHide = ! showHide;
}
for ( var j=0 ; j < oGroup.aiColumns.length ; j++ )
{
that.s.dt.oInstance.fnSetColumnVis( oGroup.aiColumns[j], showHide );
}
} )[0];
},
/**
* Create the DOM for a show / hide button
* @method _fnDomColumnButton
* @param {int} i Column in question
* @returns {Node} Created button
* @private
*/
"_fnDomColumnButton": function ( i )
{
var
that = this,
column = this.s.dt.aoColumns[i],
dt = this.s.dt;
var title = this.s.fnLabel===null ?
column.sTitle :
this.s.fnLabel( i, column.sTitle, column.nTh );
return $(
'<li '+(dt.bJUI ? 'class="ui-button ui-state-default"' : '')+'>'+
'<label>'+
'<input type="checkbox" />'+
'<span>'+title+'</span>'+
'</label>'+
'</li>'
)
.click( function (e) {
var showHide = !$('input', this).is(":checked");
if ( e.target.nodeName.toLowerCase() !== "li" )
{
if ( e.target.nodeName.toLowerCase() == "input" || that.s.fnStateChange === null )
{
showHide = ! showHide;
}
}
/* Need to consider the case where the initialiser created more than one table - change the
* API index that DataTables is using
*/
var oldIndex = $.fn.dataTableExt.iApiIndex;
$.fn.dataTableExt.iApiIndex = that._fnDataTablesApiIndex.call(that);
// Optimisation for server-side processing when scrolling - don't do a full redraw
if ( dt.oFeatures.bServerSide )
{
that.s.dt.oInstance.fnSetColumnVis( i, showHide, false );
that.s.dt.oInstance.fnAdjustColumnSizing( false );
if (dt.oScroll.sX !== "" || dt.oScroll.sY !== "" )
{
that.s.dt.oInstance.oApi._fnScrollDraw( that.s.dt );
}
that._fnDrawCallback();
}
else
{
that.s.dt.oInstance.fnSetColumnVis( i, showHide );
}
$.fn.dataTableExt.iApiIndex = oldIndex; /* Restore */
if ( that.s.fnStateChange !== null )
{
if ( e.target.nodeName.toLowerCase() == "span" )
{
e.preventDefault();
}
that.s.fnStateChange.call( that, i, showHide );
}
} )[0];
},
/**
* Get the position in the DataTables instance array of the table for this
* instance of ColVis
* @method _fnDataTablesApiIndex
* @returns {int} Index
* @private
*/
"_fnDataTablesApiIndex": function ()
{
for ( var i=0, iLen=this.s.dt.oInstance.length ; i<iLen ; i++ )
{
if ( this.s.dt.oInstance[i] == this.s.dt.nTable )
{
return i;
}
}
return 0;
},
/**
* Create the element used to contain list the columns (it is shown and
* hidden as needed)
* @method _fnDomCollection
* @returns {Node} div container for the collection
* @private
*/
"_fnDomCollection": function ()
{
return $('<ul />', {
'class': !this.s.dt.bJUI ?
"ColVis_collection" :
"ColVis_collection ui-buttonset ui-buttonset-multi"
} )
.css( {
'display': 'none',
'opacity': 0,
'position': ! this.s.bCssPosition ?
'absolute' :
''
} )[0];
},
/**
* An element to be placed on top of the activate button to catch events
* @method _fnDomCatcher
* @returns {Node} div container for the collection
* @private
*/
"_fnDomCatcher": function ()
{
var
that = this,
nCatcher = document.createElement('div');
nCatcher.className = "ColVis_catcher";
$(nCatcher).click( function () {
that._fnCollectionHide.call( that, null, null );
} );
return nCatcher;
},
/**
* Create the element used to shade the background, and capture hide events (it is shown and
* hidden as needed)
* @method _fnDomBackground
* @returns {Node} div container for the background
* @private
*/
"_fnDomBackground": function ()
{
var that = this;
var background = $('<div></div>')
.addClass( 'ColVis_collectionBackground' )
.css( 'opacity', 0 )
.click( function () {
that._fnCollectionHide.call( that, null, null );
} );
/* When considering a mouse over action for the activation, we also consider a mouse out
* which is the same as a mouse over the background - without all the messing around of
* bubbling events. Use the catcher element to avoid messing around with bubbling
*/
if ( this.s.activate == "mouseover" )
{
background.mouseover( function () {
that.s.overcollection = false;
that._fnCollectionHide.call( that, null, null );
} );
}
return background[0];
},
/**
* Show the show / hide list and the background
* @method _fnCollectionShow
* @returns void
* @private
*/
"_fnCollectionShow": function ()
{
var that = this, i, iLen, iLeft;
var oPos = $(this.dom.button).offset();
var nHidden = this.dom.collection;
var nBackground = this.dom.background;
var iDivX = parseInt(oPos.left, 10);
var iDivY = parseInt(oPos.top + $(this.dom.button).outerHeight(), 10);
if ( ! this.s.bCssPosition )
{
nHidden.style.top = iDivY+"px";
nHidden.style.left = iDivX+"px";
}
$(nHidden).css( {
'display': 'block',
'opacity': 0
} );
nBackground.style.bottom ='0px';
nBackground.style.right = '0px';
var oStyle = this.dom.catcher.style;
oStyle.height = $(this.dom.button).outerHeight()+"px";
oStyle.width = $(this.dom.button).outerWidth()+"px";
oStyle.top = oPos.top+"px";
oStyle.left = iDivX+"px";
document.body.appendChild( nBackground );
document.body.appendChild( nHidden );
document.body.appendChild( this.dom.catcher );
/* This results in a very small delay for the end user but it allows the animation to be
* much smoother. If you don't want the animation, then the setTimeout can be removed
*/
$(nHidden).animate({"opacity": 1}, that.s.iOverlayFade);
$(nBackground).animate({"opacity": 0.1}, that.s.iOverlayFade, 'linear', function () {
/* In IE6 if you set the checked attribute of a hidden checkbox, then this is not visually
* reflected. As such, we need to do it here, once it is visible. Unbelievable.
*/
if ( $.browser && $.browser.msie && $.browser.version == "6.0" )
{
that._fnDrawCallback();
}
});
/* Visual corrections to try and keep the collection visible */
if ( !this.s.bCssPosition )
{
iLeft = ( this.s.sAlign=="left" ) ?
iDivX :
iDivX - $(nHidden).outerWidth() + $(this.dom.button).outerWidth();
nHidden.style.left = iLeft+"px";
var iDivWidth = $(nHidden).outerWidth();
var iDivHeight = $(nHidden).outerHeight();
var iDocWidth = $(document).width();
if ( iLeft + iDivWidth > iDocWidth )
{
nHidden.style.left = (iDocWidth-iDivWidth)+"px";
}
}
this.s.hidden = false;
},
/**
* Hide the show / hide list and the background
* @method _fnCollectionHide
* @returns void
* @private
*/
"_fnCollectionHide": function ( )
{
var that = this;
if ( !this.s.hidden && this.dom.collection !== null )
{
this.s.hidden = true;
$(this.dom.collection).animate({"opacity": 0}, that.s.iOverlayFade, function (e) {
this.style.display = "none";
} );
$(this.dom.background).animate({"opacity": 0}, that.s.iOverlayFade, function (e) {
document.body.removeChild( that.dom.background );
document.body.removeChild( that.dom.catcher );
} );
}
},
/**
* Alter the colspan on any fnOpen rows
*/
"_fnAdjustOpenRows": function ()
{
var aoOpen = this.s.dt.aoOpenRows;
var iVisible = this.s.dt.oApi._fnVisbleColumns( this.s.dt );
for ( var i=0, iLen=aoOpen.length ; i<iLen ; i++ ) {
aoOpen[i].nTr.getElementsByTagName('td')[0].colSpan = iVisible;
}
}
};
/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
* Static object methods
* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */
/**
* Rebuild the collection for a given table, or all tables if no parameter given
* @method ColVis.fnRebuild
* @static
* @param object oTable DataTable instance to consider - optional
* @returns void
*/
ColVis.fnRebuild = function ( oTable )
{
var nTable = null;
if ( typeof oTable != 'undefined' )
{
nTable = $.fn.dataTable.Api ?
new $.fn.dataTable.Api( oTable ).table().node() :
oTable.fnSettings().nTable;
}
for ( var i=0, iLen=ColVis.aInstances.length ; i<iLen ; i++ )
{
if ( typeof oTable == 'undefined' || nTable == ColVis.aInstances[i].s.dt.nTable )
{
ColVis.aInstances[i].fnRebuild();
}
}
};
ColVis.defaults = {
/**
* Mode of activation. Can be 'click' or 'mouseover'
* @property activate
* @type string
* @default click
*/
active: 'click',
/**
* Text used for the button
* @property buttonText
* @type string
* @default Show / hide columns
*/
buttonText: 'Show / hide columns',
/**
* List of columns (integers) which should be excluded from the list
* @property aiExclude
* @type array
* @default []
*/
aiExclude: [],
/**
* Show restore button
* @property bRestore
* @type boolean
* @default false
*/
bRestore: false,
/**
* Restore button text
* @property sRestore
* @type string
* @default Restore original
*/
sRestore: 'Restore original',
/**
* Show Show-All button
* @property bShowAll
* @type boolean
* @default false
*/
bShowAll: false,
/**
* Show All button text
* @property sShowAll
* @type string
* @default Restore original
*/
sShowAll: 'Show All',
/**
* Position of the collection menu when shown - align "left" or "right"
* @property sAlign
* @type string
* @default left
*/
sAlign: 'left',
/**
* Callback function to tell the user when the state has changed
* @property fnStateChange
* @type function
* @default null
*/
fnStateChange: null,
/**
* Overlay animation duration in mS
* @property iOverlayFade
* @type integer|false
* @default 500
*/
iOverlayFade: 500,
/**
* Label callback for column names. Takes three parameters: 1. the
* column index, 2. the column title detected by DataTables and 3. the
* TH node for the column
* @property fnLabel
* @type function
* @default null
*/
fnLabel: null,
/**
* Indicate if the column list should be positioned by Javascript,
* visually below the button or allow CSS to do the positioning
* @property bCssPosition
* @type boolean
* @default false
*/
bCssPosition: false,
/**
* Group buttons
* @property aoGroups
* @type array
* @default []
*/
aoGroups: [],
/**
* Button ordering - 'alpha' (alphabetical) or 'column' (table column
* order)
* @property order
* @type string
* @default column
*/
order: 'column'
};
/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
* Static object properties
* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */
/**
* Collection of all ColVis instances
* @property ColVis.aInstances
* @static
* @type Array
* @default []
*/
ColVis.aInstances = [];
/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
* Constants
* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */
/**
* Name of this class
* @constant CLASS
* @type String
* @default ColVis
*/
ColVis.prototype.CLASS = "ColVis";
/**
* ColVis version
* @constant VERSION
* @type String
* @default See code
*/
ColVis.VERSION = "1.1.2";
ColVis.prototype.VERSION = ColVis.VERSION;
/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
* Initialisation
* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */
/*
* Register a new feature with DataTables
*/
if ( typeof $.fn.dataTable == "function" &&
typeof $.fn.dataTableExt.fnVersionCheck == "function" &&
$.fn.dataTableExt.fnVersionCheck('1.7.0') )
{
$.fn.dataTableExt.aoFeatures.push( {
"fnInit": function( oDTSettings ) {
var init = oDTSettings.oInit;
var colvis = new ColVis( oDTSettings, init.colVis || init.oColVis || {} );
return colvis.button();
},
"cFeature": "C",
"sFeature": "ColVis"
} );
}
else
{
alert( "Warning: ColVis requires DataTables 1.7 or greater - www.datatables.net/download");
}
// Make ColVis accessible from the DataTables instance
$.fn.dataTable.ColVis = ColVis;
$.fn.DataTable.ColVis = ColVis;
return ColVis;
}; // /factory
// Define as an AMD module if possible
if ( typeof define === 'function' && define.amd ) {
define( ['jquery', 'datatables'], factory );
}
else if ( typeof exports === 'object' ) {
// Node/CommonJS
factory( require('jquery'), require('datatables') );
}
else if ( jQuery && !jQuery.fn.dataTable.ColVis ) {
// Otherwise simply initialise as normal, stopping multiple evaluation
factory( jQuery, jQuery.fn.dataTable );
}
})(window, document);
| {
"pile_set_name": "Github"
} |
-------------------------------------------------------------------
Wed Aug 2 14:59:15 UTC 2017 - [email protected]
- Temporary hack
| {
"pile_set_name": "Github"
} |
/*++
Copyright (c) Microsoft Corporation. All rights reserved.
_WdfVersionBuild_
Module Name:
wdfminiport.h
Abstract:
Interfaces for WDF usage in a miniport environment
Environment:
kernel mode only
Revision History:
--*/
//
// NOTE: This header is generated by stubwork. Please make any
// modifications to the corresponding template files
// (.x or .y) and use stubwork to regenerate the header
//
#ifndef _WDFMINIPORT_H_
#define _WDFMINIPORT_H_
#ifndef WDF_EXTERN_C
#ifdef __cplusplus
#define WDF_EXTERN_C extern "C"
#define WDF_EXTERN_C_START extern "C" {
#define WDF_EXTERN_C_END }
#else
#define WDF_EXTERN_C
#define WDF_EXTERN_C_START
#define WDF_EXTERN_C_END
#endif
#endif
WDF_EXTERN_C_START
#if (NTDDI_VERSION >= NTDDI_WIN2K)
//
// WDF Function: WdfDeviceMiniportCreate
//
typedef
_Must_inspect_result_
_IRQL_requires_max_(PASSIVE_LEVEL)
WDFAPI
NTSTATUS
(*PFN_WDFDEVICEMINIPORTCREATE)(
_In_
PWDF_DRIVER_GLOBALS DriverGlobals,
_In_
WDFDRIVER Driver,
_In_opt_
PWDF_OBJECT_ATTRIBUTES Attributes,
_In_
PDEVICE_OBJECT DeviceObject,
_In_opt_
PDEVICE_OBJECT AttachedDeviceObject,
_In_opt_
PDEVICE_OBJECT Pdo,
_Out_
WDFDEVICE* Device
);
_Must_inspect_result_
_IRQL_requires_max_(PASSIVE_LEVEL)
NTSTATUS
FORCEINLINE
WdfDeviceMiniportCreate(
_In_
WDFDRIVER Driver,
_In_opt_
PWDF_OBJECT_ATTRIBUTES Attributes,
_In_
PDEVICE_OBJECT DeviceObject,
_In_opt_
PDEVICE_OBJECT AttachedDeviceObject,
_In_opt_
PDEVICE_OBJECT Pdo,
_Out_
WDFDEVICE* Device
)
{
return ((PFN_WDFDEVICEMINIPORTCREATE) WdfFunctions[WdfDeviceMiniportCreateTableIndex])(WdfDriverGlobals, Driver, Attributes, DeviceObject, AttachedDeviceObject, Pdo, Device);
}
//
// WDF Function: WdfDriverMiniportUnload
//
typedef
WDFAPI
VOID
(*PFN_WDFDRIVERMINIPORTUNLOAD)(
_In_
PWDF_DRIVER_GLOBALS DriverGlobals,
_In_
WDFDRIVER Driver
);
VOID
FORCEINLINE
WdfDriverMiniportUnload(
_In_
WDFDRIVER Driver
)
{
((PFN_WDFDRIVERMINIPORTUNLOAD) WdfDriverMiniportUnloadOverride)(WdfDriverGlobals, Driver);
}
#endif // (NTDDI_VERSION >= NTDDI_WIN2K)
WDF_EXTERN_C_END
#endif // _WDFMINIPORT_H_
| {
"pile_set_name": "Github"
} |
{"text": ["cisco", "systems", "target", "of", "unusually", "large", "options", "trading", "$", "csco", "URL"], "created_at": "Mon Dec 15 23:29:47 +0000 2014", "user_id_str": "2181281054"}
{"text": ["dont", "want", "to", "lose", "like", "you", "did", "with", "$", "seic", "$", "csco", "$", "ov", "$", "gain", "stock", "URL"], "created_at": "Tue Dec 16 08:32:10 +0000 2014", "user_id_str": "2723762664"}
{"text": ["stock", "watch", ":", "cisco", "systems", ",", "inc", ".", "(", "nasdaq", ":", "csco", ")", "$", "csco", "URL"], "created_at": "Tue Dec 16 14:50:53 +0000 2014", "user_id_str": "704897486"}
{"text": ["get", "more", "info", "on", "$", "str", "$", "csco", "$", "bcr", "$", "do", "worth", "a", "look", "URL"], "created_at": "Tue Dec 16 07:56:47 +0000 2014", "user_id_str": "2729361109"}
| {
"pile_set_name": "Github"
} |
package com.jayway.jsonpath.spi.cache;
import com.jayway.jsonpath.InvalidJsonException;
import com.jayway.jsonpath.JsonPath;
public interface Cache {
/**
* Get the Cached JsonPath
* @param key cache key to lookup the JsonPath
* @return JsonPath
*/
JsonPath get(String key);
/**
* Add JsonPath to the cache
* @param key cache key to store the JsonPath
* @param value JsonPath to be cached
* @throws InvalidJsonException
*/
void put(String key, JsonPath value);
}
| {
"pile_set_name": "Github"
} |
/*
* 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.isis.core.metamodel.facets.param.layout;
import java.util.Optional;
import org.apache.isis.applib.annotation.ParameterLayout;
import org.apache.isis.core.metamodel.facetapi.FacetHolder;
import org.apache.isis.core.metamodel.facets.objectvalue.multiline.MultiLineFacet;
import org.apache.isis.core.metamodel.facets.objectvalue.multiline.MultiLineFacetAbstract;
public class MultiLineFacetForParameterLayoutAnnotation extends MultiLineFacetAbstract {
public static MultiLineFacet create(
final Optional<ParameterLayout> parameterLayoutIfAny,
final FacetHolder holder) {
return parameterLayoutIfAny
.map(ParameterLayout::multiLine)
.filter(multiLine -> multiLine != -1)
.map(multiLine -> new MultiLineFacetForParameterLayoutAnnotation(multiLine, false, holder))
.orElse(null);
}
private MultiLineFacetForParameterLayoutAnnotation(int numberOfLines, boolean preventWrapping, FacetHolder holder) {
super(numberOfLines, preventWrapping, holder);
}
}
| {
"pile_set_name": "Github"
} |
/**
* | {
"pile_set_name": "Github"
} |
/* -*- mode: espresso; espresso-indent-level: 2; indent-tabs-mode: nil -*- */
/* vim: set softtabstop=2 shiftwidth=2 tabstop=2 expandtab: */
(function(CATMAID) {
"use strict";
var Sampling = {};
/**
* Get a sub-arbor from the passed in arbor that matches the passed in domain
* model.
*/
Sampling.domainArborFromModel = function(arbor, domain, strict) {
return CATMAID.Sampling.domainArbor(arbor, domain.start_node_id,
domain.ends.map(function(e) { return e.node_id; }), strict);
};
/**
* Get sub-arbor that starts at a start node and is pruned at all domain ends.
*/
Sampling.domainArbor = function(arbor, startNodeId, endNodeIds, strict) {
var domainArbor = arbor.subArbor(startNodeId);
var allSuccessors = domainArbor.allSuccessors();
// Remove all nodes after end nodes
domainArbor.pruneAt(endNodeIds.reduce(function(o, endNodeId) {
// Pruning is inclusive, so we need to prune the potential successors
// of the end nodes.
var successors = allSuccessors[endNodeId];
if (successors) {
for (var i=0; i<successors.length; ++i) {
o[successors[i]] = true;
}
}
return o;
}, {}));
// Remove edged that are disconnected from component that contains the root
// node.
var rootDistance = domainArbor.nodesOrderFrom(domainArbor.root);
var nodes = Object.keys(domainArbor.edges);
for (var i=0, max=nodes.length; i<max; ++i) {
var nodeId = nodes[i];
if (rootDistance[nodeId] === undefined) {
delete domainArbor.edges[nodeId];
}
}
// In strict mode, remove all parts of the arbor that are not strictly part
// of the path between root and end nodes.
if (strict) {
domainArbor = domainArbor.spanningTree([startNodeId].concat(endNodeIds));
}
return domainArbor;
};
/**
* The passed in interval map will be update with nodes from the arbor that
* are covered by the passed in interval list.
*/
Sampling.updateIntervalMap = function(arbor, intervals, targetEdgeMap,
domainStartId, intervalFilter) {
for (var i=0, imax=intervals.length; i<imax; ++i) {
let interval = intervals[i];
let intervalId = interval[0];
let startNodeId = interval[1];
let endNodeId = interval[2];
// If an interval fitler exists, show only intervals allowed by it.
if (intervalFilter &&
intervalFilter.length > 0 &&
intervalFilter.indexOf(intervalId) === -1) {
continue;
}
// Try to walk from interval end to start, assuming that an interval
// starts closer to root than it ends.
let currentNodeId = endNodeId;
while (true) {
targetEdgeMap[currentNodeId] = intervalId;
currentNodeId = arbor.edges[currentNodeId];
if (currentNodeId == startNodeId) {
// Don't set the start node of an interval explicitly. Start nodes are
// either the end of another interval or the domain start.
if (currentNodeId == domainStartId || !targetEdgeMap[currentNodeId]) {
targetEdgeMap[currentNodeId] = intervalId;
}
break;
}
if (!currentNodeId) {
throw new CATMAID.ValueError("Arrived at root node without finding interval start");
}
}
}
};
function addToTargetEdMap(nodeInfo) {
/* jshint validthis: true */
this[nodeInfo[0]] = nodeInfo[1];
}
/**
* Intervals are created by traversing a domain downstream and cutting out
* interval parts continuously. This is done by first splitting a domain into
* paritions, i.e downstream paths from root or branchpoints to leaves, in
* order of decreasing length. cutting out individual intervals.
* Partions are paths from root or branch points to leaves. Returns an object
* with an <intervals> field and and <addedNodes> field. The former is a list
* of two-element tuples which are treenodes referencing the beginning and the
* end of an interval. In <addedNodes> node IDs in <intervals> can be
* overridden and new nodes created instead. Entries in the <addedNodes> list
* are of the form [id, childId, parentId, x, y, z]. The new node will be
* created at x, y, z between the childId and parentId nodes. The location has
* to be collinear with child and parent locations and between them. The
* leafHandling parameter allows to select a strategy for handling leaf
* segments, allowed are 'ignore', 'merge', 'short-interval' and
* 'merge-or-create'. The first one ignores leaf segments (default), the
* second option merges it into the last interval, the third option creates
* a short interval containing the whole leaf segment and the last option
* merges into the last segment if possible (i.e. it is not the first segment
* in a partition) and otherwise creates a new shorter interval.
*
* If <nodeBlacklist> is provided, no new nodes will be created that are in
* the blacklist (a Map or Set)..
*/
Sampling.intervalsFromModels = function(arbor, positions, domainDetails,
intervalLength, intervalError, preferSmallerError, createNewNodes,
leafHandling, updateArborData, targetEdgeMap, nodeBlacklist, mergeLimit,
strict) {
if (!intervalLength) {
throw new CATMAID.ValueError("Need interval length for interval creation");
}
// Get domain arbor, which is then split into slabs, which are then
// further split into intervals of respective length.
var domainArbor = CATMAID.Sampling.domainArborFromModel(arbor, domainDetails, strict);
preferSmallerError = preferSmallerError === undefined ? true : !!preferSmallerError;
createNewNodes = CATMAID.tools.getDefined(createNewNodes, false);
// Find an ID number that is higher than all already used ones. This is
// needed for artificial new nodes with realistic ids without reusing
// existing IDs of the sampled skeleton.
let newPointId = Math.max(arbor.root, Math.max.apply(Math,
(Object.keys(arbor.edges).map(Number)))) + 1;
// Create Intervals from partitions
var intervals = [];
var addedNodes = [];
var currentInterval = 0;
var partitions = domainArbor.partitionSorted();
for (var i=0; i<partitions.length; ++i) {
var partition = partitions[i].map(Number);
// Walk partition toward leaves
var dist = 0, lastDist;
var intervalStartIdx = partition.length - 1;
var intervalStartPos = positions[partition[intervalStartIdx]];
var intervalNodes = [];
// Traverse partition toward leaves, i.e. from the end of the partition
// entries to branch points or root.
for (var j=partition.length - 2; j>=0; --j) {
lastDist = dist;
// Calculate new interval length, we can
var lastPos = positions[partition[j+1]];
var pos = positions[partition[j]];
dist += lastPos.distanceTo(pos);
// If sum is greater than interval length, create new interval. If
// <preferSmalError>, the end/start node is either the current one
// or the last one, whichever is closer to the ideal length. If
// <createNewNodes> is truthy, new nodes will be created so that the
// specified interval length will be matched. Otherwise this node is used.
let distance = dist - intervalLength;
if (distance < 0.0001) {
// Rember node for potentially added interval
if (targetEdgeMap) {
intervalNodes.push([
partition[j],
currentInterval
]);
}
// Node is exactly at end of interval
if (distance > -0.0001) {
intervals.push([partition[intervalStartIdx], partition[j]]);
intervalStartIdx = j;
dist = 0;
currentInterval++;
if (targetEdgeMap) {
intervalNodes.forEach(addToTargetEdMap, targetEdgeMap);
intervalNodes = [];
}
// If this is the last node of the segment, allow different leaf
// segment handling strategies.
} else if (j === 0) {
let isFirstInterval = intervalStartIdx === (partition.length - 1);
let fragmentLengthRatio = dist / intervalLength;
let canBeMerged = fragmentLengthRatio <= mergeLimit &&
(leafHandling === 'merge' || leafHandling === 'merge-or-create');
if (canBeMerged && !isFirstInterval) {
// Add the collected nodes of the current interval to the last
// interval. This only is allowed if this interval isn't the first
// interval on this segment.
let lastEndId = intervals[intervals.length - 1][1];
intervals[intervals.length - 1][1] = partition[j];
for (let k=0; k<addedNodes.length; ++k) {
let n = addedNodes[k];
let isAddedNode = n[0] == lastEndId;
if (isAddedNode) {
// Remove former newly added end node from partition, added
// nodes and from arbor.;
if (updateArborData) {
arbor.edges[partition[intervalStartIdx - 1]] = partition[intervalStartIdx + 1];
delete arbor.edges[lastEndId];
delete positions[lastEndId];
}
addedNodes.splice(k, 1);
partition.splice(j+1, 1);
break;
}
}
if (targetEdgeMap) {
for (let k=0; k<intervalNodes.length; ++k) {
// Reference last interval for all nodes of this leaf segmenet.
let nodeInfo = intervalNodes[k];
--nodeInfo[1];
}
intervalNodes.forEach(addToTargetEdMap, targetEdgeMap);
}
} else if (leafHandling === 'short-interval' ||
leafHandling === 'merge-or-create') {
// Create a new, shorter inerval
intervals.push([partition[intervalStartIdx], partition[j]]);
if (targetEdgeMap) {
intervalNodes.forEach(addToTargetEdMap, targetEdgeMap);
}
}
}
} else {
// This branch represents the case the current node is already too far
// away to match the interval length exactly.
var steps = intervalStartIdx - j;
let edgeLength = dist - lastDist;
let distanceToLast = intervalLength - lastDist;
let distanceToThis = edgeLength - distanceToLast;
let lastIsFirst = steps === 0;
let thisIsLast = j === 0;
let selectedNode = null;
// If this or the last node is closer
if (distanceToLast < distanceToThis) {
// If the last node is close enough and is not the start of the
// current interval, select it as interval boundary.
if (distanceToLast < intervalError && intervalStartIdx !== j + 1) {
// Use last node, because it is closer than this node and closer
// than the allowed interval error.
selectedNode = partition[j+1];
// To properly re-evaluate this node (it hasn't been chosen to
// end the current interval), continue from the last node with
// the next potential interval, move index back one step.
j++;
}
} else {
if (distanceToThis < intervalError) {
// Use this node, because it is closer than the last node and
// closer than the allowed interval error.
selectedNode = partition[j];
}
}
if (!selectedNode) {
let isBlacklisted = nodeBlacklist &&
(nodeBlacklist.has(partition[j]) || nodeBlacklist.has(partition[j+1]));
if (createNewNodes && !isBlacklisted) {
// Optionally, create a new node between this node and the last one.
// This also requires updating the arbor.
let dRatio = distanceToLast / edgeLength;
let newPointPos = lastPos.clone().lerpVectors(lastPos, pos, dRatio);
// Add new point into arbor
if (arbor.edges[newPointId]) {
throw new CATMAID.PreConditionError("The temporary ID for the " +
"new interval end location exists already: " + newPointId);
}
// Insert new node into arbor
let childId = partition[j];
let parentId = partition[j+1];
if (updateArborData) {
arbor.edges[childId] = newPointId;
arbor.edges[newPointId] = parentId;
positions[newPointId] = newPointPos;
}
addedNodes.push([newPointId, childId, parentId, newPointPos.x,
newPointPos.y, newPointPos.z]);
// Insert element in currently iterated loop and move one step back
// (remember, we walk backwards).
partition.splice(j+1, 0, newPointId);
selectedNode = newPointId;
j++;
// We walk the partition from end to front. Inserting the a node
// into the partition, requires us to go one step back to remain
// on the same element with our current index.
intervalStartIdx++;
// Prepare point ID for next point
newPointId++;
} else if (preferSmallerError && intervalStartIdx !== j + 1 &&
distanceToLast < distanceToThis && !lastIsFirst) {
// Optionally, make the interval smaller if this means being closer to
// the ideal interval length. This can only be done if the current
// interval has at least a length of 2 and the previous node isn't
// the interval start.
selectedNode = partition[j+1];
// To properly continue from the last node with the next interval,
// move index back one step.
j++;
} else {
selectedNode = partition[j];
}
}
// If a node was found and an edge map is passed in, add the current
// interval for the selected node.
if (!selectedNode) {
throw new CATMAID.ValueError("Could not select node for interval creation");
}
if (targetEdgeMap) {
targetEdgeMap[selectedNode] = currentInterval;
}
if (targetEdgeMap) {
intervalNodes.forEach(addToTargetEdMap, targetEdgeMap);
intervalNodes = [];
}
intervals.push([partition[intervalStartIdx], selectedNode]);
intervalStartIdx = j;
currentInterval++;
dist = 0;
intervalNodes = [];
}
}
}
return {
intervals: intervals,
addedNodes: addedNodes
};
};
/**
* Get an edge mapping for all edges in the passed in arbor that are part of
* one of the domains that are part of the passed in sampler. Optionally, only
* particular domains can be respected.
*/
Sampling.samplerEdges = function(arbor, sampler, target, allowedDomains) {
edges = target || {};
var edges = sampler.domains.reduce(function(o, d) {
if (allowedDomains &&
allowedDomains.length > 0 &&
allowedDomains.indexOf(d.id) === -1) {
return o;
}
var domainArbor = CATMAID.Sampling.domainArborFromModel(arbor, d);
// Add all edges of the domain arbor to the sampler wide edge mapping
for (var parentId in domainArbor.edges) {
o[parentId] = domainArbor.edges[parentId];
}
if (domainArbor.root) {
o[domainArbor.root] = null;
}
return o;
}, edges);
return edges;
};
/**
* Get an edge mapping for all edges in the passed in arbor that are part of
* one of the intervals of the domains of the passed in sampler. Note that
* the set of interval edges can be smaller than the domain set one.
*/
Sampling.intervalEdges = function(arbor, positions, sampler,
preferSmallerError, createNewNodes, updateArborData, target) {
// Build intervals for each domain, based on the interval length defined in
// the sampler.
return sampler.domains.reduce(function(o, d) {
var intervalConfiguration = Sampling.intervalsFromModels(arbor, positions,
d, sampler.interval_length, sampler.interval_error, preferSmallerError,
createNewNodes, sampler.leaf_segment_handling, updateArborData, target,
sampler.merge_limit);
o[d.id] = intervalConfiguration.intervals;
return o;
}, {});
};
Sampling.NodeProviders = {
'active': function(arborParser) {
var activeNodeId = SkeletonAnnotations.getActiveNodeId();
return new Promise(function(resolve, reject) {
if (!activeNodeId) {
throw new CATMAID.ValueError("No node selected");
}
// Instead of virtual nodes, their children are used.
if (!SkeletonAnnotations.isRealNode(activeNodeId)) {
activeNodeId = SkeletonAnnotations.getChildOfVirtualNode(activeNodeId);
}
if (!arborParser.arbor.contains(activeNodeId)) {
throw new CATMAID.ValueError("Active node not part of specified skeleton");
}
resolve([activeNodeId]);
});
},
'select': function(arborParser) {
return new Promise(function(resolve, reject) {
var dialog = new CATMAID.OptionsDialog("Select node", {
'Use active node': function() {
var activeNodeId = SkeletonAnnotations.getActiveNodeId();
if (!activeNodeId) {
throw new CATMAID.ValueError("No node selected");
}
// Instead of virtual nodes, their children are used.
if (!SkeletonAnnotations.isRealNode(activeNodeId)) {
activeNodeId = SkeletonAnnotations.getChildOfVirtualNode(activeNodeId);
}
if (!arborParser.arbor.contains(activeNodeId)) {
throw new CATMAID.ValueError("Active node not part of specified skeleton");
}
CATMAID.msg("Selected node", activeNodeId);
resolve([activeNodeId]);
}
});
dialog.appendMessage("Please select a node");
dialog.show('auto', 'auto', false);
});
},
'root': function(arborParser) {
return new Promise(function(resolve, reject) {
var arbor = arborParser.arbor;
if (!arbor.root) {
throw new CATMAID.ValueError("No root node found");
}
resolve([arbor.root]);
});
},
'tag': function(arborParser) {
return new Promise(function(resolve, reject) {
var tagInput = null;
var dialog = new CATMAID.OptionsDialog("Provide tag", {
'Use tagged nodes': function() {
var tag = tagInput.value;
var taggedNodes = arborParser.tags[tag];
if (!taggedNodes) {
throw new CATMAID.ValueError("No nodes found with tag \"" + tag + "\"");
}
resolve(taggedNodes.slice(0));
}
});
dialog.appendMessage("Please specify a tag to use");
tagInput = dialog.appendField("Tag", "tag-selection", "", true);
dialog.show('auto', 'auto', false);
// Add autocompletetion to tag input
$(tagInput).autocomplete({
source: Object.keys(arborParser.tags)
});
});
},
'downstream': function(arborParser, options) {
var arbor = arborParser.arbor;
var referenceNodes = options['referenceNodes'];
if (!referenceNodes) {
throw new CATMAID.ValueError("At least one reference node is required");
}
return new Promise(function(resolve, reject) {
var nodes = [];
for (var i=0; i<referenceNodes.length; ++i) {
var arbor = arbor.subArbor(referenceNodes[i]);
nodes = nodes.concat(arbor.findEndNodes());
}
resolve(nodes);
});
}
};
/**
* Get arbor information on a particular skeleton.
*/
Sampling.getArbor = function(skeletonId) {
// Get nodes and tags for skeleton
return CATMAID.fetch(project.id + '/' + skeletonId + '/1/1/1/compact-arbor', 'POST')
.then(function(result) {
var ap = new CATMAID.ArborParser();
ap.tree(result[0]);
return {
arbor: ap.arbor,
positions: ap.positions,
tags: result[2]
};
});
};
Sampling.DomainFactories = {
'covering': {
/**
* Create a single domain for a skeleton ID.
*/
makeDomains: function(skeletonId, options) {
return Sampling.getArbor(skeletonId)
.then(function(arborParser) {
return {
domains: [{
startNodeId: arborParser.arbor.root,
endNodeIds: arborParser.arbor.findEndNodes()
}],
cache: {
arbor: arborParser
}
};
});
}
},
'regular': {
/**
* Let domains grow downstream from a set of start nodes toward a set of end
* nodes.
*/
makeDomains: function(skeletonId, options) {
var startNodeProvider = CATMAID.Sampling.NodeProviders[options.domainStartNodeType];
var endNodeProvider = CATMAID.Sampling.NodeProviders[options.domainEndNodeType];
return Sampling.getArbor(skeletonId)
.then(function(arborParser) {
// Get start and end nodes and sanitize this selection so that start
// node IDs are upstream of end nodes. Let domains be greedy, i.e.
// make them as big as possible.
var domainStartNodeIds = startNodeProvider(arborParser, options);
options['referenceNodes'] = domainStartNodeIds;
return Promise.all([arborParser, domainStartNodeIds]);
})
.then(function(results) {
// Get end nodes only after start nodes have been required, which is
// mainly important for manual node selection.
var domainEndNodeIds = endNodeProvider(results[0], options);
return Promise.all([results[0], results[1], domainEndNodeIds]);
})
.then(function(results) {
var arborParser = results[0];
var domainStartNodeIds = results[1];
var domainEndNodeIds = results[2];
var arbor = arborParser.arbor;
var rootDistance = arbor.nodesOrderFrom(arbor.root);
// Sort domain start node IDs by distance to root in ascending order
domainStartNodeIds.sort(function(a, b) {
return rootDistance[a] < rootDistance[b];
});
// The goal is to find end nodes that are actually downstream of
// each start node and create domains only for those start nodes
// along with its downstram domain end nodes. Domains are currently
// allowed to overlap.
var seen = new Set();
var domains = domainStartNodeIds.reduce(function(o, startNodeId) {
// Create new Arbor instance for domain, pruned at downstream end
// nodes. All branches in between are implicitely part of the
// domain. This will also take care of removing end nodes that
// won't affect the downstream arbor.
var domainArbor = CATMAID.Sampling.domainArbor(arbor, startNodeId,
domainEndNodeIds);
o.push({
startNodeId: domainArbor.root,
endNodeIds: domainArbor.findEndNodes()
});
return o;
}, []);
return {
domains: domains,
cache: {
arbor: arborParser
}
};
});
}
}
};
/**
* Return all nodes on the straight path in then interval [startNodeId,
* endNodeId], assuming both nodes are connected through a monotone
* parent-child relationship. The direction doesn't matter as long as <strict>
* isn't set to true. If this is the case, the start node has to be closer to
* root than end node. The result can optionally be sorted by setting <sort>
* to true.
*/
Sampling.getIntervalBackboneNodes = function(arbor, startNodeId, endNodeId,
sort, strict) {
var intervalNodes = [];
// Assume end node is downstream of start node
var nodes = arbor.edges;
var lastNode = endNodeId;
while (true) {
lastNode = parseInt(lastNode, 10);
intervalNodes.push(lastNode);
if (lastNode == startNodeId) {
break;
}
lastNode = nodes[lastNode];
if (!lastNode) {
break;
}
}
if (intervalNodes.length === 0) {
return null;
}
// If the last node is not the interval start node, try reversing start/end
// node if not in strict mode.
if (intervalNodes[intervalNodes.length - 1] == startNodeId) {
return sort ? intervalNodes.reverse() : intervalNodes;
} else {
return strict ? null : CATMAID.Sampling.getIntervalBackboneNodes(arbor,
endNodeId, startNodeId, sort, true);
}
};
/**
* Return all nodes that are part of the requested interval. This set will not
* contain any branches starting off the start or end node, as these will be
* part of other intervals. Additionally a Set instance can be passed in as
* <boundaryNodes>. The returned interval nodes won't contain any nodes beyond
* any of those boundary nodes nor the boundary nodes themselves.
*/
Sampling.getIntervalNodes = function(arbor, startNodeId, endNodeId, boundaryNodes) {
startNodeId = parseInt(startNodeId, 10);
endNodeId = parseInt(endNodeId, 10);
boundaryNodes = boundaryNodes || new Set();
var intervalBackbone = CATMAID.Sampling.getIntervalBackboneNodes(arbor,
startNodeId, endNodeId, true);
if (!intervalBackbone || intervalBackbone.length === 0) {
throw new CATMAID.ValueError("Could not find interval backbone for between nodes " +
startNodeId + " and " + endNodeId);
}
var edges = arbor.edges;
var allSuccessors = arbor.allSuccessors();
// Collect nodes between start and end of the interval back-bone, all
// branches inbetween will be added. Branches originating from the start or
// end node will *not* be added, other intervals have to be used for those.
var workingSet = intervalBackbone.map(function(n) {
// Make sure we deal with numbers
return parseInt(n, 10);
});
var intervalNodes = new Set(workingSet);
while (workingSet.length > 0) {
var currentNodeId = workingSet.pop();
if (currentNodeId === startNodeId || currentNodeId === endNodeId) {
continue;
}
// Don't include children of boundary nodes
if (boundaryNodes.has(currentNodeId)) {
continue;
}
var children = allSuccessors[currentNodeId];
for (var i=0; i<children.length; ++i) {
var childId = parseInt(children[i], 10);
// Don't include children of boundary nodes
if (boundaryNodes.has(childId)) {
continue;
}
intervalNodes.add(childId);
workingSet.push(childId);
}
}
return intervalNodes;
};
/**
* Update one or more fields of a particular sampler.
*
* @param projectId {Number} The project the sampler is part of.
* @param samplerId {Number} The sampler to update;
* @param newFields {Object} Sampler fields with their new data.
* @returns {Promise} resolves with the updated sampler data.
*/
Sampling.updateSampler = function(projectId, samplerId, newProperties) {
return CATMAID.fetch(projectId + '/samplers/' + samplerId + '/', 'POST', {
'leaf_handling_mode': newProperties.leafHandlingMode,
})
.then(function(sampler) {
CATMAID.Sampling.trigger(CATMAID.Sampling.EVENT_SAMPLER_UPDATED, samplerId);
return sampler;
});
};
/**
* Create shorter intervals for each ignored fragment of a domain (i.e.
* fragments that are not of an interval, but part of a domain). This also
* sets the leaf handling mode to 'short-interval'.
*/
Sampling.updateLeafHandlingMode = function(projectId, samplerId, leafHandling) {
if (leafHandling !== 'short-interval') {
return Promise.reject(new CATMAID.ValueError("Can only transform to short interval mode"));
}
let intervalsNeedingUpdate = 0;
let intervalsUpdated = 0;
return CATMAID.Sampling.getSampler(projectId, samplerId, true, true)
.then(function(sampler) {
if (sampler.leaf_segment_handling !== 'ignore') {
throw new CATMAID.ValueError("Current leaf handling mode needs to be 'ignore'");
}
return Promise.all([
sampler,
CATMAID.fetch(project.id + '/' + sampler.skeleton_id + '/1/1/1/compact-arbor'),
]);
})
.then(function(results) {
let sampler = results[0];
let skeletonData = results[1];
let arborParser = new CATMAID.ArborParser().init('compact-skeleton', skeletonData);
// Iterate over all domains and find all ignored fragments.
let newIntervalsPerDomain = [];
for (let domain of sampler.domains) {
// If this domain does not have any intervals, ignore it
if (!domain.intervals || !domain.intervals.length) {
continue;
}
++intervalsNeedingUpdate;
// Get all ignored fragments
let fragmentInfo = CATMAID.Sampling.getIgnoredFragments(projectId,
samplerId, arborParser.arbor, arborParser.positions, domain,
domain.intervals);
// Create intervals in ignored fragments, regardless of length. This
// is done by creating intervals for temporary domains that start at
// the start of each individual ignored fragment (available from
// fragmentInfo.intervalFragments). Ends are found by walking
// successors until they are not in the ignored fragment set
// (fragmentInfo.ignoredFragmentNodeIds).
let intervalInfos = [];
for (let ignoredFragment of fragmentInfo.intervalFragments) {
var tempDomain = {
start_node_id: ignoredFragment.start,
ends: ignoredFragment.ends.map(function(endNodeId) {
return {
id: null,
node_id: endNodeId,
};
}),
intervals: []
};
let intervalMap = {};
let intervalInfo = CATMAID.Sampling.intervalsFromModels(
arborParser.arbor, arborParser.positions, tempDomain,
sampler.interval_length, sampler.interval_error, true,
sampler.create_interval_boundaries, leafHandling,
true, intervalMap, undefined, sampler.merge_limit, true);
intervalInfos.push(intervalInfo);
}
if (intervalInfos.length === 0) {
CATMAID.warn("No new intervals could be found in domain " +
domain.id);
} else {
newIntervalsPerDomain.push({
intervals: intervalInfos,
domain: domain,
fragmentInfo: fragmentInfo,
});
}
}
return {
domainIntervals: newIntervalsPerDomain,
sampler: sampler,
arborParser: arborParser,
};
})
.then(function(samplerInfo) {
let sampler = samplerInfo.sampler;
let skeletonId = sampler.skeleton_id;
let workParser = samplerInfo.arborParser;
let newIntervalsPerDomain = samplerInfo.domainIntervals;
return new Promise(function(resolve, reject) {
let dialogs = [];
var models = {};
models[skeletonId] = new CATMAID.SkeletonModel(skeletonId);
// Create virtual skeletons
let arborParsers = new Map([[skeletonId, workParser]]);
let nodeProvider = new CATMAID.ArborParserNodeProvider(arborParsers);
// This fake sampler is used to preview the new intervals. Use a
// copy of the original domain definitions, because we are going to
// slightly change them for preview.
var fakeSampler = CATMAID.tools.deepCopy(sampler);
let colorMethod = 'binary-sampler-intervals';
let showNextDialog = function() {
let dialogInfo = dialogs.pop();
if (!dialogInfo) {
resolve();
} else {
let dialog = dialogInfo.dialog;
let domain = dialogInfo.domain;
dialog.show();
// At the moment the 3D viewer is only accessible after display
var glWidget = dialog.webglapp;
let activeDomainId = domain.id;
glWidget.addSkeletons(models, function() {
// Set preview sampler information
let skeletons = glWidget.space.content.skeletons;
let skeletonIds = Object.keys(skeletons);
if (skeletonIds.length !== 1) {
throw new CATMAID.ValueError("Expected exactly one loaded skeleton");
}
let skeleton = skeletons[skeletonIds[0]];
skeleton.setSamplers([fakeSampler]);
// Set new shading and coloring methods
glWidget.options.color_method = colorMethod;
glWidget.options.shading_method = 'sampler-domains';
glWidget.options.interpolate_vertex_colots = true;
let fakeDomain = domainLookup[domain.id];
let allowedIntervalIds = fakeDomain.intervals.map(i => i[0]);
// Make sure only the active domain is visible fully and other
// parts of the skeleton only a little.
glWidget.options.sampler_domain_shading_other_weight = 0.2;
glWidget.options.allowed_sampler_domain_ids.length = 0;
glWidget.options.allowed_sampler_domain_ids.push(activeDomainId);
glWidget.options.allowed_sampler_interval_ids.length = 0;
Array.prototype.push.apply(glWidget.options.allowed_sampler_interval_ids,
allowedIntervalIds);
glWidget.updateSkeletonColors()
.then(function() { glWidget.render(); });
// Look at center of mass of skeleton and update screen
glWidget.lookAtSkeleton(skeletonId);
}, nodeProvider);
}
};
let domainLookup = fakeSampler.domains.reduce(function(o, d) {
o[d.id] = d;
return o;
}, {});
// Show a confirmation dialog for each domain
for (let domainInfo of newIntervalsPerDomain) {
let intervals = [];
let addedNodes = [];
for (let intervalInfo of domainInfo.intervals) {
Array.prototype.push.apply(intervals, intervalInfo.intervals);
Array.prototype.push.apply(addedNodes, intervalInfo.addedNodes);
}
let domain = domainLookup[domainInfo.domain.id];
domain.intervals = intervals.map(function(i, n) {
return [-1 * n, i[0], i[1], null];
});
// Show 3D viewer confirmation dialog
let dialog = new CATMAID.Confirmation3dDialog({
title: "Please confirm " + intervals.length +
" domain interval(s) that are added to replace ignored " +
"leaf nodes, " + addedNodes.length + " new nodes are " +
"created to match intervals",
showControlPanel: false,
colorMethod: colorMethod,
shadingMethod: 'sampler-domain',
extraControls: [
{
type: 'checkbox',
label: 'Binary colors',
value: true,
onclick: function() {
//widget.state['binaryIntervalColors'] = this.checked;
if (glWidget) {
colorMethod = this.checked ?
'binary-sampler-intervals' : 'multicolor-sampler-intervals';
glWidget.options.color_method = colorMethod;
glWidget.updateSkeletonColors()
.then(glWidget.render.bind(glWidget));
}
}
}
]
});
// Create intervals if OK is pressed
dialog.onOK = function() {
CATMAID.fetch(project.id + '/samplers/domains/' +
domain.id + '/intervals/add-all', 'POST', {
intervals: intervals,
added_nodes: JSON.stringify(addedNodes)
})
.then(function(result) {
++intervalsUpdated;
showNextDialog();
CATMAID.msg("Success", intervals.length + " interval(s) created, using " +
result.n_added_nodes + " new node(s)");
})
.catch(reject);
};
dialog.onCancel = function() {
CATMAID.msg("No intervals created", "Canceled by user");
showNextDialog();
};
dialogs.push({
dialog: dialog,
domain: domainInfo.domain,
fragmentInfo: domainInfo.fragmentInfo,
});
}
// Show first dialog
showNextDialog();
});
})
.then(function() {
if (intervalsNeedingUpdate === intervalsUpdated) {
// Set the sampler's leaf handling type
let newLeafHandling = 'short-interval';
return CATMAID.Sampling.updateSampler(projectId, samplerId, {
'leafHandlingMode': newLeafHandling,
});
} else {
CATMAID.warn("Could not update all domains that needed a leaf mode update");
}
});
};
// FIXME: This ignores the fact that some branches were only created after
// intervals were created and will make these regular intervals as well.
Sampling.getIgnoredFragments = function(projectId, samplerId, arbor,
positions, domain, domainListIntervals) {
var intervalMap = {};
CATMAID.Sampling.updateIntervalMap(arbor, domainListIntervals,
intervalMap, domain.start_node_id);
// Get domain arbor
let domainArbor = CATMAID.Sampling.domainArborFromModel(arbor, domain);
let successors = domainArbor.allSuccessors();
let domainEnds = domain.ends.reduce(function(o, e) {
o[e.node_id] = true;
return o;
}, {});
let workingSet = [[domain.start_node_id, null, null]];
let intervalFragments = [];
let ignoredFragmentNodeIds = [];
let currentFragment = null;
let leafFragmentLengths = {};
while (workingSet.length > 0) {
let currentNodeInfo = workingSet.shift();
let currentNodeId = currentNodeInfo[0];
let lastNodeId = currentNodeInfo[1];
let currentFragment = currentNodeInfo[2];
let intervalId = intervalMap[currentNodeId];
if (currentNodeId != domain.start_node_id &&
(intervalId === undefined || intervalId === null)) {
// This node is part of the domain, but part of no interval. This
// should only happen at the end of branches. While we don't have to
// expect more valid intervals on this branch, continue traversal for
// the sake of robustness.
if (!currentFragment) {
// Add last node, we need it for distance computations.
currentFragment = {
start: lastNodeId,
ends: [],
};
intervalFragments.push(currentFragment);
}
// Remember node as being part of an ignored fragment
ignoredFragmentNodeIds.push(currentNodeId);
// Compute and aggregate length
let lastPos = positions[lastNodeId];
let pos = positions[currentNodeId];
if (!lastPos) {
CATMAID.warn("Couldn't find position for last node " + fragment[i-1]);
}
if (!pos) {
CATMAID.warn("Couldn't find position for current node " + fragment[i]);
}
let length = leafFragmentLengths[currentFragment.start] || 0;
leafFragmentLengths[currentFragment.start] = length + lastPos.distanceTo(pos);
} else {
if (currentFragment) {
currentFragment.ends.push(currentNodeId);
}
// If the current node is part of an interval, make sure it isn't
// counted as part of an ignored leaf fragment.
currentFragment = null;
}
// If we hit a domain end, we stop looking for successors in this branch
// and can continue with the next node on another branch.
if (domainEnds[currentNodeId]) {
if (currentFragment) {
currentFragment.ends.push(currentNodeId);
}
continue;
}
let succ = successors[currentNodeId];
if (succ && succ.length > 0) {
for (let k=0; k<succ.length; ++k) {
let succId = succ[k];
workingSet.push([succId, currentNodeId, currentFragment]);
}
} else {
currentFragment = null;
}
}
return {
intervalFragments: intervalFragments,
leafFragmentLengths: leafFragmentLengths,
ignoredFragmentNodeIds: ignoredFragmentNodeIds,
domainArbor: domainArbor,
domainSuccesors: successors,
};
};
Sampling.getSampler = function(projectId, samplerId, withDomains,
withIntervals) {
return CATMAID.fetch(project.id + '/samplers/' + samplerId + '/', 'GET', {
with_domains: withDomains,
with_intervals: withIntervals,
});
};
// Be an event source and define events
CATMAID.asEventSource(Sampling);
Sampling.EVENT_SAMPLER_ADDED = 'sampler_added';
Sampling.EVENT_SAMPLER_DELETED = 'sampler_deleted';
Sampling.EVENT_SAMPLER_UPDATED = 'sampler_updated';
// Export into CATMAID namespace
CATMAID.Sampling = Sampling;
})(CATMAID);
| {
"pile_set_name": "Github"
} |
// Code generated by "stringer -type=ResourceMode -output=resource_mode_string.go resource_mode.go"; DO NOT EDIT.
package config
import "strconv"
func _() {
// An "invalid array index" compiler error signifies that the constant values have changed.
// Re-run the stringer command to generate them again.
var x [1]struct{}
_ = x[ManagedResourceMode-0]
_ = x[DataResourceMode-1]
}
const _ResourceMode_name = "ManagedResourceModeDataResourceMode"
var _ResourceMode_index = [...]uint8{0, 19, 35}
func (i ResourceMode) String() string {
if i < 0 || i >= ResourceMode(len(_ResourceMode_index)-1) {
return "ResourceMode(" + strconv.FormatInt(int64(i), 10) + ")"
}
return _ResourceMode_name[_ResourceMode_index[i]:_ResourceMode_index[i+1]]
}
| {
"pile_set_name": "Github"
} |
import common.jsn
import editor_renderer.jsn
{
view_sets:
{
example: [
main_view,
picking_view
]
},
view_set: example
}
| {
"pile_set_name": "Github"
} |
# coding=utf-8
"""Init"""
| {
"pile_set_name": "Github"
} |
# Event 16651 - task_0
###### Version: 0
## Description
None
## Data Dictionary
|Standard Name|Field Name|Type|Description|Sample Value|
|---|---|---|---|---|
|TBD|ErrorMessage|UnicodeString|None|`None`|
## Tags
* etw_level_Error
* etw_task_task_0 | {
"pile_set_name": "Github"
} |
=encoding utf8
=head1 NAME
perl588delta - what is new for perl v5.8.8
=head1 DESCRIPTION
This document describes differences between the 5.8.7 release and
the 5.8.8 release.
=head1 Incompatible Changes
There are no changes intentionally incompatible with 5.8.7. If any exist,
they are bugs and reports are welcome.
=head1 Core Enhancements
=over
=item *
C<chdir>, C<chmod> and C<chown> can now work on filehandles as well as
filenames, if the system supports respectively C<fchdir>, C<fchmod> and
C<fchown>, thanks to a patch provided by Gisle Aas.
=back
=head1 Modules and Pragmata
=over
=item *
C<Attribute::Handlers> upgraded to version 0.78_02
=over
=item *
Documentation typo fix
=back
=item *
C<attrs> upgraded to version 1.02
=over
=item *
Internal cleanup only
=back
=item *
C<autouse> upgraded to version 1.05
=over
=item *
Simplified implementation
=back
=item *
C<B> upgraded to version 1.09_01
=over
=item *
The inheritance hierarchy of the C<B::> modules has been corrected;
C<B::NV> now inherits from C<B::SV> (instead of C<B::IV>).
=back
=item *
C<blib> upgraded to version 1.03
=over
=item *
Documentation typo fix
=back
=item *
C<ByteLoader> upgraded to version 0.06
=over
=item *
Internal cleanup
=back
=item *
C<CGI> upgraded to version 3.15
=over
=item *
Extraneous "?" from C<self_url()> removed
=item *
C<scrolling_list()> select attribute fixed
=item *
C<virtual_port> now works properly with the https protocol
=item *
C<upload_hook()> and C<append()> now works in function-oriented mode
=item *
C<POST_MAX> doesn't cause the client to hang any more
=item *
Automatic tab indexes are now disabled and new C<-tabindex> pragma has
been added to turn automatic indexes back on
=item *
C<end_form()> doesn't emit empty (and non-validating) C<< <div> >>
=item *
C<CGI::Carp> works better in certain mod_perl configurations
=item *
Setting C<$CGI::TMPDIRECTORY> is now effective
=item *
Enhanced documentation
=back
=item *
C<charnames> upgraded to version 1.05
=over
=item *
C<viacode()> now accept hex strings and has been optimized.
=back
=item *
C<CPAN> upgraded to version 1.76_02
=over
=item *
1 minor bug fix for Win32
=back
=item *
C<Cwd> upgraded to version 3.12
=over
=item *
C<canonpath()> on Win32 now collapses F<foo\..> sections correctly.
=item *
Improved behaviour on Symbian OS.
=item *
Enhanced documentation and typo fixes
=item *
Internal cleanup
=back
=item *
C<Data::Dumper> upgraded to version 2.121_08
=over
=item *
A problem where C<Data::Dumper> would sometimes update the iterator state
of hashes has been fixed
=item *
Numeric labels now work
=item *
Internal cleanup
=back
=item *
C<DB> upgraded to version 1.01
=over
=item *
A problem where the state of the regexp engine would sometimes get clobbered when running
under the debugger has been fixed.
=back
=item *
C<DB_File> upgraded to version 1.814
=over
=item *
Adds support for Berkeley DB 4.4.
=back
=item *
C<Devel::DProf> upgraded to version 20050603.00
=over
=item *
Internal cleanup
=back
=item *
C<Devel::Peek> upgraded to version 1.03
=over
=item *
Internal cleanup
=back
=item *
C<Devel::PPPort> upgraded to version 3.06_01
=over
=item *
C<--compat-version> argument checking has been improved
=item *
Files passed on the command line are filtered by default
=item *
C<--nofilter> option to override the filtering has been added
=item *
Enhanced documentation
=back
=item *
C<diagnostics> upgraded to version 1.15
=over
=item *
Documentation typo fix
=back
=item *
C<Digest> upgraded to version 1.14
=over
=item *
The constructor now knows which module implements SHA-224
=item *
Documentation tweaks and typo fixes
=back
=item *
C<Digest::MD5> upgraded to version 2.36
=over
=item *
C<XSLoader> is now used for faster loading
=item *
Enhanced documentation including MD5 weaknesses discovered lately
=back
=item *
C<Dumpvalue> upgraded to version 1.12
=over
=item *
Documentation fix
=back
=item *
C<DynaLoader> upgraded but unfortunately we're not able to increment its version number :-(
=over
=item *
Implements C<dl_unload_file> on Win32
=item *
Internal cleanup
=item *
C<XSLoader> 0.06 incorporated; small optimisation for calling
C<bootstrap_inherit()> and documentation enhancements.
=back
=item *
C<Encode> upgraded to version 2.12
=over
=item *
A coderef is now acceptable for C<CHECK>!
=item *
3 new characters added to the ISO-8859-7 encoding
=item *
New encoding C<MIME-Header-ISO_2022_JP> added
=item *
Problem with partial characters and C<< encoding(utf-8-strict) >> fixed.
=item *
Documentation enhancements and typo fixes
=back
=item *
C<English> upgraded to version 1.02
=over
=item *
the C<< $COMPILING >> variable has been added
=back
=item *
C<ExtUtils::Constant> upgraded to version 0.17
=over
=item *
Improved compatibility with older versions of perl
=back
=item *
C<ExtUtils::MakeMaker> upgraded to version 6.30 (was 6.17)
=over
=item *
Too much to list here; see L<http://search.cpan.org/dist/ExtUtils-MakeMaker/Changes>
=back
=item *
C<File::Basename> upgraded to version 2.74, with changes contributed by Michael Schwern.
=over
=item *
Documentation clarified and errors corrected.
=item *
C<basename> now strips trailing path separators before processing the name.
=item *
C<basename> now returns C</> for parameter C</>, to make C<basename>
consistent with the shell utility of the same name.
=item *
The suffix is no longer stripped if it is identical to the remaining characters
in the name, again for consistency with the shell utility.
=item *
Some internal code cleanup.
=back
=item *
C<File::Copy> upgraded to version 2.09
=over
=item *
Copying a file onto itself used to fail.
=item *
Moving a file between file systems now preserves the access and
modification time stamps
=back
=item *
C<File::Find> upgraded to version 1.10
=over
=item *
Win32 portability fixes
=item *
Enhanced documentation
=back
=item *
C<File::Glob> upgraded to version 1.05
=over
=item *
Internal cleanup
=back
=item *
C<File::Path> upgraded to version 1.08
=over
=item *
C<mkpath> now preserves C<errno> when C<mkdir> fails
=back
=item *
C<File::Spec> upgraded to version 3.12
=over
=item *
C<File::Spec->rootdir()> now returns C<\> on Win32, instead of C</>
=item *
C<$^O> could sometimes become tainted. This has been fixed.
=item *
C<canonpath> on Win32 now collapses C<foo/..> (or C<foo\..>) sections
correctly, rather than doing the "misguided" work it was previously doing.
Note that C<canonpath> on Unix still does B<not> collapse these sections, as
doing so would be incorrect.
=item *
Some documentation improvements
=item *
Some internal code cleanup
=back
=item *
C<FileCache> upgraded to version 1.06
=over
=item *
POD formatting errors in the documentation fixed
=back
=item *
C<Filter::Simple> upgraded to version 0.82
=item *
C<FindBin> upgraded to version 1.47
=over
=item *
Now works better with directories where access rights are more
restrictive than usual.
=back
=item *
C<GDBM_File> upgraded to version 1.08
=over
=item *
Internal cleanup
=back
=item *
C<Getopt::Long> upgraded to version 2.35
=over
=item *
C<prefix_pattern> has now been complemented by a new configuration
option C<long_prefix_pattern> that allows the user to specify what
prefix patterns should have long option style semantics applied.
=item *
Options can now take multiple values at once (experimental)
=item *
Various bug fixes
=back
=item *
C<if> upgraded to version 0.05
=over
=item *
Give more meaningful error messages from C<if> when invoked with a
condition in list context.
=item *
Restore backwards compatibility with earlier versions of perl
=back
=item *
C<IO> upgraded to version 1.22
=over
=item *
Enhanced documentation
=item *
Internal cleanup
=back
=item *
C<IPC::Open2> upgraded to version 1.02
=over
=item *
Enhanced documentation
=back
=item *
C<IPC::Open3> upgraded to version 1.02
=over
=item *
Enhanced documentation
=back
=item *
C<List::Util> upgraded to version 1.18 (was 1.14)
=over
=item *
Fix pure-perl version of C<refaddr> to avoid blessing an un-blessed reference
=item *
Use C<XSLoader> for faster loading
=item *
Fixed various memory leaks
=item *
Internal cleanup and portability fixes
=back
=item *
C<Math::Complex> upgraded to version 1.35
=over
=item *
C<atan2(0, i)> now works, as do all the (computable) complex argument cases
=item *
Fixes for certain bugs in C<make> and C<emake>
=item *
Support returning the I<k>th root directly
=item *
Support C<[2,-3pi/8]> in C<emake>
=item *
Support C<inf> for C<make>/C<emake>
=item *
Document C<make>/C<emake> more visibly
=back
=item *
C<Math::Trig> upgraded to version 1.03
=over
=item *
Add more great circle routines: C<great_circle_waypoint> and
C<great_circle_destination>
=back
=item *
C<MIME::Base64> upgraded to version 3.07
=over
=item *
Use C<XSLoader> for faster loading
=item *
Enhanced documentation
=item *
Internal cleanup
=back
=item *
C<NDBM_File> upgraded to version 1.06
=over
=item *
Enhanced documentation
=back
=item *
C<ODBM_File> upgraded to version 1.06
=over
=item *
Documentation typo fixed
=item *
Internal cleanup
=back
=item *
C<Opcode> upgraded to version 1.06
=over
=item *
Enhanced documentation
=item *
Internal cleanup
=back
=item *
C<open> upgraded to version 1.05
=over
=item *
Enhanced documentation
=back
=item *
C<overload> upgraded to version 1.04
=over
=item *
Enhanced documentation
=back
=item *
C<PerlIO> upgraded to version 1.04
=over
=item *
C<PerlIO::via> iterate over layers properly now
=item *
C<PerlIO::scalar> understands C<< $/ = "" >> now
=item *
C<encoding(utf-8-strict)> with partial characters now works
=item *
Enhanced documentation
=item *
Internal cleanup
=back
=item *
C<Pod::Functions> upgraded to version 1.03
=over
=item *
Documentation typos fixed
=back
=item *
C<Pod::Html> upgraded to version 1.0504
=over
=item *
HTML output will now correctly link
to C<=item>s on the same page, and should be valid XHTML.
=item *
Variable names are recognized as intended
=item *
Documentation typos fixed
=back
=item *
C<Pod::Parser> upgraded to version 1.32
=over
=item *
Allow files that start with C<=head> on the first line
=item *
Win32 portability fix
=item *
Exit status of C<pod2usage> fixed
=item *
New C<-noperldoc> switch for C<pod2usage>
=item *
Arbitrary URL schemes now allowed
=item *
Documentation typos fixed
=back
=item *
C<POSIX> upgraded to version 1.09
=over
=item *
Documentation typos fixed
=item *
Internal cleanup
=back
=item *
C<re> upgraded to version 0.05
=over
=item *
Documentation typo fixed
=back
=item *
C<Safe> upgraded to version 2.12
=over
=item *
Minor documentation enhancement
=back
=item *
C<SDBM_File> upgraded to version 1.05
=over
=item *
Documentation typo fixed
=item *
Internal cleanup
=back
=item *
C<Socket> upgraded to version 1.78
=over
=item *
Internal cleanup
=back
=item *
C<Storable> upgraded to version 2.15
=over
=item *
This includes the C<STORABLE_attach> hook functionality added by
Adam Kennedy, and more frugal memory requirements when storing under C<ithreads>, by
using the C<ithreads> cloning tracking code.
=back
=item *
C<Switch> upgraded to version 2.10_01
=over
=item *
Documentation typos fixed
=back
=item *
C<Sys::Syslog> upgraded to version 0.13
=over
=item *
Now provides numeric macros and meaningful C<Exporter> tags.
=item *
No longer uses C<Sys::Hostname> as it may provide useless values in
unconfigured network environments, so instead uses C<INADDR_LOOPBACK> directly.
=item *
C<syslog()> now uses local timestamp.
=item *
C<setlogmask()> now behaves like its C counterpart.
=item *
C<setlogsock()> will now C<croak()> as documented.
=item *
Improved error and warnings messages.
=item *
Improved documentation.
=back
=item *
C<Term::ANSIColor> upgraded to version 1.10
=over
=item *
Fixes a bug in C<colored> when C<$EACHLINE> is set that caused it to not color
lines consisting solely of 0 (literal zero).
=item *
Improved tests.
=back
=item *
C<Term::ReadLine> upgraded to version 1.02
=over
=item *
Documentation tweaks
=back
=item *
C<Test::Harness> upgraded to version 2.56 (was 2.48)
=over
=item *
The C<Test::Harness> timer is now off by default.
=item *
Now shows elapsed time in milliseconds.
=item *
Various bug fixes
=back
=item *
C<Test::Simple> upgraded to version 0.62 (was 0.54)
=over
=item *
C<is_deeply()> no longer fails to work for many cases
=item *
Various minor bug fixes
=item *
Documentation enhancements
=back
=item *
C<Text::Tabs> upgraded to version 2005.0824
=over
=item *
Provides a faster implementation of C<expand>
=back
=item *
C<Text::Wrap> upgraded to version 2005.082401
=over
=item *
Adds C<$Text::Wrap::separator2>, which allows you to preserve existing newlines
but add line-breaks with some other string.
=back
=item *
C<threads> upgraded to version 1.07
=over
=item *
C<threads> will now honour C<no warnings 'threads'>
=item *
A thread's interpreter is now freed after C<< $t->join() >> rather than after
C<undef $t>, which should fix some C<ithreads> memory leaks. (Fixed by Dave
Mitchell)
=item *
Some documentation typo fixes.
=back
=item *
C<threads::shared> upgraded to version 0.94
=over
=item *
Documentation changes only
=item *
Note: An improved implementation of C<threads::shared> is available on
CPAN - this will be merged into 5.8.9 if it proves stable.
=back
=item *
C<Tie::Hash> upgraded to version 1.02
=over
=item *
Documentation typo fixed
=back
=item *
C<Time::HiRes> upgraded to version 1.86 (was 1.66)
=over
=item *
C<clock_nanosleep()> and C<clock()> functions added
=item *
Support for the POSIX C<clock_gettime()> and C<clock_getres()> has been added
=item *
Return C<undef> or an empty list if the C C<gettimeofday()> function fails
=item *
Improved C<nanosleep> detection
=item *
Internal cleanup
=item *
Enhanced documentation
=back
=item *
C<Unicode::Collate> upgraded to version 0.52
=over
=item *
Now implements UCA Revision 14 (based on Unicode 4.1.0).
=item *
C<Unicode::Collate->new> method no longer overwrites user's C<$_>
=item *
Enhanced documentation
=back
=item *
C<Unicode::UCD> upgraded to version 0.24
=over
=item *
Documentation typos fixed
=back
=item *
C<User::grent> upgraded to version 1.01
=over
=item *
Documentation typo fixed
=back
=item *
C<utf8> upgraded to version 1.06
=over
=item *
Documentation typos fixed
=back
=item *
C<vmsish> upgraded to version 1.02
=over
=item *
Documentation typos fixed
=back
=item *
C<warnings> upgraded to version 1.05
=over
=item *
Gentler messing with C<Carp::> internals
=item *
Internal cleanup
=item *
Documentation update
=back
=item *
C<Win32> upgraded to version 0.2601
=for cynics And how many perl 5.8.x versions can I release ahead of Vista?
=over
=item *
Provides Windows Vista support to C<Win32::GetOSName>
=item *
Documentation enhancements
=back
=item *
C<XS::Typemap> upgraded to version 0.02
=over
=item *
Internal cleanup
=back
=back
=head1 Utility Changes
=head2 C<h2xs> enhancements
C<h2xs> implements new option C<--use-xsloader> to force use of
C<XSLoader> even in backwards compatible modules.
The handling of authors' names that had apostrophes has been fixed.
Any enums with negative values are now skipped.
=head2 C<perlivp> enhancements
C<perlivp> implements new option C<-a> and will not check for F<*.ph>
files by default any more. Use the C<-a> option to run I<all> tests.
=head1 New Documentation
The L<perlglossary> manpage is a glossary of terms used in the Perl
documentation, technical and otherwise, kindly provided by O'Reilly Media,
inc.
=head1 Performance Enhancements
=over 4
=item *
Weak reference creation is now I<O(1)> rather than I<O(n)>, courtesy of
Nicholas Clark. Weak reference deletion remains I<O(n)>, but if deletion only
happens at program exit, it may be skipped completely.
=item *
Salvador Fandiño provided improvements to reduce the memory usage of C<sort>
and to speed up some cases.
=item *
Jarkko Hietaniemi and Andy Lester worked to mark as much data as possible in
the C source files as C<static>, to increase the proportion of the executable
file that the operating system can share between process, and thus reduce
real memory usage on multi-user systems.
=back
=head1 Installation and Configuration Improvements
Parallel makes should work properly now, although there may still be problems
if C<make test> is instructed to run in parallel.
Building with Borland's compilers on Win32 should work more smoothly. In
particular Steve Hay has worked to side step many warnings emitted by their
compilers and at least one C compiler internal error.
C<Configure> will now detect C<clearenv> and C<unsetenv>, thanks to a patch
from Alan Burlison. It will also probe for C<futimes> and whether C<sprintf>
correctly returns the length of the formatted string, which will both be used
in perl 5.8.9.
There are improved hints for next-3.0, vmesa, IX, Darwin, Solaris, Linux,
DEC/OSF, HP-UX and MPE/iX
Perl extensions on Windows now can be statically built into the Perl DLL,
thanks to a work by Vadim Konovalov. (This improvement was actually in 5.8.7,
but was accidentally omitted from L<perl587delta>).
=head1 Selected Bug Fixes
=head2 no warnings 'category' works correctly with -w
Previously when running with warnings enabled globally via C<-w>, selective
disabling of specific warning categories would actually turn off all warnings.
This is now fixed; now C<no warnings 'io';> will only turn off warnings in the
C<io> class. Previously it would erroneously turn off all warnings.
This bug fix may cause some programs to start correctly issuing warnings.
=head2 Remove over-optimisation
Perl 5.8.4 introduced a change so that assignments of C<undef> to a
scalar, or of an empty list to an array or a hash, were optimised away. As
this could cause problems when C<goto> jumps were involved, this change
has been backed out.
=head2 sprintf() fixes
Using the sprintf() function with some formats could lead to a buffer
overflow in some specific cases. This has been fixed, along with several
other bugs, notably in bounds checking.
In related fixes, it was possible for badly written code that did not follow
the documentation of C<Sys::Syslog> to have formatting vulnerabilities.
C<Sys::Syslog> has been changed to protect people from poor quality third
party code.
=head2 Debugger and Unicode slowdown
It had been reported that running under perl's debugger when processing
Unicode data could cause unexpectedly large slowdowns. The most likely cause
of this was identified and fixed by Nicholas Clark.
=head2 Smaller fixes
=over 4
=item *
C<FindBin> now works better with directories where access rights are more
restrictive than usual.
=item *
Several memory leaks in ithreads were closed. An improved implementation of
C<threads::shared> is available on CPAN - this will be merged into 5.8.9 if
it proves stable.
=item *
Trailing spaces are now trimmed from C<$!> and C<$^E>.
=item *
Operations that require perl to read a process's list of groups, such as reads
of C<$(> and C<$)>, now dynamically allocate memory rather than using a
fixed sized array. The fixed size array could cause C stack exhaustion on
systems configured to use large numbers of groups.
=item *
C<PerlIO::scalar> now works better with non-default C<$/> settings.
=item *
You can now use the C<x> operator to repeat a C<qw//> list. This used
to raise a syntax error.
=item *
The debugger now traces correctly execution in eval("")uated code that
contains #line directives.
=item *
The value of the C<open> pragma is no longer ignored for three-argument
opens.
=item *
The optimisation of C<for (reverse @a)> introduced in perl 5.8.6 could
misbehave when the array had undefined elements and was used in LVALUE
context. Dave Mitchell provided a fix.
=item *
Some case insensitive matches between UTF-8 encoded data and 8 bit regexps,
and vice versa, could give malformed character warnings. These have been
fixed by Dave Mitchell and Yves Orton.
=item *
C<lcfirst> and C<ucfirst> could corrupt the string for certain cases where
the length UTF-8 encoding of the string in lower case, upper case or title
case differed. This was fixed by Nicholas Clark.
=item *
Perl will now use the C library calls C<unsetenv> and C<clearenv> if present
to delete keys from C<%ENV> and delete C<%ENV> entirely, thanks to a patch
from Alan Burlison.
=back
=head1 New or Changed Diagnostics
=head2 Attempt to set length of freed array
This is a new warning, produced in situations such as this:
$r = do {my @a; \$#a};
$$r = 503;
=head2 Non-string passed as bitmask
This is a new warning, produced when number has been passed as a argument to
select(), instead of a bitmask.
# Wrong, will now warn
$rin = fileno(STDIN);
($nfound,$timeleft) = select($rout=$rin, undef, undef, $timeout);
# Should be
$rin = '';
vec($rin,fileno(STDIN),1) = 1;
($nfound,$timeleft) = select($rout=$rin, undef, undef, $timeout);
=head2 Search pattern not terminated or ternary operator parsed as search pattern
This syntax error indicates that the lexer couldn't find the final
delimiter of a C<?PATTERN?> construct. Mentioning the ternary operator in
this error message makes it easier to diagnose syntax errors.
=head1 Changed Internals
There has been a fair amount of refactoring of the C<C> source code, partly to
make it tidier and more maintainable. The resulting object code and the
C<perl> binary may well be smaller than 5.8.7, in particular due to a change
contributed by Dave Mitchell which reworked the warnings code to be
significantly smaller. Apart from being smaller and possibly faster, there
should be no user-detectable changes.
Andy Lester supplied many improvements to determine which function
parameters and local variables could actually be declared C<const> to the C
compiler. Steve Peters provided new C<*_set> macros and reworked the core to
use these rather than assigning to macros in LVALUE context.
Dave Mitchell improved the lexer debugging output under C<-DT>
Nicholas Clark changed the string buffer allocation so that it is now rounded
up to the next multiple of 4 (or 8 on platforms with 64 bit pointers). This
should reduce the number of calls to C<realloc> without actually using any
extra memory.
The C<HV>'s array of C<HE*>s is now allocated at the correct (minimal) size,
thanks to another change by Nicholas Clark. Compile with
C<-DPERL_USE_LARGE_HV_ALLOC> to use the old, sloppier, default.
For XS or embedding debugging purposes, if perl is compiled with
C<-DDEBUG_LEAKING_SCALARS_FORK_DUMP> in addition to
C<-DDEBUG_LEAKING_SCALARS> then a child process is C<fork>ed just before
global destruction, which is used to display the values of any scalars
found to have leaked at the end of global destruction. Without this, the
scalars have already been freed sufficiently at the point of detection that
it is impossible to produce any meaningful dump of their contents. This
feature was implemented by the indefatigable Nicholas Clark, based on an idea
by Mike Giroux.
=head1 Platform Specific Problems
The optimiser on HP-UX 11.23 (Itanium 2) is currently partly disabled (scaled
down to +O1) when using HP C-ANSI-C; the cause of problems at higher
optimisation levels is still unclear.
There are a handful of remaining test failures on VMS, mostly due to
test fixes and minor module tweaks with too many dependencies to
integrate into this release from the development stream, where they have
all been corrected. The following is a list of expected failures with
the patch number of the fix where that is known:
ext/Devel/PPPort/t/ppphtest.t #26913
ext/List/Util/t/p_tainted.t #26912
lib/ExtUtils/t/PL_FILES.t #26813
lib/ExtUtils/t/basic.t #26813
t/io/fs.t
t/op/cmp.t
=head1 Reporting Bugs
If you find what you think is a bug, you might check the articles
recently posted to the comp.lang.perl.misc newsgroup and the perl
bug database at http://bugs.perl.org. There may also be
information at http://www.perl.org, the Perl Home Page.
If you believe you have an unreported bug, please run the B<perlbug>
program included with your release. Be sure to trim your bug down
to a tiny but sufficient test case. Your bug report, along with the
output of C<perl -V>, will be sent off to [email protected] to be
analysed by the Perl porting team. You can browse and search
the Perl 5 bugs at http://bugs.perl.org/
=head1 SEE ALSO
The F<Changes> file for exhaustive details on what changed.
The F<INSTALL> file for how to build Perl.
The F<README> file for general stuff.
The F<Artistic> and F<Copying> files for copyright information.
=cut
| {
"pile_set_name": "Github"
} |
import React from 'react';
import {AppRegistry, Platform} from 'react-native';
import {Navigation} from './navigation';
export function App() {
return <Navigation />;
}
AppRegistry.registerComponent('example', () => App);
if (Platform.OS === 'web') {
AppRegistry.runApplication('example', {
rootTag: document.getElementById('root'),
});
}
| {
"pile_set_name": "Github"
} |
(*
** Copyright (C) 2011 Hongwei Xi, Boston University
**
** 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.
*)
(* ****** ****** *)
(*
** Array-based implementation of circular buffer
**
** Author: Hongwei Xi (hwxi AT cs DOT bu DOT edu)
** Time: November, 2011
*)
(* ****** ****** *)
staload _(*anon*) = "prelude/DATS/array.dats"
staload _(*anon*) = "prelude/DATS/pointer.dats"
(* ****** ****** *)
staload "circbuf.sats"
(* ****** ****** *)
typedef
cbuf_struct = @{
p_beg= ptr // the start location of the array
, m=size_t // the maximal capacity of the buffer (m > 0)
, n=size_t // the current size of the buffer (0 <= n <= m)
, f=size_t // the total number of removed elements
} // end of [cbuf_struct]
(* ****** ****** *)
absviewtype
cbufObj_minus_struct (a:viewt@ype, m:int, n:int, l:addr)
(* ****** ****** *)
extern
castfn
cbufObj_takeout_struct
{a:viewt@ype} {m,n:int} (
buf: !cbufObj (a, m, n) >> cbufObj_minus_struct (a, m, n, l)
) : #[l:addr] (cbuf_struct @ l | ptr l)
extern
praxi
cbufObj_addback_struct
{a:viewt@ype} {m,n:int} {l:addr} (
pfat: cbuf_struct @ l
| buf: !cbufObj_minus_struct (a, m, n, l) >> cbufObj (a, m, n)
) : void // end of [cbufObj_addback_struct]
(* ****** ****** *)
implement{a}
cbufObj_get_cap {m,n} (buf) = let
val (pfat | p) = cbufObj_takeout_struct (buf)
val m = p->m
prval () = cbufObj_addback_struct (pfat | buf)
extern castfn __cast (m: size_t): size_t (m)
in
__cast (m)
end // end of [circbuf_get_cap]
(* ****** ****** *)
implement{a}
cbufObj_get_size {m,n} (buf) = let
val (pfat | p) = cbufObj_takeout_struct (buf)
val n = p->n
prval () = cbufObj_addback_struct (pfat | buf)
extern castfn __cast (n: size_t): size_t (n)
in
__cast (n)
end // end of [circbuf_get_size]
(* ****** ****** *)
implement{a}
cbufObj_is_empty
{m,n} (buf) = cbufObj_get_size (buf) = 0
// end of [cbufObj_is_empty]
implement{a}
cbufObj_isnot_empty
{m,n} (buf) = cbufObj_get_size (buf) > 0
// end of [cbufObj_isnot_empty]
(* ****** ****** *)
implement{a}
cbufObj_is_full
{m,n} (buf) = let
val (pfat | p) = cbufObj_takeout_struct (buf)
val m = p->m and n = p->n
prval () = cbufObj_addback_struct (pfat | buf)
extern castfn __cast (x: bool): bool (m==n)
in
__cast (m = n)
end // end of [cbufObj_is_full]
implement{a}
cbufObj_isnot_full
{m,n} (buf) = let
val (pfat | p) = cbufObj_takeout_struct (buf)
val m = p->m and n = p->n
prval () = cbufObj_addback_struct (pfat | buf)
extern castfn __cast (x: bool): bool (n < m)
in
__cast (n < m)
end // end of [cbufObj_isnot_full]
(* ****** ****** *)
implement{a}
cbufObj_new {m} (m) = let
val (pfgc1, pfarr | parr) = array_ptr_alloc<a> (m)
val (pfgc2, pfbuf | pbuf) = ptr_alloc<cbuf_struct> ()
val () = pbuf->p_beg := parr
val () = pbuf->m := m
val () = pbuf->n := (size_of_int1)0
val () = pbuf->f := (size_of_int1)0
extern castfn ofptr {v1,v2,v3,v4:view}
(pf1:v1, pf2:v2, pf3:v2, pf4: v4 | p: ptr): cbufObj (a, m, 0)
// end of [ofptr]
in
ofptr (pfgc1, pfarr, pfgc2, pfbuf | pbuf)
end // end [cbufObj_new]
implement
cbufObj_free (buf) = let
val (pfat | p) = cbufObj_takeout_struct (buf)
val () = __free (p->p_beg) where {
extern fun __free (p: ptr): void = "ats_free_gc"
} // end of [val]
prval () = cbufObj_addback_struct (pfat | buf)
val () = __free (buf) where {
extern fun __free {vt:viewtype} (x: vt): void = "ats_free_gc"
} // end of [val]
in
// nothing
end // end of [cbufObj_free]
(* ****** ****** *)
implement
cbufObj_clear_type
{a} {m,n} (buf) = let
val (pfat | p) = cbufObj_takeout_struct (buf)
val () = p->n := (size_of_int1)0
prval () = cbufObj_addback_struct (pfat | buf)
prval () = __assert (buf) where {
extern praxi __assert (buf: !cbufObj (a, m, n) >> cbufObj (a, m, 0)): void
} // end of [prval]
in
// nothing
end // end of [cbufObj_clear_type]
(* ****** ****** *)
staload UN = "prelude/SATS/unsafe.sats"
staload _(*anon*) = "prelude/DATS/unsafe.dats"
(*
fun{a:t@ype}
cbufObj_insert
{m,n:int | n < m} (
buf: !cbufObj (a, m, n) >> cbufObj (a, m, n+1), x: a
) : void // end of [cbufObj_insert]
*)
implement{a}
cbufObj_insert {m,n} (buf, x) = {
//
prval () = cbufObj_param_lemma (buf)
//
val (pfat | p) = cbufObj_takeout_struct (buf)
val n = p->n and f = p->f
val ofs = mod_size_size (f+n, p->m) * sizeof<a>
val () = $UN.ptr0_set<a> (p->p_beg+ofs, x)
val () = p->n := n + 1
prval () = cbufObj_addback_struct (pfat | buf)
prval () = __assert (buf) where {
extern praxi __assert (buf: !cbufObj (a, m, n) >> cbufObj (a, m, n+1)): void
} // end of [prval]
} // end of [cbufObj_insert]
(*
fun{a:t@ype}
cbufObj_remove
{m,n:int | n > 0} (
buf: !cbufObj (a, m, n) >> cbufObj (a, m, n-1)
) : a // end of [cbufObj_remove]
*)
implement{a}
cbufObj_remove {m,n} (buf) = x where {
val (pfat | p) = cbufObj_takeout_struct (buf)
val f = p->f
val n = p->n and f = p->f
val ofs = mod_size_size (f, p->m) * sizeof<a>
val x = $UN.ptr0_get<a> (p->p_beg+ofs)
val () = p->n := n - 1
val () = p->f := f + 1
prval () = cbufObj_addback_struct (pfat | buf)
prval () = __assert (buf) where {
extern praxi __assert (buf: !cbufObj (a, m, n) >> cbufObj (a, m, n-1)): void
} // end of [prval]
} // end of [cbufObj_remove]
(* ****** ****** *)
implement
main () = () where
{
//
val buf = cbufObj_new (2)
//
val () = cbufObj_insert<int> (buf, 1)
val () = cbufObj_insert<int> (buf, 2)
val () = cbufObj_clear_type {int} (buf)
//
val () = cbufObj_insert<int> (buf, 1)
val () = cbufObj_insert<int> (buf, 2)
//
val x = cbufObj_remove<int> (buf)
val () = println! ("x(1) = ", x)
//
val () = cbufObj_insert<int> (buf, 3)
//
val x = cbufObj_remove<int> (buf)
val () = println! ("x(2) = ", x)
val x = cbufObj_remove<int> (buf)
val () = println! ("x(3) = ", x)
//
val () = cbufObj_insert<int> (buf, 4)
val x = cbufObj_remove<int> (buf)
val () = println! ("x(4) = ", x)
//
val () = cbufObj_free (buf)
} (* end of [main] *)
(* ****** ****** *)
(* end of [circbuf2.dats] *)
| {
"pile_set_name": "Github"
} |
#ifndef BOOST_MPL_INTEGRAL_C_FWD_HPP_INCLUDED
#define BOOST_MPL_INTEGRAL_C_FWD_HPP_INCLUDED
// Copyright Aleksey Gurtovoy 2000-2006
//
// Distributed under the Boost Software License, Version 1.0.
// (See accompanying file LICENSE_1_0.txt or copy at
// http://www.boost.org/LICENSE_1_0.txt)
//
// See http://www.boost.org/libs/mpl for documentation.
// $Id$
// $Date$
// $Revision$
#include <boost/mpl/aux_/config/workaround.hpp>
#include <boost/mpl/aux_/adl_barrier.hpp>
BOOST_MPL_AUX_ADL_BARRIER_NAMESPACE_OPEN
#if BOOST_WORKAROUND(__HP_aCC, <= 53800)
// the type of non-type template arguments may not depend on template arguments
template< typename T, long N > struct integral_c;
#else
template< typename T, T N > struct integral_c;
#endif
BOOST_MPL_AUX_ADL_BARRIER_NAMESPACE_CLOSE
BOOST_MPL_AUX_ADL_BARRIER_DECL(integral_c)
#endif // BOOST_MPL_INTEGRAL_C_FWD_HPP_INCLUDED
| {
"pile_set_name": "Github"
} |
package com.delivery.core.usecases.order;
import com.delivery.core.domain.Identity;
import com.delivery.core.domain.Order;
import java.util.Optional;
public interface OrderRepository {
Order persist(Order order);
Optional<Order> getById(Identity id);
}
| {
"pile_set_name": "Github"
} |
# Copyright 2016 The Chromium Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
import("//printing/buildflags/buildflags.gni")
import("//services/catalog/public/tools/catalog.gni")
import("//services/service_manager/public/service_manifest.gni")
source_set("test_support") {
testonly = true
sources = [
"components_test_suite.cc",
"components_test_suite.h",
]
deps = [
"//components/content_settings/core/common",
"//components/gcm_driver:gcm_driver",
"//components/signin/core/browser",
"//mojo/edk",
"//net",
"//testing/gtest",
"//ui/base",
"//ui/resources:ui_test_pak",
]
public_deps = [
"//base/test:test_support",
]
if (!is_ios) {
deps += [
"//components/invalidation/impl",
"//components/policy/core/browser",
"//ui/gl:test_support",
]
public_deps += [ "//content/test:test_support" ]
}
}
# Defines a main() function that uses components_test_suite.h
source_set("run_all_unittests") {
testonly = true
sources = [
"run_all_unittests.cc",
]
deps = [
":test_support",
]
if (enable_basic_printing) {
defines = [ "HAS_SERVICE_IN_UNIT_TEST" ]
deps += [
":components_unittests_catalog_source",
"//services/catalog:lib",
]
}
}
if (enable_basic_printing) {
# There is only one service in catalog, which depends on printing feature.
# When more services are added, the condition can be moved inside of catalog.
catalog("components_unittests_catalog") {
embedded_services = [ "//components/services/pdf_compositor:pdf_compositor_service_unittest_manifest" ]
}
catalog_cpp_source("components_unittests_catalog_source") {
testonly = true
catalog = ":components_unittests_catalog"
generated_function_name = "components::CreateUnittestsCatalog"
}
}
| {
"pile_set_name": "Github"
} |
/*
* crash-issue3.c: Written for Mac OS X Yosemite (10.10) by @rpaleari and @joystick.
*
* Exploits a missing check in
* IOBluetoothHCIController::TransferACLPacketToHW() to trigger a panic.
*
* gcc -Wall -o crash-issue3{,.c} -framework IOKit
*
*/
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <mach/mach.h>
#include <mach/vm_map.h>
#include <IOKit/IOKitLib.h>
struct BluetoothCall {
uint64_t args[7];
uint64_t sizes[7];
uint64_t index;
};
int main(void) {
/* Finding vuln service */
io_service_t service =
IOServiceGetMatchingService(kIOMasterPortDefault,
IOServiceMatching("IOBluetoothHCIController"));
if (!service) {
return -1;
}
/* Connect to vuln service */
io_connect_t port = (io_connect_t) 0;
kern_return_t kr = IOServiceOpen(service, mach_task_self(), 0, &port);
IOObjectRelease(service);
if (kr != kIOReturnSuccess) {
return kr;
}
printf(" [+] Opened connection to service on port: %d\n", port);
struct BluetoothCall a;
memset(&a, 0, sizeof(a));
a.sizes[0] = 0x1000;
a.args[0] = (uint64_t) calloc(a.sizes[0], sizeof(char));
a.sizes[1] = 0x1000;
a.args[1] = (uint64_t) calloc(a.sizes[1], sizeof(char));
memset((void *)a.args[1], 0x22, 0x1000);
/* Call DispatchHCISendRawACLData() */
a.index = 0x63;
/* Debug */
for(int i = 0; i < 120; i++) {
if(i % 8 == 0) printf("\n");
printf("\\x%02x", ((unsigned char *)&a)[i]);
}
printf("\n");
fflush(stdout);
kr = IOConnectCallMethod((mach_port_t) port, /* Connection */
(uint32_t) 0, /* Selector */
NULL, 0, /* input, inputCnt */
(const void*) &a, /* inputStruct */
sizeof(a), /* inputStructCnt */
NULL, NULL, NULL, NULL); /* Output stuff */
printf("kr: %08x\n", kr);
return IOServiceClose(port);
} | {
"pile_set_name": "Github"
} |
<?php
/**
* Copyright © Magento, Inc. All rights reserved.
* See COPYING.txt for license details.
*/
namespace Magento\Wishlist\Test\Unit\Controller\Shared;
use Magento\Framework\TestFramework\Unit\Helper\ObjectManager as ObjectManagerHelper;
use Magento\Framework\Controller\ResultFactory;
class AllcartTest extends \PHPUnit\Framework\TestCase
{
/**
* @var \Magento\Wishlist\Controller\Shared\Allcart
*/
protected $allcartController;
/**
* @var \Magento\Framework\TestFramework\Unit\Helper\ObjectManager
*/
protected $objectManagerHelper;
/**
* @var \Magento\Framework\App\Action\Context
*/
protected $context;
/**
* @var \Magento\Wishlist\Controller\Shared\WishlistProvider|\PHPUnit_Framework_MockObject_MockObject
*/
protected $wishlistProviderMock;
/**
* @var \Magento\Wishlist\Model\ItemCarrier|\PHPUnit_Framework_MockObject_MockObject
*/
protected $itemCarrierMock;
/**
* @var \Magento\Wishlist\Model\Wishlist|\PHPUnit_Framework_MockObject_MockObject
*/
protected $wishlistMock;
/**
* @var \Magento\Framework\App\Request\Http|\PHPUnit_Framework_MockObject_MockObject
*/
protected $requestMock;
/**
* @var \Magento\Framework\Controller\ResultFactory|\PHPUnit_Framework_MockObject_MockObject
*/
protected $resultFactoryMock;
/**
* @var \Magento\Framework\Controller\Result\Redirect|\PHPUnit_Framework_MockObject_MockObject
*/
protected $resultRedirectMock;
/**
* @var \Magento\Framework\Controller\Result\Forward|\PHPUnit_Framework_MockObject_MockObject
*/
protected $resultForwardMock;
protected function setUp()
{
$this->wishlistProviderMock = $this->getMockBuilder(\Magento\Wishlist\Controller\Shared\WishlistProvider::class)
->disableOriginalConstructor()
->getMock();
$this->itemCarrierMock = $this->getMockBuilder(\Magento\Wishlist\Model\ItemCarrier::class)
->disableOriginalConstructor()
->getMock();
$this->wishlistMock = $this->getMockBuilder(\Magento\Wishlist\Model\Wishlist::class)
->disableOriginalConstructor()
->getMock();
$this->requestMock = $this->getMockBuilder(\Magento\Framework\App\Request\Http::class)
->disableOriginalConstructor()
->getMock();
$this->resultFactoryMock = $this->getMockBuilder(\Magento\Framework\Controller\ResultFactory::class)
->disableOriginalConstructor()
->getMock();
$this->resultRedirectMock = $this->getMockBuilder(\Magento\Framework\Controller\Result\Redirect::class)
->disableOriginalConstructor()
->getMock();
$this->resultForwardMock = $this->getMockBuilder(\Magento\Framework\Controller\Result\Forward::class)
->disableOriginalConstructor()
->getMock();
$this->resultFactoryMock->expects($this->any())
->method('create')
->willReturnMap(
[
[ResultFactory::TYPE_REDIRECT, [], $this->resultRedirectMock],
[ResultFactory::TYPE_FORWARD, [], $this->resultForwardMock]
]
);
$this->objectManagerHelper = new ObjectManagerHelper($this);
$this->context = $this->objectManagerHelper->getObject(
\Magento\Framework\App\Action\Context::class,
[
'request' => $this->requestMock,
'resultFactory' => $this->resultFactoryMock
]
);
$this->allcartController = $this->objectManagerHelper->getObject(
\Magento\Wishlist\Controller\Shared\Allcart::class,
[
'context' => $this->context,
'wishlistProvider' => $this->wishlistProviderMock,
'itemCarrier' => $this->itemCarrierMock
]
);
}
public function testExecuteWithWishlist()
{
$url = 'http://redirect-url.com';
$quantity = 2;
$this->wishlistProviderMock->expects($this->once())
->method('getWishlist')
->willReturn($this->wishlistMock);
$this->requestMock->expects($this->any())
->method('getParam')
->with('qty')
->willReturn($quantity);
$this->itemCarrierMock->expects($this->once())
->method('moveAllToCart')
->with($this->wishlistMock, 2)
->willReturn($url);
$this->resultRedirectMock->expects($this->once())
->method('setUrl')
->with($url)
->willReturnSelf();
$this->assertSame($this->resultRedirectMock, $this->allcartController->execute());
}
public function testExecuteWithNoWishlist()
{
$this->wishlistProviderMock->expects($this->once())
->method('getWishlist')
->willReturn(false);
$this->resultForwardMock->expects($this->once())
->method('forward')
->with('noroute')
->willReturnSelf();
$this->assertSame($this->resultForwardMock, $this->allcartController->execute());
}
}
| {
"pile_set_name": "Github"
} |
<!DOCTYPE html
PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<!--
Copyright (c) 2018, Oracle and/or its affiliates. All rights reserved.
Licensed under the Universal Permissive License v 1.0 as shown at http://oss.oracle.com/licenses/upl.
-->
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en-us" lang="en-us">
<head><meta http-equiv="Content-Type" content="text/html; charset=us-ascii" />
<meta name="DC.Type" content="concept" />
<meta name="DC.Title" content="Using the Class Loading Page" />
<meta name="abstract" content="The Class Loading page contains information about classes loaded and unloaded during the recording." />
<meta name="description" content="The Class Loading page contains information about classes loaded and unloaded during the recording." />
<meta name="DC.Format" content="XHTML" />
<meta name="DC.Identifier" content="GUID-6A66D658-7FD4-4621-9FE7-662D8B8FFACF" />
<meta name="DC.Language" content="en-US" />
<meta http-equiv="Content-Style-Type" content="text/css" />
<meta http-equiv="Content-Script-Type" content="text/javascript" />
<title>Using the Class Loading Page</title>
<meta name="doctitle" content="Using the Class Loading Page
" />
<meta name="robots" content="noarchive" />
<link rel="copyright" href="http://oss.oracle.com/licenses/upl" title="Copyright" type="text/html" />
<link rel="contents" href="toc.htm" title="Contents" type="text/html" />
<link rel="prev" href="GUID-DB152DDE-4694-439D-B8A7-CF1EABFAF795.htm" title="Previous" type="text/html" />
<link rel="next" href="GUID-8E04A807-3D2B-4896-AD06-B0DE61ACBBD9.htm" title="Next" type="text/html" />
</head>
<body>
<div class="zz-skip-header"><a href="#BEGIN">Go to primary content</a></div>
<table class="simple oac_no_warn" summary="" cellspacing="0" cellpadding="0" width="100%">
<col width="86%" /><col width="*" /><tr valign="bottom">
<td></td>
<td align="center">
<a href="GUID-DB152DDE-4694-439D-B8A7-CF1EABFAF795.htm">
<img src="./dcommon/gifs/leftnav.gif" alt="Previous" /><br />
<span class="icon">Previous</span>
</a>
</td>
<td align="center">
<a href="GUID-8E04A807-3D2B-4896-AD06-B0DE61ACBBD9.htm">
<img src="./dcommon/gifs/rightnav.gif" alt="Next" /><br />
<span class="icon">Next</span>
</a>
</td>
<td> </td>
</tr>
</table><div class="ind"><a id="GUID-6A66D658-7FD4-4621-9FE7-662D8B8FFACF" name="GUID-6A66D658-7FD4-4621-9FE7-662D8B8FFACF"></a><!-- End Header -->
<h1 id="JMCOH-GUID-6A66D658-7FD4-4621-9FE7-662D8B8FFACF" class="sect1">Using the Class Loading Page</h1>
<div><p>The <span class="bold">Class Loading</span> page contains information about classes loaded and unloaded during the recording.</p>
<p>This page displays class loading data in both tables and graphs.</p>
<div class="section"><p class="subhead1">Using the Class Loading Page: Selections and Aspects</p><p>Use the drop-down menus at the top of the page to choose a selection and aspect if desired. Data from other pages can be saved to the selection drop-down menu by dragging an area of a chart (or selecting data from a table) and choosing <span class="bold">Store Selection</span> or <span class="bold">Store Selection and Set As Focused Selection</span> from the context menu.</p>
<div class="p">The following controls provide additional behavior:<ul style="list-style-type: disc;"><li><p><span class="bold">Show concurrent</span>: Show all events concurrent to the selected aspect.</p>
</li>
<li><p><span class="bold">Contained</span>: Only show events that are fully contained in the time range from the active selection aspect</p>
</li>
<li><p><span class="bold">Same threads</span>: Only show events in threads related to the active selection aspect.</p>
</li>
</ul>
</div>
</div>
<!-- class="section" -->
<div class="section"><p class="subhead1">Using the Class Loading Page: Tables and Graphs</p><p>You can select any of the following to be displayed on the graph:</p>
<div class="p"><ul style="list-style-type: disc;"><li><p><span class="bold">Class Loading</span>: The number of classes loaded during the interval.</p>
</li>
<li><p><span class="bold">Class Unloading</span>: The number of classes unloaded during the interval.</p>
</li>
<li><p><span class="bold">Loaded Class Count</span>: The number of classes loaded since JVM start.</p>
</li>
<li><p><span class="bold">Unloaded Class Count</span>: The number of classes unloaded since JVM start.</p>
</li>
</ul>
</div>
<p>The first table contains the <span class="bold">Class Loaders</span> and <span class="bold">Class Statistics</span> subtabs.</p>
<p>Table Columns are labeled as follows:</p>
<p><span class="bold">Class Loaders Tab</span></p>
<div class="p"><ul style="list-style-type: disc;"><li><p><span class="bold">Defining Class Loader</span>: The defining class loader.</p>
</li>
<li><p><span class="bold">Classes Loaded</span>: The number of classes loaded by this class loader.</p>
</li>
<li><p><span class="bold">Classes Unloaded</span>: The number of classes unloaded.</p>
</li>
</ul>
</div>
<p><span class="bold">Class Loader Statistics Tab</span></p>
<div class="p"><ul style="list-style-type: disc;"><li><p><span class="bold">Start Time</span>: The defining class loader.</p>
</li>
<li><p><span class="bold">Classes Loaded</span>: The number of classes loaded by this class loader.</p>
</li>
<li><p><span class="bold">Classes Unloaded</span>: The number of classes unloaded.</p>
</li>
</ul>
</div>
<p>This page also contains <span class="bold">Class Loading</span>, <span class="bold">Class Defining</span> and <span class="bold">Class Unloading</span> subtabs.</p>
<p><span class="bold">Class Loading Tab</span></p>
<ul style="list-style-type: disc;"><li><p><span class="bold">Loaded Class</span>: The name of the loaded class.</p>
</li>
<li><p><span class="bold">Duration</span>: The duration of the class loading.</p>
</li>
<li><p><span class="bold">Defining Class Loader</span>: The name of the defining class loader.</p>
</li>
<li><p><span class="bold">Initiating Class Loader</span>: The name of the initiating class loader.</p>
</li>
<li><p><span class="bold">Thread</span>: The thread where the class was loaded.</p>
</li>
<li><p><span class="bold">End Time</span>: The end time of the class loading event.</p>
</li>
</ul>
<p><span class="bold">Class Defining Tab</span></p>
<ul style="list-style-type: disc;"><li><p><span class="bold">Start Time</span>: The time at which the class was defined.</p>
</li>
<li><p><span class="bold">Defining Class Loader</span>: The name of the defining class loader.</p>
</li>
<li><p><span class="bold">Defined</span>: The name of the class that was defined</p>
</li>
</ul>
<p><span class="bold">Class Unloading Tab</span></p>
<ul style="list-style-type: disc;"><li><p><span class="bold">Unloaded Class</span>: The name of the unloaded class.</p>
</li>
<li><p><span class="bold">Defining Class Loader</span>: The name of the defining class loader.</p>
</li>
<li><p><span class="bold">End Time</span>: The end time of the class unloading event.</p>
</li>
</ul>
</div>
<!-- class="section" -->
<div class="section"><p class="subhead1">Using the Class Loading Page: Configuring Rules</p><p>You can set configuration attributes for the rules associated with this page by clicking the <span class="bold">Edit Configuration</span> icon.</p>
<p>The following options are available:</p>
<div class="p"><span class="bold">Class Leak</span><ul style="list-style-type: disc;"><li><p><span class="bold">Warning limit</span>: The number of loads to a class that should trigger a warning.</p>
</li>
<li><p><span class="bold">Class limit</span>: the maximum number of classes exceeding the Warning Limit to report.</p>
</li>
</ul>
</div>
<div class="p"><span class="bold">Class Loading Pressure</span><ul style="list-style-type: disc;"><li><p><span class="bold">Classloading duration limit</span>: The shortest classloading duration that should trigger a warning.</p>
</li>
<li><p><span class="bold">Classloading ratio limit</span>: The minimum ratio between time spent in classloading and the total duration of the recording.</p>
</li>
</ul>
</div>
</div>
<!-- class="section" -->
</div>
</div><!-- class="ind" --><!-- Start Footer -->
<table class="simple oac_no_warn" summary="" cellspacing="0" cellpadding="0" width="100%">
<col width="86%" /><col width="*" /><tr valign="bottom">
<td><a href="http://oss.oracle.com/licenses/upl"><br />
<span class="copyrightlogo">Copyright © 2018, Oracle and/or its affiliates. All rights reserved.</span></a></td>
<td align="center">
<a href="GUID-DB152DDE-4694-439D-B8A7-CF1EABFAF795.htm">
<img src="./dcommon/gifs/leftnav.gif" alt="Previous" /><br />
<span class="icon">Previous</span>
</a>
</td>
<td align="center">
<a href="GUID-8E04A807-3D2B-4896-AD06-B0DE61ACBBD9.htm">
<img src="./dcommon/gifs/rightnav.gif" alt="Next" /><br />
<span class="icon">Next</span>
</a>
</td>
<td> </td>
</tr>
</table>
<!-- class="footer" -->
</body>
</html> | {
"pile_set_name": "Github"
} |
{
"parent": "minecraft:recipes/root",
"rewards": {
"recipes": [
"tconstruct:casting/casts/ingots"
]
},
"criteria": {
"has_item": {
"trigger": "minecraft:inventory_changed",
"conditions": {
"items": [
{
"tag": "forge:ingots"
}
]
}
},
"has_the_recipe": {
"trigger": "minecraft:recipe_unlocked",
"conditions": {
"recipe": "tconstruct:casting/casts/ingots"
}
}
},
"requirements": [
[
"has_item",
"has_the_recipe"
]
]
} | {
"pile_set_name": "Github"
} |
@using System.Web.Mvc.Html
@using Firehose.Web.Controllers
@using MvcNavigationHelpers
<!doctype html>
<html>
<head>
<title>Planet Xamarin: Community Blog Feed</title>
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="~/Content/plugins/bootstrap/css/bootstrap.min.css" />
<link rel="stylesheet" href="~/Content/plugins/bootstrap/css/bootstrap.planetxamarin.min.css" />
<link rel="stylesheet" href="~/Content/css/site.css" />
<link rel="stylesheet" href="~/Content/plugins/animate.css" />
<link rel="alternate" type="application/rss+xml" title="Planet Xamarin" href="https://www.planetxamarin.com@((Url.UrlFor<FeedController>(c => c.Index(null, null))))" />
<link rel="apple-touch-icon" sizes="57x57" href="~/content/img/icons/apple-icon-57x57.png">
<link rel="apple-touch-icon" sizes="60x60" href="~/content/img/icons/apple-icon-60x60.png">
<link rel="apple-touch-icon" sizes="72x72" href="~/content/img/icons/apple-icon-72x72.png">
<link rel="apple-touch-icon" sizes="76x76" href="~/content/img/icons/apple-icon-76x76.png">
<link rel="apple-touch-icon" sizes="114x114" href="~/content/img/icons/apple-icon-114x114.png">
<link rel="apple-touch-icon" sizes="120x120" href="~/content/img/icons/apple-icon-120x120.png">
<link rel="apple-touch-icon" sizes="144x144" href="~/content/img/icons/apple-icon-144x144.png">
<link rel="apple-touch-icon" sizes="152x152" href="~/content/img/icons/apple-icon-152x152.png">
<link rel="apple-touch-icon" sizes="180x180" href="~/content/img/icons/apple-icon-180x180.png">
<link rel="icon" type="image/png" sizes="192x192" href="~/content/img/icons/android-icon-192x192.png">
<link rel="icon" type="image/png" sizes="32x32" href="~/content/img/icons/favicon-32x32.png">
<link rel="icon" type="image/png" sizes="96x96" href="~/content/img/icons/favicon-96x96.png">
<link rel="icon" type="image/png" sizes="16x16" href="~/content/img/icons/favicon-16x16.png">
<link rel="manifest" href="~/content/img/icons/manifest.json">
<meta name="msapplication-TileColor" content="#ffffff">
<meta name="msapplication-TileImage" content="~/content/img/icons/ms-icon-144x144.png">
<meta name="theme-color" content="#ffffff">
<link rel="stylesheet" href="~/Content/plugins/fontawesome/css/font-awesome.min.css">
@RenderSection("head", false)
<script>
(function (i, s, o, g, r, a, m) {
i['GoogleAnalyticsObject'] = r; i[r] = i[r] || function () {
(i[r].q = i[r].q || []).push(arguments)
}, i[r].l = 1 * new Date(); a = s.createElement(o),
m = s.getElementsByTagName(o)[0]; a.async = 1; a.src = g; m.parentNode.insertBefore(a, m)
})(window, document, 'script', 'https://www.google-analytics.com/analytics.js', 'ga');
ga('create', 'UA-90554801-1', 'auto');
ga('send', 'pageview');
</script>
</head>
<body>
<nav class="navbar navbar-inverse navbar-fixed-top" role="navigation">
<div class="container">
<div class="navbar-header">
<button type="button" class="navbar-toggle collapsed" data-toggle="collapse" data-target=".navbar-collapse">
<span class="icon-bar"></span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
</button>
<a class="navbar-brand" href="@Url.Content("~")">
<div class="navbar-brand-title">Planet Xamarin</div>
</a>
</div>
<div class="navbar-collapse navbar-right collapse">
<ul class="nav navbar-nav">
<li>@Html.ActionLink("Home", "Index", "Home")</li>
<li>@Html.ActionLink("Authors", "Index", "Authors")</li>
<li>@Html.ActionLink("Preview", "Index", "Preview")</li>
<li><a href="@Url.Action("Index", "Feed")"><i class="fa fa-rss" aria-hidden="true"></i> <span id="rssText">RSS Feed</span></a></li>
<li><a href="https://twitter.com/PlanetXamarin"><i class="fa fa-twitter" aria-hidden="true"></i> <span id="twitterText">Twitter</span></a></li>
<li><a href="https://www.facebook.com/planetxamarin/"><i class="fa fa-facebook" aria-hidden="true"></i> <span id="facebookText">Facebook</span></a></li>
</ul>
</div>
</div>
</nav>
@RenderBody()
<script src="~/Content/plugins/jquery/jquery-3.1.1.min.js" type="text/javascript"></script>
<script src="~/Content/plugins/bootstrap/js/bootstrap.min.js" type="text/javascript"></script>
@RenderSection("scripts", false)
<script type="text/javascript">
var clicky_site_ids = clicky_site_ids || [];
clicky_site_ids.push(101018153);
(function () {
var s = document.createElement('script');
s.type = 'text/javascript';
s.async = true;
s.src = '//static.getclicky.com/js';
(document.getElementsByTagName('head')[0] || document.getElementsByTagName('body')[0]).appendChild(s);
})();
</script>
<noscript><p><img alt="Clicky" width="1" height="1" src="//in.getclicky.com/101018153ns.gif" /></p></noscript>
</body>
</html> | {
"pile_set_name": "Github"
} |
dojo.provide("dojox.widget.tests.test_PortletInGridContainer");
dojo.require("dijit.dijit");
dojo.require("dojo.date.locale");
dojo.require("dojo.cookie");
dojo.require("dijit.form.CheckBox");
dojo.require("dijit.form.TextBox");
dojo.require("dijit.form.Slider");
dojo.require("dijit.layout.TabContainer");
dojo.require("dijit.layout.AccordionContainer");
dojo.require("dijit.layout.BorderContainer");
dojo.require("dijit.Tooltip");
dojo.require("dijit.Tree");
dojo.require("dijit.tree.ForestStoreModel");
dojo.require("dojox.image.Gallery");
dojo.require("dojox.widget.PlaceholderMenuItem");
dojo.require("dojox.data.FileStore");
dojo.require("dojox.charting.widget.Chart2D");
dojo.require("dojox.charting.themes.Grasslands");
dojo.require("dojox.charting.themes.PlotKit.orange");
dojo.require("dojox.widget.Calendar");
dojo.require("dojox.widget.Portlet");
dojo.require("dojox.layout.GridContainer");
dojo.require("dojox.layout.TableContainer");
dojo.require("dojox.grid.DataGrid");
dojo.require("dojox.data.HtmlStore");
dojo.require("dojox.data.FlickrRestStore");
dojo.require("dojox.fx.text");
dojo.require("dojox.layout.ExpandoPane");
dojo.require("dojox.charting.Chart3D");
dojo.require("dojox.charting.action2d.Highlight");
dojo.require("dojox.charting.action2d.MoveSlice");
dojo.require("dojox.charting.action2d.Tooltip");
//This must be included on the page for FeedPortlets that
//load local feeds.
dojo.require("dojox.data.AtomReadStore");
dojo.require("dojo.parser");
dojo.addOnLoad(function(){
dojo.parser.parse();
var chart = window.chart = new dojox.charting.Chart2D("zoomer");
chart.setTheme(dojox.charting.themes.PlotKit.orange);
chart.addAxis("x", {fixLower: "minor", natural: true, stroke: "grey",
majorTick: {stroke: "black", length: 4}, minorTick: {stroke: "gray", length: 2}});
chart.addAxis("y", {vertical: true, min: 0, max: 30, majorTickStep: 5, minorTickStep: 1, stroke: "grey",
majorTick: {stroke: "black", length: 4}, minorTick: {stroke: "gray", length: 2}});
chart.addPlot("default", {type: "Areas"});
chart.addSeries("Series A", [0, 25, 5, 20, 10, 15, 5, 20, 0, 25]);
chart.addAxis("x2", {fixLower: "minor", natural: true, leftBottom: false, stroke: "grey",
majorTick: {stroke: "black", length: 4}, minorTick: {stroke: "gray", length: 2}});
chart.addAxis("y2", {vertical: true, min: 0, max: 20, leftBottom: false, stroke: "grey",
majorTick: {stroke: "black", length: 4}, minorTick: {stroke: "gray", length: 2}});
chart.addPlot("plot2", {type: "Areas", hAxis: "x2", vAxis: "y2"});
chart.addSeries("Series B", [15, 0, 15, 0, 15, 0, 15, 0, 15, 0, 15, 0, 15, 0, 15, 0, 15], {plot: "plot2"});
chart.addPlot("grid", {type: "Grid", hMinorLines: true});
chart.render();
var show = setInterval(function(){
var w = dijit.byId("gridContainer");
if (w && w.domNode) {
dojo.body().removeChild(dojo.byId("masker"));
clearInterval(show);
}
}, 500);
var scaleX = 1, scaleY = 1, offsetX = 0, offsetY = 0;
dojo.connect(dijit.byId("scaleXSlider"), "onChange", function(value){
scaleX = value;
console.log("calling update");
update();
});
function update() {
chart.setWindow(scaleX, scaleY, offsetX, offsetY).render();
}
var _init = null;
var onMouseDown = function(e){
_init = {x: e.clientX, y: e.clientY, ox: offsetX, oy: offsetY};
dojo.stopEvent(e);
};
var onMouseUp = function(e){
if(_init){
_init = null;
dojo.stopEvent(e);
}
};
var onMouseMove = function(e){
if(_init){
var dx = e.clientX - _init.x,
dy = e.clientY - _init.y;
offsetX = _init.ox - dx;
offsetY = _init.oy + dy;
chart.setWindow(scaleX, scaleY, offsetX, offsetY).render();
dojo.stopEvent(e);
}
};
dojo.connect(chart.node, "onmousedown", onMouseDown);
dojo.connect(chart.node, "onmousemove", onMouseMove);
dojo.connect(chart.node, "onmouseup", onMouseUp);
createProgrammaticPortlet();
});
function createProgrammaticPortlet() {
var portlet = new dojox.widget.FeedPortlet({
id: "ProgrammaticPortlet",
dndType: "Portlet",
title: "Programmatic FeedPortlet with multiple feeds"
}, dojo.create("div", {
innerHTML: "This portlet was created programmatically, and has mulitple feeds to select from."
+ " Click the settings icon in the title bar to choose another feed."
}));
var settings = new dojox.widget.PortletFeedSettings({
id: "ProgrammaticPortletSettings",
urls: [
{
url: "http://news.google.com/news?hl=en&topic=t&output=atom",
label: "Google News"
},
{
url: "http://shaneosullivan.wordpress.com/category/dojo/feed/",
label: "Dojo Blatherings"
},
{
url: "http://www.dojotoolkit.org/aggregator/rss",
label: "Planet Dojo"
}
]
});
portlet.addChild(settings);
dijit.byId("gridContainer2").addService(portlet, 0, 0);
}
var count = 0;
function loadFeed(url, nodeId, emptyMsg, type) {
var query = {
url: url
};
var request = {query:query};
var maxBufSize = 8;
var outNode = dojo.byId(nodeId);
var testStore = new dojox.data.GoogleFeedStore();
function doAppend(items){
console.log(items);
if (items.length > 0) {
if (type == "list") {
dojo.addClass(outNode, "feedList");
var ul = dojo.create("ul", null, outNode);
dojo.forEach(items, function(item){
var li = dojo.create("li", {
innerHTML: '<a href="' + testStore.getValue(item, 'link') + '">'
+ testStore.getValue(item, 'title') + '</a>'
},ul);
dojo.connect(li, "onmouseover", function() {
dijit.showTooltip(testStore.getValue(item, "content"), li);
});
dojo.connect(li, "onmouseout", function() {
dijit.hideTooltip(li);
});
});
}
else {
var accordion = new dijit.layout.AccordionContainer({});
dojo.byId(nodeId).appendChild(accordion.domNode);
dojo.forEach(items, function(item){
var summary = testStore.getValue(item, "title");
if (summary.length > 40) {
summary = summary.substring(0, 50);
}
var contentPane = new dijit.layout.ContentPane({
title: summary,
content: testStore.getValue(item, "content")
});
dojo.style(contentPane.domNode, "width", "100%");
accordion.addChild(contentPane);
contentPane.startup();
});
var portlet = dijit.getEnclosingWidget(dojo.byId(nodeId));
portlet.addChild(accordion);
}
} else {
dojo.byId(nodeId).innerHTML = emptyMsg || "No results";
}
}
request.onBegin = function(numItems){};
request.onComplete = doAppend;
request.count = 4;
testStore.fetch(request);
}
var layoutHtmlTable = [
[
{name: 'First Name', field: 'First Name', width: '50%'},
{name: 'Last Name', field: 'Last Name', width: '25%'},
{name: 'DOB', field: 'DOB', width: '25%'}
]
];
var text_explode_2 = function(node){
if(node.style.height){
return;
}
var originalText = node.innerHTML;
var properties = {
node: node,
words: true,
distance: 1.5,
duration: 1500,
random: 0.5
};
properties.onEnd = function(){
currentAnimation = dojox.fx.text.converge(dojo.mixin(properties,{
onEnd: undefined,
text: originalText
}));
currentAnimation.play();
};
currentAnimation = dojox.fx.text.explode(properties).play();
};
| {
"pile_set_name": "Github"
} |
**Are you the copyright holder or authorized to act on the copyright owner's behalf?**
Yes, I am authorized to act on the copyright owner's behalf.
**Please describe the nature of your copyright ownership or authorization to act on the owner's behalf.**
Hello Sir/Madam,
Good day,
I am writing here behalf of Probuse Consulting Service Pvt Ltd. (Our website: www.probuse.com) , we have bit bucket repository with url [private] and we listed all our Odoo modules there and its registered with odoo apps with following link. My name is [private] (Email: [private])
https://apps.odoo.com/apps/modules/browse?author=Probuse%20Consulting%20Service%20Pvt.%20Ltd. and it contains Odoo Proprietary License v1.0.
We are raising for 5 infringer’s name in this one notice so please note it. So you will find 5 subsection in below every sections.
====================================================
xAlphaOmega (github owner) published our Odoo Proprietary License v1.0 's code as public repository please check below link which has our module and its published as public repo. https://github.com/xAlphaOmega/ebany-constraction and https://github.com/xAlphaOmega/agaf12
this all repository contains our odoo-python modules which is registered as Proprietary modules under Probuse Consulting Service Pvt Ltd. I will give you more details on below section. You can see this bundle https://apps.odoo.com/apps/modules/12.0/job_costing_contracting_bundle/ and dependant modules on bundle which are private modules to us.
====================================================
hnetw (github owner) published our Odoo Proprietary License v1.0 's code as public repository please check below link which has our module and its published as public repo. https://github.com/hnetw/demo/tree/master/construction_management_app
this all repository contains our odoo-python modules which is registered as Proprietary modules under Probuse Consulting Service Pvt Ltd. I will give you more details on below section. You can see this https://apps.odoo.com/apps/modules/12.0/construction_management_app/ which are private modules to us.
====================================================
xmarts (github owner) published our Odoo Proprietary License v1.0 's code as public repository please check below link which has our module and its published as public repo. https://github.com/xmarts/calculate_comission_category/tree/master/modsinter https://github.com/xmarts/calculate_comission_category/blob/master/modsinter/sales_commission_calculation.zip https://github.com/xmarts/calculate_comission_category/tree/master/modsinter/sales_commission_calculation
this all repository contains our odoo-python modules which is registered as Proprietary modules under Probuse Consulting Service Pvt Ltd. I will give you more details on below section. You can see this https://apps.odoo.com/apps/modules/12.0/sales_commission_calculation/ which are private modules to us.
====================================================
Admin-Ever (github owner) published our Odoo Proprietary License v1.0 's code as public repository please check below link which has our module and its published as public repo. https://github.com/Admin-Ever/miccologistics https://github.com/Admin-Ever/miccologistics/tree/stage https://github.com/Admin-Ever/miccologistics/tree/master
this all repository contains our odoo-python modules which is registered as Proprietary modules under Probuse Consulting Service Pvt Ltd. I will give you more details on below section. You can see this https://apps.odoo.com/apps/modules/12.0/car_repair_maintenance_service/ which are private modules to us.
========================================================
antoniocanovas (github owner) published our Odoo Proprietary License v1.0 's code as public repository please check below link which has our module and its published as public repo. https://github.com/antoniocanovas/dev12/tree/master/odoo_mobile_timesheet https://github.com/antoniocanovas/dev12/blob/master/odoo_mobile_timesheet-12.0.1.1.zip
this all repository contains our odoo-python modules which is registered as Proprietary modules under Probuse Consulting Service Pvt Ltd. I will give you more details on below section. You can see this https://apps.odoo.com/apps/modules/12.0/odoo_mobile_timesheet/ which are private modules to us.
==============================================================
Thank you,
[private]
**Please provide a detailed description of the original copyrighted work that has allegedly been infringed. If possible, include a URL to where it is posted online.**
Here is URL: https://apps.odoo.com/apps/modules/12.0/job_costing_contracting_bundle/ --> You can click links inside modules description for individual apps inside that bundle.
https://apps.odoo.com/apps/modules/12.0/odoo_job_costing_management
https://apps.odoo.com/apps/modules/12.0/job_costing_cost_actual
https://apps.odoo.com/apps/modules/12.0/job_costing_dashboard
https://apps.odoo.com/apps/modules/12.0/odoo_project_team
https://apps.odoo.com/apps/modules/12.0/odoo_customer_progress_billing
https://apps.odoo.com/apps/modules/12.0/odoo_job_costing_progress_billing
https://apps.odoo.com/apps/modules/12.0/job_cost_estimate_customer
https://apps.odoo.com/apps/modules/12.0/job_cost_and_estimate_relation
https://apps.odoo.com/apps/modules/12.0/job_workorder_website_request/
https://apps.odoo.com/apps/modules/12.0/job_costing_volumn_trend/
https://apps.odoo.com/apps/modules/12.0/job_cost_trend/
https://apps.odoo.com/apps/modules/12.0/material_requisition_cost_sheet/
https://apps.odoo.com/apps/modules/12.0/construction_contracting_change_order/
https://apps.odoo.com/apps/modules/12.0/job_costing_budget_contracting/
https://apps.odoo.com/apps/modules/12.0/job_costing_budget_contracting_enterprice/
https://apps.odoo.com/apps/modules/12.0/job_equipments_maintenance_request/
https://apps.odoo.com/apps/modules/12.0/job_order_card_instruction/
https://apps.odoo.com/apps/modules/12.0/job_work_order_expense/
https://apps.odoo.com/apps/modules/12.0/job_order_subcontracting/
https://apps.odoo.com/apps/modules/12.0/website_construction_project_page/
https://apps.odoo.com/apps/modules/12.0/construction_contracting_payroll/
https://apps.odoo.com/apps/modules/12.0/project_request_for_information/
https://apps.odoo.com/apps/modules/12.0/job_inspection/
https://apps.odoo.com/apps/modules/12.0/odoo_project_phases/
https://apps.odoo.com/apps/modules/12.0/project_meeting_minutes/
https://apps.odoo.com/apps/modules/12.0/construction_contracting_issue_tracking/
https://apps.odoo.com/apps/modules/12.0/issue_tracking_employee_portal/
https://apps.odoo.com/apps/modules/12.0/job_drawing_construction_contracting/
https://apps.odoo.com/apps/modules/12.0/project_notes_mobile_tablet/
https://apps.odoo.com/apps/modules/12.0/job_drawing_image_contracting/
https://apps.odoo.com/apps/modules/12.0/job_costing_contracting_document/
https://apps.odoo.com/apps/modules/12.0/transmittals_communication_document/
https://apps.odoo.com/apps/modules/12.0/construction_maintenance_equipment/
https://apps.odoo.com/apps/modules/12.0/job_order_link_cost_sheet/
https://apps.odoo.com/apps/modules/12.0/job_costing_work_package/
https://apps.odoo.com/apps/modules/12.0/construction_contracting_repair/
https://apps.odoo.com/apps/modules/12.0/construction_waste_management/
https://apps.odoo.com/apps/modules/12.0/job_costing_profit_loss/
https://apps.odoo.com/apps/modules/12.0/job_order_material_consumption/
https://apps.odoo.com/apps/modules/12.0/job_issue_capture_photo/
https://apps.odoo.com/apps/modules/12.0/job_order_material_requisition/
https://apps.odoo.com/apps/modules/12.0/job_contracting_construction_risk/
https://apps.odoo.com/apps/modules/12.0/job_costsheet_import/
===============================================
Here is URL https://apps.odoo.com/apps/modules/12.0/construction_management_app/
===============================================
Here is URL https://apps.odoo.com/apps/modules/12.0/sales_commission_calculation/
===============================================
Here is URL https://apps.odoo.com/apps/modules/12.0/car_repair_maintenance_service/
===============================================
Here is URL https://apps.odoo.com/apps/modules/12.0/odoo_mobile_timesheet/
**What files should be taken down? Please provide URLs for each file, or if the entire repository, the repository’s URL.**
Here is the specific link of our python/Odoo module which published publicly .
https://github.com/xAlphaOmega/agaf12
https://github.com/xAlphaOmega/ebany-constraction
=========================
Here is the specific link of our python/Odoo module which published publicly .
https://github.com/hnetw/demo/tree/master/construction_management_app
=========================
Here is the specific link of our python/Odoo module which published publicly .
https://github.com/xmarts/calculate_comission_category/tree/master/modsinter https://github.com/xmarts/calculate_comission_category/blob/master/modsinter/sales_commission_calculation.zip https://github.com/xmarts/calculate_comission_category/tree/master/modsinter/sales_commission_calculation
=========================
Here is the specific link of our python/Odoo module which published publicly .
https://github.com/Admin-Ever/miccologistics https://github.com/Admin-Ever/miccologistics/tree/stage https://github.com/Admin-Ever/miccologistics/tree/master
=========================
Here is the specific link of our python/Odoo module which published publicly .
https://github.com/antoniocanovas/dev12/tree/master/odoo_mobile_timesheet https://github.com/antoniocanovas/dev12/blob/master/odoo_mobile_timesheet-12.0.1.1.zip
**Have you searched for any forks of the allegedly infringing files or repositories? Each fork is a distinct repository and must be identified separately if you believe it is infringing and wish to have it taken down.**
Yes below are details of fork:
https://github.com/xAlphaOmega/agaf12/network/members -->
1 https://github.com/eslammohamed13/agaf12
2. https://github.com/izzihector/agaf12
3 https://github.com/marcelsavegnago/agaf12
4 https://github.com/odoo-modules/agaf12
And
https://github.com/xAlphaOmega/ebany-constraction/network/members --
1 https://github.com/marcelsavegnago/ebany-constraction
2 https://github.com/odoo-modules/ebany-constraction
======================
Fork for construction modules:
https://github.com/hnetw/demo/network/members --
1 https://github.com/odoo-modules/demo
2 https://github.com/xAlphaOmega/demo
=====================
Fork of commission module
https://github.com/xmarts/calculate_comission_category/network/members --
1 https://github.com/xAlphaOmega/calculate_comission_category
======================
Fork for car repair module
1 https://github.com/odoo-modules/miccologistics
2 https://github.com/xAlphaOmega/miccologistics
======================
For odoo mobile timesheet fork:
https://github.com/antoniocanovas/dev12/network/members
1. https://github.com/odoo-modules/dev12
2. https://github.com/vanthaiunghoa/dev12
3. https://github.com/xAlphaOmega/dev12
4. https://github.com/ajinvn2019/dev12
5. https://github.com/izzihector/dev12
======================
**Is the work licensed under an open source license? If so, which open source license? Are the allegedly infringing files being used under the open source license, or are they in violation of the license?**
yes, Odoo Proprietary License v1.0 (OPL-1)
**What would be the best solution for the alleged infringement? Are there specific changes the other person can make other than removal? Can the repository be made private?**
Better to make all repository down if they have valid purchase license they can put in their private repository anytime. If they have bought apps from odoo store then can redownload and put in their private github repository.
**Do you have the alleged infringer’s contact information? If so, please provide it.**
1 https://github.com/xAlphaOmega
2 https://github.com/hnetw
3. https://github.com/xmarts/
4 https://github.com/Admin-Ever
5 https://github.com/antoniocanovas
**I have a good faith belief that use of the copyrighted materials described above on the infringing web pages is not authorized by the copyright owner, or its agent, or the law.**
**I have taken <a href="https://www.lumendatabase.org/topics/22">fair use</a> into consideration.**
**I swear, under penalty of perjury, that the information in this notification is accurate and that I am the copyright owner, or am authorized to act on behalf of the owner, of an exclusive right that is allegedly infringed.**
**I have read and understand GitHub's <a href="https://help.github.com/articles/guide-to-submitting-a-dmca-takedown-notice/">Guide to Submitting a DMCA Takedown Notice</a>.**
**So that we can get back to you, please provide either your telephone number or physical address.**
Probuse Consulting Service Pvt. Ltd.
419/A, SAKAR IX, Beside Old Reserve Bank of India,
Near City Gold Cinema, Ashram Road
Ahmedabad 380009
Gujarat
India
Email: [private]
**Please type your full legal name below to sign this request.**
[private]
| {
"pile_set_name": "Github"
} |
// This file is part of Eigen, a lightweight C++ template library
// for linear algebra.
//
// Copyright (C) 2009 Gael Guennebaud <[email protected]>
//
// This Source Code Form is subject to the terms of the Mozilla
// Public License v. 2.0. If a copy of the MPL was not distributed
// with this file, You can obtain one at http://mozilla.org/MPL/2.0/.
#define SCALAR std::complex<float>
#define SCALAR_SUFFIX c
#define SCALAR_SUFFIX_UP "C"
#define REAL_SCALAR_SUFFIX s
#define ISCOMPLEX 1
#include "level1_impl.h"
#include "level1_cplx_impl.h"
#include "level2_impl.h"
#include "level2_cplx_impl.h"
#include "level3_impl.h"
| {
"pile_set_name": "Github"
} |
//===-- BPFInstrInfo.td - Target Description for BPF Target ---------------===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// This file describes the BPF instructions in TableGen format.
//
//===----------------------------------------------------------------------===//
include "BPFInstrFormats.td"
// Instruction Operands and Patterns
// These are target-independent nodes, but have target-specific formats.
def SDT_BPFCallSeqStart : SDCallSeqStart<[SDTCisVT<0, iPTR>,
SDTCisVT<1, iPTR>]>;
def SDT_BPFCallSeqEnd : SDCallSeqEnd<[SDTCisVT<0, iPTR>, SDTCisVT<1, iPTR>]>;
def SDT_BPFCall : SDTypeProfile<0, -1, [SDTCisVT<0, iPTR>]>;
def SDT_BPFSetFlag : SDTypeProfile<0, 3, [SDTCisSameAs<0, 1>]>;
def SDT_BPFSelectCC : SDTypeProfile<1, 5, [SDTCisSameAs<1, 2>,
SDTCisSameAs<0, 4>,
SDTCisSameAs<4, 5>]>;
def SDT_BPFBrCC : SDTypeProfile<0, 4, [SDTCisSameAs<0, 1>,
SDTCisVT<3, OtherVT>]>;
def SDT_BPFWrapper : SDTypeProfile<1, 1, [SDTCisSameAs<0, 1>,
SDTCisPtrTy<0>]>;
def BPFcall : SDNode<"BPFISD::CALL", SDT_BPFCall,
[SDNPHasChain, SDNPOptInGlue, SDNPOutGlue,
SDNPVariadic]>;
def BPFretflag : SDNode<"BPFISD::RET_FLAG", SDTNone,
[SDNPHasChain, SDNPOptInGlue, SDNPVariadic]>;
def BPFcallseq_start: SDNode<"ISD::CALLSEQ_START", SDT_BPFCallSeqStart,
[SDNPHasChain, SDNPOutGlue]>;
def BPFcallseq_end : SDNode<"ISD::CALLSEQ_END", SDT_BPFCallSeqEnd,
[SDNPHasChain, SDNPOptInGlue, SDNPOutGlue]>;
def BPFbrcc : SDNode<"BPFISD::BR_CC", SDT_BPFBrCC,
[SDNPHasChain, SDNPOutGlue, SDNPInGlue]>;
def BPFselectcc : SDNode<"BPFISD::SELECT_CC", SDT_BPFSelectCC, [SDNPInGlue]>;
def BPFWrapper : SDNode<"BPFISD::Wrapper", SDT_BPFWrapper>;
def brtarget : Operand<OtherVT>;
def calltarget : Operand<i64>;
def u64imm : Operand<i64> {
let PrintMethod = "printImm64Operand";
}
def i64immSExt32 : PatLeaf<(i64 imm),
[{return isInt<32>(N->getSExtValue()); }]>;
// Addressing modes.
def ADDRri : ComplexPattern<i64, 2, "SelectAddr", [], []>;
def FIri : ComplexPattern<i64, 2, "SelectFIAddr", [add, or], []>;
// Address operands
def MEMri : Operand<i64> {
let PrintMethod = "printMemOperand";
let EncoderMethod = "getMemoryOpValue";
let DecoderMethod = "decodeMemoryOpValue";
let MIOperandInfo = (ops GPR, i16imm);
}
// Conditional code predicates - used for pattern matching for jump instructions
def BPF_CC_EQ : PatLeaf<(i64 imm),
[{return (N->getZExtValue() == ISD::SETEQ);}]>;
def BPF_CC_NE : PatLeaf<(i64 imm),
[{return (N->getZExtValue() == ISD::SETNE);}]>;
def BPF_CC_GE : PatLeaf<(i64 imm),
[{return (N->getZExtValue() == ISD::SETGE);}]>;
def BPF_CC_GT : PatLeaf<(i64 imm),
[{return (N->getZExtValue() == ISD::SETGT);}]>;
def BPF_CC_GTU : PatLeaf<(i64 imm),
[{return (N->getZExtValue() == ISD::SETUGT);}]>;
def BPF_CC_GEU : PatLeaf<(i64 imm),
[{return (N->getZExtValue() == ISD::SETUGE);}]>;
// jump instructions
class JMP_RR<bits<4> Opc, string OpcodeStr, PatLeaf Cond>
: InstBPF<(outs), (ins GPR:$dst, GPR:$src, brtarget:$BrDst),
"if $dst "#OpcodeStr#" $src goto $BrDst",
[(BPFbrcc i64:$dst, i64:$src, Cond, bb:$BrDst)]> {
bits<4> op;
bits<1> BPFSrc;
bits<4> dst;
bits<4> src;
bits<16> BrDst;
let Inst{63-60} = op;
let Inst{59} = BPFSrc;
let Inst{55-52} = src;
let Inst{51-48} = dst;
let Inst{47-32} = BrDst;
let op = Opc;
let BPFSrc = 1;
let BPFClass = 5; // BPF_JMP
}
class JMP_RI<bits<4> Opc, string OpcodeStr, PatLeaf Cond>
: InstBPF<(outs), (ins GPR:$dst, i64imm:$imm, brtarget:$BrDst),
"if $dst "#OpcodeStr#" $imm goto $BrDst",
[(BPFbrcc i64:$dst, i64immSExt32:$imm, Cond, bb:$BrDst)]> {
bits<4> op;
bits<1> BPFSrc;
bits<4> dst;
bits<16> BrDst;
bits<32> imm;
let Inst{63-60} = op;
let Inst{59} = BPFSrc;
let Inst{51-48} = dst;
let Inst{47-32} = BrDst;
let Inst{31-0} = imm;
let op = Opc;
let BPFSrc = 0;
let BPFClass = 5; // BPF_JMP
}
multiclass J<bits<4> Opc, string OpcodeStr, PatLeaf Cond> {
def _rr : JMP_RR<Opc, OpcodeStr, Cond>;
def _ri : JMP_RI<Opc, OpcodeStr, Cond>;
}
let isBranch = 1, isTerminator = 1, hasDelaySlot=0 in {
// cmp+goto instructions
defm JEQ : J<0x1, "==", BPF_CC_EQ>;
defm JUGT : J<0x2, ">", BPF_CC_GTU>;
defm JUGE : J<0x3, ">=", BPF_CC_GEU>;
defm JNE : J<0x5, "!=", BPF_CC_NE>;
defm JSGT : J<0x6, "s>", BPF_CC_GT>;
defm JSGE : J<0x7, "s>=", BPF_CC_GE>;
}
// ALU instructions
class ALU_RI<bits<4> Opc, string OpcodeStr, SDNode OpNode>
: InstBPF<(outs GPR:$dst), (ins GPR:$src2, i64imm:$imm),
"$dst "#OpcodeStr#" $imm",
[(set GPR:$dst, (OpNode GPR:$src2, i64immSExt32:$imm))]> {
bits<4> op;
bits<1> BPFSrc;
bits<4> dst;
bits<32> imm;
let Inst{63-60} = op;
let Inst{59} = BPFSrc;
let Inst{51-48} = dst;
let Inst{31-0} = imm;
let op = Opc;
let BPFSrc = 0;
let BPFClass = 7; // BPF_ALU64
}
class ALU_RR<bits<4> Opc, string OpcodeStr, SDNode OpNode>
: InstBPF<(outs GPR:$dst), (ins GPR:$src2, GPR:$src),
"$dst "#OpcodeStr#" $src",
[(set GPR:$dst, (OpNode i64:$src2, i64:$src))]> {
bits<4> op;
bits<1> BPFSrc;
bits<4> dst;
bits<4> src;
let Inst{63-60} = op;
let Inst{59} = BPFSrc;
let Inst{55-52} = src;
let Inst{51-48} = dst;
let op = Opc;
let BPFSrc = 1;
let BPFClass = 7; // BPF_ALU64
}
multiclass ALU<bits<4> Opc, string OpcodeStr, SDNode OpNode> {
def _rr : ALU_RR<Opc, OpcodeStr, OpNode>;
def _ri : ALU_RI<Opc, OpcodeStr, OpNode>;
}
let Constraints = "$dst = $src2" in {
let isAsCheapAsAMove = 1 in {
defm ADD : ALU<0x0, "+=", add>;
defm SUB : ALU<0x1, "-=", sub>;
defm OR : ALU<0x4, "|=", or>;
defm AND : ALU<0x5, "&=", and>;
defm SLL : ALU<0x6, "<<=", shl>;
defm SRL : ALU<0x7, ">>=", srl>;
defm XOR : ALU<0xa, "^=", xor>;
defm SRA : ALU<0xc, "s>>=", sra>;
}
defm MUL : ALU<0x2, "*=", mul>;
defm DIV : ALU<0x3, "/=", udiv>;
}
class MOV_RR<string OpcodeStr>
: InstBPF<(outs GPR:$dst), (ins GPR:$src),
"$dst "#OpcodeStr#" $src",
[]> {
bits<4> op;
bits<1> BPFSrc;
bits<4> dst;
bits<4> src;
let Inst{63-60} = op;
let Inst{59} = BPFSrc;
let Inst{55-52} = src;
let Inst{51-48} = dst;
let op = 0xb; // BPF_MOV
let BPFSrc = 1; // BPF_X
let BPFClass = 7; // BPF_ALU64
}
class MOV_RI<string OpcodeStr>
: InstBPF<(outs GPR:$dst), (ins i64imm:$imm),
"$dst "#OpcodeStr#" $imm",
[(set GPR:$dst, (i64 i64immSExt32:$imm))]> {
bits<4> op;
bits<1> BPFSrc;
bits<4> dst;
bits<32> imm;
let Inst{63-60} = op;
let Inst{59} = BPFSrc;
let Inst{51-48} = dst;
let Inst{31-0} = imm;
let op = 0xb; // BPF_MOV
let BPFSrc = 0; // BPF_K
let BPFClass = 7; // BPF_ALU64
}
class LD_IMM64<bits<4> Pseudo, string OpcodeStr>
: InstBPF<(outs GPR:$dst), (ins u64imm:$imm),
"$dst "#OpcodeStr#" ${imm}ll",
[(set GPR:$dst, (i64 imm:$imm))]> {
bits<3> mode;
bits<2> size;
bits<4> dst;
bits<64> imm;
let Inst{63-61} = mode;
let Inst{60-59} = size;
let Inst{51-48} = dst;
let Inst{55-52} = Pseudo;
let Inst{47-32} = 0;
let Inst{31-0} = imm{31-0};
let mode = 0; // BPF_IMM
let size = 3; // BPF_DW
let BPFClass = 0; // BPF_LD
}
let isReMaterializable = 1, isAsCheapAsAMove = 1 in {
def LD_imm64 : LD_IMM64<0, "=">;
def MOV_rr : MOV_RR<"=">;
def MOV_ri : MOV_RI<"=">;
}
def FI_ri
: InstBPF<(outs GPR:$dst), (ins MEMri:$addr),
"lea\t$dst, $addr",
[(set i64:$dst, FIri:$addr)]> {
// This is a tentative instruction, and will be replaced
// with MOV_rr and ADD_ri in PEI phase
let Inst{63-61} = 0;
let Inst{60-59} = 3;
let Inst{51-48} = 0;
let Inst{55-52} = 2;
let Inst{47-32} = 0;
let Inst{31-0} = 0;
let BPFClass = 0;
}
def LD_pseudo
: InstBPF<(outs GPR:$dst), (ins i64imm:$pseudo, u64imm:$imm),
"ld_pseudo\t$dst, $pseudo, $imm",
[(set GPR:$dst, (int_bpf_pseudo imm:$pseudo, imm:$imm))]> {
bits<3> mode;
bits<2> size;
bits<4> dst;
bits<64> imm;
bits<4> pseudo;
let Inst{63-61} = mode;
let Inst{60-59} = size;
let Inst{51-48} = dst;
let Inst{55-52} = pseudo;
let Inst{47-32} = 0;
let Inst{31-0} = imm{31-0};
let mode = 0; // BPF_IMM
let size = 3; // BPF_DW
let BPFClass = 0; // BPF_LD
}
// STORE instructions
class STORE<bits<2> SizeOp, string OpcodeStr, list<dag> Pattern>
: InstBPF<(outs), (ins GPR:$src, MEMri:$addr),
"*("#OpcodeStr#" *)($addr) = $src", Pattern> {
bits<3> mode;
bits<2> size;
bits<4> src;
bits<20> addr;
let Inst{63-61} = mode;
let Inst{60-59} = size;
let Inst{51-48} = addr{19-16}; // base reg
let Inst{55-52} = src;
let Inst{47-32} = addr{15-0}; // offset
let mode = 3; // BPF_MEM
let size = SizeOp;
let BPFClass = 3; // BPF_STX
}
class STOREi64<bits<2> Opc, string OpcodeStr, PatFrag OpNode>
: STORE<Opc, OpcodeStr, [(OpNode i64:$src, ADDRri:$addr)]>;
def STW : STOREi64<0x0, "u32", truncstorei32>;
def STH : STOREi64<0x1, "u16", truncstorei16>;
def STB : STOREi64<0x2, "u8", truncstorei8>;
def STD : STOREi64<0x3, "u64", store>;
// LOAD instructions
class LOAD<bits<2> SizeOp, string OpcodeStr, list<dag> Pattern>
: InstBPF<(outs GPR:$dst), (ins MEMri:$addr),
"$dst = *("#OpcodeStr#" *)($addr)", Pattern> {
bits<3> mode;
bits<2> size;
bits<4> dst;
bits<20> addr;
let Inst{63-61} = mode;
let Inst{60-59} = size;
let Inst{51-48} = dst;
let Inst{55-52} = addr{19-16};
let Inst{47-32} = addr{15-0};
let mode = 3; // BPF_MEM
let size = SizeOp;
let BPFClass = 1; // BPF_LDX
}
class LOADi64<bits<2> SizeOp, string OpcodeStr, PatFrag OpNode>
: LOAD<SizeOp, OpcodeStr, [(set i64:$dst, (OpNode ADDRri:$addr))]>;
def LDW : LOADi64<0x0, "u32", zextloadi32>;
def LDH : LOADi64<0x1, "u16", zextloadi16>;
def LDB : LOADi64<0x2, "u8", zextloadi8>;
def LDD : LOADi64<0x3, "u64", load>;
class BRANCH<bits<4> Opc, string OpcodeStr, list<dag> Pattern>
: InstBPF<(outs), (ins brtarget:$BrDst),
!strconcat(OpcodeStr, " $BrDst"), Pattern> {
bits<4> op;
bits<16> BrDst;
bits<1> BPFSrc;
let Inst{63-60} = op;
let Inst{59} = BPFSrc;
let Inst{47-32} = BrDst;
let op = Opc;
let BPFSrc = 0;
let BPFClass = 5; // BPF_JMP
}
class CALL<string OpcodeStr>
: InstBPF<(outs), (ins calltarget:$BrDst),
!strconcat(OpcodeStr, " $BrDst"), []> {
bits<4> op;
bits<32> BrDst;
bits<1> BPFSrc;
let Inst{63-60} = op;
let Inst{59} = BPFSrc;
let Inst{31-0} = BrDst;
let op = 8; // BPF_CALL
let BPFSrc = 0;
let BPFClass = 5; // BPF_JMP
}
// Jump always
let isBranch = 1, isTerminator = 1, hasDelaySlot=0, isBarrier = 1 in {
def JMP : BRANCH<0x0, "goto", [(br bb:$BrDst)]>;
}
// Jump and link
let isCall=1, hasDelaySlot=0, Uses = [R11],
// Potentially clobbered registers
Defs = [R0, R1, R2, R3, R4, R5] in {
def JAL : CALL<"call">;
}
class NOP_I<string OpcodeStr>
: InstBPF<(outs), (ins i32imm:$imm),
!strconcat(OpcodeStr, "\t$imm"), []> {
// mov r0, r0 == nop
bits<4> op;
bits<1> BPFSrc;
bits<4> dst;
bits<4> src;
let Inst{63-60} = op;
let Inst{59} = BPFSrc;
let Inst{55-52} = src;
let Inst{51-48} = dst;
let op = 0xb; // BPF_MOV
let BPFSrc = 1; // BPF_X
let BPFClass = 7; // BPF_ALU64
let src = 0; // R0
let dst = 0; // R0
}
let hasSideEffects = 0 in
def NOP : NOP_I<"nop">;
class RET<string OpcodeStr>
: InstBPF<(outs), (ins),
!strconcat(OpcodeStr, ""), [(BPFretflag)]> {
bits<4> op;
let Inst{63-60} = op;
let Inst{59} = 0;
let Inst{31-0} = 0;
let op = 9; // BPF_EXIT
let BPFClass = 5; // BPF_JMP
}
let isReturn = 1, isTerminator = 1, hasDelaySlot=0, isBarrier = 1,
isNotDuplicable = 1 in {
def RET : RET<"exit">;
}
// ADJCALLSTACKDOWN/UP pseudo insns
let Defs = [R11], Uses = [R11] in {
def ADJCALLSTACKDOWN : Pseudo<(outs), (ins i64imm:$amt1, i64imm:$amt2),
"#ADJCALLSTACKDOWN $amt1 $amt2",
[(BPFcallseq_start timm:$amt1, timm:$amt2)]>;
def ADJCALLSTACKUP : Pseudo<(outs), (ins i64imm:$amt1, i64imm:$amt2),
"#ADJCALLSTACKUP $amt1 $amt2",
[(BPFcallseq_end timm:$amt1, timm:$amt2)]>;
}
let usesCustomInserter = 1 in {
def Select : Pseudo<(outs GPR:$dst),
(ins GPR:$lhs, GPR:$rhs, i64imm:$imm, GPR:$src, GPR:$src2),
"# Select PSEUDO $dst = $lhs $imm $rhs ? $src : $src2",
[(set i64:$dst,
(BPFselectcc i64:$lhs, i64:$rhs, (i64 imm:$imm), i64:$src, i64:$src2))]>;
def Select_Ri : Pseudo<(outs GPR:$dst),
(ins GPR:$lhs, i64imm:$rhs, i64imm:$imm, GPR:$src, GPR:$src2),
"# Select PSEUDO $dst = $lhs $imm $rhs ? $src : $src2",
[(set i64:$dst,
(BPFselectcc i64:$lhs, (i64 imm:$rhs), (i64 imm:$imm), i64:$src, i64:$src2))]>;
}
// load 64-bit global addr into register
def : Pat<(BPFWrapper tglobaladdr:$in), (LD_imm64 tglobaladdr:$in)>;
// 0xffffFFFF doesn't fit into simm32, optimize common case
def : Pat<(i64 (and (i64 GPR:$src), 0xffffFFFF)),
(SRL_ri (SLL_ri (i64 GPR:$src), 32), 32)>;
// Calls
def : Pat<(BPFcall tglobaladdr:$dst), (JAL tglobaladdr:$dst)>;
def : Pat<(BPFcall texternalsym:$dst), (JAL texternalsym:$dst)>;
def : Pat<(BPFcall imm:$dst), (JAL imm:$dst)>;
// Loads
def : Pat<(extloadi8 ADDRri:$src), (i64 (LDB ADDRri:$src))>;
def : Pat<(extloadi16 ADDRri:$src), (i64 (LDH ADDRri:$src))>;
def : Pat<(extloadi32 ADDRri:$src), (i64 (LDW ADDRri:$src))>;
// Atomics
class XADD<bits<2> SizeOp, string OpcodeStr, PatFrag OpNode>
: InstBPF<(outs GPR:$dst), (ins MEMri:$addr, GPR:$val),
"lock *("#OpcodeStr#" *)($addr) += $val",
[(set GPR:$dst, (OpNode ADDRri:$addr, GPR:$val))]> {
bits<3> mode;
bits<2> size;
bits<4> dst;
bits<20> addr;
let Inst{63-61} = mode;
let Inst{60-59} = size;
let Inst{51-48} = addr{19-16}; // base reg
let Inst{55-52} = dst;
let Inst{47-32} = addr{15-0}; // offset
let mode = 6; // BPF_XADD
let size = SizeOp;
let BPFClass = 3; // BPF_STX
}
let Constraints = "$dst = $val" in {
def XADD32 : XADD<0, "u32", atomic_load_add_32>;
def XADD64 : XADD<3, "u64", atomic_load_add_64>;
// undefined def XADD16 : XADD<1, "xadd16", atomic_load_add_16>;
// undefined def XADD8 : XADD<2, "xadd8", atomic_load_add_8>;
}
// bswap16, bswap32, bswap64
class BSWAP<bits<32> SizeOp, string OpcodeStr, list<dag> Pattern>
: InstBPF<(outs GPR:$dst), (ins GPR:$src),
!strconcat(OpcodeStr, "\t$dst"),
Pattern> {
bits<4> op;
bits<1> BPFSrc;
bits<4> dst;
bits<32> imm;
let Inst{63-60} = op;
let Inst{59} = BPFSrc;
let Inst{51-48} = dst;
let Inst{31-0} = imm;
let op = 0xd; // BPF_END
let BPFSrc = 1; // BPF_TO_BE (TODO: use BPF_TO_LE for big-endian target)
let BPFClass = 4; // BPF_ALU
let imm = SizeOp;
}
let Constraints = "$dst = $src" in {
def BSWAP16 : BSWAP<16, "bswap16", [(set GPR:$dst, (srl (bswap GPR:$src), (i64 48)))]>;
def BSWAP32 : BSWAP<32, "bswap32", [(set GPR:$dst, (srl (bswap GPR:$src), (i64 32)))]>;
def BSWAP64 : BSWAP<64, "bswap64", [(set GPR:$dst, (bswap GPR:$src))]>;
}
let Defs = [R0, R1, R2, R3, R4, R5], Uses = [R6], hasSideEffects = 1,
hasExtraDefRegAllocReq = 1, hasExtraSrcRegAllocReq = 1, mayLoad = 1 in {
class LOAD_ABS<bits<2> SizeOp, string OpcodeStr, Intrinsic OpNode>
: InstBPF<(outs), (ins GPR:$skb, i64imm:$imm),
"r0 = *("#OpcodeStr#" *)skb[$imm]",
[(set R0, (OpNode GPR:$skb, i64immSExt32:$imm))]> {
bits<3> mode;
bits<2> size;
bits<32> imm;
let Inst{63-61} = mode;
let Inst{60-59} = size;
let Inst{31-0} = imm;
let mode = 1; // BPF_ABS
let size = SizeOp;
let BPFClass = 0; // BPF_LD
}
class LOAD_IND<bits<2> SizeOp, string OpcodeStr, Intrinsic OpNode>
: InstBPF<(outs), (ins GPR:$skb, GPR:$val),
"r0 = *("#OpcodeStr#" *)skb[$val]",
[(set R0, (OpNode GPR:$skb, GPR:$val))]> {
bits<3> mode;
bits<2> size;
bits<4> val;
let Inst{63-61} = mode;
let Inst{60-59} = size;
let Inst{55-52} = val;
let mode = 2; // BPF_IND
let size = SizeOp;
let BPFClass = 0; // BPF_LD
}
}
def LD_ABS_B : LOAD_ABS<2, "u8", int_bpf_load_byte>;
def LD_ABS_H : LOAD_ABS<1, "u16", int_bpf_load_half>;
def LD_ABS_W : LOAD_ABS<0, "u32", int_bpf_load_word>;
def LD_IND_B : LOAD_IND<2, "u8", int_bpf_load_byte>;
def LD_IND_H : LOAD_IND<1, "u16", int_bpf_load_half>;
def LD_IND_W : LOAD_IND<0, "u32", int_bpf_load_word>;
| {
"pile_set_name": "Github"
} |
// Copyright (c) 2012 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
//
// Objects that handle file operations for saving files, on the file thread.
//
// The SaveFileManager owns a set of SaveFile objects, each of which connects
// with a SaveItem object which belongs to one SavePackage and runs on the file
// thread for saving data in order to avoid disk activity on either network IO
// thread or the UI thread. It coordinates the notifications from the network
// and UI.
//
// The SaveFileManager itself is a singleton object owned by the
// ResourceDispatcherHostImpl.
//
// The data sent to SaveFileManager have 2 sources, one is from
// ResourceDispatcherHostImpl, run in network IO thread, the all sub-resources
// and save-only-HTML pages will be got from network IO. The second is from
// render process, those html pages which are serialized from DOM will be
// composed in render process and encoded to its original encoding, then sent
// to UI loop in browser process, then UI loop will dispatch the data to
// SaveFileManager on the file thread. SaveFileManager will directly
// call SaveFile's method to persist data.
//
// A typical saving job operation involves multiple threads:
//
// Updating an in progress save file
// io_thread
// |----> data from net ---->|
// |
// |
// |----> data from ---->| |
// | render process | |
// ui_thread | |
// file_thread (writes to disk)
// |----> stats ---->|
// ui_thread (feedback for user)
//
//
// Cancel operations perform the inverse order when triggered by a user action:
// ui_thread (user click)
// |----> cancel command ---->|
// | | file_thread (close file)
// | |---------------------> cancel command ---->|
// | io_thread (stops net IO
// ui_thread (user close contents) for saving)
// |----> cancel command ---->|
// Render process(stop serializing DOM and sending
// data)
//
//
// The SaveFileManager tracks saving requests, mapping from a save item id to
// the SavePackage for the contents where the saving job was initiated. In the
// event of a contents closure during saving, the SavePackage will notify the
// SaveFileManage to cancel all SaveFile jobs.
#ifndef CONTENT_BROWSER_DOWNLOAD_SAVE_FILE_MANAGER_H_
#define CONTENT_BROWSER_DOWNLOAD_SAVE_FILE_MANAGER_H_
#include <stdint.h>
#include <string>
#include <unordered_map>
#include "base/macros.h"
#include "base/memory/ref_counted.h"
#include "content/browser/download/save_types.h"
#include "content/common/content_export.h"
class GURL;
namespace base {
class FilePath;
}
namespace net {
class IOBuffer;
}
namespace content {
class ResourceContext;
class SaveFile;
class SavePackage;
struct Referrer;
class SaveFileManager : public base::RefCountedThreadSafe<SaveFileManager> {
public:
SaveFileManager();
// Lifetime management.
CONTENT_EXPORT void Shutdown();
// Save the specified URL. Caller has to guarantee that |save_package| will
// be alive until the call to RemoveSaveFile. Called on the UI thread (and in
// case of network downloads forwarded to the ResourceDispatcherHostImpl on
// the IO thread).
void SaveURL(SaveItemId save_item_id,
const GURL& url,
const Referrer& referrer,
int render_process_host_id,
int render_view_routing_id,
int render_frame_routing_id,
SaveFileCreateInfo::SaveFileSource save_source,
const base::FilePath& file_full_path,
ResourceContext* context,
SavePackage* save_package);
// Notifications sent from the IO thread and run on the file thread:
void StartSave(SaveFileCreateInfo* info);
void UpdateSaveProgress(SaveItemId save_item_id,
net::IOBuffer* data,
int size);
void SaveFinished(SaveItemId save_item_id,
SavePackageId save_package_id,
bool is_success);
// Notifications sent from the UI thread and run on the file thread.
// Cancel a SaveFile instance which has specified save item id.
void CancelSave(SaveItemId save_item_id);
// Called on the UI thread to remove a save package from SaveFileManager's
// tracking map.
void RemoveSaveFile(SaveItemId save_item_id, SavePackage* package);
// Helper function for deleting specified file.
void DeleteDirectoryOrFile(const base::FilePath& full_path, bool is_dir);
// Runs on file thread to save a file by copying from file system when
// original url is using file scheme.
void SaveLocalFile(const GURL& original_file_url,
SaveItemId save_item_id,
SavePackageId save_package_id);
// Renames all the successfully saved files.
void RenameAllFiles(const FinalNamesMap& final_names,
const base::FilePath& resource_dir,
int render_process_id,
int render_frame_routing_id,
SavePackageId save_package_id);
// When the user cancels the saving, we need to remove all remaining saved
// files of this page saving job from save_file_map_.
void RemoveSavedFileFromFileMap(const std::vector<SaveItemId>& save_item_ids);
private:
friend class base::RefCountedThreadSafe<SaveFileManager>;
~SaveFileManager();
// A cleanup helper that runs on the file thread.
void OnShutdown();
// Called only on UI thread to get the SavePackage for a contents's browser
// context.
static SavePackage* GetSavePackageFromRenderIds(int render_process_id,
int render_frame_routing_id);
// Look up the SavePackage according to save item id.
SavePackage* LookupPackage(SaveItemId save_item_id);
// Called only on the file thread.
// Look up one in-progress saving item according to save item id.
SaveFile* LookupSaveFile(SaveItemId save_item_id);
// Help function for sending notification of canceling specific request.
void SendCancelRequest(SaveItemId save_item_id);
// Notifications sent from the file thread and run on the UI thread.
// Lookup the SaveManager for this WebContents' saving browser context and
// inform it the saving job has been started.
void OnStartSave(const SaveFileCreateInfo& info);
// Update the SavePackage with the current state of a started saving job.
// If the SavePackage for this saving job is gone, cancel the request.
void OnUpdateSaveProgress(SaveItemId save_item_id,
int64_t bytes_so_far,
bool write_success);
// Update the SavePackage with the finish state, and remove the request
// tracking entries.
void OnSaveFinished(SaveItemId save_item_id,
int64_t bytes_so_far,
bool is_success);
// Notifies SavePackage that the whole page saving job is finished.
void OnFinishSavePageJob(int render_process_id,
int render_frame_routing_id,
SavePackageId save_package_id);
// Notifications sent from the UI thread and run on the file thread.
// Deletes a specified file on the file thread.
void OnDeleteDirectoryOrFile(const base::FilePath& full_path, bool is_dir);
// Notifications sent from the UI thread and run on the IO thread
// Initiates a request for URL to be saved.
void OnSaveURL(const GURL& url,
const Referrer& referrer,
SaveItemId save_item_id,
SavePackageId save_package_id,
int render_process_host_id,
int render_view_routing_id,
int render_frame_routing_id,
ResourceContext* context);
// Call ResourceDispatcherHostImpl's CancelRequest method to execute cancel
// action in the IO thread.
void ExecuteCancelSaveRequest(int render_process_id, int request_id);
// A map from save_item_id into SaveFiles.
using SaveFileMap =
std::unordered_map<SaveItemId, SaveFile*, SaveItemId::Hasher>;
SaveFileMap save_file_map_;
// Tracks which SavePackage to send data to, called only on UI thread.
// SavePackageMap maps save item ids to their SavePackage.
using SavePackageMap =
std::unordered_map<SaveItemId, SavePackage*, SaveItemId::Hasher>;
SavePackageMap packages_;
DISALLOW_COPY_AND_ASSIGN(SaveFileManager);
};
} // namespace content
#endif // CONTENT_BROWSER_DOWNLOAD_SAVE_FILE_MANAGER_H_
| {
"pile_set_name": "Github"
} |
{
"extends": "../../../tsconfig.lib.json",
"compilerOptions": {
"outDir": "../../../dist/out-tsc",
"target": "es2015",
"module": "es2015",
"moduleResolution": "node",
"declaration": true,
"sourceMap": true,
"inlineSources": true,
"emitDecoratorMetadata": true,
"experimentalDecorators": true,
"importHelpers": true,
"types": [],
"lib": ["dom", "es2018"]
},
"angularCompilerOptions": {
"annotateForClosureCompiler": true,
"skipTemplateCodegen": true,
"strictMetadataEmit": true,
"fullTemplateTypeCheck": true,
"strictInjectionParameters": true,
"enableResourceInlining": true,
"flatModuleId": "AUTOGENERATED",
"flatModuleOutFile": "AUTOGENERATED"
},
"exclude": ["src/test.ts", "**/*.spec.ts"]
}
| {
"pile_set_name": "Github"
} |
{
"tag": "body",
"children": [
{
"tag": "div",
"children": [
{
"tag": "div",
"content": {
"size": [
20,
20
],
"position": [
98,
38
]
},
"padding_box": {
"size": [
20,
20
],
"position": [
98,
38
]
},
"border": [
0,
0,
0,
0
],
"border_box": {
"size": [
20,
20
],
"position": [
98,
38
]
},
"padding": [
0,
0,
0,
0
],
"id": ""
},
{
"tag": "div",
"content": {
"size": [
20,
20
],
"position": [
158,
38
]
},
"padding_box": {
"size": [
20,
20
],
"position": [
158,
38
]
},
"border": [
0,
0,
0,
0
],
"border_box": {
"size": [
20,
20
],
"position": [
158,
38
]
},
"padding": [
0,
0,
0,
0
],
"id": ""
},
{
"tag": "div",
"content": {
"size": [
20,
20
],
"position": [
38,
98
]
},
"padding_box": {
"size": [
20,
20
],
"position": [
38,
98
]
},
"border": [
0,
0,
0,
0
],
"border_box": {
"size": [
20,
20
],
"position": [
38,
98
]
},
"padding": [
0,
0,
0,
0
],
"id": ""
},
{
"tag": "div",
"content": {
"size": [
20,
20
],
"position": [
38,
158
]
},
"padding_box": {
"size": [
20,
20
],
"position": [
38,
158
]
},
"border": [
0,
0,
0,
0
],
"border_box": {
"size": [
20,
20
],
"position": [
38,
158
]
},
"padding": [
0,
0,
0,
0
],
"id": ""
}
],
"content": {
"size": [
200,
200
],
"position": [
8,
8
]
},
"padding_box": {
"size": [
200,
200
],
"position": [
8,
8
]
},
"border": [
0,
0,
0,
0
],
"border_box": {
"size": [
200,
200
],
"position": [
8,
8
]
},
"padding": [
0,
0,
0,
0
],
"id": ""
},
{
"tag": "div",
"children": [
{
"tag": "div",
"content": {
"size": [
20,
20
],
"position": [
98,
38
]
},
"padding_box": {
"size": [
20,
20
],
"position": [
98,
38
]
},
"border": [
0,
0,
0,
0
],
"border_box": {
"size": [
20,
20
],
"position": [
98,
38
]
},
"padding": [
0,
0,
0,
0
],
"id": ""
},
{
"tag": "div",
"content": {
"size": [
20,
20
],
"position": [
158,
38
]
},
"padding_box": {
"size": [
20,
20
],
"position": [
158,
38
]
},
"border": [
0,
0,
0,
0
],
"border_box": {
"size": [
20,
20
],
"position": [
158,
38
]
},
"padding": [
0,
0,
0,
0
],
"id": ""
},
{
"tag": "div",
"content": {
"size": [
20,
20
],
"position": [
38,
98
]
},
"padding_box": {
"size": [
20,
20
],
"position": [
38,
98
]
},
"border": [
0,
0,
0,
0
],
"border_box": {
"size": [
20,
20
],
"position": [
38,
98
]
},
"padding": [
0,
0,
0,
0
],
"id": ""
},
{
"tag": "div",
"content": {
"size": [
20,
20
],
"position": [
38,
158
]
},
"padding_box": {
"size": [
20,
20
],
"position": [
38,
158
]
},
"border": [
0,
0,
0,
0
],
"border_box": {
"size": [
20,
20
],
"position": [
38,
158
]
},
"padding": [
0,
0,
0,
0
],
"id": ""
}
],
"content": {
"size": [
200,
200
],
"position": [
8,
8
]
},
"padding_box": {
"size": [
200,
200
],
"position": [
8,
8
]
},
"border": [
0,
0,
0,
0
],
"border_box": {
"size": [
200,
200
],
"position": [
8,
8
]
},
"padding": [
0,
0,
0,
0
],
"id": ""
}
],
"content": {
"size": [
1008,
200
],
"position": [
8,
8
]
},
"padding_box": {
"size": [
1008,
200
],
"position": [
8,
8
]
},
"border": [
0,
0,
0,
0
],
"border_box": {
"size": [
1008,
200
],
"position": [
8,
8
]
},
"padding": [
0,
0,
0,
0
],
"id": ""
} | {
"pile_set_name": "Github"
} |
---
-api-id: T:Windows.UI.Xaml.Media.Animation.DiscreteDoubleKeyFrame
-api-type: winrt class
---
<!-- Class syntax.
public class DiscreteDoubleKeyFrame : Windows.UI.Xaml.Media.Animation.DoubleKeyFrame, Windows.UI.Xaml.Media.Animation.IDiscreteDoubleKeyFrame
-->
# Windows.UI.Xaml.Media.Animation.DiscreteDoubleKeyFrame
## -description
Animates from the [Double](/dotnet/api/system.double?redirectedfrom=MSDN) value of the previous key frame to its own [Value](doublekeyframe_value.md) using discrete values.
## -xaml-syntax
```xaml
<DiscreteDoubleKeyFrame .../>
```
## -remarks
Key-frame animations permit more than one target value that is reached at a point along the animation timeline. In other words each key frame can specify a different intermediate value, and the last key frame reached is the final animation value. By specifying multiple values to animate, you can make more complex animations. You can mix discrete, linear, and spline keyframes in the same keyframe collection.
For more info on how to use key-frame animations, see [Key-frame animations and easing function animations](/windows/uwp/graphics/key-frame-and-easing-function-animations).
## -examples
This XAML example moves a rectangle across a screen. The example uses the [DoubleAnimationUsingKeyFrames](doubleanimationusingkeyframes.md) class to animate the [X](../windows.ui.xaml.media/translatetransform_x.md) property of a [TranslateTransform](../windows.ui.xaml.media/translatetransform.md) applied to a [Rectangle](../windows.ui.xaml.shapes/rectangle.md). This animation uses three key frames in the following manner:
1. During the first three seconds, it uses an instance of the [LinearDoubleKeyFrame](lineardoublekeyframe.md) class to move the rectangle along a path at a steady rate from its starting position to the 500 position. Linear key frames like [LinearDoubleKeyFrame](lineardoublekeyframe.md) create a smooth linear transition between values.
1. At the end of the fourth second, it uses an instance of the DiscreteDoubleKeyFrame class to suddenly move the rectangle to the next position. Discrete key frames like DiscreteDoubleKeyFrame create sudden jumps between values. In this example, the rectangle is at the starting position and then suddenly appears at the 500 position.
1. In the final two seconds, it uses an instance of the [SplineDoubleKeyFrame](splinedoublekeyframe.md) class to move the rectangle back to its starting position. Spline key frames like [SplineDoubleKeyFrame](splinedoublekeyframe.md) create a variable transition between values according to the value of the [KeySpline](splinedoublekeyframe_keyspline.md) property. In this example, the rectangle begins by moving slowly and then speeds up exponentially toward the end of the time segment.
<!--<p xml:space="preserve">
<TRANSLATE_MANUALLY>
<externalLink xmlns="http://ddue.schemas.microsoft.com/authoring/2003/5">
<linkText>Run this sample</linkText>
<linkUri>http://go.microsoft.com/fwlink/p/?linkid=139798&sref=doubleanimationusingkeyframes2</linkUri>
</externalLink>
</TRANSLATE_MANUALLY>
</p>-->
[!code-xaml[Doubleanimationusingkeyframes2](../windows.ui.xaml.media.animation/code/doubleanimationusingkeyframes2/csharp/Page.xaml#SnippetDoubleanimationusingkeyframes2_cs)]
[!code-vb[Doubleanimationusingkeyframes2](../windows.ui.xaml.media.animation/code/doubleanimationusingkeyframes2/vbnet/Page.xaml.vb#SnippetDoubleanimationusingkeyframes2)]
[!code-csharp[Doubleanimationusingkeyframes2_cs](../windows.ui.xaml.media.animation/code/doubleanimationusingkeyframes2/csharp/Page.xaml.cs#SnippetDoubleanimationusingkeyframes2)]
## -see-also
[Storyboarded animations](/windows/uwp/graphics/storyboarded-animations), [Key-frame animations and easing function animations](/windows/uwp/graphics/key-frame-and-easing-function-animations), [DoubleKeyFrame](doublekeyframe.md), [DoubleAnimationUsingKeyFrames](doubleanimationusingkeyframes.md), [DoubleKeyFrameCollection](doublekeyframecollection.md), [KeyTime](doublekeyframe_keytime.md), [Value](doublekeyframe_value.md), [Value](doublekeyframe_value.md)
| {
"pile_set_name": "Github"
} |
/*
* 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.codehaus.groovy.antlr
import groovy.test.GroovyTestCase
import org.codehaus.groovy.control.MultipleCompilationErrorsException
class GStringEndTest extends GroovyTestCase {
void testInvalidEndContainsLineNumber(){
try {
assertScript '''
def Target = "releases$"
'''
} catch (MultipleCompilationErrorsException mcee) {
def text = mcee.toString();
assert text.contains("line 2, column 40")
}
}
void testErrorReportOnStringEndWithOutParser() {
// GROOVY-6608: the code did throw a NPE
try {
assertScript '''
def scanFolders()
{ doThis( ~"(?i)^sometext$",
'''
} catch (MultipleCompilationErrorsException mcee) {
def text = mcee.toString();
assert text.contains("line 3, column 39")
}
}
} | {
"pile_set_name": "Github"
} |
<template>
<div class="model-detail-wrapper">
<div class="model-info" v-bkloading="{ isLoading: $loading('searchObjects') }">
<template v-if="activeModel !== null">
<div class="choose-icon-wrapper">
<span class="model-type">{{getModelType()}}</span>
<template v-if="isEditable">
<cmdb-auth tag="div" class="icon-box"
v-if="!activeModel.bk_ispaused"
:auth="{ type: $OPERATION.U_MODEL, relation: [modelId] }"
@click="isIconListShow = true">
<i class="icon" :class="activeModel.bk_obj_icon || 'icon-cc-default'"></i>
<p class="hover-text is-paused" v-if="activeModel.bk_ispaused">{{$t('已停用')}}</p>
<p class="hover-text" v-else>{{$t('点击切换')}}</p>
</cmdb-auth>
<div class="choose-icon-box" v-if="isIconListShow" v-click-outside="hideChooseBox">
<the-choose-icon
v-model="modelInfo.objIcon"
@close="hideChooseBox"
@chooseIcon="chooseIcon">
</the-choose-icon>
</div>
</template>
<template v-else>
<div class="icon-box" style="cursor: default;">
<i class="icon" :class="activeModel.bk_obj_icon || 'icon-cc-default'"></i>
</div>
</template>
</div>
<div class="model-text">
<span>{{$t('唯一标识')}}:</span>
<span class="text-content id" :title="activeModel['bk_obj_id'] || ''">{{activeModel['bk_obj_id'] || ''}}</span>
</div>
<div class="model-text">
<span>{{$t('名称')}}:</span>
<template v-if="!isEditName">
<span class="text-content" :title="activeModel['bk_obj_name'] || ''">{{activeModel['bk_obj_name'] || ''}}</span>
<cmdb-auth tag="i" class="icon icon-cc-edit text-primary"
v-if="isEditable"
:auth="{ type: $OPERATION.U_MODEL, relation: [modelId] }"
@click="editModelName">
</cmdb-auth>
</template>
<template v-else>
<div class="cmdb-form-item" :class="{ 'is-error': errors.has('modelName') }">
<bk-input type="text" class="cmdb-form-input"
name="modelName"
v-validate="'required|singlechar|length:256'"
v-model.trim="modelInfo.objName">
</bk-input>
</div>
<span class="text-primary" @click="saveModel">{{$t('保存')}}</span>
<span class="text-primary" @click="isEditName = false">{{$t('取消')}}</span>
</template>
</div>
<div class="model-text ml10" v-if="!activeModel['bk_ispaused'] && activeModel.bk_classification_id !== 'bk_biz_topo'">
<span>{{$t('实例数量')}}:</span>
<div class="text-content-count"
:title="modelStatisticsSet[activeModel['bk_obj_id']] || 0"
@click="handleGoInstance">
<span>{{modelStatisticsSet[activeModel['bk_obj_id']] || 0}}</span>
<i class="icon-cc-share"></i>
</div>
</div>
<cmdb-auth class="restart-btn"
v-if="!isMainLine && activeModel.bk_ispaused"
:auth="{ type: $OPERATION.U_MODEL, relation: [modelId] }">
<bk-button slot-scope="{ disabled }"
theme="primary"
:disabled="disabled"
@click="dialogConfirm('restart')">
{{$t('立即启用')}}
</bk-button>
</cmdb-auth>
<div class="btn-group">
<template v-if="canBeImport">
<cmdb-auth tag="label" class="label-btn"
v-if="tab.active === 'field'"
:auth="{ type: $OPERATION.U_MODEL, relation: [modelId] }"
:class="{ 'disabled': isReadOnly }"
@click="handleImportField">
<i class="icon-cc-import"></i>
<span>{{$t('导入')}}</span>
</cmdb-auth>
<label class="label-btn" @click="exportField">
<i class="icon-cc-derivation"></i>
<span>{{$t('导出')}}</span>
</label>
</template>
<template v-if="isShowOperationButton">
<cmdb-auth class="label-btn"
v-if="!isMainLine && !activeModel['bk_ispaused']"
v-bk-tooltips="$t('保留模型和相应实例,隐藏关联关系')"
:auth="{ type: $OPERATION.U_MODEL, relation: [modelId] }">
<bk-button slot-scope="{ disabled }"
text
:disabled="disabled"
@click="dialogConfirm('stop')">
<i class="bk-icon icon-minus-circle-shape"></i>
<span>{{$t('停用')}}</span>
</bk-button>
</cmdb-auth>
<cmdb-auth class="label-btn"
v-bk-tooltips="$t('删除模型和其下所有实例,此动作不可逆,请谨慎操作')"
:auth="{ type: $OPERATION.D_MODEL, relation: [modelId] }">
<bk-button slot-scope="{ disabled }"
text
:disabled="disabled"
@click="dialogConfirm('delete')">
<i class="icon-cc-del"></i>
<span>{{$t('删除')}}</span>
</bk-button>
</cmdb-auth>
</template>
</div>
</template>
</div>
<bk-tab class="model-details-tab" type="unborder-card"
:active.sync="tab.active"
@tab-change="handleTabChange">
<bk-tab-panel name="field" :label="$t('模型字段')">
<the-field-group ref="field" v-if="tab.active === 'field'"></the-field-group>
</bk-tab-panel>
<bk-tab-panel name="relation" :label="$t('模型关联')" :visible="!!activeModel">
<the-relation v-if="tab.active === 'relation'" :model-id="modelId"></the-relation>
</bk-tab-panel>
<bk-tab-panel name="verification" :label="$t('唯一校验')">
<the-verification v-if="tab.active === 'verification'" :model-id="modelId"></the-verification>
</bk-tab-panel>
</bk-tab>
<!-- 导入字段 -->
<bk-sideslider
v-transfer-dom
:is-show.sync="importField.show"
:width="800"
:title="$t('导入字段')"
@hidden="handleSliderHide"
>
<cmdb-import
slot="content"
v-if="importField.show"
:template-url="importField.templateUrl"
:import-url="importUrl"
@upload-done="handleUploadDone"
>
<div slot="uploadResult">
<div class="upload-details-success" v-if="uploadResult.success && uploadResult.success.length">
<i class="bk-icon icon-check-circle-shape"></i>
<span>{{$t('成功导入N个字段', { N: uploadResult.success.length })}}</span>
</div>
<div class="upload-details-fail" v-if="uploadResult.insert_failed && uploadResult.insert_failed.length">
<div class="upload-details-fail-title">
<i class="bk-icon icon-close-circle-shape"></i>
<span>{{$t('新增失败列表')}}({{uploadResult.insert_failed.length}})</span>
</div>
<ul ref="failList" class="upload-details-fail-list">
<li
v-for="(fail, index) in uploadResult.insert_failed"
:title="$t('第N行字段错误信息', { N: fail.row, field: fail.bk_property_id, info: fail.info })"
:key="index">{{$t('第N行字段错误信息', { N: fail.row, field: fail.bk_property_id, info: fail.info })}}
</li>
</ul>
</div>
<div class="upload-details-fail" v-if="uploadResult.update_failed && uploadResult.update_failed.length">
<div class="upload-details-fail-title">
<i class="bk-icon icon-close-circle-shape"></i>
<span>{{$t('更新失败列表')}}({{uploadResult.update_failed.length}})</span>
</div>
<ul ref="failList" class="upload-details-fail-list">
<li
v-for="(fail, index) in uploadResult.update_failed"
:title="$t('第N行字段错误信息', { N: fail.row, field: fail.bk_property_id, info: fail.info })"
:key="index">{{$t('第N行字段错误信息', { N: fail.row, field: fail.bk_property_id, info: fail.info })}}
</li>
</ul>
</div>
</div>
</cmdb-import>
</bk-sideslider>
<!-- /导入字段 -->
</div>
</template>
<script>
import theRelation from './relation'
import theVerification from './verification'
import theFieldGroup from '@/components/model-manage/field-group'
import theChooseIcon from '@/components/model-manage/choose-icon/_choose-icon'
import cmdbImport from '@/components/import/import'
import { mapActions, mapGetters, mapMutations } from 'vuex'
import RouterQuery from '@/router/query'
import {
MENU_MODEL_MANAGEMENT,
MENU_RESOURCE_HOST,
MENU_RESOURCE_BUSINESS,
MENU_RESOURCE_INSTANCE
} from '@/dictionary/menu-symbol'
export default {
components: {
theFieldGroup,
theRelation,
theVerification,
theChooseIcon,
cmdbImport
},
data () {
return {
tab: {
active: RouterQuery.get('tab', 'field')
},
modelInfo: {
objName: '',
objIcon: ''
},
isIconListShow: false,
isEditName: false,
modelStatisticsSet: {},
importField: {
show: false,
templateUrl: ''
},
uploadResult: {
success: null,
insert_failed: null,
update_failed: null
}
}
},
computed: {
...mapGetters([
'supplierAccount',
'userName'
]),
...mapGetters('objectModel', [
'activeModel',
'isMainLine'
]),
...mapGetters('objectModelClassify', ['models']),
isShowOperationButton () {
return this.activeModel && !this.activeModel.ispre
},
isReadOnly () {
if (this.activeModel) {
return this.activeModel.bk_ispaused
}
return false
},
isEditable () {
if (this.activeModel) {
return !this.activeModel.ispre && !this.activeModel.bk_ispaused
}
return false
},
modelParams () {
const {
objIcon,
objName
} = this.modelInfo
const params = {
modifier: this.userName
}
if (objIcon) {
Object.assign(params, { bk_obj_icon: objIcon })
}
if (objName.length && objName !== this.activeModel['bk_obj_name']) {
Object.assign(params, { bk_obj_name: objName })
}
return params
},
exportUrl () {
return `${window.API_HOST}object/owner/${this.supplierAccount}/object/${this.activeModel['bk_obj_id']}/export`
},
importUrl () {
return `${window.API_HOST}object/owner/${this.supplierAccount}/object/${this.activeModel['bk_obj_id']}/import`
},
canBeImport () {
const cantImport = ['host', 'biz']
return !this.isMainLine
&& !cantImport.includes(this.$route.params.modelId)
},
modelId () {
const model = this.$store.getters['objectModelClassify/getModelById'](this.$route.params.modelId)
return model.id || null
}
},
watch: {
'$route.params.modelId' () {
this.initObject()
}
},
created () {
this.initObject()
},
methods: {
handleTabChange (tab) {
RouterQuery.set({ tab })
},
...mapActions('objectModel', [
'searchObjects',
'updateObject',
'deleteObject'
]),
...mapActions('objectBatch', [
'importObjectAttribute',
'exportObjectAttribute'
]),
...mapActions('objectMainLineModule', [
'deleteMainlineObject'
]),
...mapMutations('objectModel', [
'setActiveModel'
]),
getModelType () {
if (this.activeModel) {
return this.activeModel.ispre ? this.$t('内置') : this.$t('公共')
}
return ''
},
async handleFile (e) {
const files = e.target.files
const formData = new FormData()
formData.append('file', files[0])
try {
const res = await this.importObjectAttribute({
params: formData,
objId: this.activeModel['bk_obj_id'],
config: {
requestId: 'importObjectAttribute',
globalError: false,
transformData: false
}
}).then(res => {
this.$http.cancel(`post_searchObjectAttribute_${this.activeModel['bk_obj_id']}`)
return res
})
if (res.result) {
const data = res.data[this.activeModel['bk_obj_id']]
if (data.hasOwnProperty('insert_failed')) {
this.$error(data['insert_failed'][0])
} else if (data.hasOwnProperty('update_failed')) {
this.$error(data['update_failed'][0])
} else {
this.$success(this.$t('导入成功'))
this.$refs.field.initFieldList()
}
} else {
this.$error(res['bk_error_msg'])
}
} catch (e) {
this.$error(e.data['bk_error_msg'])
} finally {
this.$refs.fileInput.value = ''
}
},
checkModel () {
return this.models.find(model => model['bk_obj_id'] === this.$route.params.modelId)
},
hideChooseBox () {
this.isIconListShow = false
},
chooseIcon () {
this.isIconListShow = false
this.saveModel()
},
editModelName () {
this.modelInfo.objName = this.activeModel['bk_obj_name']
this.isEditName = true
},
async saveModel () {
if (!await this.$validator.validateAll()) {
return
}
await this.updateObject({
id: this.activeModel['id'],
params: this.modelParams
}).then(() => {
this.$http.cancel('post_searchClassificationsObjects')
})
this.setActiveModel({ ...this.activeModel, ...this.modelParams })
this.isEditName = false
},
async initObject () {
await this.getModelStatistics()
const model = this.$store.getters['objectModelClassify/getModelById'](this.$route.params.modelId)
if (model) {
this.$store.commit('objectModel/setActiveModel', model)
this.initModelInfo()
} else {
this.$routerActions.redirect({ name: 'status404' })
}
},
async getModelStatistics () {
const modelStatisticsSet = {}
const res = await this.$store.dispatch('objectModelClassify/getClassificationsObjectStatistics', {
config: {
requestId: 'getClassificationsObjectStatistics'
}
})
res.forEach(item => {
modelStatisticsSet[item.bk_obj_id] = item.instance_count
})
this.modelStatisticsSet = modelStatisticsSet
},
initModelInfo () {
this.modelInfo = {
objIcon: this.activeModel['bk_obj_icon'],
objName: this.activeModel['bk_obj_name']
}
},
exportExcel (response) {
const contentDisposition = response.headers['content-disposition']
const fileName = contentDisposition.substring(contentDisposition.indexOf('filename') + 9)
const url = window.URL.createObjectURL(new Blob([response.data], { type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet' }))
const link = document.createElement('a')
link.style.display = 'none'
link.href = url
link.setAttribute('download', fileName)
document.body.appendChild(link)
link.click()
document.body.removeChild(link)
},
async exportField () {
const res = await this.exportObjectAttribute({
objId: this.activeModel['bk_obj_id'],
params: {},
config: {
globalError: false,
originalResponse: true,
responseType: 'blob'
}
})
this.exportExcel(res)
},
dialogConfirm (type) {
switch (type) {
case 'restart':
this.$bkInfo({
title: this.$t('确认要启用该模型?'),
confirmFn: () => {
this.updateModelObject(false)
}
})
break
case 'stop':
this.$bkInfo({
title: this.$t('确认要停用该模型?'),
confirmFn: () => {
this.updateModelObject(true)
}
})
break
case 'delete':
this.$bkInfo({
title: this.$t('确认要删除该模型?'),
confirmFn: () => {
this.deleteModel()
}
})
break
default:
}
},
async updateModelObject (ispaused) {
await this.updateObject({
id: this.activeModel['id'],
params: {
bk_ispaused: ispaused
},
config: {
requestId: 'updateModel'
}
})
this.$store.commit('objectModelClassify/updateModel', {
bk_ispaused: ispaused,
bk_obj_id: this.activeModel.bk_obj_id
})
this.setActiveModel({ ...this.activeModel, ...{ bk_ispaused: ispaused } })
},
async deleteModel () {
if (this.isMainLine) {
await this.deleteMainlineObject({
bkObjId: this.activeModel['bk_obj_id'],
config: {
requestId: 'deleteModel'
}
})
this.$routerActions.back()
} else {
await this.deleteObject({
id: this.activeModel['id'],
config: {
requestId: 'deleteModel'
}
})
this.$routerActions.redirect({ name: MENU_MODEL_MANAGEMENT })
}
this.$http.cancel('post_searchClassificationsObjects')
},
handleGoInstance () {
const model = this.activeModel
const map = {
host: MENU_RESOURCE_HOST,
biz: MENU_RESOURCE_BUSINESS
}
if (map.hasOwnProperty(model.bk_obj_id)) {
this.$routerActions.redirect({
name: map[model.bk_obj_id]
})
} else {
this.$routerActions.redirect({
name: MENU_RESOURCE_INSTANCE,
params: {
objId: model.bk_obj_id
}
})
}
},
handleUploadDone (res) {
const data = res.data[this.activeModel['bk_obj_id']]
if (res.result) {
this.uploadResult.success = data.success
this.$success(this.$t('导入成功'))
this.$refs.field.initFieldList()
} else {
this.uploadResult.insert_failed = data['insert_failed']
this.uploadResult.update_failed = data['update_failed']
}
},
handleSliderHide () {
this.uploadResult = {
success: null,
insert_failed: null,
update_failed: null
}
},
handleImportField () {
this.importField.show = true
}
}
}
</script>
<style lang="scss" scoped>
.model-detail-wrapper {
padding: 0;
}
.model-details-tab {
height: calc(100% - 70px) !important;
/deep/ {
.bk-tab-header {
padding: 0;
margin: 0 20px;
}
.bk-tab-section {
padding: 0;
}
}
}
.model-info {
padding: 0 24px;
height: 70px;
background: #ebf4ff;
font-size: 14px;
border-bottom: 1px solid #dcdee5;
.choose-icon-wrapper {
position: relative;
float: left;
margin: 8px 30px 0 0;
.model-type {
position: absolute;
left: 42px;
top: -12px;
padding: 0 6px;
border-radius: 4px;
background-color: #ffb23a;
font-size: 20px;
line-height: 32px;
color: #fff;
white-space: nowrap;
transform: scale(.5);
transform-origin: left center;
z-index: 2;
&:after {
content: "";
position: absolute;
top: 100%;
left: 10px;
width: 0;
height: 0;
border-top: 8px solid #ffb23a;
border-right: 10px solid transparent;
transform: skew(-15deg);
transform-origin: left top;
}
}
.choose-icon-box {
position: absolute;
left: -12px;
top: 62px;
width: 600px;
height: 460px;
background: #fff;
border: 1px solid #dde4e8;
box-shadow: 0px 3px 6px 0px rgba(51, 60, 72, 0.13);
z-index: 99;
&:before {
position: absolute;
top: -13px;
left: 30px;
content: '';
border: 6px solid transparent;
border-bottom-color: rgba(51, 60, 72, 0.23);
}
&:after {
position: absolute;
top: -12px;
left: 30px;
content: '';
border: 6px solid transparent;
border-bottom-color: #fff;
}
}
}
.icon-box {
padding-top: 16px;
width: 54px;
height: 54px;
border: 1px solid #dde4eb;
border-radius: 50%;
background: #fff;
text-align: center;
font-size: 20px;
color: $cmdbBorderFocusColor;
cursor: pointer;
&:hover {
.hover-text {
background: rgba(0, 0, 0, .5);
display: block;
}
}
.hover-text {
display: none;
position: absolute;
top: 0;
left: 0;
width: 54px;
height: 54px;
line-height: 54px;
font-size: 12px;
border-radius: 50%;
text-align: center;
color: #fff;
&.is-paused {
background: rgba(0, 0, 0, .5);
display: block !important;
}
}
.icon {
vertical-align: top;
&.ispre {
color: #3a84ff;
}
}
}
.model-text {
float: left;
margin: 18px 10px 0 0;
line-height: 36px;
font-size: 0;
>span {
display: inline-block;
vertical-align: middle;
height: 36px;
font-size: 14px;
color: #737987;
}
.text-content {
max-width: 110px;
vertical-align: middle;
color: #333948;
@include ellipsis;
&.id {
min-width: 50px;
}
}
.text-content-count {
display: inline-block;
vertical-align: middle;
color: #3a84ff;
cursor: pointer;
>span {
font-size: 14px;
vertical-align: middle;
}
.icon-cc-share {
font-size: 12px;
margin-left: 6px;
vertical-align: middle;
}
}
.icon-cc-edit {
vertical-align: middle;
font-size: 14px;
}
.cmdb-form-item {
display: inline-block;
width: 156px;
vertical-align: top;
input {
vertical-align: top;
}
}
.text-primary {
cursor: pointer;
margin-left: 5px;
}
}
.restart-btn {
display: inline-block;
margin: 19px 0 0 20px;
}
.btn-group {
float: right;
height: 70px;
line-height: 70px;
display: flex;
align-items: center;
.label-btn {
line-height: normal;
outline: 0;
position: relative;
.bk-button-text {
color: #737987;
&:disabled {
color: #dcdee5 !important;
cursor: not-allowed;
}
}
&.disabled {
cursor: not-allowed;
}
input[type="file"] {
position: absolute;
left: 0;
top: 0;
opacity: 0;
width: 100%;
height: 100%;
cursor: pointer;
}
::-webkit-file-upload-button {
cursor:pointer;
}
}
.export-form {
display: inline-block;
}
.label-btn {
margin-left: 10px;
cursor: pointer;
&:hover {
color: $cmdbBorderFocusColor;
.bk-button-text {
color: $cmdbBorderFocusColor;
}
}
}
i,
span {
vertical-align: middle;
}
}
}
</style>
<style lang="scss">
@import '@/assets/scss/model-manage.scss';
</style>
| {
"pile_set_name": "Github"
} |
{
"acno": "D29776",
"acquisitionYear": 1856,
"all_artists": "Joseph Mallord William Turner",
"catalogueGroup": {
"accessionRanges": "D29772-D29813; D41133-D41135",
"completeStatus": "COMPLETE",
"finbergNumber": "CCXCVII",
"groupType": "Turner Sketchbook",
"id": 65925,
"shortTitle": "Spires and Heidelberg Sketchbook"
},
"classification": "on paper, unique",
"contributorCount": 1,
"contributors": [
{
"birthYear": 1775,
"date": "1775\u20131851",
"displayOrder": 1,
"fc": "Joseph Mallord William Turner",
"gender": "Male",
"id": 558,
"mda": "Turner, Joseph Mallord William",
"role": "artist",
"startLetter": "T"
}
],
"creditLine": "Accepted by the nation as part of the Turner Bequest 1856",
"dateRange": {
"endYear": 1844,
"startYear": 1844,
"text": "1844"
},
"dateText": "1844",
"depth": "",
"dimensions": "support: 170 x 109 mm",
"finberg": "CCXCVII 3",
"foreignTitle": null,
"groupTitle": "Spires and Heidelberg Sketchbook",
"height": "109",
"id": 57038,
"inscription": null,
"medium": "Graphite on paper",
"movementCount": 0,
"pageNumber": 7,
"subjectCount": 5,
"subjects": {
"children": [
{
"children": [
{
"children": [
{
"id": 3561,
"name": "Germany"
}
],
"id": 108,
"name": "countries and continents"
},
{
"children": [
{
"id": 14691,
"name": "Speyer"
}
],
"id": 107,
"name": "cities, towns, villages (non-UK)"
}
],
"id": 106,
"name": "places"
},
{
"children": [
{
"children": [
{
"id": 880,
"name": "mountain"
}
],
"id": 71,
"name": "landscape"
}
],
"id": 60,
"name": "nature"
},
{
"children": [
{
"children": [
{
"id": 4527,
"name": "spire"
}
],
"id": 17,
"name": "features"
},
{
"children": [
{
"id": 989,
"name": "townscape, distant"
}
],
"id": 28,
"name": "townscapes, man-made features"
}
],
"id": 13,
"name": "architecture"
}
],
"id": 1,
"name": "subject"
},
"thumbnailCopyright": null,
"thumbnailUrl": "http://www.tate.org.uk/art/images/work/D/D29/D29776_8.jpg",
"title": "Mountains and Buildings; Distant View of Speyer",
"units": "mm",
"url": "http://www.tate.org.uk/art/artworks/turner-mountains-and-buildings-distant-view-of-speyer-d29776",
"width": "170"
} | {
"pile_set_name": "Github"
} |
require 'spec_helper'
# asserts serializer resolution order:
# 1. resource_defined_class # V1::UserSerializer
# 2. collection_class # CollectionSerializer, V2::UserSerializer
# 3. options[:serializer] # V3::UserSerializer
# 4. namespace_inferred_class # V4::UserSerializer
# 5. version_inferred_class # V5::UserSerializer
# 6. resource_serializer_class # UserSerializer
# 7. missing resource # nil
describe Grape::ActiveModelSerializers::SerializerResolver do
let(:resolver) { described_class.new(resource, options) }
let(:resource) { User.new }
let(:options) {
{
serializer: options_serializer_class, # options defined
for: V4::UsersApi, # namespace inference
version: 'v5' # version inference
}
}
# resource defined
let(:resource_defined?) { true }
let(:defined_serializer_class) { V1::UserSerializer }
# options defined
let(:options_serializer_class) { V3::UserSerializer }
let(:serializer) { resolver.serializer }
before do
if resource_defined?
allow(resource).to receive(:respond_to?).and_call_original
allow(resource).to receive(:respond_to?).with(:to_ary) { true }
allow(resource).to receive(:serializer_class) { defined_serializer_class }
end
end
context 'resource defined' do
it 'returns serializer' do
expect(serializer).to be_kind_of(defined_serializer_class)
end
end
context 'not resource defined' do
let(:resource_defined?) { false }
context 'resource collection' do
let(:resource) { [User.new] }
let(:serializer_class) { ActiveModel::Serializer::CollectionSerializer }
it 'returns serializer' do
expect(serializer).to be_kind_of(serializer_class)
end
context 'each serializer' do
let(:options) {
super().except(:serializer).merge(
each_serializer: V2::UserSerializer
)
}
let(:each_serializer) { serializer.send(:options)[:serializer] }
context 'each_serializer option' do
it 'returns expected serializer' do
expect(each_serializer).to eq(V2::UserSerializer)
end
end
context 'no each_serializer option' do
let(:options) { super().except(:each_serializer) }
context 'namespace inferred' do
it 'returns expected serializer' do
expect(each_serializer).to eq(V4::UserSerializer)
end
end
context 'not namespace inferred' do
let(:options) { super().except(:for) }
context 'version inferred' do
it 'returns expected serializer' do
expect(each_serializer).to eq(V5::UserSerializer)
end
end
context 'not version inferred' do
let(:options) { super().except(:version) }
it 'returns nil' do
expect(each_serializer).to eq(nil)
end
end
end
end
end
end
context 'not resource collection' do
context 'specified by options' do
it 'returns specified serializer' do
expect(serializer).to be_kind_of(V3::UserSerializer)
end
end
context 'not specified by options' do
let(:options) { super().except(:serializer) }
context 'namespace inferred' do
it 'returns inferred serializer' do
expect(serializer).to be_kind_of(V4::UserSerializer)
end
end
context 'not namespace inferred' do
let(:options) { super().except(:for) }
context 'version inferred' do
it 'returns inferred serializer' do
expect(serializer).to be_kind_of(V5::UserSerializer)
end
end
context 'not version inferred' do
let(:options) { super().except(:version) }
context 'ASM resolved' do
it 'returns serializer' do
expect(serializer).to be_kind_of(UserSerializer)
end
end
context 'not ASM resolved' do
let(:resource) { nil }
it 'returns nil' do
expect(serializer).to eq(nil)
end
end
end
end
end
end
end
end
| {
"pile_set_name": "Github"
} |
From 268500240a551436c5003f5843ff4d090bf3e202 Mon Sep 17 00:00:00 2001
From: MilhouseVH <[email protected]>
Date: Thu, 18 May 2017 12:52:55 +0100
Subject: [PATCH] Fix build with kernel 4.12-rc1
---
x86-64/src/wl/sys/wl_cfg80211_hybrid.c | 25 +++++++++++++++++++++++++
1 file changed, 25 insertions(+)
diff --git a/x86-64/src/wl/sys/wl_cfg80211_hybrid.c b/x86-64/src/wl/sys/wl_cfg80211_hybrid.c
index 7b606e0..cedf95c 100644
--- a/x86-64/src/wl/sys/wl_cfg80211_hybrid.c
+++ b/x86-64/src/wl/sys/wl_cfg80211_hybrid.c
@@ -49,8 +49,13 @@ u32 wl_dbg_level = WL_DBG_ERR | WL_DBG_INFO;
u32 wl_dbg_level = WL_DBG_ERR;
#endif
+#if LINUX_VERSION_CODE >= KERNEL_VERSION(4, 12, 0)
+static s32 wl_cfg80211_change_iface(struct wiphy *wiphy, struct net_device *ndev,
+ enum nl80211_iftype type, struct vif_params *params);
+#else
static s32 wl_cfg80211_change_iface(struct wiphy *wiphy, struct net_device *ndev,
enum nl80211_iftype type, u32 *flags, struct vif_params *params);
+#endif
#if LINUX_VERSION_CODE >= KERNEL_VERSION(3, 6, 0)
static s32
wl_cfg80211_scan(struct wiphy *wiphy,
@@ -461,10 +466,16 @@ wl_dev_ioctl(struct net_device *dev, u32 cmd, void *arg, u32 len)
return err;
}
+#if LINUX_VERSION_CODE >= KERNEL_VERSION(4, 12, 0)
+static s32
+wl_cfg80211_change_iface(struct wiphy *wiphy, struct net_device *ndev,
+ enum nl80211_iftype type, struct vif_params *params)
+#else
static s32
wl_cfg80211_change_iface(struct wiphy *wiphy, struct net_device *ndev,
enum nl80211_iftype type, u32 *flags,
struct vif_params *params)
+#endif
{
struct wl_cfg80211_priv *wl = wiphy_to_wl(wiphy);
struct wireless_dev *wdev;
@@ -2364,6 +2375,19 @@ wl_bss_roaming_done(struct wl_cfg80211_priv *wl, struct net_device *ndev,
memcpy(wl->profile->bssid, &e->addr, ETHER_ADDR_LEN);
memcpy(&wl->bssid, &e->addr, ETHER_ADDR_LEN);
wl_update_bss_info(wl);
+#if LINUX_VERSION_CODE >= KERNEL_VERSION(4, 12, 0)
+ {
+ struct cfg80211_roam_info roam_info = {
+ .channel = &wl->conf->channel,
+ .bssid = (u8 *)&wl->bssid,
+ .req_ie = conn_info->req_ie,
+ .req_ie_len = conn_info->req_ie_len,
+ .resp_ie = conn_info->resp_ie,
+ .resp_ie_len = conn_info->resp_ie_len,
+ };
+ cfg80211_roamed(ndev, &roam_info, GFP_KERNEL);
+ }
+#else
cfg80211_roamed(ndev,
#if LINUX_VERSION_CODE > KERNEL_VERSION(2, 6, 39)
&wl->conf->channel,
@@ -2371,6 +2395,7 @@ wl_bss_roaming_done(struct wl_cfg80211_priv *wl, struct net_device *ndev,
(u8 *)&wl->bssid,
conn_info->req_ie, conn_info->req_ie_len,
conn_info->resp_ie, conn_info->resp_ie_len, GFP_KERNEL);
+#endif
WL_DBG(("Report roaming result\n"));
set_bit(WL_STATUS_CONNECTED, &wl->status);
--
2.7.4
| {
"pile_set_name": "Github"
} |
//
// Enumerates printers installed in the system
//
using System;
using System.Drawing.Printing;
public class EnumPrinters
{
public static void Main (string[] args)
{
PrinterSettings.StringCollection col = System.Drawing.Printing.PrinterSettings.InstalledPrinters;
for (int i = 0; i < col.Count; i++) {
Console.WriteLine ("--- {0}", col[i]);
PrinterSettings ps = new PrinterSettings ();
ps.PrinterName = col[i];
//Console.WriteLine (" Duplex: {0}", ps.Duplex);
Console.WriteLine (" FromPage: {0}", ps.FromPage);
Console.WriteLine (" ToPage: {0}", ps.ToPage);
Console.WriteLine (" MaximumCopies: {0}", ps.MaximumCopies);
Console.WriteLine (" IsDefaultPrinter: {0}", ps.IsDefaultPrinter);
Console.WriteLine (" SupportsColor: {0}", ps.SupportsColor);
Console.WriteLine (" MaximumPage {0}", ps.MaximumPage);
Console.WriteLine (" MinimumPage {0}", ps.MinimumPage);
Console.WriteLine (" LandscapeAngle {0}", ps.LandscapeAngle);
/*
for (int p = 0; p < ps.PrinterResolutions.Count; p++) {
Console.WriteLine (" PrinterResolutions {0}", ps.PrinterResolutions [p]);
}*/
for (int p = 0; p < ps.PaperSizes.Count; p++) {
Console.WriteLine (" PaperSize Name [{0}] Kind [{1}] Width {2} Height {3}",
ps.PaperSizes [p].PaperName, ps.PaperSizes [p].Kind,
ps.PaperSizes [p].Width, ps.PaperSizes [p].Height);
}
}
}
}
| {
"pile_set_name": "Github"
} |
<?xml version="1.0" encoding="UTF-8"?>
<debug-info version="2">
<concept fqn="c:c7d5b9dd-a05f-4be2-bc73-f2e16994cc67/3751132065236767060:jetbrains.mps.baseLanguage.lightweightdsl.structure.MethodInstance" />
<concept fqn="c:f3061a53-9226-4cc5-a443-f952ceaf5816/1082485599095:jetbrains.mps.baseLanguage.structure.BlockStatement" />
<concept fqn="c:f3061a53-9226-4cc5-a443-f952ceaf5816/1068580123140:jetbrains.mps.baseLanguage.structure.ConstructorDeclaration" />
<concept fqn="c:f3061a53-9226-4cc5-a443-f952ceaf5816/1068580123155:jetbrains.mps.baseLanguage.structure.ExpressionStatement" />
<concept fqn="c:f3061a53-9226-4cc5-a443-f952ceaf5816/1068390468200:jetbrains.mps.baseLanguage.structure.FieldDeclaration" />
<concept fqn="c:f3061a53-9226-4cc5-a443-f952ceaf5816/1144226303539:jetbrains.mps.baseLanguage.structure.ForeachStatement" />
<concept fqn="c:f3061a53-9226-4cc5-a443-f952ceaf5816/1068580123159:jetbrains.mps.baseLanguage.structure.IfStatement" />
<concept fqn="c:f3061a53-9226-4cc5-a443-f952ceaf5816/1068580123165:jetbrains.mps.baseLanguage.structure.InstanceMethodDeclaration" />
<concept fqn="c:f3061a53-9226-4cc5-a443-f952ceaf5816/1068581242864:jetbrains.mps.baseLanguage.structure.LocalVariableDeclarationStatement" />
<concept fqn="c:f3061a53-9226-4cc5-a443-f952ceaf5816/1068581242878:jetbrains.mps.baseLanguage.structure.ReturnStatement" />
<concept fqn="c:f3061a53-9226-4cc5-a443-f952ceaf5816/6329021646629104954:jetbrains.mps.baseLanguage.structure.SingleLineComment" />
<concept fqn="c:f3061a53-9226-4cc5-a443-f952ceaf5816/1068580123157:jetbrains.mps.baseLanguage.structure.Statement" />
<concept fqn="c:f3061a53-9226-4cc5-a443-f952ceaf5816/1070462154015:jetbrains.mps.baseLanguage.structure.StaticFieldDeclaration" />
<concept fqn="c:f3061a53-9226-4cc5-a443-f952ceaf5816/1081236700938:jetbrains.mps.baseLanguage.structure.StaticMethodDeclaration" />
<concept fqn="c:f3061a53-9226-4cc5-a443-f952ceaf5816/1070475587102:jetbrains.mps.baseLanguage.structure.SuperConstructorInvocation" />
<concept fqn="c:f3061a53-9226-4cc5-a443-f952ceaf5816/1178893518978:jetbrains.mps.baseLanguage.structure.ThisConstructorInvocation" />
<root>
<file name="ExtensionDescriptor.java">
<unit at="9,0,18,0" name="jetbrains.mps.ide.refactoring.plugin.ExtensionDescriptor" />
</file>
</root>
<root nodeRef="r:97d6b60a-b381-42e8-9ea4-402ec93eaf11(jetbrains.mps.ide.refactoring.plugin)/1222173496701">
<file name="ModelRefactoring_ActionGroup.java">
<node id="1222173496701" at="10,0,11,0" concept="12" trace="ID" />
<node id="1222173496701" at="12,75,13,37" concept="14" />
<node id="1222173496701" at="13,37,14,30" concept="3" />
<node id="1222173496701" at="14,30,15,25" concept="3" />
<node id="1222173496701" at="15,25,16,19" concept="3" />
<node id="3836873511016295895" at="16,19,17,96" concept="3" />
<node id="2580894021251567873" at="17,96,18,105" concept="3" />
<node id="1222173496701" at="21,44,22,16" concept="9" />
<node id="1222173496701" at="20,0,24,0" concept="7" trace="hideIfNoVisibleChildren#()Z" />
<node id="1222173496701" at="12,0,20,0" concept="2" trace="ModelRefactoring_ActionGroup#(Ljetbrains/mps/workbench/action/ApplicationPlugin;)V" />
<scope id="1222173496701" at="21,44,22,16" />
<scope id="1222173496701" at="20,0,24,0" />
<scope id="1222173496701" at="12,75,18,105" />
<scope id="1222173496701" at="12,0,20,0">
<var name="plugin" id="1222173496701" />
</scope>
<unit id="1222173496701" at="9,0,25,0" name="jetbrains.mps.ide.refactoring.plugin.ModelRefactoring_ActionGroup" />
</file>
<file name="Refactoring_ApplicationPlugin.java">
<node id="1222173496701" at="32,57,33,53" concept="3" />
<node id="1222173607728" at="37,37,38,136" concept="3" />
</file>
</root>
<root nodeRef="r:97d6b60a-b381-42e8-9ea4-402ec93eaf11(jetbrains.mps.ide.refactoring.plugin)/2580894021251553866">
<file name="Default_KeymapChanges.java">
<node id="2580894021251553866" at="11,34,12,14" concept="10" />
<node id="8047970061512463293" at="12,14,13,99" concept="3" />
<node id="830211401282059664" at="13,99,14,99" concept="3" />
<node id="8784230320738943426" at="14,99,15,105" concept="3" />
<node id="2580894021251553866" at="15,105,16,28" concept="10" />
<node id="2580894021251553866" at="16,28,17,15" concept="10" />
<node id="2580894021251553866" at="19,29,20,22" concept="9" />
<node id="2580894021251553866" at="22,53,23,70" concept="9" />
<node id="2580894021251553866" at="19,0,22,0" concept="7" trace="getScheme#()Ljava/lang/String;" />
<node id="2580894021251553866" at="22,0,25,0" concept="13" trace="getShortcut#(Ljava/lang/String;)Lcom/intellij/openapi/actionSystem/Shortcut;" />
<node id="2580894021251553866" at="11,0,19,0" concept="2" trace="Default_KeymapChanges#()V" />
<scope id="2580894021251553866" at="19,29,20,22" />
<scope id="2580894021251553866" at="22,53,23,70" />
<scope id="2580894021251553866" at="19,0,22,0" />
<scope id="2580894021251553866" at="22,0,25,0">
<var name="stroke" id="2580894021251553866" />
</scope>
<scope id="2580894021251553866" at="11,34,17,15" />
<scope id="2580894021251553866" at="11,0,19,0" />
<unit id="2580894021251553866" at="10,0,26,0" name="jetbrains.mps.ide.refactoring.plugin.Default_KeymapChanges" />
</file>
<file name="Refactoring_ApplicationPlugin.java">
<node id="2580894021251553866" at="44,92,45,71" concept="3" />
</file>
</root>
<root nodeRef="r:97d6b60a-b381-42e8-9ea4-402ec93eaf11(jetbrains.mps.ide.refactoring.plugin)/2941496348503197695">
<file name="UpdateDependentModelsRefactoringParticipant.java">
<node id="5883753008207004942" at="49,68,50,76" concept="14" />
<node id="5883753008207560983" at="52,56,53,63" concept="9" />
<node id="2941496348503424221" at="58,59,59,54" concept="9" />
<node id="2941496348503432125" at="61,57,62,53" concept="9" />
<node id="2941496348503456459" at="66,127,67,27" concept="9" />
<node id="2941496348503678958" at="70,0,71,0" concept="4" trace="myOption" />
<node id="2941496348503720003" at="73,120,74,99" concept="9" />
<node id="2941496348503754733" at="79,71,80,117" concept="9" />
<node id="2941496348503761355" at="81,5,82,0" concept="11" />
<node id="2941496348503786560" at="82,0,83,56" concept="3" />
<node id="2941496348503770735" at="83,56,84,75" concept="8" />
<node id="2941496348505148421" at="84,75,85,70" concept="8" />
<node id="2941496348503802626" at="87,25,88,164" concept="3" />
<node id="2941496348505162138" at="88,164,89,61" concept="3" />
<node id="2941496348503830262" at="91,7,92,0" concept="11" />
<node id="2941496348504126304" at="94,96,95,59" concept="8" />
<node id="2941496348505110345" at="95,59,96,252" concept="8" />
<node id="2941496348505077352" at="98,51,99,33" concept="9" />
<node id="2941496348504953859" at="103,33,104,60" concept="8" />
<node id="2941496348504953868" at="105,158,106,70" concept="3" />
<node id="2941496348504953877" at="106,70,107,81" concept="3" />
<node id="2941496348504953884" at="107,81,108,75" concept="3" />
<node id="7335312533387606255" at="109,17,110,82" concept="8" />
<node id="7335312533387536956" at="111,210,112,111" concept="3" />
<node id="2941496348504963357" at="117,10,118,22" concept="9" />
<node id="2941496348504906051" at="123,144,124,83" concept="8" />
<node id="2941496348504906068" at="126,55,127,49" concept="9" />
<node id="2941496348504906077" at="130,48,131,80" concept="9" />
<node id="2941496348504906088" at="134,44,135,55" concept="3" />
<node id="2941496348504906100" at="137,7,138,32" concept="3" />
<node id="5883753008207004942" at="49,0,52,0" concept="2" trace="UpdateDependentModelsRefactoringParticipant_extension#()V" />
<node id="5883753008207004949" at="52,0,55,0" concept="0" trace="get#()Ljetbrains/mps/refactoring/participant/MoveModelRefactoringParticipant;" />
<node id="2941496348503414673" at="58,0,61,0" concept="7" trace="beforeMove#(Lorg/jetbrains/mps/openapi/model/SModel;)Lorg/jetbrains/mps/openapi/model/SModelReference;" />
<node id="2941496348503414681" at="61,0,64,0" concept="7" trace="afterMove#(Lorg/jetbrains/mps/openapi/model/SModel;)Lorg/jetbrains/mps/openapi/model/SModelReference;" />
<node id="2941496348503449396" at="66,0,69,0" concept="7" trace="getDataCollector#()Ljetbrains/mps/refactoring/participant/RefactoringParticipant/RefactoringDataCollector;" />
<node id="2941496348503738979" at="78,274,81,5" concept="6" />
<node id="2941496348504975535" at="98,0,101,0" concept="7" trace="getSearchResults#()Ljetbrains/mps/ide/findusages/model/SearchResults;" />
<node id="7335312533387575777" at="110,82,113,17" concept="6" />
<node id="2941496348504906066" at="126,0,129,0" concept="7" trace="translate#(Lorg/jetbrains/mps/openapi/model/SNode;)Ljava/lang/Iterable;" />
<node id="2941496348504906075" at="130,0,133,0" concept="7" trace="accept#(Ljetbrains/mps/smodel/SReferenceBase;)Z" />
<node id="2941496348504906086" at="134,0,137,0" concept="7" trace="visit#(Ljetbrains/mps/smodel/SReferenceBase;)V" />
<node id="2941496348503616735" at="72,0,76,0" concept="7" trace="getAvailableOptions#(Lorg/jetbrains/mps/openapi/model/SModelReference;Lorg/jetbrains/mps/openapi/module/SRepository;)Ljava/util/List;" />
<node id="2941496348503811761" at="87,0,91,0" concept="7" trace="run#()V" />
<node id="2941496348504953866" at="104,60,109,17" concept="6" />
<node id="2941496348503811759" at="85,70,91,7" concept="3" />
<node id="2941496348503250868" at="57,0,65,0" concept="4" trace="myDataCollector" />
<node id="9163025738078139938" at="103,0,115,0" concept="7" trace="run#()V" />
<node id="2941496348504906060" at="124,83,137,7" concept="3" />
<node id="9163025738078128573" at="101,134,115,15" concept="3" />
<node id="2941496348504953849" at="101,0,117,0" concept="7" trace="confirm#(Lorg/jetbrains/mps/openapi/model/SModelReference;Lorg/jetbrains/mps/openapi/module/SRepository;Ljetbrains/mps/refactoring/participant/RefactoringSession;)V" />
<node id="2941496348505405953" at="123,0,140,0" concept="13" trace="updateUsages#(Lorg/jetbrains/mps/openapi/model/EditableSModel;Lorg/jetbrains/mps/openapi/model/SModelReference;Lorg/jetbrains/mps/openapi/model/SModelReference;)V" />
<node id="2941496348504953841" at="96,252,117,10" concept="8" />
<node id="2941496348503859295" at="94,0,120,0" concept="7" trace="select#(Lorg/jetbrains/mps/openapi/model/SModel;)Ljetbrains/mps/refactoring/participant/RefactoringParticipant/Change;" />
<node id="2941496348503836410" at="92,0,120,24" concept="9" />
<node id="2941496348503659438" at="77,0,122,0" concept="7" trace="getChanges#(Lorg/jetbrains/mps/openapi/model/SModelReference;Lorg/jetbrains/mps/openapi/module/SRepository;Ljava/util/List;Lorg/jetbrains/mps/openapi/module/SearchScope;Lorg/jetbrains/mps/openapi/util/ProgressMonitor;)Ljava/util/List;" />
<scope id="5883753008207004942" at="49,68,50,76" />
<scope id="5883753008207004953" at="52,56,53,63" />
<scope id="2941496348503414679" at="58,59,59,54" />
<scope id="2941496348503414687" at="61,57,62,53" />
<scope id="2941496348503449424" at="66,127,67,27" />
<scope id="2941496348503616752" at="73,120,74,99" />
<scope id="2941496348503738980" at="79,71,80,117" />
<scope id="2941496348504975542" at="98,51,99,33" />
<scope id="7335312533387575779" at="111,210,112,111" />
<scope id="2941496348504906067" at="126,55,127,49" />
<scope id="2941496348504906076" at="130,48,131,80" />
<scope id="2941496348504906087" at="134,44,135,55" />
<scope id="2941496348503811763" at="87,25,89,61" />
<scope id="5883753008207004942" at="49,0,52,0" />
<scope id="5883753008207004949" at="52,0,55,0" />
<scope id="2941496348503414673" at="58,0,61,0">
<var name="modelToMove" id="2941496348503414677" />
</scope>
<scope id="2941496348503414681" at="61,0,64,0">
<var name="movedModel" id="2941496348503414685" />
</scope>
<scope id="2941496348503449396" at="66,0,69,0" />
<scope id="2941496348504975535" at="98,0,101,0" />
<scope id="2941496348504953867" at="105,158,108,75" />
<scope id="2941496348504906066" at="126,0,129,0">
<var name="it" id="2941496348504906066" />
</scope>
<scope id="2941496348504906075" at="130,0,133,0">
<var name="it" id="2941496348504906075" />
</scope>
<scope id="2941496348504906086" at="134,0,137,0">
<var name="it" id="2941496348504906086" />
</scope>
<scope id="2941496348503616735" at="72,0,76,0">
<var name="initialState" id="2941496348503616736" />
<var name="repository" id="2941496348503616738" />
</scope>
<scope id="2941496348503811761" at="87,0,91,0" />
<scope id="9163025738078139939" at="103,33,113,17">
<var name="targetModule" id="7335312533387606256" />
<var name="usage" id="2941496348504953860" />
</scope>
<scope id="9163025738078139938" at="103,0,115,0" />
<scope id="2941496348504953858" at="101,134,115,15" />
<scope id="2941496348504906050" at="123,144,138,32">
<var name="nodes" id="2941496348504906052" />
</scope>
<scope id="2941496348504953849" at="101,0,117,0">
<var name="finalState" id="2941496348504953852" />
<var name="refactoringSession" id="2941496348504953856" />
<var name="repository" id="2941496348504953854" />
</scope>
<scope id="2941496348505405953" at="123,0,140,0">
<var name="newModelReference" id="2941496348504906110" />
<var name="oldModelReference" id="2941496348504906108" />
<var name="usageModel" id="2941496348504906106" />
</scope>
<scope id="2941496348503859296" at="94,96,118,22">
<var name="change" id="2941496348504953842" />
<var name="searchResults" id="1762976820112517819" />
<var name="usageRef" id="2941496348504126305" />
</scope>
<scope id="2941496348503859295" at="94,0,120,0">
<var name="it" id="2941496348503859295" />
</scope>
<scope id="2941496348503659471" at="78,274,120,24">
<var name="sourceModel" id="2941496348505148422" />
<var name="usages" id="2941496348503770736" />
</scope>
<scope id="2941496348503659438" at="77,0,122,0">
<var name="initialState" id="2941496348503659439" />
<var name="progressMonitor" id="2941496348503659448" />
<var name="repository" id="2941496348503659441" />
<var name="searchScope" id="2941496348503659446" />
<var name="selectedOptions" id="2941496348503659443" />
</scope>
<unit id="2941496348504906066" at="125,47,129,5" name="jetbrains.mps.ide.refactoring.plugin.UpdateDependentModelsRefactoringParticipant$4" />
<unit id="2941496348504906075" at="129,46,133,5" name="jetbrains.mps.ide.refactoring.plugin.UpdateDependentModelsRefactoringParticipant$5" />
<unit id="2941496348504906086" at="133,20,137,5" name="jetbrains.mps.ide.refactoring.plugin.UpdateDependentModelsRefactoringParticipant$6" />
<unit id="2941496348503811761" at="86,50,91,5" name="jetbrains.mps.ide.refactoring.plugin.UpdateDependentModelsRefactoringParticipant$2" />
<unit id="2941496348503414671" at="57,136,64,3" name="jetbrains.mps.ide.refactoring.plugin.UpdateDependentModelsRefactoringParticipant$1" />
<unit id="5883753008207004942" at="48,0,56,0" name="jetbrains.mps.ide.refactoring.plugin.UpdateDependentModelsRefactoringParticipant$UpdateDependentModelsRefactoringParticipant_extension" />
<unit id="9163025738078139938" at="102,50,115,13" name="jetbrains.mps.ide.refactoring.plugin.UpdateDependentModelsRefactoringParticipant$3$1$1" />
<unit id="2941496348504953845" at="97,85,117,9" name="jetbrains.mps.ide.refactoring.plugin.UpdateDependentModelsRefactoringParticipant$3$1" />
<unit id="2941496348503859295" at="93,56,120,5" name="jetbrains.mps.ide.refactoring.plugin.UpdateDependentModelsRefactoringParticipant$3" />
<unit id="2941496348503197695" at="46,0,142,0" name="jetbrains.mps.ide.refactoring.plugin.UpdateDependentModelsRefactoringParticipant" />
</file>
</root>
<root nodeRef="r:97d6b60a-b381-42e8-9ea4-402ec93eaf11(jetbrains.mps.ide.refactoring.plugin)/3201523885428164994">
<file name="Refactoring_ApplicationPlugin.java">
<node id="3201523885428164994" at="34,63,35,65" concept="3" />
<node id="3201523885428165826" at="38,136,39,161" concept="3" />
</file>
<file name="TouchBarDefault_shift_rename_ActionGroup.java">
<node id="3201523885428164994" at="10,0,11,0" concept="12" trace="ID" />
<node id="3201523885428164994" at="12,87,13,54" concept="14" />
<node id="3201523885428164994" at="13,54,14,25" concept="3" />
<node id="3201523885428164994" at="14,25,15,20" concept="3" />
<node id="3201523885428164999" at="15,20,16,118" concept="3" />
<node id="3201523885428164994" at="12,0,18,0" concept="2" trace="TouchBarDefault_shift_rename_ActionGroup#(Ljetbrains/mps/workbench/action/ApplicationPlugin;)V" />
<scope id="3201523885428164994" at="12,87,16,118" />
<scope id="3201523885428164994" at="12,0,18,0">
<var name="plugin" id="3201523885428164994" />
</scope>
<unit id="3201523885428164994" at="9,0,19,0" name="jetbrains.mps.ide.refactoring.plugin.TouchBarDefault_shift_rename_ActionGroup" />
</file>
</root>
<root nodeRef="r:97d6b60a-b381-42e8-9ea4-402ec93eaf11(jetbrains.mps.ide.refactoring.plugin)/3201523885428189419">
<file name="Refactoring_ApplicationPlugin.java">
<node id="3201523885428189419" at="33,53,34,63" concept="3" />
<node id="3201523885428189424" at="39,161,40,157" concept="3" />
</file>
<file name="TouchBarDefault_shift_move_ActionGroup.java">
<node id="3201523885428189419" at="10,0,11,0" concept="12" trace="ID" />
<node id="3201523885428189419" at="12,85,13,52" concept="14" />
<node id="3201523885428189419" at="13,52,14,25" concept="3" />
<node id="3201523885428189419" at="14,25,15,20" concept="3" />
<node id="3201523885428189426" at="15,20,16,115" concept="3" />
<node id="3201523885428189431" at="16,115,17,115" concept="3" />
<node id="3201523885428189419" at="12,0,19,0" concept="2" trace="TouchBarDefault_shift_move_ActionGroup#(Ljetbrains/mps/workbench/action/ApplicationPlugin;)V" />
<scope id="3201523885428189419" at="12,85,17,115" />
<scope id="3201523885428189419" at="12,0,19,0">
<var name="plugin" id="3201523885428189419" />
</scope>
<unit id="3201523885428189419" at="9,0,20,0" name="jetbrains.mps.ide.refactoring.plugin.TouchBarDefault_shift_move_ActionGroup" />
</file>
</root>
<root nodeRef="r:97d6b60a-b381-42e8-9ea4-402ec93eaf11(jetbrains.mps.ide.refactoring.plugin)/3237050918235387019">
<file name="MoveModelDialog.java">
<node id="5284818426851376380" at="14,108,15,62" concept="14" />
<node id="5284818426851283307" at="17,67,18,142" concept="8" />
<node id="5284818426851121851" at="18,142,19,68" concept="3" />
<node id="5284818426851121860" at="19,68,20,96" concept="3" />
<node id="5284818426851293314" at="20,96,21,18" concept="9" />
<node id="4507335185602817723" at="25,45,26,32" concept="9" />
<node id="7124265151436810514" at="29,32,30,42" concept="9" />
<node id="6253192823645564985" at="14,0,17,0" concept="2" trace="MoveModelDialog#(Ljetbrains/mps/project/MPSProject;Ljava/lang/String;Ljava/lang/Iterable;)V" />
<node id="7124265151436804223" at="28,0,32,0" concept="7" trace="getHelpId#()Ljava/lang/String;" />
<node id="4507335185602817717" at="23,0,28,0" concept="7" trace="getDimensionServiceKey#()Ljava/lang/String;" />
<node id="5284818426851253399" at="17,0,23,0" concept="7" trace="createChooseData#()Ljetbrains/mps/workbench/choose/ChooseByNameData;" />
<scope id="6253192823645564989" at="14,108,15,62" />
<scope id="4507335185602817722" at="25,45,26,32" />
<scope id="7124265151436804229" at="29,32,30,42" />
<scope id="6253192823645564985" at="14,0,17,0">
<var name="modules" id="909541774322468653" />
<var name="mpsProject" id="6253192823645564992" />
<var name="title" id="7124265151437105436" />
</scope>
<scope id="5284818426851253403" at="17,67,21,18">
<var name="result" id="5284818426851283308" />
</scope>
<scope id="7124265151436804223" at="28,0,32,0" />
<scope id="4507335185602817717" at="23,0,28,0" />
<scope id="5284818426851253399" at="17,0,23,0" />
<unit id="3237050918235387019" at="13,0,33,0" name="jetbrains.mps.ide.refactoring.plugin.MoveModelDialog" />
</file>
</root>
<root nodeRef="r:97d6b60a-b381-42e8-9ea4-402ec93eaf11(jetbrains.mps.ide.refactoring.plugin)/4448668666024728349">
<file name="MoveModelActionExecutor.java">
<node id="4448668666025045983" at="38,0,39,0" concept="4" trace="myDialogSettingsFactory" />
<node id="4448668666025060619" at="39,0,40,0" concept="4" trace="myOriginalModel" />
<node id="4448668666025060817" at="41,76,42,83" concept="15" />
<node id="4448668666025060836" at="45,130,46,19" concept="14" />
<node id="4448668666025060839" at="46,19,47,36" concept="3" />
<node id="4448668666025060843" at="47,36,48,52" concept="3" />
<node id="4448668666025121378" at="52,42,53,100" concept="8" />
<node id="4448668666025121391" at="56,99,57,81" concept="3" />
<node id="4448668666025121416" at="60,7,61,117" concept="8" />
<node id="4448668666025121427" at="62,33,63,18" concept="9" />
<node id="4448668666025120882" at="64,5,65,0" concept="11" />
<node id="4448668666025113744" at="67,32,68,65" concept="9" />
<node id="4448668666025155592" at="75,53,76,84" concept="8" />
<node id="4448668666025816101" at="76,84,77,0" concept="11" />
<node id="4448668666025155810" at="77,0,78,156" concept="3" />
<node id="4448668666025805086" at="78,156,79,0" concept="11" />
<node id="4448668666025808448" at="79,0,80,41" concept="9" />
<node id="4448668666025062210" at="84,104,85,122" concept="9" />
<node id="4448668666025062223" at="88,62,89,49" concept="9" />
<node id="4448668666025062242" at="92,78,93,76" concept="9" />
<node id="4141424609793694411" at="96,36,97,57" concept="9" />
<node id="4448668666025472068" at="101,0,102,0" concept="4" trace="myParticipants" />
<node id="4448668666025662734" at="102,0,103,0" concept="4" trace="myModule" />
<node id="4448668666025436282" at="103,0,104,0" concept="4" trace="myNewModel" />
<node id="4448668666025676229" at="105,53,106,24" concept="3" />
<node id="4448668666025466328" at="109,40,110,24" concept="9" />
<node id="4448668666025484608" at="113,107,114,28" concept="9" />
<node id="4448668666025436277" at="117,45,118,85" concept="9" />
<node id="4448668666025436290" at="121,38,122,124" concept="8" />
<node id="4448668666025436299" at="122,124,123,20" concept="3" />
<node id="4448668666025436303" at="123,20,124,106" concept="3" />
<node id="4448668666025436334" at="128,31,129,15" concept="9" />
<node id="4448668666025436338" at="130,7,131,0" concept="11" />
<node id="7208221877951487735" at="132,61,133,177" concept="8" />
<node id="4448668666025436341" at="133,177,134,176" concept="8" />
<node id="4448668666025436356" at="135,205,136,88" concept="8" />
<node id="4448668666025436371" at="137,110,138,107" concept="3" />
<node id="4448668666025436404" at="141,7,142,134" concept="3" />
<node id="4448668666025436411" at="142,134,143,83" concept="3" />
<node id="4448668666025436428" at="146,57,147,24" concept="9" />
<node id="4448668666025436434" at="150,29,151,20" concept="10" />
<node id="4448668666025611775" at="154,41,155,24" concept="9" />
<node id="4448668666025436306" at="159,36,160,61" concept="9" />
<node id="4448668666025436306" at="161,5,162,16" concept="9" />
<node id="4448668666025436307" at="165,36,166,63" concept="9" />
<node id="4448668666025436307" at="167,5,168,16" concept="9" />
<node id="4448668666025060807" at="41,0,44,0" concept="2" trace="MoveModelActionExecutor#(Ljetbrains/mps/project/MPSProject;Lorg/jetbrains/mps/openapi/model/SModel;)V" />
<node id="4448668666025121388" at="55,25,58,9" concept="5" />
<node id="4448668666025121425" at="61,117,64,5" concept="6" />
<node id="4448668666025113742" at="67,0,70,0" concept="7" trace="compute#()Lorg/jetbrains/mps/openapi/module/SModule;" />
<node id="4448668666025062208" at="84,0,87,0" concept="13" trace="getDefaultSettingsFactoryForMoved#(Lorg/jetbrains/mps/openapi/model/SModel;)Ljetbrains/mps/ide/dialogs/project/creation/NewModelDialogSettings/Factory;" />
<node id="4448668666025062221" at="88,0,91,0" concept="13" trace="getNameForMoved#(Lorg/jetbrains/mps/openapi/model/SModel;)Ljava/lang/String;" />
<node id="4448668666025062240" at="92,0,95,0" concept="13" trace="getStereotypeForMoved#(Lorg/jetbrains/mps/openapi/model/SModel;)Ljetbrains/mps/ide/ui/tree/module/StereotypeProvider;" />
<node id="4141424609793686151" at="96,0,99,0" concept="13" trace="getTitle#()Ljava/lang/String;" />
<node id="4448668666025676221" at="105,0,108,0" concept="2" trace="MoveModelRefactoringBody#(Lorg/jetbrains/mps/openapi/module/SModule;)V" />
<node id="4448668666025436254" at="109,0,112,0" concept="7" trace="getRefactoringName#()Ljava/lang/String;" />
<node id="4448668666025436260" at="113,0,116,0" concept="7" trace="getAllAvailableParticipants#()Ljava/lang/Iterable;" />
<node id="4448668666025436272" at="117,0,120,0" concept="7" trace="findInitialStates#()Ljava/util/List;" />
<node id="4448668666025436332" at="127,176,130,7" concept="6" />
<node id="4448668666025436369" at="136,88,139,11" concept="6" />
<node id="4448668666025436422" at="146,0,149,0" concept="7" trace="getFinalStateFor#(Lorg/jetbrains/mps/openapi/model/SModel;)Lorg/jetbrains/mps/openapi/model/SModel;" />
<node id="4448668666025436430" at="150,0,153,0" concept="7" trace="doCleanup#()V" />
<node id="4448668666025583245" at="154,0,157,0" concept="7" trace="getNewModel#()Lorg/jetbrains/mps/openapi/model/EditableSModel;" />
<node id="4448668666025436306" at="158,91,161,5" concept="6" />
<node id="4448668666025436307" at="164,119,167,5" concept="6" />
<node id="4448668666025060824" at="45,0,50,0" concept="2" trace="MoveModelActionExecutor#(Ljetbrains/mps/project/MPSProject;Lorg/jetbrains/mps/openapi/model/SModel;Ljetbrains/mps/ide/dialogs/project/creation/NewModelDialogSettings/Factory;)V" />
<node id="4448668666025121386" at="55,0,60,0" concept="7" trace="run#()V" />
<node id="4448668666025113739" at="65,0,70,7" concept="9" />
<node id="4448668666025436286" at="121,0,126,0" concept="7" trace="prepareRefactoring#()V" />
<node id="4448668666025436353" at="134,176,140,9" concept="5" />
<node id="4448668666025436306" at="158,0,164,0" concept="13" trace="check_lf1t34_a0c0m22#(Ljetbrains/mps/ide/dialogs/project/creation/ModelCreateHelper;)Lorg/jetbrains/mps/openapi/model/EditableSModel;" />
<node id="4448668666025436307" at="164,0,170,0" concept="13" trace="check_lf1t34_a0a2a21w#(Ljetbrains/mps/ide/dialogs/project/creation/ModelCreateHelper;Lorg/jetbrains/mps/openapi/model/SModel;)Ljetbrains/mps/ide/dialogs/project/creation/ModelCreateHelper;" />
<node id="4448668666025121385" at="53,100,60,7" concept="3" />
<node id="4448668666025152019" at="74,0,82,0" concept="7" trace="showDialog#(Lorg/jetbrains/mps/openapi/module/SModule;)Lorg/jetbrains/mps/openapi/model/SModel;" />
<node id="4448668666025436339" at="131,0,141,7" concept="6" />
<node id="4448668666025436317" at="127,0,145,0" concept="7" trace="doRefactor#(Ljava/lang/Iterable;Ljetbrains/mps/refactoring/participant/RefactoringSession;)V" />
<node id="4448668666025113735" at="51,0,72,0" concept="7" trace="selectModule#()Lorg/jetbrains/mps/openapi/module/SModule;" />
<scope id="4448668666025060816" at="41,76,42,83" />
<scope id="4448668666025121390" at="56,99,57,81" />
<scope id="4448668666025121426" at="62,33,63,18" />
<scope id="4448668666025113743" at="67,32,68,65" />
<scope id="4448668666025062209" at="84,104,85,122" />
<scope id="4448668666025062222" at="88,62,89,49" />
<scope id="4448668666025062241" at="92,78,93,76" />
<scope id="4141424609793686154" at="96,36,97,57" />
<scope id="4448668666025676225" at="105,53,106,24" />
<scope id="4448668666025436257" at="109,40,110,24" />
<scope id="4448668666025436269" at="113,107,114,28" />
<scope id="4448668666025436276" at="117,45,118,85" />
<scope id="4448668666025436333" at="128,31,129,15" />
<scope id="4448668666025436370" at="137,110,138,107" />
<scope id="4448668666025436427" at="146,57,147,24" />
<scope id="4448668666025436433" at="150,29,151,20" />
<scope id="4448668666025583248" at="154,41,155,24" />
<scope id="4448668666025436306" at="159,36,160,61" />
<scope id="4448668666025436307" at="165,36,166,63" />
<scope id="4448668666025060807" at="41,0,44,0">
<var name="originalModel" id="4448668666025060812" />
<var name="project" id="4448668666025060810" />
</scope>
<scope id="4448668666025060835" at="45,130,48,52" />
<scope id="4448668666025121387" at="55,25,58,9" />
<scope id="4448668666025121388" at="55,25,58,9">
<var name="module" id="4448668666025121389" />
</scope>
<scope id="4448668666025113742" at="67,0,70,0" />
<scope id="4448668666025062208" at="84,0,87,0">
<var name="originalModel" id="4448668666025062218" />
</scope>
<scope id="4448668666025062221" at="88,0,91,0">
<var name="originalModel" id="4448668666025062237" />
</scope>
<scope id="4448668666025062240" at="92,0,95,0">
<var name="model" id="4448668666025062268" />
</scope>
<scope id="4141424609793686151" at="96,0,99,0" />
<scope id="4448668666025676221" at="105,0,108,0">
<var name="module" id="4448668666025676228" />
</scope>
<scope id="4448668666025436254" at="109,0,112,0" />
<scope id="4448668666025436260" at="113,0,116,0" />
<scope id="4448668666025436272" at="117,0,120,0" />
<scope id="4448668666025436289" at="121,38,124,106">
<var name="dialog" id="4448668666025436291" />
</scope>
<scope id="4448668666025436422" at="146,0,149,0">
<var name="initialState" id="4448668666025436423" />
</scope>
<scope id="4448668666025436430" at="150,0,153,0" />
<scope id="4448668666025583245" at="154,0,157,0" />
<scope id="4448668666025436355" at="135,205,139,11">
<var name="depModule" id="4448668666025436357" />
</scope>
<scope id="4448668666025436306" at="158,91,162,16" />
<scope id="4448668666025436307" at="164,119,168,16" />
<scope id="4448668666025060824" at="45,0,50,0">
<var name="dialogSettingsFactory" id="4448668666025060831" />
<var name="originalModel" id="4448668666025060829" />
<var name="project" id="4448668666025060827" />
</scope>
<scope id="4448668666025121386" at="55,0,60,0" />
<scope id="4448668666025152028" at="75,53,80,41">
<var name="refactoringBody" id="4448668666025155593" />
</scope>
<scope id="4448668666025436286" at="121,0,126,0" />
<scope id="4448668666025436353" at="134,176,140,9">
<var name="dependency" id="4448668666025436354" />
</scope>
<scope id="4448668666025436306" at="158,0,164,0">
<var name="checkedDotOperand" id="4448668666025436306" />
</scope>
<scope id="4448668666025436307" at="164,0,170,0">
<var name="checkedDotOperand" id="4448668666025436307" />
<var name="myOriginalModel" id="4448668666025513055" />
</scope>
<scope id="4448668666025152019" at="74,0,82,0">
<var name="module" id="4448668666025152020" />
</scope>
<scope id="4448668666025436340" at="132,61,140,9">
<var name="exisingModuleDependencies" id="4448668666025436342" />
<var name="oldModuleDependencies" id="7208221877951487736" />
</scope>
<scope id="4448668666025436331" at="127,176,143,83" />
<scope id="4448668666025113738" at="52,42,70,7">
<var name="modules" id="4448668666025121379" />
<var name="selectedModule" id="4448668666025121417" />
</scope>
<scope id="4448668666025436317" at="127,0,145,0">
<var name="participantStates" id="4448668666025436318" />
<var name="refactoringSession" id="4448668666025436327" />
</scope>
<scope id="4448668666025113735" at="51,0,72,0" />
<unit id="4448668666025113742" at="66,79,70,5" name="jetbrains.mps.ide.refactoring.plugin.MoveModelActionExecutor$2" />
<unit id="4448668666025121386" at="54,65,60,5" name="jetbrains.mps.ide.refactoring.plugin.MoveModelActionExecutor$1" />
<unit id="4448668666025419157" at="100,0,158,0" name="jetbrains.mps.ide.refactoring.plugin.MoveModelActionExecutor$MoveModelRefactoringBody" />
<unit id="4448668666024728349" at="36,0,171,0" name="jetbrains.mps.ide.refactoring.plugin.MoveModelActionExecutor" />
</file>
</root>
<root nodeRef="r:97d6b60a-b381-42e8-9ea4-402ec93eaf11(jetbrains.mps.ide.refactoring.plugin)/8047970061511569310">
<file name="MoveModel_Action.java">
<node id="8047970061511569310" at="21,0,22,0" concept="12" trace="ICON" />
<node id="8047970061511569310" at="23,29,24,34" concept="14" />
<node id="8047970061511569310" at="24,34,25,35" concept="3" />
<node id="8047970061511569310" at="25,35,26,40" concept="3" />
<node id="8047970061511569310" at="29,32,30,16" concept="9" />
<node id="7110462768345143751" at="33,89,34,56" concept="8" />
<node id="7110462768345174603" at="34,56,35,0" concept="11" />
<node id="7110462768345141938" at="35,0,36,284" concept="3" />
<node id="7110462768345174886" at="36,284,37,0" concept="11" />
<node id="7110462768345175762" at="37,0,38,72" concept="3" />
<node id="8047970061511569310" at="42,53,43,19" concept="9" />
<node id="8047970061512627759" at="45,5,46,56" concept="8" />
<node id="8047970061512627759" at="46,56,47,51" concept="3" />
<node id="8047970061512627760" at="48,22,49,21" concept="9" />
<node id="7011458479952017092" at="51,61,52,21" concept="9" />
<node id="8047970061511569380" at="55,5,56,66" concept="8" />
<node id="8047970061511569380" at="56,66,57,53" concept="3" />
<node id="8047970061511569381" at="58,22,59,21" concept="9" />
<node id="8047970061512627763" at="62,5,63,71" concept="8" />
<node id="8047970061512627763" at="63,71,64,53" concept="3" />
<node id="8047970061512627764" at="65,22,66,21" concept="9" />
<node id="8047970061511569310" at="68,5,69,16" concept="9" />
<node id="4448668666025936371" at="72,96,73,57" concept="3" />
<node id="4448668666025890028" at="75,84,76,153" concept="9" />
<node id="8047970061511569310" at="41,95,44,5" concept="6" />
<node id="8047970061512627760" at="47,51,50,7" concept="6" />
<node id="7011458479952017092" at="50,7,53,7" concept="6" />
<node id="8047970061511569381" at="57,53,60,7" concept="6" />
<node id="8047970061512627764" at="64,53,67,7" concept="6" />
<node id="4448668666025874915" at="75,0,78,0" concept="7" trace="getExecutor#(Ljava/util/Map;)Ljetbrains/mps/ide/refactoring/plugin/MoveModelActionExecutor;" />
<node id="8047970061511569310" at="28,0,32,0" concept="7" trace="isDumbAware#()Z" />
<node id="8047970061511569310" at="71,0,75,0" concept="7" trace="doExecute#(Lcom/intellij/openapi/actionSystem/AnActionEvent;Ljava/util/Map;)V" />
<node id="8047970061511569310" at="23,0,28,0" concept="2" trace="MoveModel_Action#()V" />
<node id="8047970061511569380" at="54,5,61,5" concept="1" />
<node id="8047970061512627763" at="61,5,68,5" concept="1" />
<node id="8047970061511569310" at="32,0,40,0" concept="7" trace="doUpdate#(Lcom/intellij/openapi/actionSystem/AnActionEvent;Ljava/util/Map;)V" />
<node id="8047970061512627759" at="44,5,54,5" concept="1" />
<node id="8047970061511569310" at="40,0,71,0" concept="7" trace="collectActionData#(Lcom/intellij/openapi/actionSystem/AnActionEvent;Ljava/util/Map;)Z" />
<scope id="8047970061511569310" at="29,32,30,16" />
<scope id="8047970061511569310" at="42,53,43,19" />
<scope id="8047970061512627760" at="48,22,49,21" />
<scope id="7011458479952017092" at="51,61,52,21" />
<scope id="8047970061511569381" at="58,22,59,21" />
<scope id="8047970061512627764" at="65,22,66,21" />
<scope id="8047970061511569310" at="72,96,73,57" />
<scope id="4448668666025874917" at="75,84,76,153" />
<scope id="8047970061511569310" at="23,29,26,40" />
<scope id="4448668666025874915" at="75,0,78,0">
<var name="_params" id="4448668666025874915" />
</scope>
<scope id="8047970061511569310" at="28,0,32,0" />
<scope id="8047970061511569310" at="71,0,75,0">
<var name="_params" id="8047970061511569310" />
<var name="event" id="8047970061511569310" />
</scope>
<scope id="8047970061511569310" at="23,0,28,0" />
<scope id="7110462768345139368" at="33,89,38,72">
<var name="presentation" id="7110462768345143752" />
</scope>
<scope id="8047970061511569380" at="55,5,60,7">
<var name="p" id="8047970061511569380" />
</scope>
<scope id="8047970061512627763" at="62,5,67,7">
<var name="p" id="8047970061512627763" />
</scope>
<scope id="8047970061511569310" at="32,0,40,0">
<var name="_params" id="8047970061511569310" />
<var name="event" id="8047970061511569310" />
</scope>
<scope id="8047970061512627759" at="45,5,53,7">
<var name="p" id="8047970061512627759" />
</scope>
<scope id="8047970061511569310" at="41,95,69,16" />
<scope id="8047970061511569310" at="40,0,71,0">
<var name="_params" id="8047970061511569310" />
<var name="event" id="8047970061511569310" />
</scope>
<unit id="8047970061511569310" at="20,0,79,0" name="jetbrains.mps.ide.refactoring.plugin.MoveModel_Action" />
</file>
<file name="Refactoring_ApplicationPlugin.java">
<node id="8047970061511569310" at="27,30,28,38" concept="3" />
</file>
</root>
<root nodeRef="r:97d6b60a-b381-42e8-9ea4-402ec93eaf11(jetbrains.mps.ide.refactoring.plugin)/830211401282058525">
<file name="MoveNodes_Action.java">
<node id="830211401282058525" at="28,0,29,0" concept="12" trace="ICON" />
<node id="830211401282058525" at="30,29,31,34" concept="14" />
<node id="830211401282058525" at="31,34,32,35" concept="3" />
<node id="830211401282058525" at="32,35,33,40" concept="3" />
<node id="830211401282058525" at="36,32,37,16" concept="9" />
<node id="8451255343455509707" at="42,41,43,249" concept="9" />
<node id="8451255343455520935" at="45,9,46,48" concept="3" />
<node id="8451255343455521261" at="46,48,47,13" concept="9" />
<node id="1929018697515884390" at="49,177,50,198" concept="8" />
<node id="1929018697515884954" at="50,198,51,61" concept="3" />
<node id="3396928246103286372" at="51,61,52,47" concept="3" />
<node id="7217668918195409420" at="53,12,54,48" concept="3" />
<node id="830211401282058525" at="59,53,60,19" concept="9" />
<node id="830211401282058526" at="62,5,63,65" concept="8" />
<node id="830211401282058526" at="64,26,65,62" concept="3" />
<node id="830211401282058526" at="66,14,67,120" concept="3" />
<node id="830211401282058529" at="69,26,70,21" concept="9" />
<node id="830211401282058529" at="72,28,73,21" concept="9" />
<node id="830211401282058526" at="74,7,75,0" concept="11" />
<node id="830211401282058530" at="77,5,78,66" concept="8" />
<node id="830211401282058530" at="78,66,79,53" concept="3" />
<node id="830211401282058531" at="80,22,81,21" concept="9" />
<node id="3207605520775490518" at="84,5,85,90" concept="8" />
<node id="3207605520775490518" at="86,67,87,31" concept="3" />
<node id="3207605520775490518" at="88,7,89,75" concept="3" />
<node id="830211401282058525" at="90,5,91,16" concept="9" />
<node id="1929018697515858043" at="94,96,95,299" concept="3" />
<node id="7217668918195409218" at="53,10,55,5" concept="1" />
<node id="830211401282058526" at="66,12,68,7" concept="1" />
<node id="8451255343455508601" at="42,0,45,0" concept="7" trace="accept#(Lorg/jetbrains/mps/openapi/model/SNode;)Z" />
<node id="830211401282058525" at="58,95,61,5" concept="6" />
<node id="830211401282058529" at="68,7,71,7" concept="6" />
<node id="830211401282058529" at="71,7,74,7" concept="6" />
<node id="830211401282058531" at="79,53,82,7" concept="6" />
<node id="3207605520775490518" at="85,90,88,7" concept="6" />
<node id="830211401282058525" at="35,0,39,0" concept="7" trace="isDumbAware#()Z" />
<node id="830211401282058525" at="93,0,97,0" concept="7" trace="doExecute#(Lcom/intellij/openapi/actionSystem/AnActionEvent;Ljava/util/Map;)V" />
<node id="830211401282058525" at="30,0,35,0" concept="2" trace="MoveNodes_Action#()V" />
<node id="830211401282058526" at="63,65,68,7" concept="6" />
<node id="7217668918195405500" at="48,5,55,5" concept="6" />
<node id="830211401282058530" at="76,5,83,5" concept="1" />
<node id="3207605520775490518" at="83,5,90,5" concept="1" />
<node id="8451255343455518243" at="40,89,48,5" concept="6" />
<node id="830211401282058526" at="61,5,76,5" concept="1" />
<node id="830211401282058525" at="39,0,57,0" concept="7" trace="doUpdate#(Lcom/intellij/openapi/actionSystem/AnActionEvent;Ljava/util/Map;)V" />
<node id="830211401282058525" at="57,0,93,0" concept="7" trace="collectActionData#(Lcom/intellij/openapi/actionSystem/AnActionEvent;Ljava/util/Map;)Z" />
<scope id="830211401282058525" at="36,32,37,16" />
<scope id="8451255343455508602" at="42,41,43,249" />
<scope id="7217668918195409219" at="53,12,54,48" />
<scope id="830211401282058525" at="59,53,60,19" />
<scope id="830211401282058526" at="64,26,65,62" />
<scope id="830211401282058526" at="66,14,67,120" />
<scope id="830211401282058529" at="69,26,70,21" />
<scope id="830211401282058529" at="72,28,73,21" />
<scope id="830211401282058531" at="80,22,81,21" />
<scope id="3207605520775490518" at="86,67,87,31" />
<scope id="830211401282058525" at="94,96,95,299" />
<scope id="8451255343455518245" at="45,9,47,13" />
<scope id="830211401282058525" at="30,29,33,40" />
<scope id="8451255343455508601" at="42,0,45,0">
<var name="node" id="8451255343455508601" />
</scope>
<scope id="7217668918195405502" at="49,177,52,47">
<var name="refactoring" id="1929018697515884391" />
</scope>
<scope id="830211401282058525" at="35,0,39,0" />
<scope id="830211401282058525" at="93,0,97,0">
<var name="_params" id="830211401282058525" />
<var name="event" id="830211401282058525" />
</scope>
<scope id="830211401282058525" at="30,0,35,0" />
<scope id="830211401282058530" at="77,5,82,7">
<var name="p" id="830211401282058530" />
</scope>
<scope id="3207605520775490518" at="84,5,89,75">
<var name="editorComponent" id="3207605520775490518" />
</scope>
<scope id="830211401282058526" at="62,5,75,0">
<var name="nodes" id="830211401282058526" />
</scope>
<scope id="3396928246103147349" at="40,89,55,5" />
<scope id="830211401282058525" at="39,0,57,0">
<var name="_params" id="830211401282058525" />
<var name="event" id="830211401282058525" />
</scope>
<scope id="830211401282058525" at="58,95,91,16" />
<scope id="830211401282058525" at="57,0,93,0">
<var name="_params" id="830211401282058525" />
<var name="event" id="830211401282058525" />
</scope>
<unit id="8451255343455508601" at="41,186,45,5" name="jetbrains.mps.ide.refactoring.plugin.MoveNodes_Action$1" />
<unit id="830211401282058525" at="27,0,98,0" name="jetbrains.mps.ide.refactoring.plugin.MoveNodes_Action" />
</file>
<file name="Refactoring_ApplicationPlugin.java">
<node id="830211401282058525" at="28,38,29,38" concept="3" />
</file>
</root>
<root nodeRef="r:97d6b60a-b381-42e8-9ea4-402ec93eaf11(jetbrains.mps.ide.refactoring.plugin)/8406474294175974068">
<file name="Refactoring_ApplicationPlugin.java">
<node id="8406474294175974068" at="16,0,17,0" concept="4" trace="myId" />
<node id="8406474294175974068" at="22,27,23,16" concept="9" />
<node id="8406474294175974068" at="26,30,27,30" concept="10" />
<node id="8406474294175974068" at="30,39,31,14" concept="10" />
<node id="8406474294175974068" at="43,48,44,92" concept="8" />
<node id="8406474294175974068" at="45,71,46,15" concept="9" />
<node id="8406474294175974068" at="18,0,20,0" concept="2" trace="Refactoring_ApplicationPlugin#()V" />
<node id="8406474294175974068" at="21,0,25,0" concept="7" trace="getId#()Lcom/intellij/openapi/extensions/PluginId;" />
<node id="8406474294175974068" at="43,0,48,0" concept="7" trace="initKeymaps#()Ljava/util/List;" />
<node id="8406474294175974068" at="37,0,43,0" concept="7" trace="adjustRegularGroups#()V" />
<node id="8406474294175974068" at="26,0,37,0" concept="7" trace="createGroups#()V" />
<scope id="8406474294175974068" at="18,42,18,42" />
<scope id="8406474294175974068" at="22,27,23,16" />
<scope id="8406474294175974068" at="18,0,20,0" />
<scope id="8406474294175974068" at="43,48,46,15">
<var name="res" id="8406474294175974068" />
</scope>
<scope id="8406474294175974068" at="21,0,25,0" />
<scope id="8406474294175974068" at="37,37,41,136" />
<scope id="8406474294175974068" at="43,0,48,0" />
<scope id="8406474294175974068" at="37,0,43,0" />
<scope id="8406474294175974068" at="26,30,35,65" />
<scope id="8406474294175974068" at="26,0,37,0" />
<unit id="8406474294175974068" at="15,0,49,0" name="jetbrains.mps.ide.refactoring.plugin.Refactoring_ApplicationPlugin" />
</file>
</root>
<root nodeRef="r:97d6b60a-b381-42e8-9ea4-402ec93eaf11(jetbrains.mps.ide.refactoring.plugin)/8784230320738943351">
<file name="CoreNodeRefactorings_ActionGroup.java">
<node id="8784230320738943351" at="10,0,11,0" concept="12" trace="ID" />
<node id="8784230320738943351" at="12,79,13,46" concept="14" />
<node id="8784230320738943351" at="13,46,14,25" concept="3" />
<node id="8784230320738943351" at="14,25,15,20" concept="3" />
<node id="8784230320738943429" at="15,20,16,110" concept="3" />
<node id="5300313260161721910" at="16,110,17,109" concept="3" />
<node id="8784230320738943351" at="12,0,19,0" concept="2" trace="CoreNodeRefactorings_ActionGroup#(Ljetbrains/mps/workbench/action/ApplicationPlugin;)V" />
<scope id="8784230320738943351" at="12,79,17,109" />
<scope id="8784230320738943351" at="12,0,19,0">
<var name="plugin" id="8784230320738943351" />
</scope>
<unit id="8784230320738943351" at="9,0,20,0" name="jetbrains.mps.ide.refactoring.plugin.CoreNodeRefactorings_ActionGroup" />
</file>
<file name="Refactoring_ApplicationPlugin.java">
<node id="8784230320738943351" at="31,14,32,57" concept="3" />
<node id="8784230320738944343" at="40,157,41,136" concept="3" />
</file>
</root>
<root nodeRef="r:97d6b60a-b381-42e8-9ea4-402ec93eaf11(jetbrains.mps.ide.refactoring.plugin)/8784230320738943353">
<file name="Refactoring_ApplicationPlugin.java">
<node id="8784230320738943353" at="29,38,30,39" concept="3" />
</file>
<file name="RenameNode_Action.java">
<node id="8784230320738943353" at="38,0,39,0" concept="12" trace="LOG" />
<node id="8784230320738943353" at="39,0,40,0" concept="12" trace="ICON" />
<node id="8784230320738943353" at="41,30,42,30" concept="14" />
<node id="8784230320738943353" at="42,30,43,35" concept="3" />
<node id="8784230320738943353" at="43,35,44,40" concept="3" />
<node id="8784230320738943353" at="47,32,48,16" concept="9" />
<node id="8784230320738943419" at="51,87,52,157" concept="9" />
<node id="8784230320738943353" at="55,89,56,85" concept="3" />
<node id="8784230320738943353" at="60,53,61,19" concept="9" />
<node id="8784230320738943354" at="63,5,64,57" concept="8" />
<node id="8784230320738943354" at="65,93,66,20" concept="3" />
<node id="8784230320738943354" at="67,7,68,55" concept="3" />
<node id="8784230320738943357" at="69,25,70,21" concept="9" />
<node id="8784230320738943358" at="73,5,74,66" concept="8" />
<node id="8784230320738943358" at="74,66,75,53" concept="3" />
<node id="8784230320738943359" at="76,22,77,21" concept="9" />
<node id="8784230320738943360" at="80,5,81,55" concept="8" />
<node id="8784230320738943360" at="81,55,82,51" concept="3" />
<node id="8784230320738943361" at="83,22,84,21" concept="9" />
<node id="8784230320738943353" at="86,5,87,16" concept="9" />
<node id="1744445256079578769" at="90,96,91,79" concept="3" />
<node id="5049109624533344526" at="91,79,92,0" concept="11" />
<node id="8139782154295720561" at="92,0,93,66" concept="8" />
<node id="8139782154295720536" at="93,66,94,67" concept="8" />
<node id="8139782154295720554" at="96,25,97,74" concept="3" />
<node id="8139782154295720565" at="97,74,98,125" concept="3" />
<node id="8784230320738943373" at="101,32,102,227" concept="3" />
<node id="8784230320738943381" at="102,227,103,13" concept="9" />
<node id="78629976131166978" at="109,82,110,36" concept="9" />
<node id="78629976131155675" at="111,9,112,34" concept="9" />
<node id="78629976131102610" at="114,6,115,18" concept="3" />
<node id="78629976131102627" at="115,18,116,51" concept="8" />
<node id="78629976131121304" at="116,51,117,0" concept="11" />
<node id="8784230320738943405" at="118,26,119,13" concept="9" />
<node id="3846646991041474831" at="120,5,121,223" concept="8" />
<node id="8193174057328069111" at="121,223,122,231" concept="3" />
<node id="8784230320738948502" at="124,67,125,71" concept="10" />
<node id="2546796854245076454" at="125,71,126,112" concept="8" />
<node id="885736485116251747" at="126,112,127,95" concept="8" />
<node id="1782978073203079389" at="127,95,128,87" concept="8" />
<node id="3818729150937331795" at="130,42,131,107" concept="3" />
<node id="885736485116253659" at="132,7,133,19" concept="9" />
<node id="885736485116253661" at="134,5,135,46" concept="9" />
<node id="78629976130903540" at="137,85,138,112" concept="8" />
<node id="78629976130903320" at="138,112,139,95" concept="8" />
<node id="78629976130903327" at="139,95,140,88" concept="8" />
<node id="78629976130904464" at="140,88,141,115" concept="9" />
<node id="8784230320738943353" at="145,0,146,0" concept="12" trace="INamedConcept$Kd" />
<node id="8784230320738943353" at="149,0,150,0" concept="12" trace="name$MnvL" />
<node id="8784230320738943353" at="59,95,62,5" concept="6" />
<node id="8784230320738943354" at="64,57,67,7" concept="6" />
<node id="8784230320738943357" at="68,55,71,7" concept="6" />
<node id="8784230320738943359" at="75,53,78,7" concept="6" />
<node id="8784230320738943361" at="82,51,85,7" concept="6" />
<node id="78629976131153026" at="108,37,111,9" concept="6" />
<node id="8784230320738943403" at="117,0,120,5" concept="6" />
<node id="3818729150937331795" at="129,37,132,7" concept="6" />
<node id="8784230320738943353" at="46,0,50,0" concept="7" trace="isDumbAware#()Z" />
<node id="8784230320738943353" at="50,0,54,0" concept="7" trace="isApplicable#(Lcom/intellij/openapi/actionSystem/AnActionEvent;Ljava/util/Map;)Z" />
<node id="8784230320738943353" at="54,0,58,0" concept="7" trace="doUpdate#(Lcom/intellij/openapi/actionSystem/AnActionEvent;Ljava/util/Map;)V" />
<node id="8193174057324768547" at="96,0,100,0" concept="7" trace="run#()V" />
<node id="8784230320738943371" at="100,7,104,5" concept="6" />
<node id="8784230320738943353" at="41,0,46,0" concept="2" trace="RenameNode_Action#()V" />
<node id="8193174057324768545" at="94,67,100,7" concept="3" />
<node id="885736485116253648" at="128,87,134,5" concept="6" />
<node id="78629976130901182" at="137,0,143,0" concept="7" trace="validateValue#(Ljava/lang/String;Ljava/util/Map;)Z" />
<node id="8784230320738943358" at="72,5,79,5" concept="1" />
<node id="8784230320738943360" at="79,5,86,5" concept="1" />
<node id="78629976131124773" at="106,0,114,0" concept="7" trace="checkValue#()Ljava/lang/String;" />
<node id="8784230320738943354" at="62,5,72,5" concept="1" />
<node id="78629976131102602" at="104,5,114,6" concept="8" />
<node id="2176361721956945585" at="124,0,137,0" concept="7" trace="canBeRenamed#(Ljava/util/Map;)Z" />
<node id="8784230320738943353" at="58,0,89,0" concept="7" trace="collectActionData#(Lcom/intellij/openapi/actionSystem/AnActionEvent;Ljava/util/Map;)Z" />
<node id="8784230320738943353" at="89,0,124,0" concept="7" trace="doExecute#(Lcom/intellij/openapi/actionSystem/AnActionEvent;Ljava/util/Map;)V" />
<scope id="8784230320738943353" at="47,32,48,16" />
<scope id="8784230320738943418" at="51,87,52,157" />
<scope id="8784230320738943353" at="55,89,56,85" />
<scope id="8784230320738943353" at="60,53,61,19" />
<scope id="8784230320738943354" at="65,93,66,20" />
<scope id="8784230320738943357" at="69,25,70,21" />
<scope id="8784230320738943359" at="76,22,77,21" />
<scope id="8784230320738943361" at="83,22,84,21" />
<scope id="78629976131162312" at="109,82,110,36" />
<scope id="8784230320738943404" at="118,26,119,13" />
<scope id="3818729150937331795" at="130,42,131,107" />
<scope id="8193174057324768549" at="96,25,98,125" />
<scope id="8784230320738943372" at="101,32,103,13" />
<scope id="8784230320738943353" at="41,30,44,40" />
<scope id="8784230320738943353" at="46,0,50,0" />
<scope id="8784230320738943353" at="50,0,54,0">
<var name="_params" id="8784230320738943353" />
<var name="event" id="8784230320738943353" />
</scope>
<scope id="8784230320738943353" at="54,0,58,0">
<var name="_params" id="8784230320738943353" />
<var name="event" id="8784230320738943353" />
</scope>
<scope id="8193174057324768547" at="96,0,100,0" />
<scope id="78629976131124819" at="108,37,112,34" />
<scope id="885736485116253653" at="129,37,133,19" />
<scope id="78629976130901184" at="137,85,141,115">
<var name="cd" id="78629976130903321" />
<var name="concept" id="78629976130903541" />
<var name="propertyConstraints" id="78629976130903328" />
</scope>
<scope id="8784230320738943353" at="41,0,46,0" />
<scope id="8784230320738943358" at="73,5,78,7">
<var name="p" id="8784230320738943358" />
</scope>
<scope id="8784230320738943360" at="80,5,85,7">
<var name="p" id="8784230320738943360" />
</scope>
<scope id="78629976130901182" at="137,0,143,0">
<var name="_params" id="78629976130901182" />
<var name="newValue" id="78629976130910192" />
</scope>
<scope id="8784230320738943354" at="63,5,71,7">
<var name="node" id="8784230320738943354" />
</scope>
<scope id="78629976131124773" at="106,0,114,0" />
<scope id="2176361721956945587" at="124,67,135,46">
<var name="cd" id="885736485116251748" />
<var name="concept" id="2546796854245076455" />
<var name="propertyConstraint" id="1782978073203079390" />
</scope>
<scope id="2176361721956945585" at="124,0,137,0">
<var name="_params" id="2176361721956945585" />
</scope>
<scope id="8784230320738943353" at="59,95,87,16" />
<scope id="8784230320738943353" at="58,0,89,0">
<var name="_params" id="8784230320738943353" />
<var name="event" id="8784230320738943353" />
</scope>
<scope id="8784230320738943353" at="90,96,122,231">
<var name="canBeRenamed" id="8139782154295720537" />
<var name="dialog" id="78629976131102603" />
<var name="newName" id="78629976131102628" />
<var name="oldName" id="8139782154295720562" />
<var name="refactoringBody" id="3846646991041474832" />
</scope>
<scope id="8784230320738943353" at="89,0,124,0">
<var name="_params" id="8784230320738943353" />
<var name="event" id="8784230320738943353" />
</scope>
<unit id="8784230320738943353" at="144,0,147,0" name="jetbrains.mps.ide.refactoring.plugin.RenameNode_Action$CONCEPTS" />
<unit id="8784230320738943353" at="148,0,151,0" name="jetbrains.mps.ide.refactoring.plugin.RenameNode_Action$PROPS" />
<unit id="8193174057324768547" at="95,114,100,5" name="jetbrains.mps.ide.refactoring.plugin.RenameNode_Action$1" />
<unit id="78629976131124148" at="105,30,114,5" name="jetbrains.mps.ide.refactoring.plugin.RenameNode_Action$2" />
<unit id="8784230320738943353" at="37,0,152,0" name="jetbrains.mps.ide.refactoring.plugin.RenameNode_Action" />
</file>
</root>
</debug-info>
| {
"pile_set_name": "Github"
} |
package com.tencent.ttpic.filter;
import android.graphics.PointF;
import com.tencent.filter.m.g;
import com.tencent.filter.m.n;
import com.tencent.matrix.trace.core.AppMethodBeat;
import com.tencent.ttpic.baseutils.FileUtils;
import com.tencent.ttpic.gles.GlUtil.DRAW_MODE;
import com.tencent.ttpic.util.VideoGlobalContext;
import com.tencent.ttpic.util.VideoMaterialUtil;
import java.util.List;
import java.util.Map;
public class ReshapeCombineFilter extends VideoFilterBase {
public static final String FRAGMENT_SHADER = FileUtils.loadAssetsString(VideoGlobalContext.getContext(), "camera/camera_video/shader/ReshapeCombineFragmentShader.dat");
public static final String VERTEX_SHADER = FileUtils.loadAssetsString(VideoGlobalContext.getContext(), "camera/camera_video/shader/ReshapeCombineVertexShader.dat");
public static final int XCOORD_NUM = 128;
public static final int YCOORD_NUM = 128;
private int eyeMaskTex = 0;
private List<PointF> mFullscreenVerticesPortrait = VideoMaterialUtil.genFullScreenVertices(128, 128, 0.0f, 1.0f, 0.0f, 1.0f);
private List<PointF> mInitTextureCoordinatesPortrait = VideoMaterialUtil.genFullScreenVertices(128, 128, 0.0f, 1.0f, 0.0f, 1.0f);
private float[] positionArray = null;
private float[] size = new float[]{1.0f, 1.0f};
private float[] vectorMapSize = new float[]{1.0f, 1.0f};
static {
AppMethodBeat.i(82752);
AppMethodBeat.o(82752);
}
public ReshapeCombineFilter() {
super(VERTEX_SHADER, FRAGMENT_SHADER);
AppMethodBeat.i(82745);
initParams();
AppMethodBeat.o(82745);
}
public ReshapeCombineFilter(float f, float f2, float f3, float f4) {
super(VERTEX_SHADER, FRAGMENT_SHADER);
AppMethodBeat.i(82746);
this.mFullscreenVerticesPortrait = VideoMaterialUtil.genFullScreenVertices(128, 128, f, f2, f3, f4);
initParams();
AppMethodBeat.o(82746);
}
public void updateSize(float f, float f2, float f3, float f4) {
AppMethodBeat.i(82747);
if (this.positionArray == null) {
this.positionArray = new float[(this.mFullscreenVerticesPortrait.size() * 2)];
}
VideoMaterialUtil.genFullScreenVertices(this.positionArray, 128, 128, f, f2, f3, f4);
setPositions(this.positionArray, false);
AppMethodBeat.o(82747);
}
public void initParams() {
AppMethodBeat.i(82748);
addParam(new n("inputImageTexture2", this.eyeMaskTex, 33986));
addParam(new g("size", this.size));
addParam(new g("vectorMapSize", this.vectorMapSize));
AppMethodBeat.o(82748);
}
public void initAttribParams() {
AppMethodBeat.i(82749);
setPositions(VideoMaterialUtil.toFlatArray((PointF[]) this.mFullscreenVerticesPortrait.toArray(new PointF[0])), false);
setTexCords(VideoMaterialUtil.toFlatArray((PointF[]) this.mInitTextureCoordinatesPortrait.toArray(new PointF[0])), false);
setCoordNum(32897);
AppMethodBeat.o(82749);
}
public void ApplyGLSLFilter() {
AppMethodBeat.i(82750);
initParams();
super.ApplyGLSLFilter();
setDrawMode(DRAW_MODE.TRIANGLE_STRIP);
AppMethodBeat.o(82750);
}
public void setParam(Map<String, Object> map) {
AppMethodBeat.i(82751);
if (map == null || map.isEmpty()) {
AppMethodBeat.o(82751);
return;
}
if (map.containsKey("inputImageTexture2")) {
this.eyeMaskTex = ((Integer) map.get("inputImageTexture2")).intValue();
}
if (map.containsKey("size")) {
this.size = (float[]) map.get("size");
}
if (map.containsKey("vectorMapSize")) {
this.vectorMapSize = (float[]) map.get("vectorMapSize");
}
initParams();
AppMethodBeat.o(82751);
}
}
| {
"pile_set_name": "Github"
} |
package main
import (
"fmt"
"os"
"path/filepath"
"runtime"
"github.com/Sirupsen/logrus"
"github.com/docker/docker/cli"
cliflags "github.com/docker/docker/cli/flags"
"github.com/docker/docker/daemon/config"
"github.com/docker/docker/dockerversion"
"github.com/docker/docker/pkg/reexec"
"github.com/docker/docker/pkg/term"
"github.com/spf13/cobra"
"github.com/spf13/pflag"
)
type daemonOptions struct {
version bool
configFile string
daemonConfig *config.Config
common *cliflags.CommonOptions
flags *pflag.FlagSet
}
func newDaemonCommand() *cobra.Command {
opts := daemonOptions{
daemonConfig: config.New(),
common: cliflags.NewCommonOptions(),
}
cmd := &cobra.Command{
Use: "dockerd [OPTIONS]",
Short: "A self-sufficient runtime for containers.",
SilenceUsage: true,
SilenceErrors: true,
Args: cli.NoArgs,
RunE: func(cmd *cobra.Command, args []string) error {
opts.flags = cmd.Flags()
return runDaemon(opts)
},
}
cli.SetupRootCommand(cmd)
flags := cmd.Flags()
flags.BoolVarP(&opts.version, "version", "v", false, "Print version information and quit")
flags.StringVar(&opts.configFile, flagDaemonConfigFile, defaultDaemonConfigFile, "Daemon configuration file")
opts.common.InstallFlags(flags)
installConfigFlags(opts.daemonConfig, flags)
installServiceFlags(flags)
return cmd
}
func runDaemon(opts daemonOptions) error {
if opts.version {
showVersion()
return nil
}
daemonCli := NewDaemonCli()
// Windows specific settings as these are not defaulted.
if runtime.GOOS == "windows" {
if opts.daemonConfig.Pidfile == "" {
opts.daemonConfig.Pidfile = filepath.Join(opts.daemonConfig.Root, "docker.pid")
}
if opts.configFile == "" {
opts.configFile = filepath.Join(opts.daemonConfig.Root, `config\daemon.json`)
}
}
// On Windows, this may be launching as a service or with an option to
// register the service.
stop, err := initService(daemonCli)
if err != nil {
logrus.Fatal(err)
}
if stop {
return nil
}
err = daemonCli.start(opts)
notifyShutdown(err)
return err
}
func showVersion() {
fmt.Printf("Docker version %s, build %s\n", dockerversion.Version, dockerversion.GitCommit)
}
func main() {
if reexec.Init() {
return
}
// Set terminal emulation based on platform as required.
_, stdout, stderr := term.StdStreams()
logrus.SetOutput(stderr)
cmd := newDaemonCommand()
cmd.SetOutput(stdout)
if err := cmd.Execute(); err != nil {
fmt.Fprintf(stderr, "%s\n", err)
os.Exit(1)
}
}
| {
"pile_set_name": "Github"
} |
# Copyright 2016 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.
# ==============================================================================
"""TF-Slim grouped API. Please see README.md for details and usage."""
# pylint: disable=unused-import
# Collapse tf-slim into a single namespace.
from inception.slim import inception_model as inception
from inception.slim import models as models
from inception.slim import losses
from inception.slim import ops
from inception.slim import scopes
from inception.slim import variables
from inception.slim.scopes import arg_scope
| {
"pile_set_name": "Github"
} |
.bs-docs-header
.container
h1 Options
.container
table.table.table-bordered.table-striped.table-responsive
thead
tr
th Name
th Attribute
th Type
th Description
th Values
th Default
tbody
tr
td state
td checked
td Boolean
td The checkbox state
td true, false
td true
tr
td size
td data-size
td String
td The checkbox size
td null, 'mini', 'small', 'normal', 'large'
td null
tr
td animate
td data-animate
td Boolean
td Animate the switch
td true, false
td true
tr
td disabled
td disabled
td Boolean
td Disable state
td true, false
td false
tr
td readonly
td readonly
td Boolean
td Readonly state
td true, false
td false
tr
td indeterminate
td data-indeterminate
td Boolean
td Indeterminate state
td true, false
td false
tr
td inverse
td data-inverse
td Boolean
td Inverse switch direction
td true, false
td false
tr
td radioAllOff
td data-radio-all-off
td Boolean
td Allow this radio button to be unchecked by the user
td true, false
td false
tr
td onColor
td data-on-color
td String
td Color of the left side of the switch
td 'primary', 'info', 'success', 'warning', 'danger', 'default'
td 'primary'
tr
td offColor
td data-off-color
td String
td Color of the right side of the switch
td 'primary', 'info', 'success', 'warning', 'danger', 'default'
td 'default'
tr
td onText
td data-on-text
td String
td Text of the left side of the switch
td String
td 'ON'
tr
td offText
td data-off-text
td String
td Text of the right side of the switch
td String
td 'OFF'
tr
td labelText
td data-label-text
td String
td Text of the center handle of the switch
td String
td '&nbsp;'
tr
td handleWidth
td data-handle-width
td String | Number
td Width of the left and right sides in pixels
td 'auto' or Number
td 'auto'
tr
td labelWidth
td data-label-width
td String | Number
td Width of the center handle in pixels
td 'auto' or Number
td 'auto'
tr
td baseClass
td data-base-class
td String
td Global class prefix
td String
td 'bootstrap-switch'
tr
td wrapperClass
td data-wrapper-class
td String | Array
td Container element class(es)
td String | Array
td 'wrapper'
tr
td onInit
td
td Function
td Callback function to execute on initialization
td Function
td: pre: code.javascript function(event, state) {}
tr
td onSwitchChange
td
td Function
td Callback function to execute on switch state change. If false is returned, the status will be reverted, otherwise nothing changes
td Function
td: pre: code.javascript function(event, state) {}
h2 Global Defaults Overriding
p Follow the jQuery convention to override the default options of the library. For instance:
pre
code
| $.fn.bootstrapSwitch.defaults.size = 'large';
| $.fn.bootstrapSwitch.defaults.onColor = 'success';
| {
"pile_set_name": "Github"
} |
/*M///////////////////////////////////////////////////////////////////////////////////////
//
// IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING.
//
// By downloading, copying, installing or using the software you agree to this license.
// If you do not agree to this license, do not download, install,
// copy or use the software.
//
// Copyright (C) 2013, Alfonso Sanchez-Beato, all rights reserved.
// Third party copyrights are property of their respective owners.
//
// Redistribution and use in source and binary forms, with or without modification,
// are permitted provided that the following conditions are met:
//
// * Redistribution's of source code must retain the above copyright notice,
// this list of conditions and the following disclaimer.
//
// * Redistribution's 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.
//
// * The name of the copyright holders may not 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 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.
//
//M*/
#ifndef MAP_H_
#define MAP_H_
#include <opencv2/core.hpp> // Basic OpenCV structures (cv::Mat, Scalar)
/** @defgroup reg Image Registration
The Registration module implements parametric image registration. The implemented method is direct
alignment, that is, it uses directly the pixel values for calculating the registration between a
pair of images, as opposed to feature-based registration. The implementation follows essentially the
corresponding part of @cite Szeliski06 .
Feature based methods have some advantages over pixel based methods when we are trying to register
pictures that have been shoot under different lighting conditions or exposition times, or when the
images overlap only partially. On the other hand, the main advantage of pixel-based methods when
compared to feature based methods is their better precision for some pictures (those shoot under
similar lighting conditions and that have a significative overlap), due to the fact that we are
using all the information available in the image, which allows us to achieve subpixel accuracy. This
is particularly important for certain applications like multi-frame denoising or super-resolution.
In fact, pixel and feature registration methods can complement each other: an application could
first obtain a coarse registration using features and then refine the registration using a pixel
based method on the overlapping area of the images. The code developed allows this use case.
The module implements classes derived from the abstract classes cv::reg::Map or cv::reg::Mapper. The
former models a coordinate transformation between two reference frames, while the later encapsulates
a way of invoking a method that calculates a Map between two images. Although the objective has been
to implement pixel based methods, the module can be extended to support other methods that can
calculate transformations between images (feature methods, optical flow, etc.).
Each class derived from Map implements a motion model, as follows:
- MapShift: Models a simple translation
- MapAffine: Models an affine transformation
- MapProjec: Models a projective transformation
MapProject can also be used to model affine motion or translations, but some operations on it are
more costly, and that is the reason for defining the other two classes.
The classes derived from Mapper are
- MapperGradShift: Gradient based alignment for calculating translations. It produces a MapShift
(two parameters that correspond to the shift vector).
- MapperGradEuclid: Gradient based alignment for euclidean motions, that is, rotations and
translations. It calculates three parameters (angle and shift vector), although the result is
stored in a MapAffine object for convenience.
- MapperGradSimilar: Gradient based alignment for calculating similarities, which adds scaling to
the euclidean motion. It calculates four parameters (two for the anti-symmetric matrix and two
for the shift vector), although the result is stored in a MapAffine object for better
convenience.
- MapperGradAffine: Gradient based alignment for an affine motion model. The number of parameters
is six and the result is stored in a MapAffine object.
- MapperGradProj: Gradient based alignment for calculating projective transformations. The number
of parameters is eight and the result is stored in a MapProject object.
- MapperPyramid: It implements hyerarchical motion estimation using a Gaussian pyramid. Its
constructor accepts as argument any other object that implements the Mapper interface, and it is
that mapper the one called by MapperPyramid for each scale of the pyramid.
If the motion between the images is not very small, the normal way of using these classes is to
create a MapperGrad\* object and use it as input to create a MapperPyramid, which in turn is called
to perform the calculation. However, if the motion between the images is small enough, we can use
directly the MapperGrad\* classes. Another possibility is to use first a feature based method to
perform a coarse registration and then do a refinement through MapperPyramid or directly a
MapperGrad\* object. The "calculate" method of the mappers accepts an initial estimation of the
motion as input.
When deciding which MapperGrad to use we must take into account that mappers with more parameters
can handle more complex motions, but involve more calculations and are therefore slower. Also, if we
are confident on the motion model that is followed by the sequence, increasing the number of
parameters beyond what we need will decrease the accuracy: it is better to use the least number of
degrees of freedom that we can.
In the module tests there are examples that show how to register a pair of images using any of the
implemented mappers.
*/
namespace cv {
namespace reg {
//! @addtogroup reg
//! @{
/** @brief Base class for modelling a Map between two images.
The class is only used to define the common interface for any possible map.
*/
class CV_EXPORTS Map
{
public:
/*!
* Virtual destructor
*/
virtual ~Map(void);
/*!
* Warps image to a new coordinate frame. The calculation is img2(x)=img1(T^{-1}(x)), as we
* have to apply the inverse transformation to the points to move them to were the values
* of img2 are.
* \param[in] img1 Original image
* \param[out] img2 Warped image
*/
virtual void warp(const cv::Mat& img1, cv::Mat& img2) const;
/*!
* Warps image to a new coordinate frame. The calculation is img2(x)=img1(T(x)), so in fact
* this is the inverse warping as we are taking the value of img1 with the forward
* transformation of the points.
* \param[in] img1 Original image
* \param[out] img2 Warped image
*/
virtual void inverseWarp(const cv::Mat& img1, cv::Mat& img2) const = 0;
/*!
* Calculates the inverse map
* \return Inverse map
*/
virtual cv::Ptr<Map> inverseMap(void) const = 0;
/*!
* Changes the map composing the current transformation with the one provided in the call.
* The order is first the current transformation, then the input argument.
* \param[in] map Transformation to compose with.
*/
virtual void compose(const Map& map) = 0;
/*!
* Scales the map by a given factor as if the coordinates system is expanded/compressed
* by that factor.
* \param[in] factor Expansion if bigger than one, compression if smaller than one
*/
virtual void scale(double factor) = 0;
};
//! @}
}} // namespace cv::reg
#endif // MAP_H_
| {
"pile_set_name": "Github"
} |
/*
* jQuery File Upload Plugin
* https://github.com/blueimp/jQuery-File-Upload
*
* Copyright 2010, Sebastian Tschan
* https://blueimp.net
*
* Licensed under the MIT license:
* https://opensource.org/licenses/MIT
*/
/* jshint nomen:false */
/* global define, require, window, document, location, Blob, FormData */
;(function (factory) {
'use strict';
if (typeof define === 'function' && define.amd) {
// Register as an anonymous AMD module:
define([
'jquery',
'jquery-ui/ui/widget'
], factory);
} else if (typeof exports === 'object') {
// Node/CommonJS:
factory(
require('jquery'),
require('./vendor/jquery.ui.widget')
);
} else {
// Browser globals:
factory(window.jQuery);
}
}(function ($) {
'use strict';
// Detect file input support, based on
// http://viljamis.com/blog/2012/file-upload-support-on-mobile/
$.support.fileInput = !(new RegExp(
// Handle devices which give false positives for the feature detection:
'(Android (1\\.[0156]|2\\.[01]))' +
'|(Windows Phone (OS 7|8\\.0))|(XBLWP)|(ZuneWP)|(WPDesktop)' +
'|(w(eb)?OSBrowser)|(webOS)' +
'|(Kindle/(1\\.0|2\\.[05]|3\\.0))'
).test(window.navigator.userAgent) ||
// Feature detection for all other devices:
$('<input type="file"/>').prop('disabled'));
// The FileReader API is not actually used, but works as feature detection,
// as some Safari versions (5?) support XHR file uploads via the FormData API,
// but not non-multipart XHR file uploads.
// window.XMLHttpRequestUpload is not available on IE10, so we check for
// window.ProgressEvent instead to detect XHR2 file upload capability:
$.support.xhrFileUpload = !!(window.ProgressEvent && window.FileReader);
$.support.xhrFormDataFileUpload = !!window.FormData;
// Detect support for Blob slicing (required for chunked uploads):
$.support.blobSlice = window.Blob && (Blob.prototype.slice ||
Blob.prototype.webkitSlice || Blob.prototype.mozSlice);
// Helper function to create drag handlers for dragover/dragenter/dragleave:
function getDragHandler(type) {
var isDragOver = type === 'dragover';
return function (e) {
e.dataTransfer = e.originalEvent && e.originalEvent.dataTransfer;
var dataTransfer = e.dataTransfer;
if (dataTransfer && $.inArray('Files', dataTransfer.types) !== -1 &&
this._trigger(
type,
$.Event(type, {delegatedEvent: e})
) !== false) {
e.preventDefault();
if (isDragOver) {
dataTransfer.dropEffect = 'copy';
}
}
};
}
// The fileupload widget listens for change events on file input fields defined
// via fileInput setting and paste or drop events of the given dropZone.
// In addition to the default jQuery Widget methods, the fileupload widget
// exposes the "add" and "send" methods, to add or directly send files using
// the fileupload API.
// By default, files added via file input selection, paste, drag & drop or
// "add" method are uploaded immediately, but it is possible to override
// the "add" callback option to queue file uploads.
$.widget('blueimp.fileupload', {
options: {
// The drop target element(s), by the default the complete document.
// Set to null to disable drag & drop support:
dropZone: $(document),
// The paste target element(s), by the default undefined.
// Set to a DOM node or jQuery object to enable file pasting:
pasteZone: undefined,
// The file input field(s), that are listened to for change events.
// If undefined, it is set to the file input fields inside
// of the widget element on plugin initialization.
// Set to null to disable the change listener.
fileInput: undefined,
// By default, the file input field is replaced with a clone after
// each input field change event. This is required for iframe transport
// queues and allows change events to be fired for the same file
// selection, but can be disabled by setting the following option to false:
replaceFileInput: true,
// The parameter name for the file form data (the request argument name).
// If undefined or empty, the name property of the file input field is
// used, or "files[]" if the file input name property is also empty,
// can be a string or an array of strings:
paramName: undefined,
// By default, each file of a selection is uploaded using an individual
// request for XHR type uploads. Set to false to upload file
// selections in one request each:
singleFileUploads: true,
// To limit the number of files uploaded with one XHR request,
// set the following option to an integer greater than 0:
limitMultiFileUploads: undefined,
// The following option limits the number of files uploaded with one
// XHR request to keep the request size under or equal to the defined
// limit in bytes:
limitMultiFileUploadSize: undefined,
// Multipart file uploads add a number of bytes to each uploaded file,
// therefore the following option adds an overhead for each file used
// in the limitMultiFileUploadSize configuration:
limitMultiFileUploadSizeOverhead: 512,
// Set the following option to true to issue all file upload requests
// in a sequential order:
sequentialUploads: false,
// To limit the number of concurrent uploads,
// set the following option to an integer greater than 0:
limitConcurrentUploads: undefined,
// Set the following option to true to force iframe transport uploads:
forceIframeTransport: false,
// Set the following option to the location of a redirect url on the
// origin server, for cross-domain iframe transport uploads:
redirect: undefined,
// The parameter name for the redirect url, sent as part of the form
// data and set to 'redirect' if this option is empty:
redirectParamName: undefined,
// Set the following option to the location of a postMessage window,
// to enable postMessage transport uploads:
postMessage: undefined,
// By default, XHR file uploads are sent as multipart/form-data.
// The iframe transport is always using multipart/form-data.
// Set to false to enable non-multipart XHR uploads:
multipart: true,
// To upload large files in smaller chunks, set the following option
// to a preferred maximum chunk size. If set to 0, null or undefined,
// or the browser does not support the required Blob API, files will
// be uploaded as a whole.
maxChunkSize: undefined,
// When a non-multipart upload or a chunked multipart upload has been
// aborted, this option can be used to resume the upload by setting
// it to the size of the already uploaded bytes. This option is most
// useful when modifying the options object inside of the "add" or
// "send" callbacks, as the options are cloned for each file upload.
uploadedBytes: undefined,
// By default, failed (abort or error) file uploads are removed from the
// global progress calculation. Set the following option to false to
// prevent recalculating the global progress data:
recalculateProgress: true,
// Interval in milliseconds to calculate and trigger progress events:
progressInterval: 100,
// Interval in milliseconds to calculate progress bitrate:
bitrateInterval: 500,
// By default, uploads are started automatically when adding files:
autoUpload: true,
// Error and info messages:
messages: {
uploadedBytes: 'Uploaded bytes exceed file size'
},
// Translation function, gets the message key to be translated
// and an object with context specific data as arguments:
i18n: function (message, context) {
message = this.messages[message] || message.toString();
if (context) {
$.each(context, function (key, value) {
message = message.replace('{' + key + '}', value);
});
}
return message;
},
// Additional form data to be sent along with the file uploads can be set
// using this option, which accepts an array of objects with name and
// value properties, a function returning such an array, a FormData
// object (for XHR file uploads), or a simple object.
// The form of the first fileInput is given as parameter to the function:
formData: function (form) {
return form.serializeArray();
},
// The add callback is invoked as soon as files are added to the fileupload
// widget (via file input selection, drag & drop, paste or add API call).
// If the singleFileUploads option is enabled, this callback will be
// called once for each file in the selection for XHR file uploads, else
// once for each file selection.
//
// The upload starts when the submit method is invoked on the data parameter.
// The data object contains a files property holding the added files
// and allows you to override plugin options as well as define ajax settings.
//
// Listeners for this callback can also be bound the following way:
// .bind('fileuploadadd', func);
//
// data.submit() returns a Promise object and allows to attach additional
// handlers using jQuery's Deferred callbacks:
// data.submit().done(func).fail(func).always(func);
add: function (e, data) {
if (e.isDefaultPrevented()) {
return false;
}
if (data.autoUpload || (data.autoUpload !== false &&
$(this).fileupload('option', 'autoUpload'))) {
data.process().done(function () {
data.submit();
});
}
},
// Other callbacks:
// Callback for the submit event of each file upload:
// submit: function (e, data) {}, // .bind('fileuploadsubmit', func);
// Callback for the start of each file upload request:
// send: function (e, data) {}, // .bind('fileuploadsend', func);
// Callback for successful uploads:
// done: function (e, data) {}, // .bind('fileuploaddone', func);
// Callback for failed (abort or error) uploads:
// fail: function (e, data) {}, // .bind('fileuploadfail', func);
// Callback for completed (success, abort or error) requests:
// always: function (e, data) {}, // .bind('fileuploadalways', func);
// Callback for upload progress events:
// progress: function (e, data) {}, // .bind('fileuploadprogress', func);
// Callback for global upload progress events:
// progressall: function (e, data) {}, // .bind('fileuploadprogressall', func);
// Callback for uploads start, equivalent to the global ajaxStart event:
// start: function (e) {}, // .bind('fileuploadstart', func);
// Callback for uploads stop, equivalent to the global ajaxStop event:
// stop: function (e) {}, // .bind('fileuploadstop', func);
// Callback for change events of the fileInput(s):
// change: function (e, data) {}, // .bind('fileuploadchange', func);
// Callback for paste events to the pasteZone(s):
// paste: function (e, data) {}, // .bind('fileuploadpaste', func);
// Callback for drop events of the dropZone(s):
// drop: function (e, data) {}, // .bind('fileuploaddrop', func);
// Callback for dragover events of the dropZone(s):
// dragover: function (e) {}, // .bind('fileuploaddragover', func);
// Callback for the start of each chunk upload request:
// chunksend: function (e, data) {}, // .bind('fileuploadchunksend', func);
// Callback for successful chunk uploads:
// chunkdone: function (e, data) {}, // .bind('fileuploadchunkdone', func);
// Callback for failed (abort or error) chunk uploads:
// chunkfail: function (e, data) {}, // .bind('fileuploadchunkfail', func);
// Callback for completed (success, abort or error) chunk upload requests:
// chunkalways: function (e, data) {}, // .bind('fileuploadchunkalways', func);
// The plugin options are used as settings object for the ajax calls.
// The following are jQuery ajax settings required for the file uploads:
processData: false,
contentType: false,
cache: false,
timeout: 0
},
// A list of options that require reinitializing event listeners and/or
// special initialization code:
_specialOptions: [
'fileInput',
'dropZone',
'pasteZone',
'multipart',
'forceIframeTransport'
],
_blobSlice: $.support.blobSlice && function () {
var slice = this.slice || this.webkitSlice || this.mozSlice;
return slice.apply(this, arguments);
},
_BitrateTimer: function () {
this.timestamp = ((Date.now) ? Date.now() : (new Date()).getTime());
this.loaded = 0;
this.bitrate = 0;
this.getBitrate = function (now, loaded, interval) {
var timeDiff = now - this.timestamp;
if (!this.bitrate || !interval || timeDiff > interval) {
this.bitrate = (loaded - this.loaded) * (1000 / timeDiff) * 8;
this.loaded = loaded;
this.timestamp = now;
}
return this.bitrate;
};
},
_isXHRUpload: function (options) {
return !options.forceIframeTransport &&
((!options.multipart && $.support.xhrFileUpload) ||
$.support.xhrFormDataFileUpload);
},
_getFormData: function (options) {
var formData;
if ($.type(options.formData) === 'function') {
return options.formData(options.form);
}
if ($.isArray(options.formData)) {
return options.formData;
}
if ($.type(options.formData) === 'object') {
formData = [];
$.each(options.formData, function (name, value) {
formData.push({name: name, value: value});
});
return formData;
}
return [];
},
_getTotal: function (files) {
var total = 0;
$.each(files, function (index, file) {
total += file.size || 1;
});
return total;
},
_initProgressObject: function (obj) {
var progress = {
loaded: 0,
total: 0,
bitrate: 0
};
if (obj._progress) {
$.extend(obj._progress, progress);
} else {
obj._progress = progress;
}
},
_initResponseObject: function (obj) {
var prop;
if (obj._response) {
for (prop in obj._response) {
if (obj._response.hasOwnProperty(prop)) {
delete obj._response[prop];
}
}
} else {
obj._response = {};
}
},
_onProgress: function (e, data) {
if (e.lengthComputable) {
var now = ((Date.now) ? Date.now() : (new Date()).getTime()),
loaded;
if (data._time && data.progressInterval &&
(now - data._time < data.progressInterval) &&
e.loaded !== e.total) {
return;
}
data._time = now;
loaded = Math.floor(
e.loaded / e.total * (data.chunkSize || data._progress.total)
) + (data.uploadedBytes || 0);
// Add the difference from the previously loaded state
// to the global loaded counter:
this._progress.loaded += (loaded - data._progress.loaded);
this._progress.bitrate = this._bitrateTimer.getBitrate(
now,
this._progress.loaded,
data.bitrateInterval
);
data._progress.loaded = data.loaded = loaded;
data._progress.bitrate = data.bitrate = data._bitrateTimer.getBitrate(
now,
loaded,
data.bitrateInterval
);
// Trigger a custom progress event with a total data property set
// to the file size(s) of the current upload and a loaded data
// property calculated accordingly:
this._trigger(
'progress',
$.Event('progress', {delegatedEvent: e}),
data
);
// Trigger a global progress event for all current file uploads,
// including ajax calls queued for sequential file uploads:
this._trigger(
'progressall',
$.Event('progressall', {delegatedEvent: e}),
this._progress
);
}
},
_initProgressListener: function (options) {
var that = this,
xhr = options.xhr ? options.xhr() : $.ajaxSettings.xhr();
// Accesss to the native XHR object is required to add event listeners
// for the upload progress event:
if (xhr.upload) {
$(xhr.upload).bind('progress', function (e) {
var oe = e.originalEvent;
// Make sure the progress event properties get copied over:
e.lengthComputable = oe.lengthComputable;
e.loaded = oe.loaded;
e.total = oe.total;
that._onProgress(e, options);
});
options.xhr = function () {
return xhr;
};
}
},
_isInstanceOf: function (type, obj) {
// Cross-frame instanceof check
return Object.prototype.toString.call(obj) === '[object ' + type + ']';
},
_initXHRData: function (options) {
var that = this,
formData,
file = options.files[0],
// Ignore non-multipart setting if not supported:
multipart = options.multipart || !$.support.xhrFileUpload,
paramName = $.type(options.paramName) === 'array' ?
options.paramName[0] : options.paramName;
options.headers = $.extend({}, options.headers);
if (options.contentRange) {
options.headers['Content-Range'] = options.contentRange;
}
if (!multipart || options.blob || !this._isInstanceOf('File', file)) {
options.headers['Content-Disposition'] = 'attachment; filename="' +
encodeURI(file.uploadName || file.name) + '"';
}
if (!multipart) {
options.contentType = file.type || 'application/octet-stream';
options.data = options.blob || file;
} else if ($.support.xhrFormDataFileUpload) {
if (options.postMessage) {
// window.postMessage does not allow sending FormData
// objects, so we just add the File/Blob objects to
// the formData array and let the postMessage window
// create the FormData object out of this array:
formData = this._getFormData(options);
if (options.blob) {
formData.push({
name: paramName,
value: options.blob
});
} else {
$.each(options.files, function (index, file) {
formData.push({
name: ($.type(options.paramName) === 'array' &&
options.paramName[index]) || paramName,
value: file
});
});
}
} else {
if (that._isInstanceOf('FormData', options.formData)) {
formData = options.formData;
} else {
formData = new FormData();
$.each(this._getFormData(options), function (index, field) {
formData.append(field.name, field.value);
});
}
if (options.blob) {
formData.append(
paramName,
options.blob,
file.uploadName || file.name
);
} else {
$.each(options.files, function (index, file) {
// This check allows the tests to run with
// dummy objects:
if (that._isInstanceOf('File', file) ||
that._isInstanceOf('Blob', file)) {
formData.append(
($.type(options.paramName) === 'array' &&
options.paramName[index]) || paramName,
file,
file.uploadName || file.name
);
}
});
}
}
options.data = formData;
}
// Blob reference is not needed anymore, free memory:
options.blob = null;
},
_initIframeSettings: function (options) {
var targetHost = $('<a></a>').prop('href', options.url).prop('host');
// Setting the dataType to iframe enables the iframe transport:
options.dataType = 'iframe ' + (options.dataType || '');
// The iframe transport accepts a serialized array as form data:
options.formData = this._getFormData(options);
// Add redirect url to form data on cross-domain uploads:
if (options.redirect && targetHost && targetHost !== location.host) {
options.formData.push({
name: options.redirectParamName || 'redirect',
value: options.redirect
});
}
},
_initDataSettings: function (options) {
if (this._isXHRUpload(options)) {
if (!this._chunkedUpload(options, true)) {
if (!options.data) {
this._initXHRData(options);
}
this._initProgressListener(options);
}
if (options.postMessage) {
// Setting the dataType to postmessage enables the
// postMessage transport:
options.dataType = 'postmessage ' + (options.dataType || '');
}
} else {
this._initIframeSettings(options);
}
},
_getParamName: function (options) {
var fileInput = $(options.fileInput),
paramName = options.paramName;
if (!paramName) {
paramName = [];
fileInput.each(function () {
var input = $(this),
name = input.prop('name') || 'files[]',
i = (input.prop('files') || [1]).length;
while (i) {
paramName.push(name);
i -= 1;
}
});
if (!paramName.length) {
paramName = [fileInput.prop('name') || 'files[]'];
}
} else if (!$.isArray(paramName)) {
paramName = [paramName];
}
return paramName;
},
_initFormSettings: function (options) {
// Retrieve missing options from the input field and the
// associated form, if available:
if (!options.form || !options.form.length) {
options.form = $(options.fileInput.prop('form'));
// If the given file input doesn't have an associated form,
// use the default widget file input's form:
if (!options.form.length) {
options.form = $(this.options.fileInput.prop('form'));
}
}
options.paramName = this._getParamName(options);
if (!options.url) {
options.url = options.form.prop('action') || location.href;
}
// The HTTP request method must be "POST" or "PUT":
options.type = (options.type ||
($.type(options.form.prop('method')) === 'string' &&
options.form.prop('method')) || ''
).toUpperCase();
if (options.type !== 'POST' && options.type !== 'PUT' &&
options.type !== 'PATCH') {
options.type = 'POST';
}
if (!options.formAcceptCharset) {
options.formAcceptCharset = options.form.attr('accept-charset');
}
},
_getAJAXSettings: function (data) {
var options = $.extend({}, this.options, data);
this._initFormSettings(options);
this._initDataSettings(options);
return options;
},
// jQuery 1.6 doesn't provide .state(),
// while jQuery 1.8+ removed .isRejected() and .isResolved():
_getDeferredState: function (deferred) {
if (deferred.state) {
return deferred.state();
}
if (deferred.isResolved()) {
return 'resolved';
}
if (deferred.isRejected()) {
return 'rejected';
}
return 'pending';
},
// Maps jqXHR callbacks to the equivalent
// methods of the given Promise object:
_enhancePromise: function (promise) {
promise.success = promise.done;
promise.error = promise.fail;
promise.complete = promise.always;
return promise;
},
// Creates and returns a Promise object enhanced with
// the jqXHR methods abort, success, error and complete:
_getXHRPromise: function (resolveOrReject, context, args) {
var dfd = $.Deferred(),
promise = dfd.promise();
context = context || this.options.context || promise;
if (resolveOrReject === true) {
dfd.resolveWith(context, args);
} else if (resolveOrReject === false) {
dfd.rejectWith(context, args);
}
promise.abort = dfd.promise;
return this._enhancePromise(promise);
},
// Adds convenience methods to the data callback argument:
_addConvenienceMethods: function (e, data) {
var that = this,
getPromise = function (args) {
return $.Deferred().resolveWith(that, args).promise();
};
data.process = function (resolveFunc, rejectFunc) {
if (resolveFunc || rejectFunc) {
data._processQueue = this._processQueue =
(this._processQueue || getPromise([this])).then(
function () {
if (data.errorThrown) {
return $.Deferred()
.rejectWith(that, [data]).promise();
}
return getPromise(arguments);
}
).then(resolveFunc, rejectFunc);
}
return this._processQueue || getPromise([this]);
};
data.submit = function () {
if (this.state() !== 'pending') {
data.jqXHR = this.jqXHR =
(that._trigger(
'submit',
$.Event('submit', {delegatedEvent: e}),
this
) !== false) && that._onSend(e, this);
}
return this.jqXHR || that._getXHRPromise();
};
data.abort = function () {
if (this.jqXHR) {
return this.jqXHR.abort();
}
this.errorThrown = 'abort';
that._trigger('fail', null, this);
return that._getXHRPromise(false);
};
data.state = function () {
if (this.jqXHR) {
return that._getDeferredState(this.jqXHR);
}
if (this._processQueue) {
return that._getDeferredState(this._processQueue);
}
};
data.processing = function () {
return !this.jqXHR && this._processQueue && that
._getDeferredState(this._processQueue) === 'pending';
};
data.progress = function () {
return this._progress;
};
data.response = function () {
return this._response;
};
},
// Parses the Range header from the server response
// and returns the uploaded bytes:
_getUploadedBytes: function (jqXHR) {
var range = jqXHR.getResponseHeader('Range'),
parts = range && range.split('-'),
upperBytesPos = parts && parts.length > 1 &&
parseInt(parts[1], 10);
return upperBytesPos && upperBytesPos + 1;
},
// Uploads a file in multiple, sequential requests
// by splitting the file up in multiple blob chunks.
// If the second parameter is true, only tests if the file
// should be uploaded in chunks, but does not invoke any
// upload requests:
_chunkedUpload: function (options, testOnly) {
options.uploadedBytes = options.uploadedBytes || 0;
var that = this,
file = options.files[0],
fs = file.size,
ub = options.uploadedBytes,
mcs = options.maxChunkSize || fs,
slice = this._blobSlice,
dfd = $.Deferred(),
promise = dfd.promise(),
jqXHR,
upload;
if (!(this._isXHRUpload(options) && slice && (ub || ($.type(mcs) === 'function' ? mcs(options) : mcs) < fs)) ||
options.data) {
return false;
}
if (testOnly) {
return true;
}
if (ub >= fs) {
file.error = options.i18n('uploadedBytes');
return this._getXHRPromise(
false,
options.context,
[null, 'error', file.error]
);
}
// The chunk upload method:
upload = function () {
// Clone the options object for each chunk upload:
var o = $.extend({}, options),
currentLoaded = o._progress.loaded;
o.blob = slice.call(
file,
ub,
ub + ($.type(mcs) === 'function' ? mcs(o) : mcs),
file.type
);
// Store the current chunk size, as the blob itself
// will be dereferenced after data processing:
o.chunkSize = o.blob.size;
// Expose the chunk bytes position range:
o.contentRange = 'bytes ' + ub + '-' +
(ub + o.chunkSize - 1) + '/' + fs;
// Process the upload data (the blob and potential form data):
that._initXHRData(o);
// Add progress listeners for this chunk upload:
that._initProgressListener(o);
jqXHR = ((that._trigger('chunksend', null, o) !== false && $.ajax(o)) ||
that._getXHRPromise(false, o.context))
.done(function (result, textStatus, jqXHR) {
ub = that._getUploadedBytes(jqXHR) ||
(ub + o.chunkSize);
// Create a progress event if no final progress event
// with loaded equaling total has been triggered
// for this chunk:
if (currentLoaded + o.chunkSize - o._progress.loaded) {
that._onProgress($.Event('progress', {
lengthComputable: true,
loaded: ub - o.uploadedBytes,
total: ub - o.uploadedBytes
}), o);
}
options.uploadedBytes = o.uploadedBytes = ub;
o.result = result;
o.textStatus = textStatus;
o.jqXHR = jqXHR;
that._trigger('chunkdone', null, o);
that._trigger('chunkalways', null, o);
if (ub < fs) {
// File upload not yet complete,
// continue with the next chunk:
upload();
} else {
dfd.resolveWith(
o.context,
[result, textStatus, jqXHR]
);
}
})
.fail(function (jqXHR, textStatus, errorThrown) {
o.jqXHR = jqXHR;
o.textStatus = textStatus;
o.errorThrown = errorThrown;
that._trigger('chunkfail', null, o);
that._trigger('chunkalways', null, o);
dfd.rejectWith(
o.context,
[jqXHR, textStatus, errorThrown]
);
});
};
this._enhancePromise(promise);
promise.abort = function () {
return jqXHR.abort();
};
upload();
return promise;
},
_beforeSend: function (e, data) {
if (this._active === 0) {
// the start callback is triggered when an upload starts
// and no other uploads are currently running,
// equivalent to the global ajaxStart event:
this._trigger('start');
// Set timer for global bitrate progress calculation:
this._bitrateTimer = new this._BitrateTimer();
// Reset the global progress values:
this._progress.loaded = this._progress.total = 0;
this._progress.bitrate = 0;
}
// Make sure the container objects for the .response() and
// .progress() methods on the data object are available
// and reset to their initial state:
this._initResponseObject(data);
this._initProgressObject(data);
data._progress.loaded = data.loaded = data.uploadedBytes || 0;
data._progress.total = data.total = this._getTotal(data.files) || 1;
data._progress.bitrate = data.bitrate = 0;
this._active += 1;
// Initialize the global progress values:
this._progress.loaded += data.loaded;
this._progress.total += data.total;
},
_onDone: function (result, textStatus, jqXHR, options) {
var total = options._progress.total,
response = options._response;
if (options._progress.loaded < total) {
// Create a progress event if no final progress event
// with loaded equaling total has been triggered:
this._onProgress($.Event('progress', {
lengthComputable: true,
loaded: total,
total: total
}), options);
}
response.result = options.result = result;
response.textStatus = options.textStatus = textStatus;
response.jqXHR = options.jqXHR = jqXHR;
this._trigger('done', null, options);
},
_onFail: function (jqXHR, textStatus, errorThrown, options) {
var response = options._response;
if (options.recalculateProgress) {
// Remove the failed (error or abort) file upload from
// the global progress calculation:
this._progress.loaded -= options._progress.loaded;
this._progress.total -= options._progress.total;
}
response.jqXHR = options.jqXHR = jqXHR;
response.textStatus = options.textStatus = textStatus;
response.errorThrown = options.errorThrown = errorThrown;
this._trigger('fail', null, options);
},
_onAlways: function (jqXHRorResult, textStatus, jqXHRorError, options) {
// jqXHRorResult, textStatus and jqXHRorError are added to the
// options object via done and fail callbacks
this._trigger('always', null, options);
},
_onSend: function (e, data) {
if (!data.submit) {
this._addConvenienceMethods(e, data);
}
var that = this,
jqXHR,
aborted,
slot,
pipe,
options = that._getAJAXSettings(data),
send = function () {
that._sending += 1;
// Set timer for bitrate progress calculation:
options._bitrateTimer = new that._BitrateTimer();
jqXHR = jqXHR || (
((aborted || that._trigger(
'send',
$.Event('send', {delegatedEvent: e}),
options
) === false) &&
that._getXHRPromise(false, options.context, aborted)) ||
that._chunkedUpload(options) || $.ajax(options)
).done(function (result, textStatus, jqXHR) {
that._onDone(result, textStatus, jqXHR, options);
}).fail(function (jqXHR, textStatus, errorThrown) {
that._onFail(jqXHR, textStatus, errorThrown, options);
}).always(function (jqXHRorResult, textStatus, jqXHRorError) {
that._onAlways(
jqXHRorResult,
textStatus,
jqXHRorError,
options
);
that._sending -= 1;
that._active -= 1;
if (options.limitConcurrentUploads &&
options.limitConcurrentUploads > that._sending) {
// Start the next queued upload,
// that has not been aborted:
var nextSlot = that._slots.shift();
while (nextSlot) {
if (that._getDeferredState(nextSlot) === 'pending') {
nextSlot.resolve();
break;
}
nextSlot = that._slots.shift();
}
}
if (that._active === 0) {
// The stop callback is triggered when all uploads have
// been completed, equivalent to the global ajaxStop event:
that._trigger('stop');
}
});
return jqXHR;
};
this._beforeSend(e, options);
if (this.options.sequentialUploads ||
(this.options.limitConcurrentUploads &&
this.options.limitConcurrentUploads <= this._sending)) {
if (this.options.limitConcurrentUploads > 1) {
slot = $.Deferred();
this._slots.push(slot);
pipe = slot.then(send);
} else {
this._sequence = this._sequence.then(send, send);
pipe = this._sequence;
}
// Return the piped Promise object, enhanced with an abort method,
// which is delegated to the jqXHR object of the current upload,
// and jqXHR callbacks mapped to the equivalent Promise methods:
pipe.abort = function () {
aborted = [undefined, 'abort', 'abort'];
if (!jqXHR) {
if (slot) {
slot.rejectWith(options.context, aborted);
}
return send();
}
return jqXHR.abort();
};
return this._enhancePromise(pipe);
}
return send();
},
_onAdd: function (e, data) {
var that = this,
result = true,
options = $.extend({}, this.options, data),
files = data.files,
filesLength = files.length,
limit = options.limitMultiFileUploads,
limitSize = options.limitMultiFileUploadSize,
overhead = options.limitMultiFileUploadSizeOverhead,
batchSize = 0,
paramName = this._getParamName(options),
paramNameSet,
paramNameSlice,
fileSet,
i,
j = 0;
if (!filesLength) {
return false;
}
if (limitSize && files[0].size === undefined) {
limitSize = undefined;
}
if (!(options.singleFileUploads || limit || limitSize) ||
!this._isXHRUpload(options)) {
fileSet = [files];
paramNameSet = [paramName];
} else if (!(options.singleFileUploads || limitSize) && limit) {
fileSet = [];
paramNameSet = [];
for (i = 0; i < filesLength; i += limit) {
fileSet.push(files.slice(i, i + limit));
paramNameSlice = paramName.slice(i, i + limit);
if (!paramNameSlice.length) {
paramNameSlice = paramName;
}
paramNameSet.push(paramNameSlice);
}
} else if (!options.singleFileUploads && limitSize) {
fileSet = [];
paramNameSet = [];
for (i = 0; i < filesLength; i = i + 1) {
batchSize += files[i].size + overhead;
if (i + 1 === filesLength ||
((batchSize + files[i + 1].size + overhead) > limitSize) ||
(limit && i + 1 - j >= limit)) {
fileSet.push(files.slice(j, i + 1));
paramNameSlice = paramName.slice(j, i + 1);
if (!paramNameSlice.length) {
paramNameSlice = paramName;
}
paramNameSet.push(paramNameSlice);
j = i + 1;
batchSize = 0;
}
}
} else {
paramNameSet = paramName;
}
data.originalFiles = files;
$.each(fileSet || files, function (index, element) {
var newData = $.extend({}, data);
newData.files = fileSet ? element : [element];
newData.paramName = paramNameSet[index];
that._initResponseObject(newData);
that._initProgressObject(newData);
that._addConvenienceMethods(e, newData);
result = that._trigger(
'add',
$.Event('add', {delegatedEvent: e}),
newData
);
return result;
});
return result;
},
_replaceFileInput: function (data) {
var input = data.fileInput,
inputClone = input.clone(true),
restoreFocus = input.is(document.activeElement);
// Add a reference for the new cloned file input to the data argument:
data.fileInputClone = inputClone;
$('<form></form>').append(inputClone)[0].reset();
// Detaching allows to insert the fileInput on another form
// without loosing the file input value:
input.after(inputClone).detach();
// If the fileInput had focus before it was detached,
// restore focus to the inputClone.
if (restoreFocus) {
inputClone.focus();
}
// Avoid memory leaks with the detached file input:
$.cleanData(input.unbind('remove'));
// Replace the original file input element in the fileInput
// elements set with the clone, which has been copied including
// event handlers:
this.options.fileInput = this.options.fileInput.map(function (i, el) {
if (el === input[0]) {
return inputClone[0];
}
return el;
});
// If the widget has been initialized on the file input itself,
// override this.element with the file input clone:
if (input[0] === this.element[0]) {
this.element = inputClone;
}
},
_handleFileTreeEntry: function (entry, path) {
var that = this,
dfd = $.Deferred(),
entries = [],
dirReader,
errorHandler = function (e) {
if (e && !e.entry) {
e.entry = entry;
}
// Since $.when returns immediately if one
// Deferred is rejected, we use resolve instead.
// This allows valid files and invalid items
// to be returned together in one set:
dfd.resolve([e]);
},
successHandler = function (entries) {
that._handleFileTreeEntries(
entries,
path + entry.name + '/'
).done(function (files) {
dfd.resolve(files);
}).fail(errorHandler);
},
readEntries = function () {
dirReader.readEntries(function (results) {
if (!results.length) {
successHandler(entries);
} else {
entries = entries.concat(results);
readEntries();
}
}, errorHandler);
};
path = path || '';
if (entry.isFile) {
if (entry._file) {
// Workaround for Chrome bug #149735
entry._file.relativePath = path;
dfd.resolve(entry._file);
} else {
entry.file(function (file) {
file.relativePath = path;
dfd.resolve(file);
}, errorHandler);
}
} else if (entry.isDirectory) {
dirReader = entry.createReader();
readEntries();
} else {
// Return an empy list for file system items
// other than files or directories:
dfd.resolve([]);
}
return dfd.promise();
},
_handleFileTreeEntries: function (entries, path) {
var that = this;
return $.when.apply(
$,
$.map(entries, function (entry) {
return that._handleFileTreeEntry(entry, path);
})
).then(function () {
return Array.prototype.concat.apply(
[],
arguments
);
});
},
_getDroppedFiles: function (dataTransfer) {
dataTransfer = dataTransfer || {};
var items = dataTransfer.items;
if (items && items.length && (items[0].webkitGetAsEntry ||
items[0].getAsEntry)) {
return this._handleFileTreeEntries(
$.map(items, function (item) {
var entry;
if (item.webkitGetAsEntry) {
entry = item.webkitGetAsEntry();
if (entry) {
// Workaround for Chrome bug #149735:
entry._file = item.getAsFile();
}
return entry;
}
return item.getAsEntry();
})
);
}
return $.Deferred().resolve(
$.makeArray(dataTransfer.files)
).promise();
},
_getSingleFileInputFiles: function (fileInput) {
fileInput = $(fileInput);
var entries = fileInput.prop('webkitEntries') ||
fileInput.prop('entries'),
files,
value;
if (entries && entries.length) {
return this._handleFileTreeEntries(entries);
}
files = $.makeArray(fileInput.prop('files'));
if (!files.length) {
value = fileInput.prop('value');
if (!value) {
return $.Deferred().resolve([]).promise();
}
// If the files property is not available, the browser does not
// support the File API and we add a pseudo File object with
// the input value as name with path information removed:
files = [{name: value.replace(/^.*\\/, '')}];
} else if (files[0].name === undefined && files[0].fileName) {
// File normalization for Safari 4 and Firefox 3:
$.each(files, function (index, file) {
file.name = file.fileName;
file.size = file.fileSize;
});
}
return $.Deferred().resolve(files).promise();
},
_getFileInputFiles: function (fileInput) {
if (!(fileInput instanceof $) || fileInput.length === 1) {
return this._getSingleFileInputFiles(fileInput);
}
return $.when.apply(
$,
$.map(fileInput, this._getSingleFileInputFiles)
).then(function () {
return Array.prototype.concat.apply(
[],
arguments
);
});
},
_onChange: function (e) {
var that = this,
data = {
fileInput: $(e.target),
form: $(e.target.form)
};
this._getFileInputFiles(data.fileInput).always(function (files) {
data.files = files;
if (that.options.replaceFileInput) {
that._replaceFileInput(data);
}
if (that._trigger(
'change',
$.Event('change', {delegatedEvent: e}),
data
) !== false) {
that._onAdd(e, data);
}
});
},
_onPaste: function (e) {
var items = e.originalEvent && e.originalEvent.clipboardData &&
e.originalEvent.clipboardData.items,
data = {files: []};
if (items && items.length) {
$.each(items, function (index, item) {
var file = item.getAsFile && item.getAsFile();
if (file) {
data.files.push(file);
}
});
if (this._trigger(
'paste',
$.Event('paste', {delegatedEvent: e}),
data
) !== false) {
this._onAdd(e, data);
}
}
},
_onDrop: function (e) {
e.dataTransfer = e.originalEvent && e.originalEvent.dataTransfer;
var that = this,
dataTransfer = e.dataTransfer,
data = {};
if (dataTransfer && dataTransfer.files && dataTransfer.files.length) {
e.preventDefault();
this._getDroppedFiles(dataTransfer).always(function (files) {
data.files = files;
if (that._trigger(
'drop',
$.Event('drop', {delegatedEvent: e}),
data
) !== false) {
that._onAdd(e, data);
}
});
}
},
_onDragOver: getDragHandler('dragover'),
_onDragEnter: getDragHandler('dragenter'),
_onDragLeave: getDragHandler('dragleave'),
_initEventHandlers: function () {
if (this._isXHRUpload(this.options)) {
this._on(this.options.dropZone, {
dragover: this._onDragOver,
drop: this._onDrop,
// event.preventDefault() on dragenter is required for IE10+:
dragenter: this._onDragEnter,
// dragleave is not required, but added for completeness:
dragleave: this._onDragLeave
});
this._on(this.options.pasteZone, {
paste: this._onPaste
});
}
if ($.support.fileInput) {
this._on(this.options.fileInput, {
change: this._onChange
});
}
},
_destroyEventHandlers: function () {
this._off(this.options.dropZone, 'dragenter dragleave dragover drop');
this._off(this.options.pasteZone, 'paste');
this._off(this.options.fileInput, 'change');
},
_destroy: function () {
this._destroyEventHandlers();
},
_setOption: function (key, value) {
var reinit = $.inArray(key, this._specialOptions) !== -1;
if (reinit) {
this._destroyEventHandlers();
}
this._super(key, value);
if (reinit) {
this._initSpecialOptions();
this._initEventHandlers();
}
},
_initSpecialOptions: function () {
var options = this.options;
if (options.fileInput === undefined) {
options.fileInput = this.element.is('input[type="file"]') ?
this.element : this.element.find('input[type="file"]');
} else if (!(options.fileInput instanceof $)) {
options.fileInput = $(options.fileInput);
}
if (!(options.dropZone instanceof $)) {
options.dropZone = $(options.dropZone);
}
if (!(options.pasteZone instanceof $)) {
options.pasteZone = $(options.pasteZone);
}
},
_getRegExp: function (str) {
var parts = str.split('/'),
modifiers = parts.pop();
parts.shift();
return new RegExp(parts.join('/'), modifiers);
},
_isRegExpOption: function (key, value) {
return key !== 'url' && $.type(value) === 'string' &&
/^\/.*\/[igm]{0,3}$/.test(value);
},
_initDataAttributes: function () {
var that = this,
options = this.options,
data = this.element.data();
// Initialize options set via HTML5 data-attributes:
$.each(
this.element[0].attributes,
function (index, attr) {
var key = attr.name.toLowerCase(),
value;
if (/^data-/.test(key)) {
// Convert hyphen-ated key to camelCase:
key = key.slice(5).replace(/-[a-z]/g, function (str) {
return str.charAt(1).toUpperCase();
});
value = data[key];
if (that._isRegExpOption(key, value)) {
value = that._getRegExp(value);
}
options[key] = value;
}
}
);
},
_create: function () {
this._initDataAttributes();
this._initSpecialOptions();
this._slots = [];
this._sequence = this._getXHRPromise(true);
this._sending = this._active = 0;
this._initProgressObject(this);
this._initEventHandlers();
},
// This method is exposed to the widget API and allows to query
// the number of active uploads:
active: function () {
return this._active;
},
// This method is exposed to the widget API and allows to query
// the widget upload progress.
// It returns an object with loaded, total and bitrate properties
// for the running uploads:
progress: function () {
return this._progress;
},
// This method is exposed to the widget API and allows adding files
// using the fileupload API. The data parameter accepts an object which
// must have a files property and can contain additional options:
// .fileupload('add', {files: filesList});
add: function (data) {
var that = this;
if (!data || this.options.disabled) {
return;
}
if (data.fileInput && !data.files) {
this._getFileInputFiles(data.fileInput).always(function (files) {
data.files = files;
that._onAdd(null, data);
});
} else {
data.files = $.makeArray(data.files);
this._onAdd(null, data);
}
},
// This method is exposed to the widget API and allows sending files
// using the fileupload API. The data parameter accepts an object which
// must have a files or fileInput property and can contain additional options:
// .fileupload('send', {files: filesList});
// The method returns a Promise object for the file upload call.
send: function (data) {
if (data && !this.options.disabled) {
if (data.fileInput && !data.files) {
var that = this,
dfd = $.Deferred(),
promise = dfd.promise(),
jqXHR,
aborted;
promise.abort = function () {
aborted = true;
if (jqXHR) {
return jqXHR.abort();
}
dfd.reject(null, 'abort', 'abort');
return promise;
};
this._getFileInputFiles(data.fileInput).always(
function (files) {
if (aborted) {
return;
}
if (!files.length) {
dfd.reject();
return;
}
data.files = files;
jqXHR = that._onSend(null, data);
jqXHR.then(
function (result, textStatus, jqXHR) {
dfd.resolve(result, textStatus, jqXHR);
},
function (jqXHR, textStatus, errorThrown) {
dfd.reject(jqXHR, textStatus, errorThrown);
}
);
}
);
return this._enhancePromise(promise);
}
data.files = $.makeArray(data.files);
if (data.files.length) {
return this._onSend(null, data);
}
}
return this._getXHRPromise(false, data && data.context);
}
});
}));
| {
"pile_set_name": "Github"
} |
# Translation of Odoo Server.
# This file contains the translation of the following modules:
# * hr_recruitment_survey
#
msgid ""
msgstr ""
"Project-Id-Version: Odoo Server 10.saas~18\n"
"Report-Msgid-Bugs-To: \n"
"POT-Creation-Date: 2017-09-20 09:53+0000\n"
"PO-Revision-Date: 2017-09-20 09:53+0000\n"
"Language-Team: Nepali (https://www.transifex.com/odoo/teams/41243/ne/)\n"
"MIME-Version: 1.0\n"
"Content-Type: text/plain; charset=UTF-8\n"
"Content-Transfer-Encoding: \n"
"Language: ne\n"
"Plural-Forms: nplurals=2; plural=(n != 1);\n"
#. module: hr_recruitment_survey
#: model:survey.label,value:hr_recruitment_survey.recruitment_1_3_1
msgid "0-15"
msgstr ""
#. module: hr_recruitment_survey
#: model:survey.label,value:hr_recruitment_survey.recruitment_1_3_2
msgid "16-20"
msgstr ""
#. module: hr_recruitment_survey
#: model:survey.label,value:hr_recruitment_survey.recruitment_1_3_3
msgid "21-30"
msgstr ""
#. module: hr_recruitment_survey
#: model:survey.label,value:hr_recruitment_survey.recruitment_1_3_4
msgid "31-40"
msgstr ""
#. module: hr_recruitment_survey
#: model:survey.label,value:hr_recruitment_survey.recruitment_1_3_5
msgid "41-50"
msgstr ""
#. module: hr_recruitment_survey
#: model:survey.label,value:hr_recruitment_survey.recruitment_1_3_6
msgid "51-60"
msgstr ""
#. module: hr_recruitment_survey
#: model:survey.label,value:hr_recruitment_survey.recruitment_1_3_7
msgid "61-70"
msgstr ""
#. module: hr_recruitment_survey
#: model:survey.label,value:hr_recruitment_survey.recruitment_1_3_8
msgid "71+"
msgstr ""
#. module: hr_recruitment_survey
#: model_terms:ir.ui.view,arch_db:hr_recruitment_survey.crm_case_form_view_job_inherit
msgid ""
"<span class=\"o_stat_text\">Print</span>\n"
" <span class=\"o_stat_text\">Interview</span>"
msgstr ""
#. module: hr_recruitment_survey
#: model_terms:ir.ui.view,arch_db:hr_recruitment_survey.crm_case_form_view_job_inherit
msgid ""
"<span class=\"o_stat_text\">Start</span>\n"
" <span class=\"o_stat_text\">Interview</span>"
msgstr ""
#. module: hr_recruitment_survey
#: model:survey.question,question:hr_recruitment_survey.recruitment_2_4
msgid "Activities"
msgstr ""
#. module: hr_recruitment_survey
#: model_terms:ir.ui.view,arch_db:hr_recruitment_survey.crm_case_form_view_job_inherit
msgid "Answer related job question"
msgstr ""
#. module: hr_recruitment_survey
#: model:ir.model,name:hr_recruitment_survey.model_hr_applicant
msgid "Applicant"
msgstr ""
#. module: hr_recruitment_survey
#: model:survey.page,title:hr_recruitment_survey.recruitment_1
msgid "Basic information"
msgstr ""
#. module: hr_recruitment_survey
#: model:ir.model.fields,help:hr_recruitment_survey.field_hr_applicant_survey_id
#: model:ir.model.fields,help:hr_recruitment_survey.field_hr_job_survey_id
msgid ""
"Choose an interview form for this job position and you will be able to "
"print/answer this interview from all applicants who apply for this job"
msgstr ""
#. module: hr_recruitment_survey
#: model:survey.label,value:hr_recruitment_survey.rrow_2_1_4
msgid "Desk space"
msgstr ""
#. module: hr_recruitment_survey
#: model_terms:ir.ui.view,arch_db:hr_recruitment_survey.hr_job_survey_inherit
#: model_terms:ir.ui.view,arch_db:hr_recruitment_survey.view_hr_job_kanban_inherit
msgid "Display Interview Form"
msgstr ""
#. module: hr_recruitment_survey
#: model:survey.label,value:hr_recruitment_survey.rrow_2_1_11
msgid "Dress code"
msgstr ""
#. module: hr_recruitment_survey
#: model:survey.question,question:hr_recruitment_survey.recruitment_2_2
msgid "Education"
msgstr ""
#. module: hr_recruitment_survey
#: model:survey.page,title:hr_recruitment_survey.recruitment_2
msgid "Education and Activities"
msgstr ""
#. module: hr_recruitment_survey
#: model:survey.question,question:hr_recruitment_survey.recruitment_2_3
msgid "Experience"
msgstr ""
#. module: hr_recruitment_survey
#: model:survey.label,value:hr_recruitment_survey.recruitment_1_2_2
msgid "Female"
msgstr ""
#. module: hr_recruitment_survey
#: model:survey.label,value:hr_recruitment_survey.rrow_2_1_8
msgid "Freebies such as tea, coffee and stationery"
msgstr ""
#. module: hr_recruitment_survey
#: model:survey.question,question:hr_recruitment_survey.recruitment_1_1
msgid "From which university will you graduate?"
msgstr ""
#. module: hr_recruitment_survey
#: model:survey.label,value:hr_recruitment_survey.rrow_2_1_2
msgid "Getting on with colleagues"
msgstr ""
#. module: hr_recruitment_survey
#: model:survey.label,value:hr_recruitment_survey.rrow_2_1_7
msgid "Good management"
msgstr ""
#. module: hr_recruitment_survey
#: model:survey.label,value:hr_recruitment_survey.rrow_2_1_1
msgid "Good pay"
msgstr ""
#. module: hr_recruitment_survey
#: model:survey.label,value:hr_recruitment_survey.rrow_2_1_13
msgid "Good social life"
msgstr ""
#. module: hr_recruitment_survey
#: model:survey.question,comments_message:hr_recruitment_survey.recruitment_1_1
#: model:survey.question,comments_message:hr_recruitment_survey.recruitment_1_2
#: model:survey.question,comments_message:hr_recruitment_survey.recruitment_1_3
#: model:survey.question,comments_message:hr_recruitment_survey.recruitment_2_1
#: model:survey.question,comments_message:hr_recruitment_survey.recruitment_2_2
#: model:survey.question,comments_message:hr_recruitment_survey.recruitment_2_3
#: model:survey.question,comments_message:hr_recruitment_survey.recruitment_2_4
#: model:survey.question,comments_message:hr_recruitment_survey.recruitment_3_1
msgid "If other, please specify:"
msgstr ""
#. module: hr_recruitment_survey
#: model:survey.page,title:hr_recruitment_survey.recruitment_3
msgid "Importance"
msgstr ""
#. module: hr_recruitment_survey
#: model:survey.label,value:hr_recruitment_survey.rcol_3_1_3
msgid "Important"
msgstr ""
#. module: hr_recruitment_survey
#: model:ir.model.fields,field_description:hr_recruitment_survey.field_hr_job_survey_id
#: model_terms:ir.ui.view,arch_db:hr_recruitment_survey.view_hr_job_kanban_inherit
msgid "Interview Form"
msgstr ""
#. module: hr_recruitment_survey
#: model_terms:ir.ui.view,arch_db:hr_recruitment_survey.res_config_settings_view_form
msgid "Interview Forms"
msgstr ""
#. module: hr_recruitment_survey
#: model:ir.model,name:hr_recruitment_survey.model_hr_job
msgid "Job Position"
msgstr ""
#. module: hr_recruitment_survey
#: model:survey.question,question:hr_recruitment_survey.recruitment_2_1
msgid "Knowledge"
msgstr ""
#. module: hr_recruitment_survey
#: model:survey.label,value:hr_recruitment_survey.recruitment_1_2_1
msgid "Male"
msgstr ""
#. module: hr_recruitment_survey
#: model:survey.label,value:hr_recruitment_survey.rcol_3_1_5
msgid "Most important"
msgstr ""
#. module: hr_recruitment_survey
#: model_terms:ir.ui.view,arch_db:hr_recruitment_survey.view_hr_job_kanban_inherit
msgid "No Interview Form"
msgstr ""
#. module: hr_recruitment_survey
#: model:survey.label,value:hr_recruitment_survey.rrow_2_1_10
msgid "No out of hours working"
msgstr ""
#. module: hr_recruitment_survey
#: model:survey.label,value:hr_recruitment_survey.rcol_3_1_1
msgid "Not important"
msgstr ""
#. module: hr_recruitment_survey
#: model:survey.label,value:hr_recruitment_survey.rrow_2_1_3
msgid "Office environment"
msgstr ""
#. module: hr_recruitment_survey
#: model:survey.label,value:hr_recruitment_survey.rrow_2_1_6
msgid "Office location"
msgstr ""
#. module: hr_recruitment_survey
#: model:survey.label,value:hr_recruitment_survey.rrow_2_1_9
msgid "Perks such as free parking, gym passes"
msgstr ""
#. module: hr_recruitment_survey
#: model_terms:ir.ui.view,arch_db:hr_recruitment_survey.crm_case_form_view_job_inherit
msgid "Print interview report"
msgstr ""
#. module: hr_recruitment_survey
#: model:survey.question,question:hr_recruitment_survey.recruitment_3_1
msgid "Rate the Importance"
msgstr ""
#. module: hr_recruitment_survey
#: model:survey.survey,title:hr_recruitment_survey.recruitment_form
msgid "Recruitment Form"
msgstr ""
#. module: hr_recruitment_survey
#: model:survey.label,value:hr_recruitment_survey.rrow_2_1_12
msgid "Regular meetings"
msgstr ""
#. module: hr_recruitment_survey
#: model:ir.model.fields,field_description:hr_recruitment_survey.field_hr_applicant_response_id
msgid "Response"
msgstr ""
#. module: hr_recruitment_survey
#: model:survey.label,value:hr_recruitment_survey.rcol_3_1_2
msgid "Somewhat important"
msgstr ""
#. module: hr_recruitment_survey
#: model:survey.label,value:hr_recruitment_survey.rrow_2_1_5
msgid "State of the art technology"
msgstr ""
#. module: hr_recruitment_survey
#: model:ir.model.fields,field_description:hr_recruitment_survey.field_hr_applicant_survey_id
msgid "Survey"
msgstr ""
#. module: hr_recruitment_survey
#: model:survey.question,validation_error_msg:hr_recruitment_survey.recruitment_1_1
#: model:survey.question,validation_error_msg:hr_recruitment_survey.recruitment_1_2
#: model:survey.question,validation_error_msg:hr_recruitment_survey.recruitment_1_3
#: model:survey.question,validation_error_msg:hr_recruitment_survey.recruitment_2_1
#: model:survey.question,validation_error_msg:hr_recruitment_survey.recruitment_2_2
#: model:survey.question,validation_error_msg:hr_recruitment_survey.recruitment_2_3
#: model:survey.question,validation_error_msg:hr_recruitment_survey.recruitment_2_4
#: model:survey.question,validation_error_msg:hr_recruitment_survey.recruitment_3_1
msgid "The answer you entered has an invalid format."
msgstr ""
#. module: hr_recruitment_survey
#: model:survey.survey,description:hr_recruitment_survey.recruitment_form
msgid ""
"This form is intended to help the responsible of a recruitment interview."
msgstr ""
#. module: hr_recruitment_survey
#: model:survey.question,constr_error_msg:hr_recruitment_survey.recruitment_1_1
#: model:survey.question,constr_error_msg:hr_recruitment_survey.recruitment_1_2
#: model:survey.question,constr_error_msg:hr_recruitment_survey.recruitment_1_3
#: model:survey.question,constr_error_msg:hr_recruitment_survey.recruitment_2_1
#: model:survey.question,constr_error_msg:hr_recruitment_survey.recruitment_2_2
#: model:survey.question,constr_error_msg:hr_recruitment_survey.recruitment_2_3
#: model:survey.question,constr_error_msg:hr_recruitment_survey.recruitment_2_4
#: model:survey.question,constr_error_msg:hr_recruitment_survey.recruitment_3_1
msgid "This question requires an answer."
msgstr ""
#. module: hr_recruitment_survey
#: model:survey.label,value:hr_recruitment_survey.rcol_3_1_4
msgid "Very important"
msgstr ""
#. module: hr_recruitment_survey
#: model:survey.question,question:hr_recruitment_survey.recruitment_1_3
msgid "What age group do you belong to?"
msgstr ""
#. module: hr_recruitment_survey
#: model:survey.question,question:hr_recruitment_survey.recruitment_1_2
msgid "What is your gender?"
msgstr ""
| {
"pile_set_name": "Github"
} |
/*!
* Copyright 2017-2020 XGBoost contributors
*/
#include <dmlc/filesystem.h>
#include <gtest/gtest.h>
#include <xgboost/predictor.h>
#include "../helpers.h"
#include "../predictor/test_predictor.h"
#include "../../../src/gbm/gbtree_model.h"
#include "../../../src/data/adapter.h"
namespace xgboost {
TEST(Plugin, OneAPIPredictorBasic) {
auto lparam = CreateEmptyGenericParam(0);
std::unique_ptr<Predictor> oneapi_predictor =
std::unique_ptr<Predictor>(Predictor::Create("oneapi_predictor", &lparam));
int kRows = 5;
int kCols = 5;
LearnerModelParam param;
param.num_feature = kCols;
param.base_score = 0.0;
param.num_output_group = 1;
gbm::GBTreeModel model = CreateTestModel(¶m);
auto dmat = RandomDataGenerator(kRows, kCols, 0).GenerateDMatrix();
// Test predict batch
PredictionCacheEntry out_predictions;
oneapi_predictor->PredictBatch(dmat.get(), &out_predictions, model, 0);
ASSERT_EQ(model.trees.size(), out_predictions.version);
std::vector<float>& out_predictions_h = out_predictions.predictions.HostVector();
for (size_t i = 0; i < out_predictions.predictions.Size(); i++) {
ASSERT_EQ(out_predictions_h[i], 1.5);
}
// Test predict instance
auto const &batch = *dmat->GetBatches<xgboost::SparsePage>().begin();
for (size_t i = 0; i < batch.Size(); i++) {
std::vector<float> instance_out_predictions;
oneapi_predictor->PredictInstance(batch[i], &instance_out_predictions, model);
ASSERT_EQ(instance_out_predictions[0], 1.5);
}
// Test predict leaf
std::vector<float> leaf_out_predictions;
oneapi_predictor->PredictLeaf(dmat.get(), &leaf_out_predictions, model);
for (auto v : leaf_out_predictions) {
ASSERT_EQ(v, 0);
}
// Test predict contribution
std::vector<float> out_contribution;
oneapi_predictor->PredictContribution(dmat.get(), &out_contribution, model);
ASSERT_EQ(out_contribution.size(), kRows * (kCols + 1));
for (size_t i = 0; i < out_contribution.size(); ++i) {
auto const& contri = out_contribution[i];
// shift 1 for bias, as test tree is a decision dump, only global bias is filled with LeafValue().
if ((i+1) % (kCols+1) == 0) {
ASSERT_EQ(out_contribution.back(), 1.5f);
} else {
ASSERT_EQ(contri, 0);
}
}
// Test predict contribution (approximate method)
oneapi_predictor->PredictContribution(dmat.get(), &out_contribution, model, 0, nullptr, true);
for (size_t i = 0; i < out_contribution.size(); ++i) {
auto const& contri = out_contribution[i];
// shift 1 for bias, as test tree is a decision dump, only global bias is filled with LeafValue().
if ((i+1) % (kCols+1) == 0) {
ASSERT_EQ(out_contribution.back(), 1.5f);
} else {
ASSERT_EQ(contri, 0);
}
}
}
TEST(Plugin, OneAPIPredictorExternalMemory) {
dmlc::TemporaryDirectory tmpdir;
std::string filename = tmpdir.path + "/big.libsvm";
std::unique_ptr<DMatrix> dmat = CreateSparsePageDMatrix(12, 64, filename);
auto lparam = CreateEmptyGenericParam(0);
std::unique_ptr<Predictor> oneapi_predictor =
std::unique_ptr<Predictor>(Predictor::Create("oneapi_predictor", &lparam));
LearnerModelParam param;
param.base_score = 0;
param.num_feature = dmat->Info().num_col_;
param.num_output_group = 1;
gbm::GBTreeModel model = CreateTestModel(¶m);
// Test predict batch
PredictionCacheEntry out_predictions;
oneapi_predictor->PredictBatch(dmat.get(), &out_predictions, model, 0);
std::vector<float> &out_predictions_h = out_predictions.predictions.HostVector();
ASSERT_EQ(out_predictions.predictions.Size(), dmat->Info().num_row_);
for (const auto& v : out_predictions_h) {
ASSERT_EQ(v, 1.5);
}
// Test predict leaf
std::vector<float> leaf_out_predictions;
oneapi_predictor->PredictLeaf(dmat.get(), &leaf_out_predictions, model);
ASSERT_EQ(leaf_out_predictions.size(), dmat->Info().num_row_);
for (const auto& v : leaf_out_predictions) {
ASSERT_EQ(v, 0);
}
// Test predict contribution
std::vector<float> out_contribution;
oneapi_predictor->PredictContribution(dmat.get(), &out_contribution, model);
ASSERT_EQ(out_contribution.size(), dmat->Info().num_row_ * (dmat->Info().num_col_ + 1));
for (size_t i = 0; i < out_contribution.size(); ++i) {
auto const& contri = out_contribution[i];
// shift 1 for bias, as test tree is a decision dump, only global bias is filled with LeafValue().
if ((i + 1) % (dmat->Info().num_col_ + 1) == 0) {
ASSERT_EQ(out_contribution.back(), 1.5f);
} else {
ASSERT_EQ(contri, 0);
}
}
// Test predict contribution (approximate method)
std::vector<float> out_contribution_approximate;
oneapi_predictor->PredictContribution(dmat.get(), &out_contribution_approximate, model, 0, nullptr, true);
ASSERT_EQ(out_contribution_approximate.size(),
dmat->Info().num_row_ * (dmat->Info().num_col_ + 1));
for (size_t i = 0; i < out_contribution.size(); ++i) {
auto const& contri = out_contribution[i];
// shift 1 for bias, as test tree is a decision dump, only global bias is filled with LeafValue().
if ((i + 1) % (dmat->Info().num_col_ + 1) == 0) {
ASSERT_EQ(out_contribution.back(), 1.5f);
} else {
ASSERT_EQ(contri, 0);
}
}
}
TEST(Plugin, OneAPIPredictorInplacePredict) {
bst_row_t constexpr kRows{128};
bst_feature_t constexpr kCols{64};
auto gen = RandomDataGenerator{kRows, kCols, 0.5}.Device(-1);
{
HostDeviceVector<float> data;
gen.GenerateDense(&data);
ASSERT_EQ(data.Size(), kRows * kCols);
std::shared_ptr<data::DenseAdapter> x{
new data::DenseAdapter(data.HostPointer(), kRows, kCols)};
TestInplacePrediction(x, "oneapi_predictor", kRows, kCols, -1);
}
{
HostDeviceVector<float> data;
HostDeviceVector<bst_row_t> rptrs;
HostDeviceVector<bst_feature_t> columns;
gen.GenerateCSR(&data, &rptrs, &columns);
std::shared_ptr<data::CSRAdapter> x{new data::CSRAdapter(
rptrs.HostPointer(), columns.HostPointer(), data.HostPointer(), kRows,
data.Size(), kCols)};
TestInplacePrediction(x, "oneapi_predictor", kRows, kCols, -1);
}
}
} // namespace xgboost
| {
"pile_set_name": "Github"
} |
let score (input : double list) =
let func0 =
if ((input.[12]) <= (8.91)) then
if ((input.[5]) <= (6.902)) then
if ((input.[7]) <= (1.48495)) then
50.0
else
25.320000000000004
else
38.34810126582279
else
if ((input.[0]) <= (5.84803)) then
19.99185520361991
else
12.102469135802467
let func1 =
if ((input.[12]) <= (9.725)) then
if ((input.[5]) <= (7.4525)) then
if ((input.[5]) <= (6.7539997)) then
24.801739130434775
else
32.47230769230769
else
47.075
else
if ((input.[12]) <= (15.0)) then
20.44094488188976
else
14.823214285714291
((func0) + (func1)) * (0.5)
| {
"pile_set_name": "Github"
} |
<?xml version="1.0" ?><!DOCTYPE TS><TS language="lv_LV" version="2.1">
<context>
<name>AutoScrollSettings</name>
<message>
<location filename="../autoscrollsettings.ui" line="14"/>
<source>AutoScroll Settings</source>
<translation>Automātiskās ritināšanas iestatījumi</translation>
</message>
<message>
<location filename="../autoscrollsettings.ui" line="68"/>
<source><h1>AutoScroll</h1></source>
<translation><h1>Automātiskā ritināšana</h1></translation>
</message>
<message>
<location filename="../autoscrollsettings.ui" line="105"/>
<source>Scroll Divider:</source>
<translation>Ritināšanas atdalītājs:</translation>
</message>
<message>
<location filename="../autoscrollsettings.ui" line="134"/>
<source><b>Note:</b> Setting higher divider will slow down scrolling</source>
<translation><b>Piezīme:</b> Augstāka atdalītāja uzstādīšana samazināt ritināšanas ātrumu</translation>
</message>
</context>
</TS> | {
"pile_set_name": "Github"
} |
/*
* Copyright (c) 2013 The WebRTC 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 in the root of the source
* tree. An additional intellectual property rights grant can be found
* in the file PATENTS. All contributing project authors may
* be found in the AUTHORS file in the root of the source tree.
*/
#include "webrtc/modules/video_coding/main/source/test/stream_generator.h"
#include <string.h>
#include <list>
#include "testing/gtest/include/gtest/gtest.h"
#include "webrtc/modules/video_coding/main/source/packet.h"
#include "webrtc/modules/video_coding/main/test/test_util.h"
#include "webrtc/system_wrappers/interface/clock.h"
namespace webrtc {
StreamGenerator::StreamGenerator(uint16_t start_seq_num,
uint32_t start_timestamp,
int64_t current_time)
: packets_(),
sequence_number_(start_seq_num),
timestamp_(start_timestamp),
start_time_(current_time) {}
void StreamGenerator::Init(uint16_t start_seq_num,
uint32_t start_timestamp,
int64_t current_time) {
packets_.clear();
sequence_number_ = start_seq_num;
timestamp_ = start_timestamp;
start_time_ = current_time;
memset(&packet_buffer, 0, sizeof(packet_buffer));
}
void StreamGenerator::GenerateFrame(FrameType type,
int num_media_packets,
int num_empty_packets,
int64_t current_time) {
timestamp_ = 90 * (current_time - start_time_);
for (int i = 0; i < num_media_packets; ++i) {
const int packet_size =
(kFrameSize + num_media_packets / 2) / num_media_packets;
bool marker_bit = (i == num_media_packets - 1);
packets_.push_back(GeneratePacket(
sequence_number_, timestamp_, packet_size, (i == 0), marker_bit, type));
++sequence_number_;
}
for (int i = 0; i < num_empty_packets; ++i) {
packets_.push_back(GeneratePacket(
sequence_number_, timestamp_, 0, false, false, kFrameEmpty));
++sequence_number_;
}
}
VCMPacket StreamGenerator::GeneratePacket(uint16_t sequence_number,
uint32_t timestamp,
unsigned int size,
bool first_packet,
bool marker_bit,
FrameType type) {
EXPECT_LT(size, kMaxPacketSize);
VCMPacket packet;
packet.seqNum = sequence_number;
packet.timestamp = timestamp;
packet.frameType = type;
packet.isFirstPacket = first_packet;
packet.markerBit = marker_bit;
packet.sizeBytes = size;
packet.dataPtr = packet_buffer;
if (packet.isFirstPacket)
packet.completeNALU = kNaluStart;
else if (packet.markerBit)
packet.completeNALU = kNaluEnd;
else
packet.completeNALU = kNaluIncomplete;
return packet;
}
bool StreamGenerator::PopPacket(VCMPacket* packet, int index) {
std::list<VCMPacket>::iterator it = GetPacketIterator(index);
if (it == packets_.end())
return false;
if (packet)
*packet = (*it);
packets_.erase(it);
return true;
}
bool StreamGenerator::GetPacket(VCMPacket* packet, int index) {
std::list<VCMPacket>::iterator it = GetPacketIterator(index);
if (it == packets_.end())
return false;
if (packet)
*packet = (*it);
return true;
}
bool StreamGenerator::NextPacket(VCMPacket* packet) {
if (packets_.empty())
return false;
if (packet != NULL)
*packet = packets_.front();
packets_.pop_front();
return true;
}
void StreamGenerator::DropLastPacket() { packets_.pop_back(); }
uint16_t StreamGenerator::NextSequenceNumber() const {
if (packets_.empty())
return sequence_number_;
return packets_.front().seqNum;
}
int StreamGenerator::PacketsRemaining() const { return packets_.size(); }
std::list<VCMPacket>::iterator StreamGenerator::GetPacketIterator(int index) {
std::list<VCMPacket>::iterator it = packets_.begin();
for (int i = 0; i < index; ++i) {
++it;
if (it == packets_.end())
break;
}
return it;
}
} // namespace webrtc
| {
"pile_set_name": "Github"
} |
"OK" = "OK";
"Back" = "Back";
"Done" = "Done";
"Sorry" = "Sorry";
"Cancel" = "Cancel";
"Setting" = "Setting";
"Photos" = "Photos";
"Videos" = "Videos";
"Preview" = "Preview";
"Full image" = "Full image";
"Processing..." = "Processing...";
"Synchronizing photos from iCloud" = "Synchronizing photos from iCloud";
"Can not use camera" = "Can not use camera";
"Can not choose both video and photo" = "Can not choose both video and photo";
"Can not choose both photo and GIF" = "Can not choose both photo and GIF";
"Select the video when in multi state, we will handle the video as a photo" = "Select the video when in multi state, we will handle the video as a photo";
"Can not jump to the privacy settings page, please go to the settings page by self, thank you" = "Can not jump to the privacy settings page, please go to the settings page by self, thank you";
"Select a maximum of %zd photos" = "Select a maximum of %zd photos";
"Select a minimum of %zd photos" = "Select a minimum of %zd photos";
"Allow %@ to access your album in \"Settings -> Privacy -> Photos\"" = "Allow %@ to access your album in \"Settings -> Privacy -> Photos\"";
"Please allow %@ to access your camera in \"Settings -> Privacy -> Camera\"" = "Please allow %@ to access your camera in \"Settings -> Privacy -> Camera\"";
| {
"pile_set_name": "Github"
} |
# Makefile for kernel module
KERNEL_VERSION:=$(shell uname -r)
KERNEL_PATH:=/lib/modules/$(KERNEL_VERSION)/build
obj-m = litepcie.o
litepcie-objs = main.o
all: litepcie.ko
litepcie.ko: main.c
make -C $(KERNEL_PATH) M=$(PWD) modules
clean:
make -C $(KERNEL_PATH) M=$(PWD) clean
rm -f *~
| {
"pile_set_name": "Github"
} |
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>CSS Test: URL with missing closing parenthesis</title>
<link rel="author" title="Microsoft" href="http://www.microsoft.com/" />
<link rel="help" href="http://www.w3.org/TR/CSS21/syndata.html#uri" />
<link rel="match" href="../reference/no-red-filler-text-ref.xht"/>
<meta name="flags" content="image invalid" />
<meta name="assert" content="Url functions with missing closing parenthesis are ignored." />
<style type="text/css">
div
{
background: url("support/red_box.png";
}
</style>
</head>
<body>
<p>Test passes if there is no red visible on the page.</p>
<div>Filler Text</div>
</body>
</html> | {
"pile_set_name": "Github"
} |
#!/bin/bash -e
if [ ! -d qemu/qemu ]; then
cd qemu
git clone https://github.com/geohot/qemu.git --depth 1 --branch qira
cd ..
fi
cd qemu/qemu
./configure --target-list=i386-linux-user,x86_64-linux-user,arm-linux-user,ppc-linux-user,aarch64-linux-user,mips-linux-user,mipsel-linux-user --enable-tcg-interpreter --enable-debug-tcg --cpu=unknown --python=python
make -j$(getconf _NPROCESSORS_ONLN)
| {
"pile_set_name": "Github"
} |
<?php
namespace App\Jobs\Setting;
use App\Abstracts\Job;
use App\Models\Setting\Tax;
class CreateTax extends Job
{
protected $tax;
protected $request;
/**
* Create a new job instance.
*
* @param $request
*/
public function __construct($request)
{
$this->request = $this->getRequestInstance($request);
}
/**
* Execute the job.
*
* @return Tax
*/
public function handle()
{
\DB::transaction(function () {
$this->tax = Tax::create($this->request->all());
});
return $this->tax;
}
}
| {
"pile_set_name": "Github"
} |
{"channel_id":"244567637332328449","emoji":{"id":"238039508006862848","name":"AkaShrug~1"},"message_id":"302928389764022282","user_id":"114941315417899012"}
| {
"pile_set_name": "Github"
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.