max_stars_count
int64 301
224k
| text
stringlengths 6
1.05M
| token_count
int64 3
727k
|
---|---|---|
317 | <reponame>neha03071990/tutorial-examples
/**
* Copyright (c) 2014 Oracle and/or its affiliates. All rights reserved.
*
* You may not modify, use, reproduce, or distribute this software except in
* compliance with the terms of the License at:
* https://github.com/javaee/tutorial-examples/LICENSE.txt
*/
package javaeetutorial.web.websocketbot.messages;
/* Represents an information message, like
* an user entering or leaving the chat */
public class InfoMessage extends Message {
private String info;
public InfoMessage(String info) {
this.info = info;
}
public String getInfo() {
return info;
}
/* For logging purposes */
@Override
public String toString() {
return "[InfoMessage] " + info;
}
}
| 300 |
1,338 | {
"enterConferenceNameOrUrl": "Entrez un nom pour votre conférence ou une URL Jitsi",
"go": "Rejoindre",
"help": "Aide",
"termsLink": "Conditions d'utilisation",
"privacyLink": "Politique de confidentialité",
"sendFeedbackLink": "Envoyer des commentaires",
"aboutLink": "A propos",
"sourceLink": "Code source",
"versionLabel": "Version: {{version}}",
"onboarding": {
"startTour": "Démarrez le tutoriel",
"skip": "Passer",
"welcome": "Bienvenue sur {{appName}}",
"letUsShowYouAround": "Laissez-nous vous montrer!",
"next": "Suivant",
"conferenceUrl": "Entrez le nom (ou l'URL complète) de la conférence que vous souhaitez rejoindre. Vous pouvez choisir ce que vous voulez, dites simplement à vos contacts d'utiliser le même nom.",
"settingsDrawerButton": "Cliquez içi pour ouvrir le panneau de configuration.",
"nameSetting": "Ceçi est votre nom, les participants vous verrons avec celui çi.",
"emailSetting": "L'email que vous entrez içi fera partie de votre profil utilisateur.",
"startMutedToggles": "Vous pouvez choisir de démarrer vos conférences avec l'audio et la vidéo désactivés. Ceci sera appliqué à toutes les conférences.",
"serverSetting": "Ceçi est le serveur utilisé pour vos conférences. Vous pouvez utiliser le votre, mais vous n'êtes pas obligés!",
"serverTimeout": "Delai pour rejoindre la conférence. Si la conférence ne s'est pas ouverte avant ce delai, elle sera abandonnée.",
"alwaysOnTop": "Vous pouvez activer la fenêtre \"Toujours au Dessus\", qui sera affichée quand la fenêtre principale n'est plus en premier plan. Ceci sera appliqué à toutes les conférences.."
},
"settings": {
"back": "Retour",
"name": "Nom",
"email": "Email",
"advancedSettings": "Paramètres avancés",
"alwaysOnTopWindow": "Fenêtre Toujours au Dessus",
"startWithAudioMuted": "Démarrer avec le micro coupé",
"startWithVideoMuted": "Démarrer avec la caméra coupée",
"invalidServer": "URL invalide",
"serverUrl": "URL du serveur",
"serverTimeout": "Délai de connexion au server (en secondes)"
}
}
| 797 |
2,329 | <filename>shenyu-admin/src/main/java/org/apache/shenyu/admin/utils/ShenyuDictH2Trigger.java
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
package org.apache.shenyu.admin.utils;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import org.apache.shenyu.common.exception.ShenyuException;
import org.h2.api.Trigger;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* Trigger for shenyu_dict of h2.
*/
public class ShenyuDictH2Trigger implements Trigger {
private static final Logger LOG = LoggerFactory.getLogger(ShenyuDictH2Trigger.class);
@Override
public void init(final Connection connection, final String s, final String s1, final String s2, final boolean b, final int i) throws SQLException {
}
@Override
public void fire(final Connection connection, final Object[] oldRow, final Object[] newRow) throws SQLException {
try (PreparedStatement statement = connection.prepareStatement(
"INSERT IGNORE INTO SHENYU_DICT (`ID`,`TYPE`,`DICT_CODE`,`DICT_NAME`,`DICT_VALUE`,`DESC`,`SORT`,`ENABLED`)"
+ " VALUES ( ?, ?, ?, ?, ?, ?, ?, ?)")) {
BaseTrigger.sqlExecute(newRow, statement);
} catch (ShenyuException e) {
LOG.error("ShenyuDictH2Trigger Error:" + e);
}
}
@Override
public void close() throws SQLException {
}
@Override
public void remove() throws SQLException {
}
}
| 757 |
1,176 | // Copyright (c) 2014 <NAME>.
// See the LICENSE file.
//
#include "src/browser/session/thrust_session_visitedlink_store.h"
#include "url/gurl.h"
#include "content/public/browser/browser_thread.h"
#include "src/browser/session/thrust_session.h"
#include "src/browser/visitedlink/visitedlink_master.h"
using namespace content;
namespace thrust_shell {
ThrustSessionVisitedLinkStore::ThrustSessionVisitedLinkStore(
ThrustSession* parent)
: parent_(parent),
visitedlink_master_(new visitedlink::VisitedLinkMaster(
parent, this, !parent->IsOffTheRecord()))
{
}
ThrustSessionVisitedLinkStore::~ThrustSessionVisitedLinkStore()
{
}
bool
ThrustSessionVisitedLinkStore::Init()
{
return visitedlink_master_->Init();
}
void
ThrustSessionVisitedLinkStore::Add(
const std::string& url)
{
if(!parent_->IsOffTheRecord()) {
visitedlink_master_->AddURL(GURL(url));
}
}
void
ThrustSessionVisitedLinkStore::Clear()
{
visitedlink_master_->DeleteAllURLs();
}
void
ThrustSessionVisitedLinkStore::RebuildTable(
const scoped_refptr<URLEnumerator>& enumerator)
{
/* We return no URL as the master here. The master takes care of persisting */
/* the visited links, and this API is used in case of failure or when off */
/* the record. */
enumerator->OnComplete(true);
}
} // namespace thrust_shell
| 515 |
465 | #include "realtime_srv/net/ClientProxy.h"
#include "realtime_srv/net/NetworkMgr.h"
#include "realtime_srv/game_obj/GameObj.h"
using namespace realtime_srv;
GameObj::GameObj() :
isPendingToDie_(false),
hasMaster_(false),
objId_(0)
{}
void GameObj::SetStateDirty(uint32_t repState)
{
assert(networkMgr_);
networkMgr_->SetRepStateDirty(objId_, repState);
}
void GameObj::Update()
{
BeforeProcessInput();
if (hasMaster_)
{
ActionList& actionList = GetMaster()->GetUnprocessedActionList();
for (const Action& unprocessedAction : actionList)
{
const InputStatePtr& currentState = unprocessedAction.GetInputState();
float deltaTime = unprocessedAction.GetDeltaTime();
ProcessInput(deltaTime, currentState);
}
actionList.Clear();
}
AfterProcessInput();
}
void GameObj::LoseMaster()
{
if (ClientProxyPtr m = master_.lock())
m->RealeaseSpecificOwnedGameObj(objId_);
hasMaster_ = false;
master_.reset();
}
void GameObj::SetMaster(std::shared_ptr<ClientProxy> cp)
{ master_ = cp; hasMaster_ = true; cp->AddGameObj(shared_from_this()); }
void GameObj::SetPendingToDie()
{ isPendingToDie_ = true; LoseMaster(); }
| 426 |
376 |
extern zend_class_entry *ice_validation_validator_notin_ce;
ZEPHIR_INIT_CLASS(Ice_Validation_Validator_NotIn);
PHP_METHOD(Ice_Validation_Validator_NotIn, validate);
ZEND_BEGIN_ARG_INFO_EX(arginfo_ice_validation_validator_notin_validate, 0, 0, 2)
ZEND_ARG_OBJ_INFO(0, validation, Ice\\Validation, 0)
ZEND_ARG_INFO(0, field)
ZEND_END_ARG_INFO()
ZEPHIR_INIT_FUNCS(ice_validation_validator_notin_method_entry) {
PHP_ME(Ice_Validation_Validator_NotIn, validate, arginfo_ice_validation_validator_notin_validate, ZEND_ACC_PUBLIC)
PHP_FE_END
};
| 239 |
434 | <gh_stars>100-1000
/*
* TP-LINK TL-WR1041 v2 board support
*
* Copyright (C) 2010-2012 <NAME> <<EMAIL>>
* Copyright (C) 2011-2012 <NAME> <<EMAIL>>
*
* This program is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 as published
* by the Free Software Foundation.
*/
#include <linux/pci.h>
#include <linux/phy.h>
#include <linux/platform_device.h>
#include <linux/ath9k_platform.h>
#include <linux/ar8216_platform.h>
#include <asm/mach-ath79/ar71xx_regs.h>
#include "common.h"
#include "dev-ap9x-pci.h"
#include "dev-eth.h"
#include "dev-gpio-buttons.h"
#include "dev-leds-gpio.h"
#include "dev-m25p80.h"
#include "dev-spi.h"
#include "dev-wmac.h"
#include "machtypes.h"
#define TL_WR1041NV2_GPIO_BTN_RESET 14
#define TL_WR1041NV2_GPIO_LED_WPS 13
#define TL_WR1041NV2_GPIO_LED_WLAN 11
#define TL_WR1041NV2_GPIO_LED_SYSTEM 12
#define TL_WR1041NV2_KEYS_POLL_INTERVAL 20 /* msecs */
#define TL_WR1041NV2_KEYS_DEBOUNCE_INTERVAL (3 * TL_WR1041NV2_KEYS_POLL_INTERVAL)
#define TL_WR1041NV2_PCIE_CALDATA_OFFSET 0x5000
static const char *tl_wr1041nv2_part_probes[] = {
"tp-link",
NULL,
};
static struct flash_platform_data tl_wr1041nv2_flash_data = {
.part_probes = tl_wr1041nv2_part_probes,
};
static struct gpio_led tl_wr1041nv2_leds_gpio[] __initdata = {
{
.name = "tp-link:green:system",
.gpio = TL_WR1041NV2_GPIO_LED_SYSTEM,
.active_low = 1,
}, {
.name = "tp-link:green:wps",
.gpio = TL_WR1041NV2_GPIO_LED_WPS,
.active_low = 1,
}, {
.name = "tp-link:green:wlan",
.gpio = TL_WR1041NV2_GPIO_LED_WLAN,
.active_low = 1,
}
};
static struct gpio_keys_button tl_wr1041nv2_gpio_keys[] __initdata = {
{
.desc = "reset",
.type = EV_KEY,
.code = KEY_RESTART,
.debounce_interval = TL_WR1041NV2_KEYS_DEBOUNCE_INTERVAL,
.gpio = TL_WR1041NV2_GPIO_BTN_RESET,
.active_low = 1,
}
};
static const struct ar8327_led_info tl_wr1041n_leds_ar8327[] = {
AR8327_LED_INFO(PHY0_0, HW, "tp-link:green:wan"),
AR8327_LED_INFO(PHY1_0, HW, "tp-link:green:lan1"),
AR8327_LED_INFO(PHY2_0, HW, "tp-link:green:lan2"),
AR8327_LED_INFO(PHY3_0, HW, "tp-link:green:lan3"),
AR8327_LED_INFO(PHY4_0, HW, "tp-link:green:lan4"),
};
static struct ar8327_led_cfg wr1041n_v2_ar8327_led_cfg = {
.led_ctrl0 = 0xcf35cf35, /* LED0: blink at 10/100/1000M */
.led_ctrl1 = 0xcf35cf35, /* LED1: blink at 10/100/1000M: anyway, no LED1 on tl-wr1041n */
.led_ctrl2 = 0xcf35cf35, /* LED2: blink at 10/100/1000M: anyway, no LED2 on tl-wr1041n */
.led_ctrl3 = 0x03ffff00, /* Pattern enabled for LED 0-2 of port 1-3 */
.open_drain = true,
};
static struct ar8327_pad_cfg db120_ar8327_pad0_cfg = {
.mode = AR8327_PAD_MAC_RGMII,
.txclk_delay_en = true,
.rxclk_delay_en = true,
.txclk_delay_sel = AR8327_CLK_DELAY_SEL1,
.rxclk_delay_sel = AR8327_CLK_DELAY_SEL2,
};
static struct ar8327_platform_data db120_ar8327_data = {
.pad0_cfg = &db120_ar8327_pad0_cfg,
.port0_cfg = {
.force_link = 1,
.speed = AR8327_PORT_SPEED_1000,
.duplex = 1,
.txpause = 1,
.rxpause = 1,
},
.led_cfg = &wr1041n_v2_ar8327_led_cfg,
.num_leds = ARRAY_SIZE(tl_wr1041n_leds_ar8327),
.leds = tl_wr1041n_leds_ar8327
};
static struct mdio_board_info db120_mdio0_info[] = {
{
.bus_id = "ag71xx-mdio.0",
.phy_addr = 0,
.platform_data = &db120_ar8327_data,
},
};
static void __init tl_wr1041nv2_setup(void)
{
u8 *mac = (u8 *) KSEG1ADDR(0x1f01fc00);
u8 *ee = (u8 *) KSEG1ADDR(0x1fff1000);
ath79_register_m25p80(&tl_wr1041nv2_flash_data);
ath79_register_leds_gpio(-1, ARRAY_SIZE(tl_wr1041nv2_leds_gpio),
tl_wr1041nv2_leds_gpio);
ath79_register_gpio_keys_polled(-1, TL_WR1041NV2_KEYS_POLL_INTERVAL,
ARRAY_SIZE(tl_wr1041nv2_gpio_keys),
tl_wr1041nv2_gpio_keys);
ath79_register_wmac(ee, mac);
ath79_setup_ar934x_eth_cfg(AR934X_ETH_CFG_RGMII_GMAC0 |
AR934X_ETH_CFG_SW_ONLY_MODE);
ath79_register_mdio(1, 0x0);
ath79_register_mdio(0, 0x0);
ath79_init_mac(ath79_eth0_data.mac_addr, mac, 1);
mdiobus_register_board_info(db120_mdio0_info,
ARRAY_SIZE(db120_mdio0_info));
/* GMAC0 is connected to an AR8327 switch */
ath79_eth0_data.phy_if_mode = PHY_INTERFACE_MODE_RGMII;
ath79_eth0_data.phy_mask = BIT(0);
ath79_eth0_data.mii_bus_dev = &ath79_mdio0_device.dev;
ath79_eth0_pll_data.pll_1000 = 0x06000000;
ath79_register_eth(0);
}
MIPS_MACHINE(ATH79_MACH_TL_WR1041N_V2, "TL-WR1041N-v2",
"TP-LINK TL-WR1041N v2", tl_wr1041nv2_setup);
| 2,232 |
5,142 | # Copyright (c) 2016-2019 Uber Technologies, 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 __future__ import absolute_import
import requests
from utils import tls_opts_with_client_certs
class Uploader(object):
def __init__(self, addr):
self.addr = addr
def _start(self, name):
url = 'https://{addr}/namespace/testfs/blobs/sha256:{name}/uploads'.format(
addr=self.addr, name=name)
res = requests.post(url, **tls_opts_with_client_certs())
res.raise_for_status()
return res.headers['Location']
def _patch(self, name, uid, start, stop, chunk):
url = 'https://{addr}/namespace/testfs/blobs/sha256:{name}/uploads/{uid}'.format(
addr=self.addr, name=name, uid=uid)
res = requests.patch(url, headers={'Content-Range': '%d-%d' % (start, stop)}, data=chunk, **tls_opts_with_client_certs())
res.raise_for_status()
def _commit(self, name, uid):
url = 'https://{addr}/namespace/testfs/blobs/sha256:{name}/uploads/{uid}'.format(
addr=self.addr, name=name, uid=uid)
res = requests.put(url, **tls_opts_with_client_certs())
res.raise_for_status()
def upload(self, name, blob):
uid = self._start(name)
self._patch(name, uid, 0, len(blob), blob)
self._commit(name, uid)
| 713 |
337 | /**
* synflood API generated from synflood.yang
*
* NOTE: This file is auto generated by polycube-codegen
* https://github.com/polycube-network/polycube-codegen
*/
/* Do not edit this file manually */
/*
* SynfloodApiImpl.h
*
*
*/
#pragma once
#include <memory>
#include <map>
#include <mutex>
#include "../Synflood.h"
#include "StatsJsonObject.h"
#include "SynfloodJsonObject.h"
#include <vector>
namespace polycube {
namespace service {
namespace api {
using namespace polycube::service::model;
namespace SynfloodApiImpl {
void create_synflood_by_id(const std::string &name, const SynfloodJsonObject &value);
void delete_synflood_by_id(const std::string &name);
SynfloodJsonObject read_synflood_by_id(const std::string &name);
std::vector<SynfloodJsonObject> read_synflood_list_by_id();
StatsJsonObject read_synflood_stats_by_id(const std::string &name);
std::string read_synflood_stats_deliverratio_by_id(const std::string &name);
uint64_t read_synflood_stats_lastupdate_by_id(const std::string &name);
std::string read_synflood_stats_responseratio_by_id(const std::string &name);
std::string read_synflood_stats_tcpattemptfails_by_id(const std::string &name);
std::string read_synflood_stats_tcpoutrsts_by_id(const std::string &name);
void replace_synflood_by_id(const std::string &name, const SynfloodJsonObject &value);
void update_synflood_by_id(const std::string &name, const SynfloodJsonObject &value);
void update_synflood_list_by_id(const std::vector<SynfloodJsonObject> &value);
/* help related */
std::vector<nlohmann::fifo_map<std::string, std::string>> read_synflood_list_by_id_get_list();
}
}
}
}
| 604 |
346 | void star1(const int n, prk::vector<double> & in, prk::vector<double> & out) {
auto dim = ranges::views::iota(1,n-1);
auto inside = ranges::views::cartesian_product(dim,dim);
for (auto ij : inside) {
auto [i, j] = ij;
out[i*n+j] += +in[(i)*n+(j-1)] * -0.5
+in[(i-1)*n+(j)] * -0.5
+in[(i+1)*n+(j)] * 0.5
+in[(i)*n+(j+1)] * 0.5;
}
}
void star1(const int n, const int t, prk::vector<double> & in, prk::vector<double> & out) {
auto s2 = ranges::views::cartesian_product(ranges::stride_view(ranges::views::iota(0, n), t),ranges::stride_view(ranges::views::iota(0, n), t));
auto t2 = ranges::views::cartesian_product(ranges::views::iota(0, t),ranges::views::iota(0, t));
const auto r = 1;
for (auto itjt : s2) {
auto [it, jt] = itjt;
for (auto iijj : t2) {
auto [ii, jj] = iijj;
auto i = ii + it;
auto j = jj + jt;
if (r <= i && i < n-r && r <= j && j < n-r) {
out[i*n+j] += +in[(i)*n+(j-1)] * -0.5
+in[(i-1)*n+(j)] * -0.5
+in[(i+1)*n+(j)] * 0.5
+in[(i)*n+(j+1)] * 0.5;
}
}
}
}
void star2(const int n, prk::vector<double> & in, prk::vector<double> & out) {
auto dim = ranges::views::iota(2,n-2);
auto inside = ranges::views::cartesian_product(dim,dim);
for (auto ij : inside) {
auto [i, j] = ij;
out[i*n+j] += +in[(i)*n+(j-2)] * -0.125
+in[(i)*n+(j-1)] * -0.25
+in[(i-2)*n+(j)] * -0.125
+in[(i-1)*n+(j)] * -0.25
+in[(i+1)*n+(j)] * 0.25
+in[(i+2)*n+(j)] * 0.125
+in[(i)*n+(j+1)] * 0.25
+in[(i)*n+(j+2)] * 0.125;
}
}
void star2(const int n, const int t, prk::vector<double> & in, prk::vector<double> & out) {
auto s2 = ranges::views::cartesian_product(ranges::stride_view(ranges::views::iota(0, n), t),ranges::stride_view(ranges::views::iota(0, n), t));
auto t2 = ranges::views::cartesian_product(ranges::views::iota(0, t),ranges::views::iota(0, t));
const auto r = 2;
for (auto itjt : s2) {
auto [it, jt] = itjt;
for (auto iijj : t2) {
auto [ii, jj] = iijj;
auto i = ii + it;
auto j = jj + jt;
if (r <= i && i < n-r && r <= j && j < n-r) {
out[i*n+j] += +in[(i)*n+(j-2)] * -0.125
+in[(i)*n+(j-1)] * -0.25
+in[(i-2)*n+(j)] * -0.125
+in[(i-1)*n+(j)] * -0.25
+in[(i+1)*n+(j)] * 0.25
+in[(i+2)*n+(j)] * 0.125
+in[(i)*n+(j+1)] * 0.25
+in[(i)*n+(j+2)] * 0.125;
}
}
}
}
void star3(const int n, prk::vector<double> & in, prk::vector<double> & out) {
auto dim = ranges::views::iota(3,n-3);
auto inside = ranges::views::cartesian_product(dim,dim);
for (auto ij : inside) {
auto [i, j] = ij;
out[i*n+j] += +in[(i)*n+(j-3)] * -0.05555555555555555
+in[(i)*n+(j-2)] * -0.08333333333333333
+in[(i)*n+(j-1)] * -0.16666666666666666
+in[(i-3)*n+(j)] * -0.05555555555555555
+in[(i-2)*n+(j)] * -0.08333333333333333
+in[(i-1)*n+(j)] * -0.16666666666666666
+in[(i+1)*n+(j)] * 0.16666666666666666
+in[(i+2)*n+(j)] * 0.08333333333333333
+in[(i+3)*n+(j)] * 0.05555555555555555
+in[(i)*n+(j+1)] * 0.16666666666666666
+in[(i)*n+(j+2)] * 0.08333333333333333
+in[(i)*n+(j+3)] * 0.05555555555555555;
}
}
void star3(const int n, const int t, prk::vector<double> & in, prk::vector<double> & out) {
auto s2 = ranges::views::cartesian_product(ranges::stride_view(ranges::views::iota(0, n), t),ranges::stride_view(ranges::views::iota(0, n), t));
auto t2 = ranges::views::cartesian_product(ranges::views::iota(0, t),ranges::views::iota(0, t));
const auto r = 3;
for (auto itjt : s2) {
auto [it, jt] = itjt;
for (auto iijj : t2) {
auto [ii, jj] = iijj;
auto i = ii + it;
auto j = jj + jt;
if (r <= i && i < n-r && r <= j && j < n-r) {
out[i*n+j] += +in[(i)*n+(j-3)] * -0.05555555555555555
+in[(i)*n+(j-2)] * -0.08333333333333333
+in[(i)*n+(j-1)] * -0.16666666666666666
+in[(i-3)*n+(j)] * -0.05555555555555555
+in[(i-2)*n+(j)] * -0.08333333333333333
+in[(i-1)*n+(j)] * -0.16666666666666666
+in[(i+1)*n+(j)] * 0.16666666666666666
+in[(i+2)*n+(j)] * 0.08333333333333333
+in[(i+3)*n+(j)] * 0.05555555555555555
+in[(i)*n+(j+1)] * 0.16666666666666666
+in[(i)*n+(j+2)] * 0.08333333333333333
+in[(i)*n+(j+3)] * 0.05555555555555555;
}
}
}
}
void star4(const int n, prk::vector<double> & in, prk::vector<double> & out) {
auto dim = ranges::views::iota(4,n-4);
auto inside = ranges::views::cartesian_product(dim,dim);
for (auto ij : inside) {
auto [i, j] = ij;
out[i*n+j] += +in[(i)*n+(j-4)] * -0.03125
+in[(i)*n+(j-3)] * -0.041666666666666664
+in[(i)*n+(j-2)] * -0.0625
+in[(i)*n+(j-1)] * -0.125
+in[(i-4)*n+(j)] * -0.03125
+in[(i-3)*n+(j)] * -0.041666666666666664
+in[(i-2)*n+(j)] * -0.0625
+in[(i-1)*n+(j)] * -0.125
+in[(i+1)*n+(j)] * 0.125
+in[(i+2)*n+(j)] * 0.0625
+in[(i+3)*n+(j)] * 0.041666666666666664
+in[(i+4)*n+(j)] * 0.03125
+in[(i)*n+(j+1)] * 0.125
+in[(i)*n+(j+2)] * 0.0625
+in[(i)*n+(j+3)] * 0.041666666666666664
+in[(i)*n+(j+4)] * 0.03125;
}
}
void star4(const int n, const int t, prk::vector<double> & in, prk::vector<double> & out) {
auto s2 = ranges::views::cartesian_product(ranges::stride_view(ranges::views::iota(0, n), t),ranges::stride_view(ranges::views::iota(0, n), t));
auto t2 = ranges::views::cartesian_product(ranges::views::iota(0, t),ranges::views::iota(0, t));
const auto r = 4;
for (auto itjt : s2) {
auto [it, jt] = itjt;
for (auto iijj : t2) {
auto [ii, jj] = iijj;
auto i = ii + it;
auto j = jj + jt;
if (r <= i && i < n-r && r <= j && j < n-r) {
out[i*n+j] += +in[(i)*n+(j-4)] * -0.03125
+in[(i)*n+(j-3)] * -0.041666666666666664
+in[(i)*n+(j-2)] * -0.0625
+in[(i)*n+(j-1)] * -0.125
+in[(i-4)*n+(j)] * -0.03125
+in[(i-3)*n+(j)] * -0.041666666666666664
+in[(i-2)*n+(j)] * -0.0625
+in[(i-1)*n+(j)] * -0.125
+in[(i+1)*n+(j)] * 0.125
+in[(i+2)*n+(j)] * 0.0625
+in[(i+3)*n+(j)] * 0.041666666666666664
+in[(i+4)*n+(j)] * 0.03125
+in[(i)*n+(j+1)] * 0.125
+in[(i)*n+(j+2)] * 0.0625
+in[(i)*n+(j+3)] * 0.041666666666666664
+in[(i)*n+(j+4)] * 0.03125;
}
}
}
}
void star5(const int n, prk::vector<double> & in, prk::vector<double> & out) {
auto dim = ranges::views::iota(5,n-5);
auto inside = ranges::views::cartesian_product(dim,dim);
for (auto ij : inside) {
auto [i, j] = ij;
out[i*n+j] += +in[(i)*n+(j-5)] * -0.02
+in[(i)*n+(j-4)] * -0.025
+in[(i)*n+(j-3)] * -0.03333333333333333
+in[(i)*n+(j-2)] * -0.05
+in[(i)*n+(j-1)] * -0.1
+in[(i-5)*n+(j)] * -0.02
+in[(i-4)*n+(j)] * -0.025
+in[(i-3)*n+(j)] * -0.03333333333333333
+in[(i-2)*n+(j)] * -0.05
+in[(i-1)*n+(j)] * -0.1
+in[(i+1)*n+(j)] * 0.1
+in[(i+2)*n+(j)] * 0.05
+in[(i+3)*n+(j)] * 0.03333333333333333
+in[(i+4)*n+(j)] * 0.025
+in[(i+5)*n+(j)] * 0.02
+in[(i)*n+(j+1)] * 0.1
+in[(i)*n+(j+2)] * 0.05
+in[(i)*n+(j+3)] * 0.03333333333333333
+in[(i)*n+(j+4)] * 0.025
+in[(i)*n+(j+5)] * 0.02;
}
}
void star5(const int n, const int t, prk::vector<double> & in, prk::vector<double> & out) {
auto s2 = ranges::views::cartesian_product(ranges::stride_view(ranges::views::iota(0, n), t),ranges::stride_view(ranges::views::iota(0, n), t));
auto t2 = ranges::views::cartesian_product(ranges::views::iota(0, t),ranges::views::iota(0, t));
const auto r = 5;
for (auto itjt : s2) {
auto [it, jt] = itjt;
for (auto iijj : t2) {
auto [ii, jj] = iijj;
auto i = ii + it;
auto j = jj + jt;
if (r <= i && i < n-r && r <= j && j < n-r) {
out[i*n+j] += +in[(i)*n+(j-5)] * -0.02
+in[(i)*n+(j-4)] * -0.025
+in[(i)*n+(j-3)] * -0.03333333333333333
+in[(i)*n+(j-2)] * -0.05
+in[(i)*n+(j-1)] * -0.1
+in[(i-5)*n+(j)] * -0.02
+in[(i-4)*n+(j)] * -0.025
+in[(i-3)*n+(j)] * -0.03333333333333333
+in[(i-2)*n+(j)] * -0.05
+in[(i-1)*n+(j)] * -0.1
+in[(i+1)*n+(j)] * 0.1
+in[(i+2)*n+(j)] * 0.05
+in[(i+3)*n+(j)] * 0.03333333333333333
+in[(i+4)*n+(j)] * 0.025
+in[(i+5)*n+(j)] * 0.02
+in[(i)*n+(j+1)] * 0.1
+in[(i)*n+(j+2)] * 0.05
+in[(i)*n+(j+3)] * 0.03333333333333333
+in[(i)*n+(j+4)] * 0.025
+in[(i)*n+(j+5)] * 0.02;
}
}
}
}
void grid1(const int n, prk::vector<double> & in, prk::vector<double> & out) {
auto dim = ranges::views::iota(1,n-1);
auto inside = ranges::views::cartesian_product(dim,dim);
for (auto ij : inside) {
auto [i, j] = ij;
out[i*n+j] += +in[(i-1)*n+(j-1)] * -0.25
+in[(i)*n+(j-1)] * -0.25
+in[(i-1)*n+(j)] * -0.25
+in[(i+1)*n+(j)] * 0.25
+in[(i)*n+(j+1)] * 0.25
+in[(i+1)*n+(j+1)] * 0.25
;
}
}
void grid1(const int n, const int t, prk::vector<double> & in, prk::vector<double> & out) {
auto s2 = ranges::views::cartesian_product(ranges::stride_view(ranges::views::iota(0, n), t),ranges::stride_view(ranges::views::iota(0, n), t));
auto t2 = ranges::views::cartesian_product(ranges::views::iota(0, t),ranges::views::iota(0, t));
const auto r = 1;
for (auto itjt : s2) {
auto [it, jt] = itjt;
for (auto iijj : t2) {
auto [ii, jj] = iijj;
auto i = ii + it;
auto j = jj + jt;
if (r <= i && i < n-r && r <= j && j < n-r) {
out[i*n+j] += +in[(i-1)*n+(j-1)] * -0.25
+in[(i)*n+(j-1)] * -0.25
+in[(i-1)*n+(j)] * -0.25
+in[(i+1)*n+(j)] * 0.25
+in[(i)*n+(j+1)] * 0.25
+in[(i+1)*n+(j+1)] * 0.25
;
}
}
}
}
void grid2(const int n, prk::vector<double> & in, prk::vector<double> & out) {
auto dim = ranges::views::iota(2,n-2);
auto inside = ranges::views::cartesian_product(dim,dim);
for (auto ij : inside) {
auto [i, j] = ij;
out[i*n+j] += +in[(i-2)*n+(j-2)] * -0.0625
+in[(i-1)*n+(j-2)] * -0.020833333333333332
+in[(i)*n+(j-2)] * -0.020833333333333332
+in[(i+1)*n+(j-2)] * -0.020833333333333332
+in[(i-2)*n+(j-1)] * -0.020833333333333332
+in[(i-1)*n+(j-1)] * -0.125
+in[(i)*n+(j-1)] * -0.125
+in[(i+2)*n+(j-1)] * 0.020833333333333332
+in[(i-2)*n+(j)] * -0.020833333333333332
+in[(i-1)*n+(j)] * -0.125
+in[(i+1)*n+(j)] * 0.125
+in[(i+2)*n+(j)] * 0.020833333333333332
+in[(i-2)*n+(j+1)] * -0.020833333333333332
+in[(i)*n+(j+1)] * 0.125
+in[(i+1)*n+(j+1)] * 0.125
+in[(i+2)*n+(j+1)] * 0.020833333333333332
+in[(i-1)*n+(j+2)] * 0.020833333333333332
+in[(i)*n+(j+2)] * 0.020833333333333332
+in[(i+1)*n+(j+2)] * 0.020833333333333332
+in[(i+2)*n+(j+2)] * 0.0625
;
}
}
void grid2(const int n, const int t, prk::vector<double> & in, prk::vector<double> & out) {
auto s2 = ranges::views::cartesian_product(ranges::stride_view(ranges::views::iota(0, n), t),ranges::stride_view(ranges::views::iota(0, n), t));
auto t2 = ranges::views::cartesian_product(ranges::views::iota(0, t),ranges::views::iota(0, t));
const auto r = 2;
for (auto itjt : s2) {
auto [it, jt] = itjt;
for (auto iijj : t2) {
auto [ii, jj] = iijj;
auto i = ii + it;
auto j = jj + jt;
if (r <= i && i < n-r && r <= j && j < n-r) {
out[i*n+j] += +in[(i-2)*n+(j-2)] * -0.0625
+in[(i-1)*n+(j-2)] * -0.020833333333333332
+in[(i)*n+(j-2)] * -0.020833333333333332
+in[(i+1)*n+(j-2)] * -0.020833333333333332
+in[(i-2)*n+(j-1)] * -0.020833333333333332
+in[(i-1)*n+(j-1)] * -0.125
+in[(i)*n+(j-1)] * -0.125
+in[(i+2)*n+(j-1)] * 0.020833333333333332
+in[(i-2)*n+(j)] * -0.020833333333333332
+in[(i-1)*n+(j)] * -0.125
+in[(i+1)*n+(j)] * 0.125
+in[(i+2)*n+(j)] * 0.020833333333333332
+in[(i-2)*n+(j+1)] * -0.020833333333333332
+in[(i)*n+(j+1)] * 0.125
+in[(i+1)*n+(j+1)] * 0.125
+in[(i+2)*n+(j+1)] * 0.020833333333333332
+in[(i-1)*n+(j+2)] * 0.020833333333333332
+in[(i)*n+(j+2)] * 0.020833333333333332
+in[(i+1)*n+(j+2)] * 0.020833333333333332
+in[(i+2)*n+(j+2)] * 0.0625
;
}
}
}
}
void grid3(const int n, prk::vector<double> & in, prk::vector<double> & out) {
auto dim = ranges::views::iota(3,n-3);
auto inside = ranges::views::cartesian_product(dim,dim);
for (auto ij : inside) {
auto [i, j] = ij;
out[i*n+j] += +in[(i-3)*n+(j-3)] * -0.027777777777777776
+in[(i-2)*n+(j-3)] * -0.005555555555555556
+in[(i-1)*n+(j-3)] * -0.005555555555555556
+in[(i)*n+(j-3)] * -0.005555555555555556
+in[(i+1)*n+(j-3)] * -0.005555555555555556
+in[(i+2)*n+(j-3)] * -0.005555555555555556
+in[(i-3)*n+(j-2)] * -0.005555555555555556
+in[(i-2)*n+(j-2)] * -0.041666666666666664
+in[(i-1)*n+(j-2)] * -0.013888888888888888
+in[(i)*n+(j-2)] * -0.013888888888888888
+in[(i+1)*n+(j-2)] * -0.013888888888888888
+in[(i+3)*n+(j-2)] * 0.005555555555555556
+in[(i-3)*n+(j-1)] * -0.005555555555555556
+in[(i-2)*n+(j-1)] * -0.013888888888888888
+in[(i-1)*n+(j-1)] * -0.08333333333333333
+in[(i)*n+(j-1)] * -0.08333333333333333
+in[(i+2)*n+(j-1)] * 0.013888888888888888
+in[(i+3)*n+(j-1)] * 0.005555555555555556
+in[(i-3)*n+(j)] * -0.005555555555555556
+in[(i-2)*n+(j)] * -0.013888888888888888
+in[(i-1)*n+(j)] * -0.08333333333333333
+in[(i+1)*n+(j)] * 0.08333333333333333
+in[(i+2)*n+(j)] * 0.013888888888888888
+in[(i+3)*n+(j)] * 0.005555555555555556
+in[(i-3)*n+(j+1)] * -0.005555555555555556
+in[(i-2)*n+(j+1)] * -0.013888888888888888
+in[(i)*n+(j+1)] * 0.08333333333333333
+in[(i+1)*n+(j+1)] * 0.08333333333333333
+in[(i+2)*n+(j+1)] * 0.013888888888888888
+in[(i+3)*n+(j+1)] * 0.005555555555555556
+in[(i-3)*n+(j+2)] * -0.005555555555555556
+in[(i-1)*n+(j+2)] * 0.013888888888888888
+in[(i)*n+(j+2)] * 0.013888888888888888
+in[(i+1)*n+(j+2)] * 0.013888888888888888
+in[(i+2)*n+(j+2)] * 0.041666666666666664
+in[(i+3)*n+(j+2)] * 0.005555555555555556
+in[(i-2)*n+(j+3)] * 0.005555555555555556
+in[(i-1)*n+(j+3)] * 0.005555555555555556
+in[(i)*n+(j+3)] * 0.005555555555555556
+in[(i+1)*n+(j+3)] * 0.005555555555555556
+in[(i+2)*n+(j+3)] * 0.005555555555555556
+in[(i+3)*n+(j+3)] * 0.027777777777777776
;
}
}
void grid3(const int n, const int t, prk::vector<double> & in, prk::vector<double> & out) {
auto s2 = ranges::views::cartesian_product(ranges::stride_view(ranges::views::iota(0, n), t),ranges::stride_view(ranges::views::iota(0, n), t));
auto t2 = ranges::views::cartesian_product(ranges::views::iota(0, t),ranges::views::iota(0, t));
const auto r = 3;
for (auto itjt : s2) {
auto [it, jt] = itjt;
for (auto iijj : t2) {
auto [ii, jj] = iijj;
auto i = ii + it;
auto j = jj + jt;
if (r <= i && i < n-r && r <= j && j < n-r) {
out[i*n+j] += +in[(i-3)*n+(j-3)] * -0.027777777777777776
+in[(i-2)*n+(j-3)] * -0.005555555555555556
+in[(i-1)*n+(j-3)] * -0.005555555555555556
+in[(i)*n+(j-3)] * -0.005555555555555556
+in[(i+1)*n+(j-3)] * -0.005555555555555556
+in[(i+2)*n+(j-3)] * -0.005555555555555556
+in[(i-3)*n+(j-2)] * -0.005555555555555556
+in[(i-2)*n+(j-2)] * -0.041666666666666664
+in[(i-1)*n+(j-2)] * -0.013888888888888888
+in[(i)*n+(j-2)] * -0.013888888888888888
+in[(i+1)*n+(j-2)] * -0.013888888888888888
+in[(i+3)*n+(j-2)] * 0.005555555555555556
+in[(i-3)*n+(j-1)] * -0.005555555555555556
+in[(i-2)*n+(j-1)] * -0.013888888888888888
+in[(i-1)*n+(j-1)] * -0.08333333333333333
+in[(i)*n+(j-1)] * -0.08333333333333333
+in[(i+2)*n+(j-1)] * 0.013888888888888888
+in[(i+3)*n+(j-1)] * 0.005555555555555556
+in[(i-3)*n+(j)] * -0.005555555555555556
+in[(i-2)*n+(j)] * -0.013888888888888888
+in[(i-1)*n+(j)] * -0.08333333333333333
+in[(i+1)*n+(j)] * 0.08333333333333333
+in[(i+2)*n+(j)] * 0.013888888888888888
+in[(i+3)*n+(j)] * 0.005555555555555556
+in[(i-3)*n+(j+1)] * -0.005555555555555556
+in[(i-2)*n+(j+1)] * -0.013888888888888888
+in[(i)*n+(j+1)] * 0.08333333333333333
+in[(i+1)*n+(j+1)] * 0.08333333333333333
+in[(i+2)*n+(j+1)] * 0.013888888888888888
+in[(i+3)*n+(j+1)] * 0.005555555555555556
+in[(i-3)*n+(j+2)] * -0.005555555555555556
+in[(i-1)*n+(j+2)] * 0.013888888888888888
+in[(i)*n+(j+2)] * 0.013888888888888888
+in[(i+1)*n+(j+2)] * 0.013888888888888888
+in[(i+2)*n+(j+2)] * 0.041666666666666664
+in[(i+3)*n+(j+2)] * 0.005555555555555556
+in[(i-2)*n+(j+3)] * 0.005555555555555556
+in[(i-1)*n+(j+3)] * 0.005555555555555556
+in[(i)*n+(j+3)] * 0.005555555555555556
+in[(i+1)*n+(j+3)] * 0.005555555555555556
+in[(i+2)*n+(j+3)] * 0.005555555555555556
+in[(i+3)*n+(j+3)] * 0.027777777777777776
;
}
}
}
}
void grid4(const int n, prk::vector<double> & in, prk::vector<double> & out) {
auto dim = ranges::views::iota(4,n-4);
auto inside = ranges::views::cartesian_product(dim,dim);
for (auto ij : inside) {
auto [i, j] = ij;
out[i*n+j] += +in[(i-4)*n+(j-4)] * -0.015625
+in[(i-3)*n+(j-4)] * -0.002232142857142857
+in[(i-2)*n+(j-4)] * -0.002232142857142857
+in[(i-1)*n+(j-4)] * -0.002232142857142857
+in[(i)*n+(j-4)] * -0.002232142857142857
+in[(i+1)*n+(j-4)] * -0.002232142857142857
+in[(i+2)*n+(j-4)] * -0.002232142857142857
+in[(i+3)*n+(j-4)] * -0.002232142857142857
+in[(i-4)*n+(j-3)] * -0.002232142857142857
+in[(i-3)*n+(j-3)] * -0.020833333333333332
+in[(i-2)*n+(j-3)] * -0.004166666666666667
+in[(i-1)*n+(j-3)] * -0.004166666666666667
+in[(i)*n+(j-3)] * -0.004166666666666667
+in[(i+1)*n+(j-3)] * -0.004166666666666667
+in[(i+2)*n+(j-3)] * -0.004166666666666667
+in[(i+4)*n+(j-3)] * 0.002232142857142857
+in[(i-4)*n+(j-2)] * -0.002232142857142857
+in[(i-3)*n+(j-2)] * -0.004166666666666667
+in[(i-2)*n+(j-2)] * -0.03125
+in[(i-1)*n+(j-2)] * -0.010416666666666666
+in[(i)*n+(j-2)] * -0.010416666666666666
+in[(i+1)*n+(j-2)] * -0.010416666666666666
+in[(i+3)*n+(j-2)] * 0.004166666666666667
+in[(i+4)*n+(j-2)] * 0.002232142857142857
+in[(i-4)*n+(j-1)] * -0.002232142857142857
+in[(i-3)*n+(j-1)] * -0.004166666666666667
+in[(i-2)*n+(j-1)] * -0.010416666666666666
+in[(i-1)*n+(j-1)] * -0.0625
+in[(i)*n+(j-1)] * -0.0625
+in[(i+2)*n+(j-1)] * 0.010416666666666666
+in[(i+3)*n+(j-1)] * 0.004166666666666667
+in[(i+4)*n+(j-1)] * 0.002232142857142857
+in[(i-4)*n+(j)] * -0.002232142857142857
+in[(i-3)*n+(j)] * -0.004166666666666667
+in[(i-2)*n+(j)] * -0.010416666666666666
+in[(i-1)*n+(j)] * -0.0625
+in[(i+1)*n+(j)] * 0.0625
+in[(i+2)*n+(j)] * 0.010416666666666666
+in[(i+3)*n+(j)] * 0.004166666666666667
+in[(i+4)*n+(j)] * 0.002232142857142857
+in[(i-4)*n+(j+1)] * -0.002232142857142857
+in[(i-3)*n+(j+1)] * -0.004166666666666667
+in[(i-2)*n+(j+1)] * -0.010416666666666666
+in[(i)*n+(j+1)] * 0.0625
+in[(i+1)*n+(j+1)] * 0.0625
+in[(i+2)*n+(j+1)] * 0.010416666666666666
+in[(i+3)*n+(j+1)] * 0.004166666666666667
+in[(i+4)*n+(j+1)] * 0.002232142857142857
+in[(i-4)*n+(j+2)] * -0.002232142857142857
+in[(i-3)*n+(j+2)] * -0.004166666666666667
+in[(i-1)*n+(j+2)] * 0.010416666666666666
+in[(i)*n+(j+2)] * 0.010416666666666666
+in[(i+1)*n+(j+2)] * 0.010416666666666666
+in[(i+2)*n+(j+2)] * 0.03125
+in[(i+3)*n+(j+2)] * 0.004166666666666667
+in[(i+4)*n+(j+2)] * 0.002232142857142857
+in[(i-4)*n+(j+3)] * -0.002232142857142857
+in[(i-2)*n+(j+3)] * 0.004166666666666667
+in[(i-1)*n+(j+3)] * 0.004166666666666667
+in[(i)*n+(j+3)] * 0.004166666666666667
+in[(i+1)*n+(j+3)] * 0.004166666666666667
+in[(i+2)*n+(j+3)] * 0.004166666666666667
+in[(i+3)*n+(j+3)] * 0.020833333333333332
+in[(i+4)*n+(j+3)] * 0.002232142857142857
+in[(i-3)*n+(j+4)] * 0.002232142857142857
+in[(i-2)*n+(j+4)] * 0.002232142857142857
+in[(i-1)*n+(j+4)] * 0.002232142857142857
+in[(i)*n+(j+4)] * 0.002232142857142857
+in[(i+1)*n+(j+4)] * 0.002232142857142857
+in[(i+2)*n+(j+4)] * 0.002232142857142857
+in[(i+3)*n+(j+4)] * 0.002232142857142857
+in[(i+4)*n+(j+4)] * 0.015625
;
}
}
void grid4(const int n, const int t, prk::vector<double> & in, prk::vector<double> & out) {
auto s2 = ranges::views::cartesian_product(ranges::stride_view(ranges::views::iota(0, n), t),ranges::stride_view(ranges::views::iota(0, n), t));
auto t2 = ranges::views::cartesian_product(ranges::views::iota(0, t),ranges::views::iota(0, t));
const auto r = 4;
for (auto itjt : s2) {
auto [it, jt] = itjt;
for (auto iijj : t2) {
auto [ii, jj] = iijj;
auto i = ii + it;
auto j = jj + jt;
if (r <= i && i < n-r && r <= j && j < n-r) {
out[i*n+j] += +in[(i-4)*n+(j-4)] * -0.015625
+in[(i-3)*n+(j-4)] * -0.002232142857142857
+in[(i-2)*n+(j-4)] * -0.002232142857142857
+in[(i-1)*n+(j-4)] * -0.002232142857142857
+in[(i)*n+(j-4)] * -0.002232142857142857
+in[(i+1)*n+(j-4)] * -0.002232142857142857
+in[(i+2)*n+(j-4)] * -0.002232142857142857
+in[(i+3)*n+(j-4)] * -0.002232142857142857
+in[(i-4)*n+(j-3)] * -0.002232142857142857
+in[(i-3)*n+(j-3)] * -0.020833333333333332
+in[(i-2)*n+(j-3)] * -0.004166666666666667
+in[(i-1)*n+(j-3)] * -0.004166666666666667
+in[(i)*n+(j-3)] * -0.004166666666666667
+in[(i+1)*n+(j-3)] * -0.004166666666666667
+in[(i+2)*n+(j-3)] * -0.004166666666666667
+in[(i+4)*n+(j-3)] * 0.002232142857142857
+in[(i-4)*n+(j-2)] * -0.002232142857142857
+in[(i-3)*n+(j-2)] * -0.004166666666666667
+in[(i-2)*n+(j-2)] * -0.03125
+in[(i-1)*n+(j-2)] * -0.010416666666666666
+in[(i)*n+(j-2)] * -0.010416666666666666
+in[(i+1)*n+(j-2)] * -0.010416666666666666
+in[(i+3)*n+(j-2)] * 0.004166666666666667
+in[(i+4)*n+(j-2)] * 0.002232142857142857
+in[(i-4)*n+(j-1)] * -0.002232142857142857
+in[(i-3)*n+(j-1)] * -0.004166666666666667
+in[(i-2)*n+(j-1)] * -0.010416666666666666
+in[(i-1)*n+(j-1)] * -0.0625
+in[(i)*n+(j-1)] * -0.0625
+in[(i+2)*n+(j-1)] * 0.010416666666666666
+in[(i+3)*n+(j-1)] * 0.004166666666666667
+in[(i+4)*n+(j-1)] * 0.002232142857142857
+in[(i-4)*n+(j)] * -0.002232142857142857
+in[(i-3)*n+(j)] * -0.004166666666666667
+in[(i-2)*n+(j)] * -0.010416666666666666
+in[(i-1)*n+(j)] * -0.0625
+in[(i+1)*n+(j)] * 0.0625
+in[(i+2)*n+(j)] * 0.010416666666666666
+in[(i+3)*n+(j)] * 0.004166666666666667
+in[(i+4)*n+(j)] * 0.002232142857142857
+in[(i-4)*n+(j+1)] * -0.002232142857142857
+in[(i-3)*n+(j+1)] * -0.004166666666666667
+in[(i-2)*n+(j+1)] * -0.010416666666666666
+in[(i)*n+(j+1)] * 0.0625
+in[(i+1)*n+(j+1)] * 0.0625
+in[(i+2)*n+(j+1)] * 0.010416666666666666
+in[(i+3)*n+(j+1)] * 0.004166666666666667
+in[(i+4)*n+(j+1)] * 0.002232142857142857
+in[(i-4)*n+(j+2)] * -0.002232142857142857
+in[(i-3)*n+(j+2)] * -0.004166666666666667
+in[(i-1)*n+(j+2)] * 0.010416666666666666
+in[(i)*n+(j+2)] * 0.010416666666666666
+in[(i+1)*n+(j+2)] * 0.010416666666666666
+in[(i+2)*n+(j+2)] * 0.03125
+in[(i+3)*n+(j+2)] * 0.004166666666666667
+in[(i+4)*n+(j+2)] * 0.002232142857142857
+in[(i-4)*n+(j+3)] * -0.002232142857142857
+in[(i-2)*n+(j+3)] * 0.004166666666666667
+in[(i-1)*n+(j+3)] * 0.004166666666666667
+in[(i)*n+(j+3)] * 0.004166666666666667
+in[(i+1)*n+(j+3)] * 0.004166666666666667
+in[(i+2)*n+(j+3)] * 0.004166666666666667
+in[(i+3)*n+(j+3)] * 0.020833333333333332
+in[(i+4)*n+(j+3)] * 0.002232142857142857
+in[(i-3)*n+(j+4)] * 0.002232142857142857
+in[(i-2)*n+(j+4)] * 0.002232142857142857
+in[(i-1)*n+(j+4)] * 0.002232142857142857
+in[(i)*n+(j+4)] * 0.002232142857142857
+in[(i+1)*n+(j+4)] * 0.002232142857142857
+in[(i+2)*n+(j+4)] * 0.002232142857142857
+in[(i+3)*n+(j+4)] * 0.002232142857142857
+in[(i+4)*n+(j+4)] * 0.015625
;
}
}
}
}
void grid5(const int n, prk::vector<double> & in, prk::vector<double> & out) {
auto dim = ranges::views::iota(5,n-5);
auto inside = ranges::views::cartesian_product(dim,dim);
for (auto ij : inside) {
auto [i, j] = ij;
out[i*n+j] += +in[(i-5)*n+(j-5)] * -0.01
+in[(i-4)*n+(j-5)] * -0.0011111111111111111
+in[(i-3)*n+(j-5)] * -0.0011111111111111111
+in[(i-2)*n+(j-5)] * -0.0011111111111111111
+in[(i-1)*n+(j-5)] * -0.0011111111111111111
+in[(i)*n+(j-5)] * -0.0011111111111111111
+in[(i+1)*n+(j-5)] * -0.0011111111111111111
+in[(i+2)*n+(j-5)] * -0.0011111111111111111
+in[(i+3)*n+(j-5)] * -0.0011111111111111111
+in[(i+4)*n+(j-5)] * -0.0011111111111111111
+in[(i-5)*n+(j-4)] * -0.0011111111111111111
+in[(i-4)*n+(j-4)] * -0.0125
+in[(i-3)*n+(j-4)] * -0.0017857142857142857
+in[(i-2)*n+(j-4)] * -0.0017857142857142857
+in[(i-1)*n+(j-4)] * -0.0017857142857142857
+in[(i)*n+(j-4)] * -0.0017857142857142857
+in[(i+1)*n+(j-4)] * -0.0017857142857142857
+in[(i+2)*n+(j-4)] * -0.0017857142857142857
+in[(i+3)*n+(j-4)] * -0.0017857142857142857
+in[(i+5)*n+(j-4)] * 0.0011111111111111111
+in[(i-5)*n+(j-3)] * -0.0011111111111111111
+in[(i-4)*n+(j-3)] * -0.0017857142857142857
+in[(i-3)*n+(j-3)] * -0.016666666666666666
+in[(i-2)*n+(j-3)] * -0.0033333333333333335
+in[(i-1)*n+(j-3)] * -0.0033333333333333335
+in[(i)*n+(j-3)] * -0.0033333333333333335
+in[(i+1)*n+(j-3)] * -0.0033333333333333335
+in[(i+2)*n+(j-3)] * -0.0033333333333333335
+in[(i+4)*n+(j-3)] * 0.0017857142857142857
+in[(i+5)*n+(j-3)] * 0.0011111111111111111
+in[(i-5)*n+(j-2)] * -0.0011111111111111111
+in[(i-4)*n+(j-2)] * -0.0017857142857142857
+in[(i-3)*n+(j-2)] * -0.0033333333333333335
+in[(i-2)*n+(j-2)] * -0.025
+in[(i-1)*n+(j-2)] * -0.008333333333333333
+in[(i)*n+(j-2)] * -0.008333333333333333
+in[(i+1)*n+(j-2)] * -0.008333333333333333
+in[(i+3)*n+(j-2)] * 0.0033333333333333335
+in[(i+4)*n+(j-2)] * 0.0017857142857142857
+in[(i+5)*n+(j-2)] * 0.0011111111111111111
+in[(i-5)*n+(j-1)] * -0.0011111111111111111
+in[(i-4)*n+(j-1)] * -0.0017857142857142857
+in[(i-3)*n+(j-1)] * -0.0033333333333333335
+in[(i-2)*n+(j-1)] * -0.008333333333333333
+in[(i-1)*n+(j-1)] * -0.05
+in[(i)*n+(j-1)] * -0.05
+in[(i+2)*n+(j-1)] * 0.008333333333333333
+in[(i+3)*n+(j-1)] * 0.0033333333333333335
+in[(i+4)*n+(j-1)] * 0.0017857142857142857
+in[(i+5)*n+(j-1)] * 0.0011111111111111111
+in[(i-5)*n+(j)] * -0.0011111111111111111
+in[(i-4)*n+(j)] * -0.0017857142857142857
+in[(i-3)*n+(j)] * -0.0033333333333333335
+in[(i-2)*n+(j)] * -0.008333333333333333
+in[(i-1)*n+(j)] * -0.05
+in[(i+1)*n+(j)] * 0.05
+in[(i+2)*n+(j)] * 0.008333333333333333
+in[(i+3)*n+(j)] * 0.0033333333333333335
+in[(i+4)*n+(j)] * 0.0017857142857142857
+in[(i+5)*n+(j)] * 0.0011111111111111111
+in[(i-5)*n+(j+1)] * -0.0011111111111111111
+in[(i-4)*n+(j+1)] * -0.0017857142857142857
+in[(i-3)*n+(j+1)] * -0.0033333333333333335
+in[(i-2)*n+(j+1)] * -0.008333333333333333
+in[(i)*n+(j+1)] * 0.05
+in[(i+1)*n+(j+1)] * 0.05
+in[(i+2)*n+(j+1)] * 0.008333333333333333
+in[(i+3)*n+(j+1)] * 0.0033333333333333335
+in[(i+4)*n+(j+1)] * 0.0017857142857142857
+in[(i+5)*n+(j+1)] * 0.0011111111111111111
+in[(i-5)*n+(j+2)] * -0.0011111111111111111
+in[(i-4)*n+(j+2)] * -0.0017857142857142857
+in[(i-3)*n+(j+2)] * -0.0033333333333333335
+in[(i-1)*n+(j+2)] * 0.008333333333333333
+in[(i)*n+(j+2)] * 0.008333333333333333
+in[(i+1)*n+(j+2)] * 0.008333333333333333
+in[(i+2)*n+(j+2)] * 0.025
+in[(i+3)*n+(j+2)] * 0.0033333333333333335
+in[(i+4)*n+(j+2)] * 0.0017857142857142857
+in[(i+5)*n+(j+2)] * 0.0011111111111111111
+in[(i-5)*n+(j+3)] * -0.0011111111111111111
+in[(i-4)*n+(j+3)] * -0.0017857142857142857
+in[(i-2)*n+(j+3)] * 0.0033333333333333335
+in[(i-1)*n+(j+3)] * 0.0033333333333333335
+in[(i)*n+(j+3)] * 0.0033333333333333335
+in[(i+1)*n+(j+3)] * 0.0033333333333333335
+in[(i+2)*n+(j+3)] * 0.0033333333333333335
+in[(i+3)*n+(j+3)] * 0.016666666666666666
+in[(i+4)*n+(j+3)] * 0.0017857142857142857
+in[(i+5)*n+(j+3)] * 0.0011111111111111111
+in[(i-5)*n+(j+4)] * -0.0011111111111111111
+in[(i-3)*n+(j+4)] * 0.0017857142857142857
+in[(i-2)*n+(j+4)] * 0.0017857142857142857
+in[(i-1)*n+(j+4)] * 0.0017857142857142857
+in[(i)*n+(j+4)] * 0.0017857142857142857
+in[(i+1)*n+(j+4)] * 0.0017857142857142857
+in[(i+2)*n+(j+4)] * 0.0017857142857142857
+in[(i+3)*n+(j+4)] * 0.0017857142857142857
+in[(i+4)*n+(j+4)] * 0.0125
+in[(i+5)*n+(j+4)] * 0.0011111111111111111
+in[(i-4)*n+(j+5)] * 0.0011111111111111111
+in[(i-3)*n+(j+5)] * 0.0011111111111111111
+in[(i-2)*n+(j+5)] * 0.0011111111111111111
+in[(i-1)*n+(j+5)] * 0.0011111111111111111
+in[(i)*n+(j+5)] * 0.0011111111111111111
+in[(i+1)*n+(j+5)] * 0.0011111111111111111
+in[(i+2)*n+(j+5)] * 0.0011111111111111111
+in[(i+3)*n+(j+5)] * 0.0011111111111111111
+in[(i+4)*n+(j+5)] * 0.0011111111111111111
+in[(i+5)*n+(j+5)] * 0.01
;
}
}
void grid5(const int n, const int t, prk::vector<double> & in, prk::vector<double> & out) {
auto s2 = ranges::views::cartesian_product(ranges::stride_view(ranges::views::iota(0, n), t),ranges::stride_view(ranges::views::iota(0, n), t));
auto t2 = ranges::views::cartesian_product(ranges::views::iota(0, t),ranges::views::iota(0, t));
const auto r = 5;
for (auto itjt : s2) {
auto [it, jt] = itjt;
for (auto iijj : t2) {
auto [ii, jj] = iijj;
auto i = ii + it;
auto j = jj + jt;
if (r <= i && i < n-r && r <= j && j < n-r) {
out[i*n+j] += +in[(i-5)*n+(j-5)] * -0.01
+in[(i-4)*n+(j-5)] * -0.0011111111111111111
+in[(i-3)*n+(j-5)] * -0.0011111111111111111
+in[(i-2)*n+(j-5)] * -0.0011111111111111111
+in[(i-1)*n+(j-5)] * -0.0011111111111111111
+in[(i)*n+(j-5)] * -0.0011111111111111111
+in[(i+1)*n+(j-5)] * -0.0011111111111111111
+in[(i+2)*n+(j-5)] * -0.0011111111111111111
+in[(i+3)*n+(j-5)] * -0.0011111111111111111
+in[(i+4)*n+(j-5)] * -0.0011111111111111111
+in[(i-5)*n+(j-4)] * -0.0011111111111111111
+in[(i-4)*n+(j-4)] * -0.0125
+in[(i-3)*n+(j-4)] * -0.0017857142857142857
+in[(i-2)*n+(j-4)] * -0.0017857142857142857
+in[(i-1)*n+(j-4)] * -0.0017857142857142857
+in[(i)*n+(j-4)] * -0.0017857142857142857
+in[(i+1)*n+(j-4)] * -0.0017857142857142857
+in[(i+2)*n+(j-4)] * -0.0017857142857142857
+in[(i+3)*n+(j-4)] * -0.0017857142857142857
+in[(i+5)*n+(j-4)] * 0.0011111111111111111
+in[(i-5)*n+(j-3)] * -0.0011111111111111111
+in[(i-4)*n+(j-3)] * -0.0017857142857142857
+in[(i-3)*n+(j-3)] * -0.016666666666666666
+in[(i-2)*n+(j-3)] * -0.0033333333333333335
+in[(i-1)*n+(j-3)] * -0.0033333333333333335
+in[(i)*n+(j-3)] * -0.0033333333333333335
+in[(i+1)*n+(j-3)] * -0.0033333333333333335
+in[(i+2)*n+(j-3)] * -0.0033333333333333335
+in[(i+4)*n+(j-3)] * 0.0017857142857142857
+in[(i+5)*n+(j-3)] * 0.0011111111111111111
+in[(i-5)*n+(j-2)] * -0.0011111111111111111
+in[(i-4)*n+(j-2)] * -0.0017857142857142857
+in[(i-3)*n+(j-2)] * -0.0033333333333333335
+in[(i-2)*n+(j-2)] * -0.025
+in[(i-1)*n+(j-2)] * -0.008333333333333333
+in[(i)*n+(j-2)] * -0.008333333333333333
+in[(i+1)*n+(j-2)] * -0.008333333333333333
+in[(i+3)*n+(j-2)] * 0.0033333333333333335
+in[(i+4)*n+(j-2)] * 0.0017857142857142857
+in[(i+5)*n+(j-2)] * 0.0011111111111111111
+in[(i-5)*n+(j-1)] * -0.0011111111111111111
+in[(i-4)*n+(j-1)] * -0.0017857142857142857
+in[(i-3)*n+(j-1)] * -0.0033333333333333335
+in[(i-2)*n+(j-1)] * -0.008333333333333333
+in[(i-1)*n+(j-1)] * -0.05
+in[(i)*n+(j-1)] * -0.05
+in[(i+2)*n+(j-1)] * 0.008333333333333333
+in[(i+3)*n+(j-1)] * 0.0033333333333333335
+in[(i+4)*n+(j-1)] * 0.0017857142857142857
+in[(i+5)*n+(j-1)] * 0.0011111111111111111
+in[(i-5)*n+(j)] * -0.0011111111111111111
+in[(i-4)*n+(j)] * -0.0017857142857142857
+in[(i-3)*n+(j)] * -0.0033333333333333335
+in[(i-2)*n+(j)] * -0.008333333333333333
+in[(i-1)*n+(j)] * -0.05
+in[(i+1)*n+(j)] * 0.05
+in[(i+2)*n+(j)] * 0.008333333333333333
+in[(i+3)*n+(j)] * 0.0033333333333333335
+in[(i+4)*n+(j)] * 0.0017857142857142857
+in[(i+5)*n+(j)] * 0.0011111111111111111
+in[(i-5)*n+(j+1)] * -0.0011111111111111111
+in[(i-4)*n+(j+1)] * -0.0017857142857142857
+in[(i-3)*n+(j+1)] * -0.0033333333333333335
+in[(i-2)*n+(j+1)] * -0.008333333333333333
+in[(i)*n+(j+1)] * 0.05
+in[(i+1)*n+(j+1)] * 0.05
+in[(i+2)*n+(j+1)] * 0.008333333333333333
+in[(i+3)*n+(j+1)] * 0.0033333333333333335
+in[(i+4)*n+(j+1)] * 0.0017857142857142857
+in[(i+5)*n+(j+1)] * 0.0011111111111111111
+in[(i-5)*n+(j+2)] * -0.0011111111111111111
+in[(i-4)*n+(j+2)] * -0.0017857142857142857
+in[(i-3)*n+(j+2)] * -0.0033333333333333335
+in[(i-1)*n+(j+2)] * 0.008333333333333333
+in[(i)*n+(j+2)] * 0.008333333333333333
+in[(i+1)*n+(j+2)] * 0.008333333333333333
+in[(i+2)*n+(j+2)] * 0.025
+in[(i+3)*n+(j+2)] * 0.0033333333333333335
+in[(i+4)*n+(j+2)] * 0.0017857142857142857
+in[(i+5)*n+(j+2)] * 0.0011111111111111111
+in[(i-5)*n+(j+3)] * -0.0011111111111111111
+in[(i-4)*n+(j+3)] * -0.0017857142857142857
+in[(i-2)*n+(j+3)] * 0.0033333333333333335
+in[(i-1)*n+(j+3)] * 0.0033333333333333335
+in[(i)*n+(j+3)] * 0.0033333333333333335
+in[(i+1)*n+(j+3)] * 0.0033333333333333335
+in[(i+2)*n+(j+3)] * 0.0033333333333333335
+in[(i+3)*n+(j+3)] * 0.016666666666666666
+in[(i+4)*n+(j+3)] * 0.0017857142857142857
+in[(i+5)*n+(j+3)] * 0.0011111111111111111
+in[(i-5)*n+(j+4)] * -0.0011111111111111111
+in[(i-3)*n+(j+4)] * 0.0017857142857142857
+in[(i-2)*n+(j+4)] * 0.0017857142857142857
+in[(i-1)*n+(j+4)] * 0.0017857142857142857
+in[(i)*n+(j+4)] * 0.0017857142857142857
+in[(i+1)*n+(j+4)] * 0.0017857142857142857
+in[(i+2)*n+(j+4)] * 0.0017857142857142857
+in[(i+3)*n+(j+4)] * 0.0017857142857142857
+in[(i+4)*n+(j+4)] * 0.0125
+in[(i+5)*n+(j+4)] * 0.0011111111111111111
+in[(i-4)*n+(j+5)] * 0.0011111111111111111
+in[(i-3)*n+(j+5)] * 0.0011111111111111111
+in[(i-2)*n+(j+5)] * 0.0011111111111111111
+in[(i-1)*n+(j+5)] * 0.0011111111111111111
+in[(i)*n+(j+5)] * 0.0011111111111111111
+in[(i+1)*n+(j+5)] * 0.0011111111111111111
+in[(i+2)*n+(j+5)] * 0.0011111111111111111
+in[(i+3)*n+(j+5)] * 0.0011111111111111111
+in[(i+4)*n+(j+5)] * 0.0011111111111111111
+in[(i+5)*n+(j+5)] * 0.01
;
}
}
}
}
| 34,453 |
473 | /*
* Copyright (c) 2014 Kaprica Security, Inc.
*
* 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.
*
*/
#include "cgc_stdlib.h"
#include "cgc_string.h"
#include "cgc_db_client.h"
typedef struct {
unsigned int count;
int price;
} item_details;
static struct {
char *name;
item_details details;
} g_items[] = {
{"Apple", { 10, 110 }},
{"Banana", { 25, 30 }},
{"Orange", { 10, 120 }},
{"Computer", { 1, 100000 }}
};
void cgc_read_until(int fd, char * buf, cgc_size_t length, char end)
{
cgc_size_t i;
for (i = 0; i < length; i++)
{
cgc_size_t bytes;
if (cgc_receive(fd, &buf[i], 1, &bytes) != 0 || bytes != 1)
break;
if (buf[i] == end)
break;
}
buf[i] = 0;
}
static int abs(int v)
{
if (v < 0)
return -v;
return v;
}
void cgc_list()
{
char buf[4096];
key k;
result res;
cgc_size_t bytes;
buf[0] = 0;
k.data.count = 0;
res = cgc_db_next(k);
while (res.status == SUCCESS)
{
#ifdef PATCHED
if (cgc_strlen(buf) + cgc_strlen((char*)res.rec.data->k.data.data) + 30 > sizeof(buf))
break;
#endif
item_details *d = (item_details *)res.rec.data->data.data;
cgc_sprintf(buf, "%s%s (Price: %d.%02d, Count: %d)\n", buf, res.rec.data->k.data.data,
(int)(d->price / 100), abs(d->price % 100), d->count);
res = cgc_db_next(res.rec.data->k);
}
cgc_transmit(STDOUT, buf, cgc_strlen(buf), &bytes);
}
void cgc_buy()
{
char name[200];
key k;
result res;
cgc_read_until(STDIN, name, 200, '\n');
k.data.count = cgc_strlen(name) + 1;
k.data.data = (opaque *)name;
res = cgc_db_lookup(k);
if (res.status == SUCCESS)
{
item_details *d = (item_details *)res.rec.data->data.data;
if (d->count < 1)
{
cgc_printf("Not enought items\n");
}
else
{
d->count--;
if (d->count == 0)
cgc_db_delete(k);
else
cgc_db_insert(*res.rec.data);
}
}
else
{
cgc_printf("Item not found\n");
}
}
void cgc_sell()
{
char *name;
char tmp[50];
cgc_size_t bytes;
record rec;
item_details d;
name = cgc_malloc(200);
cgc_read_until(STDIN, name, 200, '\n');
cgc_read_until(STDIN, tmp, sizeof(tmp), '\n');
d.price = cgc_strtol(tmp, NULL, 10);
cgc_read_until(STDIN, tmp, sizeof(tmp), '\n');
d.count = cgc_strtoul(tmp, NULL, 10);
rec.k.data.count = cgc_strlen(name) + 1;
rec.k.data.data = (opaque *)name;
rec.data.count = sizeof(d);
rec.data.data = (opaque *)&d;
cgc_db_insert(rec);
}
char cgc_menu()
{
char choice;
cgc_size_t bytes;
cgc_printf("\nPlease make a selection:\n\ta) List products\n\tb) Buy a product\n\tc) Sell a product\n");
if (cgc_receive(STDIN, &choice, 1, &bytes) != 0 || bytes != 1)
return 0;
return choice;
}
void cgc_init_db()
{
int i;
record rec;
cgc_memset(&rec, 0, sizeof(rec));
for (i = 0; i < sizeof(g_items) / sizeof(g_items[0]); i++)
{
rec.k.data.count = cgc_strlen(g_items[i].name) + 1;
rec.k.data.data = (opaque *)g_items[i].name;
rec.data.count = sizeof(g_items[i].details);
rec.data.data = (opaque *)&g_items[i].details;
cgc_db_insert(rec);
}
}
int main(int cgc_argc, char *cgc_argv[])
{
cgc_database_init(4, 5);
cgc_init_db();
cgc_printf("Welcome to eCommerce v0.1\n");
while (1)
{
char choice = cgc_menu();
if (choice == 0)
break;
else if (choice == 'a')
cgc_list();
else if (choice == 'b')
cgc_buy();
else if (choice == 'c')
cgc_sell();
else
cgc_printf("Invalid selection\n");
}
cgc_database_close();
return 0;
}
| 2,273 |
636 | package org.hyperledger.indy.sdk.ledger;
import org.hyperledger.indy.sdk.IndyIntegrationTest;
import org.json.JSONObject;
import org.junit.Test;
public class AuthorAgreementRequestTest extends IndyIntegrationTest {
private String TEXT = "indy agreement";
private String VERSION = "1.0.0";
@Test
public void testBuildTxnAuthorAgreementRequest() throws Exception {
JSONObject expectedResult = new JSONObject()
.put("identifier", DID)
.put("operation",
new JSONObject()
.put("type", "4")
.put("text", TEXT)
.put("version", VERSION)
);
String request = Ledger.buildTxnAuthorAgreementRequest(DID, TEXT, VERSION, -1, -1).get();
assert (new JSONObject(request).toMap().entrySet()
.containsAll(
expectedResult.toMap().entrySet()));
}
@Test
public void testBuildTxnAuthorAgreementRequestForRetiredAndRatificatedWoText() throws Exception {
JSONObject expectedResult = new JSONObject()
.put("identifier", DID)
.put("operation",
new JSONObject()
.put("type", "4")
.put("text", TEXT)
.put("version", VERSION)
.put("ratification_ts", 12345)
.put("retirement_ts", 54321)
);
String request = Ledger.buildTxnAuthorAgreementRequest(DID, TEXT, VERSION, 12345, 54321).get();
assert (new JSONObject(request).toMap().entrySet()
.containsAll(
expectedResult.toMap().entrySet()));
}
@Test
public void testBuildGetTxnAuthorAgreementRequest() throws Exception {
JSONObject expectedResult = new JSONObject()
.put("operation",
new JSONObject()
.put("type", "6")
);
String request = Ledger.buildGetTxnAuthorAgreementRequest(null, null).get();
assert (new JSONObject(request).toMap().entrySet()
.containsAll(
expectedResult.toMap().entrySet()));
}
@Test
public void testBuildGetTxnAuthorAgreementRequestForVersion() throws Exception {
JSONObject data = new JSONObject()
.put("version", VERSION);
JSONObject expectedResult = new JSONObject()
.put("operation",
new JSONObject()
.put("type", "6")
.put("version", VERSION)
);
String request = Ledger.buildGetTxnAuthorAgreementRequest(null, data.toString()).get();
assert (new JSONObject(request).toMap().entrySet()
.containsAll(
expectedResult.toMap().entrySet()));
}
@Test
public void testBuildDisableAllTxnAuthorAgreementsRequest() throws Exception {
JSONObject expectedResult = new JSONObject()
.put("operation",
new JSONObject()
.put("type", "8")
);
String request = Ledger.buildDisableAllTxnAuthorAgreementsRequest(DID).get();
assert (new JSONObject(request).toMap().entrySet()
.containsAll(
expectedResult.toMap().entrySet()));
}
} | 1,044 |
348 | <reponame>chamberone/Leaflet.PixiOverlay
{"nom":"Solesmes","circ":"4ème circonscription","dpt":"Sarthe","inscrits":1087,"abs":465,"votants":622,"blancs":30,"nuls":13,"exp":579,"res":[{"nuance":"LR","nom":"M. <NAME>","voix":391},{"nuance":"SOC","nom":"M. <NAME>","voix":188}]} | 115 |
715 | <reponame>JVuns/Driver-Log-Recorder---Final-Project
import numpy as np
from PIL import Image, ImageDraw, ImageFont, ImageMath
from pyray.rotation import general_rotation, planar_rotation, axis_rotation,\
rotate_point_about_axis
from pyray.shapes.twod.plot import Canvas
from pyray.axes import ZigZagPath
import pyray.grid as grd
def basic_grid():
im=Image.new("RGB", (512, 512), (0,0,0))
draw = ImageDraw.Draw(im,'RGBA')
gg=grd.Grid(end=np.array([6.0,6.0]),\
center=np.array([0,0]),origin=np.array([40,256]),
rot=planar_rotation(-np.pi/4),scale=32)
gg.draw(draw,width=3)
## Draw horizontal line corresponding to the main diagonal.
pt1=gg.get_grid_pt(0,0)
pt2=gg.get_grid_pt(6,6)
draw.line((pt1[0],pt1[1],pt2[0],pt2[1]), fill="purple", width=3)
draw.ellipse((pt1[0]-5, pt1[1]-5, pt1[0]+5, \
pt1[1]+5),fill='blue')
draw.ellipse((pt2[0]-5, pt2[1]-5, pt2[0]+5, \
pt2[1]+5),fill='red')
## Draw horizontal line corresponding to one above the main diagonal.
pt1=gg.get_grid_pt(0,1)
pt2=gg.get_grid_pt(5,6)
draw.line((pt1[0],pt1[1],pt2[0],pt2[1]), fill="orange", width=2)
return im, draw, gg
basedir = '.\\Images\\RotatingCube\\'
### Grid path 0
for i in range(6):
im,draw,gg=basic_grid()
pt1=gg.get_grid_pt(0,1)
pt2=gg.get_grid_pt(5,6)
pts=[gg.get_grid_pt(a,b) for a,b in [(0,0),(5,0),(5,6)]]
zg=ZigZagPath(pts)
zg.draw_lines(draw,prop_dist=i/5.0)
im.save(basedir + "im" + str(i) + ".png")
### Grid path 1
for i in range(6):
im,draw,gg=basic_grid()
pt1=gg.get_grid_pt(0,1)
pt2=gg.get_grid_pt(5,6)
pts=[gg.get_grid_pt(a,b) for a,b in [(0,0),(5,0),(5,6)]]
pts1=[rotate_point_about_axis(np.concatenate((pts[j],[0])),
np.concatenate((pt1,[0])),\
np.concatenate((pt2,[0])),np.pi*i/5.0) \
for j in range(len(pts))]
zg=ZigZagPath(pts1)
zg.draw_lines(draw,prop_dist=1.0)
draw.ellipse((pts1[0][0]-5, pts1[0][1]-5, pts1[0][0]+5, \
pts1[0][1]+5),fill='blue')
im.save(basedir + "im" + str(5+i) + ".png")
### Grid path 2
for i in range(6):
im,draw,gg=basic_grid()
pt1=gg.get_grid_pt(0,1)
pt2=gg.get_grid_pt(5,6)
pts=[gg.get_grid_pt(a,b) for a,b in [(0,0),(5,0),(5,6)]]
pts1=[rotate_point_about_axis(np.concatenate((pts[j],[0])),
np.concatenate((pt1,[0])),\
np.concatenate((pt2,[0])),np.pi*5.0/5.0) \
for j in range(len(pts))]
zg=ZigZagPath(pts1)
zg.draw_lines(draw,prop_dist=1.0)
draw.ellipse((pts1[0][0]-5, pts1[0][1]-5, pts1[0][0]+5, \
pts1[0][1]+5),fill='blue')
pts=[gg.get_grid_pt(a,b) for a,b in [(0,0),(0,1)]]
pts1=[rotate_point_about_axis(np.concatenate((pts[j],[0])),
np.concatenate((pt1,[0])),\
np.concatenate((pt2,[0])),np.pi*i/5.0) \
for j in range(len(pts))]
zg=ZigZagPath(pts1)
zg.draw_lines(draw,prop_dist=1.0)
draw.ellipse((pts1[0][0]-5, pts1[0][1]-5, pts1[0][0]+5, \
pts1[0][1]+5),fill='blue')
im.save(basedir + "im" + str(10+i) + ".png")
### Grid path 3
for i in range(6):
im,draw,gg=basic_grid()
pt1=gg.get_grid_pt(0,1)
pt2=gg.get_grid_pt(5,6)
pts=[gg.get_grid_pt(a,b) for a,b in [(0,0),(5,0),(5,6)]]
pts1=[rotate_point_about_axis(np.concatenate((pts[j],[0])),
np.concatenate((pt1,[0])),\
np.concatenate((pt2,[0])),np.pi*5.0/5.0) \
for j in range(len(pts))]
zg=ZigZagPath(pts1)
zg.draw_lines(draw,prop_dist=1.0)
draw.ellipse((pts1[0][0]-5, pts1[0][1]-5, pts1[0][0]+5, \
pts1[0][1]+5),fill='blue')
pts=[gg.get_grid_pt(a,b) for a,b in [(0,0),(0,1)]]
pts1=[rotate_point_about_axis(np.concatenate((pts[j],[0])),
np.concatenate((pt1,[0])),\
np.concatenate((pt2,[0])),np.pi*5.0/5.0) \
for j in range(len(pts))]
zg=ZigZagPath(pts1)
zg.draw_lines(draw,prop_dist=1.0)
draw.ellipse((pts1[0][0]-5, pts1[0][1]-5, pts1[0][0]+5, \
pts1[0][1]+5),fill='blue')
pts=[gg.get_grid_pt(a,b) for a,b in [(0,0),(1,0),(1,2)]]
pts1=[rotate_point_about_axis(np.concatenate((pts[j],[0])),
np.concatenate((pt1,[0])),\
np.concatenate((pt2,[0])),np.pi*i/5.0) \
for j in range(len(pts))]
zg=ZigZagPath(pts1)
zg.draw_lines(draw,prop_dist=1.0)
draw.ellipse((pts1[0][0]-5, pts1[0][1]-5, pts1[0][0]+5, \
pts1[0][1]+5),fill='blue')
im.save(basedir + "im" + str(15+i) + ".png")
### Grid path 4
for i in range(6):
im,draw,gg=basic_grid()
pt1=gg.get_grid_pt(0,1)
pt2=gg.get_grid_pt(5,6)
pts=[gg.get_grid_pt(a,b) for a,b in [(0,0),(5,0),(5,6)]]
pts1=[rotate_point_about_axis(np.concatenate((pts[j],[0])),
np.concatenate((pt1,[0])),\
np.concatenate((pt2,[0])),np.pi*5.0/5.0) \
for j in range(len(pts))]
zg=ZigZagPath(pts1)
zg.draw_lines(draw,prop_dist=1.0)
draw.ellipse((pts1[0][0]-5, pts1[0][1]-5, pts1[0][0]+5, \
pts1[0][1]+5),fill='blue')
pts=[gg.get_grid_pt(a,b) for a,b in [(0,0),(0,1)]]
pts1=[rotate_point_about_axis(np.concatenate((pts[j],[0])),
np.concatenate((pt1,[0])),\
np.concatenate((pt2,[0])),np.pi*5.0/5.0) \
for j in range(len(pts))]
zg=ZigZagPath(pts1)
zg.draw_lines(draw,prop_dist=1.0)
pts=[gg.get_grid_pt(a,b) for a,b in [(0,0),(1,0),(1,2)]]
pts1=[rotate_point_about_axis(np.concatenate((pts[j],[0])),
np.concatenate((pt1,[0])),\
np.concatenate((pt2,[0])),np.pi*5.0/5.0) \
for j in range(len(pts))]
zg=ZigZagPath(pts1)
zg.draw_lines(draw,prop_dist=1.0)
pts=[gg.get_grid_pt(a,b) for a,b in [(0,0),(3,0),(3,4)]]
pts1=[rotate_point_about_axis(np.concatenate((pts[j],[0])),
np.concatenate((pt1,[0])),\
np.concatenate((pt2,[0])),np.pi*i/5.0) \
for j in range(len(pts))]
zg=ZigZagPath(pts1)
zg.draw_lines(draw,prop_dist=1.0)
im.save(basedir + "im" + str(20+i) + ".png")
### Wrap around grid
for i in range(6):
im,draw,gg=basic_grid()
pt1=gg.get_grid_pt(0,1)
pt2=gg.get_grid_pt(5,6)
pts=[gg.get_grid_pt(a,b) for a,b in [(0,0),(5,0),(5,6)]]
pts1=[rotate_point_about_axis(np.concatenate((pts[j],[0])),
np.concatenate((pt1,[0])),\
np.concatenate((pt2,[0])),np.pi*5.0/5.0) \
for j in range(len(pts))]
zg=ZigZagPath(pts1)
zg.draw_lines(draw,prop_dist=1.0)
draw.ellipse((pts1[0][0]-5, pts1[0][1]-5, pts1[0][0]+5, \
pts1[0][1]+5),fill='blue')
pts=[gg.get_grid_pt(a,b) for a,b in [(0,0),(0,1)]]
pts1=[rotate_point_about_axis(np.concatenate((pts[j],[0])),
np.concatenate((pt1,[0])),\
np.concatenate((pt2,[0])),np.pi*5.0/5.0) \
for j in range(len(pts))]
zg=ZigZagPath(pts1)
zg.draw_lines(draw,prop_dist=1.0)
draw.ellipse((pts1[0][0]-5, pts1[0][1]-5, pts1[0][0]+5, \
pts1[0][1]+5),fill='blue')
pts=[gg.get_grid_pt(a,b) for a,b in [(0,0),(1,0),(1,2)]]
pts1=[rotate_point_about_axis(np.concatenate((pts[j],[0])),
np.concatenate((pt1,[0])),\
np.concatenate((pt2,[0])),np.pi*5/5.0) \
for j in range(len(pts))]
zg=ZigZagPath(pts1)
zg.draw_lines(draw,prop_dist=1.0)
draw.ellipse((pts1[0][0]-5, pts1[0][1]-5, pts1[0][0]+5, \
pts1[0][1]+5),fill='blue')
pts=[gg.get_grid_pt(a,b) for a,b in [(0,0),(3,0),(3,4)]]
pts1=[rotate_point_about_axis(np.concatenate((pts[j],[0])),
np.concatenate((pt1,[0])),\
np.concatenate((pt2,[0])),np.pi*5.0/5.0) \
for j in range(len(pts))]
zg=ZigZagPath(pts1)
zg.draw_lines(draw,prop_dist=1.0)
pts=[gg.get_grid_pt(a,b) for a,b in [(0,1),(6,1)]]
zg=ZigZagPath(pts)
zg.draw_lines(draw,prop_dist=i/5.0)
pts=[gg.get_grid_pt(a,b) for a,b in [(5,6),(6,6),(6,1)]]
zg=ZigZagPath(pts)
zg.draw_lines(draw,prop_dist=i/5.0)
im.save(basedir + "im" + str(25+i) + ".png")
##### How to create videos from the images.
#ffmpeg -framerate 10 -f image2 -i im%d.png -vb 20M vid.avi
#ffmpeg -i vid.avi -pix_fmt rgb24 -loop 0 out.gif
| 5,562 |
5,169 | <reponame>Gantios/Specs<gh_stars>1000+
{
"name": "Retrofire",
"version": "1.0",
"summary": "Simply and elegant HTTP Networking in Swift. Based on Alamofire and Retrofit",
"description": "Retrofire is a framework written in swift that generate API requests and build models elegantly. We combine two powerful libs, Alamofire and SwiftyJSON to generate a better response to you.",
"homepage": "https://github.com/stantmob/retrofire",
"license": {
"type": "MIT",
"file": "LICENSE"
},
"authors": {
"<NAME>": "<EMAIL>"
},
"social_media_url": "https://twitter.com/rcachidcalazans",
"platforms": {
"ios": "9.0"
},
"source": {
"git": "https://github.com/stantmob/Retrofire.git",
"tag": "1.0"
},
"source_files": [
"Retrofire",
"Retrofire/**/*.{h,m}",
"Retrofire/**/*.swift"
],
"exclude_files": "Classes/Exclude",
"dependencies": {
"Alamofire": [
"~> 4.4.0"
],
"SwiftyJSON": [
]
},
"pushed_with_swift_version": "3.0"
}
| 415 |
2,151 | // Copyright (c) 2012 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "remoting/host/dns_blackhole_checker.h"
#include "base/callback_helpers.h"
#include "net/url_request/url_fetcher.h"
#include "net/url_request/url_request_context_getter.h"
#include "remoting/base/logging.h"
#include "url/gurl.h"
namespace remoting {
// Default prefix added to the base talkgadget URL.
const char kDefaultHostTalkGadgetPrefix[] = "chromoting-host";
// The base talkgadget URL.
const char kTalkGadgetUrl[] = ".talkgadget.google.com/talkgadget/"
"oauth/chrome-remote-desktop-host";
DnsBlackholeChecker::DnsBlackholeChecker(
const scoped_refptr<net::URLRequestContextGetter>& request_context_getter,
std::string talkgadget_prefix)
: url_request_context_getter_(request_context_getter),
talkgadget_prefix_(talkgadget_prefix) {
}
DnsBlackholeChecker::~DnsBlackholeChecker() = default;
// This is called in response to the TalkGadget http request initiated from
// CheckStatus().
void DnsBlackholeChecker::OnURLFetchComplete(const net::URLFetcher* source) {
int response = source->GetResponseCode();
bool allow = false;
if (source->GetResponseCode() == 200) {
HOST_LOG << "Successfully connected to host talkgadget.";
allow = true;
} else {
HOST_LOG << "Unable to connect to host talkgadget (" << response << ")";
}
url_fetcher_.reset(nullptr);
base::ResetAndReturn(&callback_).Run(allow);
}
void DnsBlackholeChecker::CheckForDnsBlackhole(
const base::Callback<void(bool)>& callback) {
// Make sure we're not currently in the middle of a connection check.
if (!url_fetcher_.get()) {
DCHECK(callback_.is_null());
callback_ = callback;
std::string talkgadget_url("https://");
if (talkgadget_prefix_.empty()) {
talkgadget_url += kDefaultHostTalkGadgetPrefix;
} else {
talkgadget_url += talkgadget_prefix_;
}
talkgadget_url += kTalkGadgetUrl;
HOST_LOG << "Verifying connection to " << talkgadget_url;
url_fetcher_ = net::URLFetcher::Create(GURL(talkgadget_url),
net::URLFetcher::GET, this);
url_fetcher_->SetRequestContext(url_request_context_getter_.get());
url_fetcher_->Start();
} else {
HOST_LOG << "Pending connection check";
}
}
} // namespace remoting
| 928 |
358 | # -*- coding: utf-8 -*-
# pyswip -- Python SWI-Prolog bridge
# Copyright (c) 2007-2018 <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.
from pyswip import *
def main():
p = Prolog()
assertz = Functor("assertz")
parent = Functor("parent", 2)
test1 = newModule("test1")
test2 = newModule("test2")
call(assertz(parent("john", "bob")), module=test1)
call(assertz(parent("jane", "bob")), module=test1)
call(assertz(parent("mike", "bob")), module=test2)
call(assertz(parent("gina", "bob")), module=test2)
print("knowledgebase test1")
X = Variable()
q = Query(parent(X, "bob"), module=test1)
while q.nextSolution():
print(X.value)
q.closeQuery()
print("knowledgebase test2")
q = Query(parent(X, "bob"), module=test2)
while q.nextSolution():
print(X.value)
q.closeQuery()
if __name__ == "__main__":
main() | 644 |
309 | custom_params = {}
custom_params['model_dir'] = 'nn_models/pb_only/model_data/'
custom_params['out_dir'] = 'output/pb_only/'
custom_params['feat_mask'] = [0.0, 0.0, 0.0, 1.0, 0.0]
| 79 |
736 | <gh_stars>100-1000
#include "StdAfx.h"
#include "InjectionBuffer.h"
namespace FSecure::WinTools
{
InjectionBuffer::InjectionBuffer(FSecure::ByteView code) : m_Size(code.size())
{
// Allocate memory as R/W
auto codePointer = VirtualAlloc(0, m_Size, MEM_COMMIT, PAGE_READWRITE);
if (!codePointer)
throw std::runtime_error{ OBF("Couldn't allocate R/W virtual memory: ") + std::to_string(GetLastError()) + OBF(".") };
m_Buffer = decltype(m_Buffer)(codePointer, [](void* buffer) { VirtualFree(buffer, 0, MEM_RELEASE); } );
// copy the code into buffer
memcpy_s(m_Buffer.get(), m_Size, code.data(), code.size());
MarkAsExecutable();
FlushInstructionCache(GetCurrentProcess(), m_Buffer.get(), m_Size);
}
void InjectionBuffer::MarkAsExecutable() const
{
// Mark the memory region R/X
DWORD prev;
if (!VirtualProtect(m_Buffer.get(), m_Size, PAGE_EXECUTE_READ, &prev))
throw std::runtime_error(OBF("Couldn't mark virtual memory as R/X. ") + std::to_string(GetLastError()));
}
}
| 378 |
7,471 | <filename>DearPyGui/src/ui/Theming/mvImGuiColors.h
#pragma once
#define mvImGuiCol_Text mvColor(255, 255, 255, 255)
#define mvImGuiCol_TextSelectedBg mvColor(66, 150, 250, 51)
#define mvImGuiCol_TextDisabled mvColor(128, 128, 128, 255)
#define mvImGuiCol_WindowBg mvColor(15, 15, 15, 240)
#define mvImGuiCol_ChildBg mvColor(0, 0, 0, 0)
#define mvImGuiCol_PopupBg mvColor(20, 20, 20, 240)
#define mvImGuiCol_Border mvColor(110, 110, 128, 128)
#define mvImGuiCol_BorderShadow mvColor(0, 0, 0, 0)
#define mvImGuiCol_FrameBg mvColor(41, 74, 122, 138)
#define mvImGuiCol_FrameBgHovered mvColor(66, 150, 250, 102)
#define mvImGuiCol_FrameBgActive mvColor(66, 150, 250, 171)
#define mvImGuiCol_TitleBg mvColor(10, 10, 10, 255)
#define mvImGuiCol_TitleBgActive mvColor(41, 74, 122, 255)
#define mvImGuiCol_TitleBgCollapsed mvColor(0, 0, 0, 130)
#define mvImGuiCol_MenuBarBg mvColor(36, 36, 36, 255)
#define mvImGuiCol_ScrollbarBg mvColor(5, 5, 5, 135)
#define mvImGuiCol_ScrollbarGrab mvColor(79, 79, 79, 255)
#define mvImGuiCol_ScrollbarGrabHovered mvColor(105, 105, 105, 255)
#define mvImGuiCol_ScrollbarGrabActive mvColor(130, 130, 130, 255)
#define mvImGuiCol_CheckMark mvColor(66, 150, 250, 255)
#define mvImGuiCol_SliderGrab mvColor(61, 133, 224, 255)
#define mvImGuiCol_SliderGrabActive mvColor(66, 150, 250, 255)
#define mvImGuiCol_Button mvColor(66, 150, 250, 102)
#define mvImGuiCol_ButtonHovered mvColor(66, 150, 250, 255)
#define mvImGuiCol_ButtonActive mvColor(15, 135, 250, 255)
#define mvImGuiCol_Header mvColor(66, 150, 250, 79)
#define mvImGuiCol_HeaderHovered mvColor(66, 150, 250, 204)
#define mvImGuiCol_HeaderActive mvColor(66, 150, 250, 255)
#define mvImGuiCol_Separator mvColor(110, 110, 128, 128)
#define mvImGuiCol_SeparatorHovered mvColor(26, 102, 191, 199)
#define mvImGuiCol_SeparatorActive mvColor(26, 102, 191, 255)
#define mvImGuiCol_ResizeGrip mvColor(66, 150, 250, 64)
#define mvImGuiCol_ResizeGripHovered mvColor(66, 150, 250, 171)
#define mvImGuiCol_ResizeGripActive mvColor(66, 150, 250, 242)
#define mvImGuiCol_Tab mvColor(46, 89, 148, 220)
#define mvImGuiCol_TabHovered mvColor(66, 150, 250, 204)
#define mvImGuiCol_TabActive mvColor(51, 105, 173, 255)
#define mvImGuiCol_TabUnfocused mvColor(17, 26, 38, 248)
#define mvImGuiCol_TabUnfocusedActive mvColor(35, 67, 108, 255)
#define mvImGuiCol_DockingPreview mvColor(66, 150, 250, 179)
#define mvImGuiCol_DockingEmptyBg mvColor(51, 51, 51, 255)
#define mvImGuiCol_PlotLines mvColor(156, 156, 156, 255)
#define mvImGuiCol_PlotLinesHovered mvColor(255, 110, 89, 255)
#define mvImGuiCol_PlotHistogram mvColor(230, 179, 0, 255)
#define mvImGuiCol_PlotHistogramHovered mvColor(255, 153, 0, 255)
#define mvImGuiCol_DragDropTarget mvColor(255, 255, 0, 230)
#define mvImGuiCol_NavHighlight mvColor(66, 150, 250, 255)
#define mvImGuiCol_NavWindowingHighlight mvColor(255, 255, 255, 179)
#define mvImGuiCol_NavWindowingDimBg mvColor(204, 204, 204, 51)
#define mvImGuiCol_ModalWindowDimBg mvColor(204, 204, 204, 89)
#define mvImGuiCol_NodeBackground mvColor(50, 50, 50, 255)
#define mvImGuiCol_NodeBackgroundHovered mvColor(75, 75, 75, 255)
#define mvImGuiCol_NodeBackgroundSelected mvColor(75, 75, 75, 255)
#define mvImGuiCol_NodeOutline mvColor(100, 100, 100, 255)
#define mvImGuiCol_Link mvColor(61, 133, 224, 200)
#define mvImGuiCol_LinkHovered mvColor(66, 150, 250, 255)
#define mvImGuiCol_LinkSelected mvColor(66, 150, 250, 255)
#define mvImGuiCol_Pin mvColor(53, 150, 250, 180)
#define mvImGuiCol_PinHovered mvColor(53, 150, 250, 255)
#define mvImGuiCol_BoxSelector mvColor(61, 133, 224, 30)
#define mvImGuiCol_BoxSelectorOutline mvColor(61, 133, 224, 150)
#define mvImGuiCol_GridBackground mvColor(40, 40, 50, 200)
#define mvImGuiCol_GridLine mvColor(200, 200, 200, 40)
#define mvImGuiCol_TableHeaderBg mvColor(48, 48, 51, 255)
#define mvImGuiCol_TableBorderStrong mvColor(79, 79, 89, 255)
#define mvImGuiCol_TableBorderLight mvColor(59, 59, 64, 255)
#define mvImGuiCol_TableRowBg mvColor(0, 0, 0, 0)
#define mvImGuiCol_TableRowBgAlt mvColor(255, 255, 255, 15)
| 1,759 |
3,073 | /* j/2/scag.c
**
*/
#include "all.h"
u3_noun
u3qb_scag(u3_atom a, u3_noun b)
{
if ( u3_nul == b ) {
return u3_nul;
}
else if ( !_(u3a_is_cat(a)) ) {
return u3m_bail(c3__fail);
}
else {
u3_noun pro;
u3_noun* lit = &pro;
{
c3_w len_w = (c3_w)a;
u3_noun* hed;
u3_noun* tel;
u3_noun i, t = b;
while ( len_w-- && (u3_nul != t) ) {
u3x_cell(t, &i, &t);
*lit = u3i_defcons(&hed, &tel);
*hed = u3k(i);
lit = tel;
}
}
*lit = u3_nul;
return pro;
}
}
u3_noun
u3wb_scag(u3_noun cor)
{
u3_noun a, b;
u3x_mean(cor, u3x_sam_2, &a, u3x_sam_3, &b, 0);
if ( (c3n == u3ud(a)) && (u3_nul != b) ) {
return u3m_bail(c3__exit);
}
return u3qb_scag(a, b);
}
| 493 |
1,144 | package de.metas.bpartner.service;
import de.metas.bpartner.BPGroupId;
import de.metas.bpartner.BPartnerId;
import de.metas.bpartner.name.strategy.BPartnerNameAndGreetingStrategyId;
import de.metas.util.ISingletonService;
import lombok.NonNull;
import org.adempiere.service.ClientId;
import org.compiere.model.I_C_BP_Group;
import javax.annotation.Nullable;
/*
* #%L
* de.metas.adempiere.adempiere.base
* %%
* Copyright (C) 2018 metas GmbH
* %%
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as
* published by the Free Software Foundation, either version 2 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public
* License along with this program. If not, see
* <http://www.gnu.org/licenses/gpl-2.0.html>.
* #L%
*/
public interface IBPGroupDAO extends ISingletonService
{
I_C_BP_Group getById(BPGroupId bpGroupId);
/**
* Loading within currently inherited trx.
* Use case: this method ca be called when the BPGroup in question was only just created, and that trx was not yet committed.
*/
I_C_BP_Group getByIdInInheritedTrx(BPGroupId bpGroupId);
I_C_BP_Group getByBPartnerId(BPartnerId bpartnerId);
BPGroupId getBPGroupByBPartnerId(BPartnerId bpartnerId);
@Nullable
I_C_BP_Group getDefaultByClientId(ClientId clientId);
BPartnerNameAndGreetingStrategyId getBPartnerNameAndGreetingStrategyId(@NonNull BPGroupId bpGroupId);
}
| 587 |
3,976 | <filename>Jaccorot/0010/0010.py
#!/usr/bin/python
#coding=utf-8
"""
第 0010 题:使用 Python 生成字母验证码图片
"""
from PIL import Image, ImageDraw, ImageFont, ImageFilter
import random
IMAGE_MODE = 'RGB'
IMAGE_BG_COLOR = (255,255,255)
Image_Font = 'arial.ttf'
text = ''.join(random.sample('abcdefghijklmnopqrstuvwxyz\
ABCDEFGHIJKLMNOPQRSTUVWXYZ',4))
def colorRandom():
return (random.randint(32,127),random.randint(32,127),random.randint(32,127))
#change 噪点频率(%)
def create_identifying_code(strs, width=400, height=200, chance=2):
im = Image.new(IMAGE_MODE, (width, height), IMAGE_BG_COLOR)
draw = ImageDraw.Draw(im)
#绘制背景噪点
for w in xrange(width):
for h in xrange(height):
if chance < random.randint(1, 100):
draw.point((w, h), fill=colorRandom())
font = ImageFont.truetype(Image_Font, 80)
font_width, font_height = font.getsize(strs)
strs_len = len(strs)
x = (width - font_width)/2
y = (height - font_height)/2
#逐个绘制文字
for i in strs:
draw.text((x,y), i, colorRandom(), font)
x += font_width/strs_len
#模糊
im = im.filter(ImageFilter.BLUR)
im.save('identifying_code_pic.jpg')
if __name__ == '__main__':
create_identifying_code(text)
| 624 |
4,020 | <gh_stars>1000+
package me.coley.recaf.util;
import org.objectweb.asm.tree.AbstractInsnNode;
import java.lang.reflect.Field;
import static org.objectweb.asm.Opcodes.*;
/**
* Instruction level utilities.
*
* @author Matt
*/
public class InsnUtil {
private static Field INSN_INDEX;
/**
* @param opcode
* Instruction opcode. Should be of type
* {@link org.objectweb.asm.tree.AbstractInsnNode#INSN}.
*
* @return value represented by the instruction.
*
* @throws IllegalArgumentException
* Thrown if the opcode does not have a known value.
*/
public static int getValue(int opcode) {
switch(opcode) {
case ICONST_M1:
return -1;
case FCONST_0:
case LCONST_0:
case DCONST_0:
case ICONST_0:
return 0;
case FCONST_1:
case LCONST_1:
case DCONST_1:
case ICONST_1:
return 1;
case FCONST_2:
case ICONST_2:
return 2;
case ICONST_3:
return 3;
case ICONST_4:
return 4;
case ICONST_5:
return 5;
default:
throw new IllegalArgumentException("Invalid opcode, does not have a known value: " + opcode);
}
}
/**
* Calculate the index of an instruction.
*
* @param ain
* instruction.
*
* @return Instruction index.
*/
public static int index(AbstractInsnNode ain) {
try {
int v = (int) INSN_INDEX.get(ain);
// Can return -1
if (v >= 0)
return v;
} catch(Exception ex) { /* Fail */ }
// Fallback
int index = 0;
while(ain.getPrevious() != null) {
ain = ain.getPrevious();
index++;
}
return index;
}
/**
* Get the first insn connected to the given one.
*
* @param insn
* instruction
*
* @return First insn in the insn-list.
*/
public static AbstractInsnNode getFirst(AbstractInsnNode insn) {
while(insn.getPrevious() != null)
insn = insn.getPrevious();
return insn;
}
static {
try {
INSN_INDEX = AbstractInsnNode.class.getDeclaredField("index");
INSN_INDEX.setAccessible(true);
} catch(Exception ex) {
Log.warn("Failed to fetch AbstractInsnNode index field!");
}
}
}
| 864 |
311 | <reponame>zcf7822/joyqueue<gh_stars>100-1000
package org.joyqueue.broker.network.command;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import org.joyqueue.network.command.CommandType;
import org.joyqueue.network.transport.command.JoyQueuePayload;
import java.util.List;
import java.util.Map;
/**
* GetPartitionGroupClusterResponse
* author: gaohaoxiang
* date: 2020/3/19
*/
public class GetPartitionGroupClusterResponse extends JoyQueuePayload {
private Map<String, Map<Integer, PartitionGroupCluster>> groups;
public void setGroups(Map<String, Map<Integer, PartitionGroupCluster>> groups) {
this.groups = groups;
}
public Map<String, Map<Integer, PartitionGroupCluster>> getGroups() {
return groups;
}
public PartitionGroupCluster getCluster(String topic, int group) {
if (groups == null) {
return null;
}
Map<Integer, PartitionGroupCluster> topicMap = groups.get(topic);
if (topicMap == null) {
return null;
}
return topicMap.get(group);
}
public void addCluster(String topic, int group, PartitionGroupCluster cluster) {
if (groups == null) {
groups = Maps.newHashMap();
}
Map<Integer, PartitionGroupCluster> topicMap = groups.get(topic);
if (topicMap == null) {
topicMap = Maps.newHashMap();
groups.put(topic, topicMap);
}
topicMap.put(group, cluster);
}
@Override
public int type() {
return CommandType.GET_PARTITION_GROUP_CLUSTER_RESPONSE;
}
public static class PartitionGroupCluster {
private List<PartitionGroupNode> nodes;
public void addNode(PartitionGroupNode node) {
if (nodes == null) {
nodes = Lists.newLinkedList();
}
nodes.add(node);
}
public PartitionGroupNode getRWNode() {
for (PartitionGroupNode node : nodes) {
if (node.isWritable() && node.isReadable()) {
return node;
}
}
return null;
}
public PartitionGroupNode getWritableNode() {
for (PartitionGroupNode node : nodes) {
if (node.isWritable()) {
return node;
}
}
return null;
}
public List<PartitionGroupNode> getReadableNodes() {
List<PartitionGroupNode> result = Lists.newArrayListWithCapacity(nodes.size());
for (PartitionGroupNode node : nodes) {
if (node.isReadable()) {
result.add(node);
}
}
return result;
}
public List<PartitionGroupNode> getNodes() {
return nodes;
}
public void setNodes(List<PartitionGroupNode> nodes) {
this.nodes = nodes;
}
}
public static class PartitionGroupNode {
private int id;
private boolean writable;
private boolean readable;
public PartitionGroupNode() {
}
public PartitionGroupNode(int id, boolean writable, boolean readable) {
this.id = id;
this.writable = writable;
this.readable = readable;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public boolean isWritable() {
return writable;
}
public void setWritable(boolean writable) {
this.writable = writable;
}
public boolean isReadable() {
return readable;
}
public void setReadable(boolean readable) {
this.readable = readable;
}
}
} | 1,788 |
349 | #!/usr/bin/python
# -*- coding: utf-8 -*-
# monkey 任务
from library.api.db import EntityModel, db
class Monkey(EntityModel):
ACTIVE = 0
DISABLE = 1
TEST_TYPE = {'monkey': 1, 'performance': 2}
app_name = db.Column(db.String(100)) # app 名称,例如:萌推
package_name = db.Column(db.String(100)) # 要测试的包名
app_version = db.Column(db.String(100)) # app 版本
app_id = db.Column(db.Integer) # app package id
download_app_status = db.Column(db.Integer) # app 下载状态
begin_time = db.Column(db.TIMESTAMP) # 开始时间
end_time = db.Column(db.TIMESTAMP) # 结束时间
jenkins_url = db.Column(db.String(100)) # jenkins 构建任务的 url
report_url = db.Column(db.String(100)) # 需要请求进行报告的 url
user_id = db.Column(db.Integer) # 触发用户 ID
mobile_ids = db.Column(db.String(100)) # 设备的 IDs
parameters = db.Column(db.String(1000)) # 请求的参数
process = db.Column(db.Integer) # 完成度 %100
status = db.Column(db.Integer, default=ACTIVE) # 状态 可用 0,不可用 1
type_id = db.Column(db.Integer) # monkey 类型 ID
run_time = db.Column(db.Integer) # 运行时间
actual_run_time = db.Column(db.Integer) # 实际运行时间
app_install_required = db.Column(db.Integer) # 是否需要安装 app
system_device = db.Column(db.Integer) # 是否是 系统设备
login_required = db.Column(db.Integer) # 是否需要登陆
login_username = db.Column(db.String(100)) # 登陆 用户名
login_password = db.Column(db.String(100)) # 登陆 密码
cancel_status = db.Column(db.Integer, default=DISABLE) # 是否cancel 此次monkey,默认 1,0为确认
test_type = db.Column(db.Integer) # 测试类型 monkey:1, performance:2
# monkey log
class MonkeyErrorLog(EntityModel):
ACTIVE = 0
DISABLE = 1
monkey_id = db.Column(db.Integer) # monkey id
task_id = db.Column(db.Integer) # monkey device id
error_type = db.Column(db.String(100)) # error log 类型
error_message = db.Column(db.TEXT) # error message
error_count = db.Column(db.Integer) # error show count in test
# monkey log
class MonkeyReport(EntityModel):
ACTIVE = 0
DISABLE = 1
monkey_id = db.Column(db.Integer) # monkey id
task_id = db.Column(db.Integer) # monkey device id
report_type = db.Column(db.Integer, default=1) # report 类型,1 bug_report
report_url = db.Column(db.String(1000)) # report url on oss
# monkey packages
class MonkeyPackage(EntityModel):
ACTIVE = 0
DISABLE = 1
PACKAGE_TYPE = {'monkey': 1, 'performance': 2}
name = db.Column(db.String(100)) # package name
package_name = db.Column(db.String(100)) # android package name
oss_url = db.Column(db.String(200)) # package oss url
picture = db.Column(db.Text) # package picture
version = db.Column(db.String(200)) # picture url
default_activity = db.Column(db.String(100)) # default activity
user_id = db.Column(db.Integer) # upload user id
status = db.Column(db.Integer, default=ACTIVE) # package status
size = db.Column(db.String(200)) # package size
test_type = db.Column(db.Integer) # test type : monkey=1,performance=2
# monkey device using
class MonkeyDeviceUsing(EntityModel):
ACTIVE = 0
DISABLE = 1
serial = db.Column(db.String(100)) # serial number
status = db.Column(db.Integer, default=ACTIVE) # status
using = db.Column(db.Integer, default=DISABLE) # not using
# monkey device status
class MonkeyDeviceStatus(EntityModel):
ACTIVE = 0
DISABLE = 1
monkey_id = db.Column(db.Integer) # monkey id
mobile_id = db.Column(db.Integer) # mobile id
mobile_serial = db.Column(db.String(100)) # 序列号
mobile_model = db.Column(db.String(100)) # mobile_model
mobile_version = db.Column(db.String(100)) # mobile version
process = db.Column(db.Integer) # 进程
activity_count = db.Column(db.Integer) # 测试的当前包的 Activity 数量
activity_tested_count = db.Column(db.Integer) # 当前包的 已经测试的 Activity 数量
activity_all = db.Column(db.String(10000)) # 测试的当前 app 的 activity
activity_tested = db.Column(db.String(10000)) # 测试的当前包的 已经测试过得 activity
anr_count = db.Column(db.Integer) # anr 数量
crash_count = db.Column(db.Integer) # crash 数量
crash_rate = db.Column(db.Integer) # crash 比率
exception_count = db.Column(db.Integer) # exception 数量
exception_run_time = db.Column(db.Integer) # exception 运行时间
# 状态 0:未开始, 1:成功, 2:失败
device_connect_status = db.Column(db.Integer) # 设备连接状态
screen_lock_status = db.Column(db.Integer) # 设备锁屏状态
setup_install_app_status = db.Column(db.Integer) # 安装 app
start_app_status = db.Column(db.Integer) # 启动 app
setup_uninstall_app_status = db.Column(db.Integer) # 卸载 app
login_app_status = db.Column(db.Integer) # 登录 app
running_status = db.Column(db.Integer) # 运行状态
teardown_uninstall_app_status = db.Column(db.Integer) # 最后卸载 app
current_stage = db.Column(db.Integer, default=0) # 当前执行的具体步骤
begin_time = db.Column(db.TIMESTAMP) # 开始时间
end_time = db.Column(db.TIMESTAMP) # 结束时间
run_time = db.Column(db.Integer) # 运行时间
running_error_reason = db.Column(db.String(1000)) # 运行失败的具体原因
mobile_resolution = db.Column(db.String(100)) # device 分辨率
cancel_status = db.Column(db.Integer, default=DISABLE) # 取消此设备的构建,默认 1,取消为 0
| 2,525 |
1,354 | <reponame>erraghawmishra/HackerRank-All-Solutions-in-Java<filename>HackerRankDashboard/CoreCS/Algorithms/src/main/java/com/javaaid/hackerrank/solutions/algorithms/sorting/LuckBalance.java<gh_stars>1000+
/**
*
* Problem Statement-
* [Luck Balance](https://www.hackerrank.com/challenges/luck-balance/problem)
*
*/
package com.javaaid.hackerrank.solutions.algorithms.sorting;
import java.util.Scanner;
/**
* @author <NAME>
*
*/
public class LuckBalance {
public static void sort(int a[], int lo, int hi) {
if (hi > lo) {
int q = partition(a, lo, hi);
sort(a, lo, q - 1);
sort(a, q + 1, hi);
}
}
public static int partition(int a[], int lo, int hi) {
int i = lo;
int j = hi + 1;
while (hi > lo) {
while (a[++i] < a[lo])
if (i == hi)
break;
while (a[--j] > a[lo])
if (j == lo)
break;
if (i >= j)
break;
swap(a, i, j);
}
swap(a, lo, j);
return j;
}
public static void swap(int a[], int i, int j) {
int temp = a[i];
a[i] = a[j];
a[j] = temp;
}
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int N = sc.nextInt();
int K = sc.nextInt();
int win = 0;
int a[] = new int[N];
int sum = 0;
for (int i = 0; i < N; i++) {
int temp = sc.nextInt();
if (sc.nextInt() == 1) {
win++;
a[i] = temp;
} else {
a[i] = Integer.MAX_VALUE;
}
sum += temp;
}
sort(a, 0, a.length - 1);
int s2 = 0;
for (int i = 0; i < win - K; i++) {
s2 += a[i];
}
System.out.println(sum - 2 * s2);
sc.close();
}
} | 818 |
1,068 | <gh_stars>1000+
#include "mini.h"
#ifdef DEBUG_MODE
#include "leaktracker.h"
#endif
#define STYPE_NULL 0
#define STYPE_SECTION 1
#define STYPE_KEY 2
#define SINI_MAX_SIZE 4096
SSECTION * newSECTION( const char * name ) {
SSECTION * newSection = NULL ;
if( name==NULL ) return NULL ;
if( strlen(name)<=0 ) return NULL ;
if( ( newSection = (SSECTION*) malloc( sizeof( SSECTION ) ) ) != NULL ) {
newSection->type = STYPE_SECTION ;
if( ( newSection->name = (char*) malloc( strlen( name ) + 1 ) ) != NULL )
strcpy( newSection->name, name ) ;
newSection->next = NULL ;
newSection->first = NULL ;
}
return newSection ;
}
SKEY * newKEY( const char * name, const char * value ) {
SKEY * newKey = NULL ;
if( name==NULL ) return NULL ;
if( strlen(name)<= 0 ) return NULL ;
if( ( newKey = (SKEY*) malloc( sizeof( SKEY ) ) ) != NULL ) {
newKey->type = STYPE_KEY ;
if( ( newKey->name = (char*) malloc( strlen( name ) + 1 ) ) != NULL )
strcpy( newKey->name, name ) ;
if( ( newKey->value = (char*) malloc( strlen( value ) + 1 ) ) != NULL )
strcpy( (char*)newKey->value, value ) ;
newKey->next = NULL ;
}
return newKey ;
}
SINI * newINI( void ) {
SINI * newIni = NULL ;
if( ( newIni = (SINI*) malloc( sizeof( SINI ) ) ) != NULL ) {
newIni->name = NULL ;
newIni->first = NULL ;
}
return newIni ;
}
void freeSECTION( SSECTION ** Section ) {
if( Section == NULL ) return ;
if( (*Section) == NULL ) return ;
if( (*Section)->next != NULL )
{ freeSECTION( &((*Section)->next) ) ; (*Section)->next = NULL ; }
if( (*Section)->first != NULL )
{ freeKEY( &((*Section)->first) ) ; (*Section)->first = NULL ; }
if( (*Section)->name != NULL ) { free( (*Section)->name ) ; (*Section)->name = NULL ; }
(*Section)->type = STYPE_NULL ;
free( *Section ) ;
(*Section) = NULL ;
}
void freeKEY( SKEY ** Key ) {
if( Key == NULL ) return ;
if( (*Key) == NULL ) return ;
if( (*Key)->next != NULL )
{ freeKEY( &((*Key)->next) ) ; (*Key)->next = NULL ; }
if( (*Key)->name != NULL ) { free( (*Key)->name ) ; (*Key)->name = NULL ; }
if( (*Key)->value != NULL ) { free( (*Key)->value ) ; (*Key)->value = NULL ; }
(*Key)->type = STYPE_NULL ;
free( *Key ) ;
(*Key) = NULL ;
}
void freeINI( SINI ** Ini ) {
if( Ini == NULL ) return ;
if( (*Ini) == NULL ) return ;
if( (*Ini)->name != NULL ) { free( (*Ini)->name ) ; (*Ini)->name = NULL ; }
freeSECTION( & ((*Ini)->first) ) ;
free( *Ini ) ;
(*Ini) = NULL ;
}
int addSECTION( SSECTION * Section, SSECTION * SectionAdd ) {
SSECTION * Current ;
if( Section == NULL ) return 0 ;
if( SectionAdd == NULL ) return 0 ;
Current = Section->next ;
if( Current == NULL ) {
Section->next = SectionAdd ;
}
else {
while( Current->next != NULL ) { Current = Current->next ; }
Current->next = SectionAdd ;
}
return 1 ;
}
int addINI( SINI * Ini, SSECTION * Section ) {
int return_code = 1 ;
if( Ini->first == NULL ) Ini->first = Section ;
else return_code = addSECTION( Ini->first, Section ) ;
return return_code ;
}
int delSECTION( SSECTION * Section, const char * name ) {
int return_code = 0 ;
SSECTION * Current, * Last = NULL, * Next = NULL ;
if( Section == NULL ) return 0 ;
if( name == NULL ) return 0 ;
if( strlen( name ) == 0 ) return 0 ;
Current = Section->next ;
if( Current == NULL ) return 0 ;
while( (Current != NULL) && ( strcmp( Current->name, name ) ) ) {
Last = Current ;
Current = Current->next ;
Next = Current->next ;
}
if( !strcmp( Current->name, name ) && ( Current->type = STYPE_SECTION ) ) {
freeSECTION( &Current ) ;
if( Last != NULL ) Last->next = Next ;
else Section->next = Next ;
return_code = 1 ;
}
return return_code ;
}
int addKEY( SSECTION * Section, SKEY * Key ) {
SKEY * Current ;
if( Section == NULL ) return 0 ;
if( Key == NULL ) return 0 ;
if( ( Current = getKEY( Section, Key->name ) ) != NULL ) { // Si la clé existe déjà on la supprime d'abord
//if( !delKEY( Section, Key->name ) ) return 0 ;
if( Current->value != NULL ) { free( Current->value ) ; Current->value = NULL ; }
if( ( Current->value = malloc( strlen( (const char*)(Key->value) ) + 1 ) ) == NULL ) return 0 ;
//strcpy( Current->value, Key->value ) ;
memcpy( Current->value, Key->value, strlen( (const char*)Key->value ) + 1 ) ;
freeKEY( &Key ) ;
return 1 ;
}
Current = Section->first ;
if( Current == NULL ) {
Section->first = Key ;
}
else {
while( Current->next != NULL ) { Current = Current->next ; }
Current->next = Key ;
}
return 1 ;
}
void freeSKEY( SKEY ** c ) { free( *c ) ; }
int delKEY( SSECTION * Section, const char * name ) {
int return_code = 0 ;
SKEY * Current, * Last = NULL, * Next = NULL ;
if( Section == NULL ) return 0 ;
if( name == NULL ) return 0 ;
if( strlen( name ) == 0 ) return 0 ;
Current = Section->first ;
if( Current == NULL ) return 0 ;
while( (Current != NULL ) && ( strcmp( Current->name, name ) ) ) {
Last = Current ;
Current = Current->next ;
if( Current != NULL ) Next = Current->next ; else Next = NULL ;
}
if( Current != NULL )
if( !strcmp( Current->name, name ) && ( Current->type = STYPE_KEY ) ) {
free( Current->name ) ; Current->name = NULL ;
if( Current->value != NULL )
{ free( Current->value ) ; Current->value = NULL ; }
Current->type = STYPE_NULL ;
freeSKEY( &Current ) ;
Current = NULL ;
if( Last != NULL ) Last->next = Next ;
else Section->first = Next ;
return_code = 1 ;
}
return return_code ;
}
SSECTION * getSECTION( SSECTION * Section, const char * name ) {
SSECTION * Current ;
if( Section == NULL ) return NULL ;
if( name == NULL ) return Section ;
if( strlen( name ) == 0 ) return Section ;
Current = Section ;
while( ( Current != NULL ) && ( strcmp( Current->name, name ) ) ) {
Current = Current->next ;
}
return Current ;
}
SSECTION * lastSECTION( SSECTION * Section ) {
SSECTION * Current ;
if( Section == NULL ) return NULL ;
Current = Section ;
while( Current->next != NULL ) {
Current = Current->next ;
}
return Current ;
}
SKEY * getKEY( SSECTION * Section, const char * name ) {
SKEY * Current ;
if( Section == NULL ) return NULL ;
if( name == NULL ) return Section->first ;
if( strlen( name ) == 0 ) return Section->first ;
Current = Section->first ;
while( ( Current != NULL ) && ( strcmp( Current->name, name ) ) ) {
Current = Current->next ;
}
return Current ;
}
char * getvalueKEY( SKEY * Key ) {
if( Key == NULL ) return NULL ;
return (char*)Key->value ;
}
int setKEY( SKEY * Key, char * value ) {
if( Key == NULL ) return 0 ;
if( Key->value != NULL ) { free( Key->value ) ; Key->value = NULL ; }
if( value != NULL ) {
if( ( Key->value = (char*) malloc( strlen( value ) + 1 ) ) == NULL ) return 0 ;
strcpy( (char*)Key->value, value ) ;
}
return 1 ;
}
SSECTION * getINI( SINI * Ini ) {
if( Ini == NULL ) return NULL ;
return Ini->first ;
}
void printKEY( SKEY * Key ) {
if( Key == NULL ) return ;
printf( "%s=%s\n", Key->name, (char*)Key->value ) ;
if( Key->next != NULL ) printKEY( Key->next ) ;
}
void printSECTION( SSECTION * Section ) {
if( Section == NULL ) return ;
if( Section->type == STYPE_SECTION ) printf( "[%s]\n", Section->name ) ;
if( Section->first != NULL ) printKEY( Section->first ) ;
if( Section->next != NULL ) printSECTION( Section->next ) ;
}
void printINI( SINI * Ini ) {
if( Ini == NULL ) return ;
printSECTION( Ini->first ) ;
}
int loadINI( SINI * Ini, const char * filename ) {
FILE * fp ;
SSECTION * Section, * Last = NULL ;
SKEY * Key ;
char buffer[SINI_MAX_SIZE], name[SINI_MAX_SIZE], value[SINI_MAX_SIZE] ;
unsigned int i, p ;
if( Ini == NULL ) return 0 ;
if( filename==NULL ) return 0 ;
if( strlen(filename)<=0 ) return 0 ;
freeSECTION( &(Ini->first) ) ;
if( ( fp = fopen( filename, "r" ) ) == NULL ) { return 0 ; }
while( fgets( buffer, SINI_MAX_SIZE, fp ) != NULL ) {
buffer[SINI_MAX_SIZE-1]='\0';
while( (buffer[strlen(buffer)-1]=='\n')||(buffer[strlen(buffer)-1]=='\r') ) buffer[strlen(buffer)-1]='\0' ;
while( (buffer[0]==' ')||(buffer[0]=='\t') )
for( i=0; i<strlen(buffer); i++ )
buffer[i] = buffer[i+1] ;
if( buffer[0] == '[' ) { // Nouvelle section
while( (buffer[strlen(buffer)-1]==' ')||(buffer[strlen(buffer)-1]=='\t') ) buffer[strlen(buffer)-1]='\0' ;
if( buffer[strlen(buffer)-1]==']' ) {
buffer[strlen(buffer)-1]='\0' ;
if( (Section = getSECTION( Ini->first, buffer+1 )) == NULL ) { //On recherche si la section existe deja
Section = newSECTION( buffer+1 ) ;
if( Ini->first == NULL ) Ini->first = Section ;
else addSECTION( Ini->first, Section ) ;
}
Last = Section ;
}
}
else if( Last!= NULL ) { // Nouvelle clé dans la section en cours
name[0] = '\0' ; value[0] = '\0' ;
p = 0 ;
for( i=0; (i<strlen(buffer))&&(buffer[i]!='='); i++ ) p = i+1 ;
if( (p>0) && (p<(strlen(buffer)-1) ) ) {
for( i=0; i<p; i++ ) { name[i] = buffer[i] ; } name[p]='\0' ;
for( i=p+1; i<strlen(buffer); i++ ) { value[i-p-1]=buffer[i] ; value[i-p]='\0' ; }
while( (name[strlen(name)-1]==' ')||(name[strlen(name)-1]=='\t') ) name[strlen(name)-1]='\0' ;
Key = newKEY( name, value ) ;
addKEY( Last, Key ) ;
}
else if( p==(strlen(buffer)-1) ) {
buffer[strlen(buffer)-1] = '\0' ;
strcpy( name, buffer ) ;
while( (name[strlen(name)-1]==' ')||(name[strlen(name)-1]=='\t') ) name[strlen(name)-1]='\0' ;
strcpy( value, "" ) ;
Key = newKEY( name, value ) ;
addKEY( Last, Key ) ;
}
}
}
fclose( fp ) ;
return 1 ;
}
int storeKEY( SKEY * Key, FILE * fp ) {
if( Key == NULL ) return 0 ;
if( fp==NULL ) return 0 ;
fprintf( fp, "%s=%s\n", Key->name, (char*)Key->value ) ;
if( Key->next != NULL ) storeKEY( Key->next, fp ) ;
return 1 ;
}
int storeSECTION( SSECTION * Section, FILE * fp ) {
if( Section == NULL ) return 0 ;
if( fp==NULL ) return 0 ;
fprintf( fp, "[%s]\n", Section->name ) ;
if( Section->first != NULL ) storeKEY( Section->first, fp ) ;
if( Section->next != NULL ) storeSECTION( Section->next, fp ) ;
return 1 ;
}
int storeINI( SINI * Ini, const char * filename ) {
FILE * fp ;
if( filename==NULL ) return 0 ;
if( strlen(filename)<=0 ) return 0 ;
if( ( fp = fopen( filename, "w" ) ) == NULL ) return 0 ;
if( _locking( fileno(fp) , LK_LOCK, 1000000L ) == -1 ) { fclose(fp) ; return 0 ; }
storeSECTION( getINI( Ini ), fp ) ;
_locking( fileno(fp) , LK_UNLCK, 1000000L );
fclose( fp ) ;
return 1 ;
}
/* Amelioration pour ne pas relire le fichier à chaque fois */
static char * mini_filename = NULL ;
static time_t mini_mtime = 0 ;
static SINI * mini_Ini = NULL ;
int readINI( const char * filename, const char * section, const char * key, char * pStr) {
int return_code = 0 ;
struct stat buf ;
//SINI * Ini = NULL ;
SSECTION * Section = NULL ;
SKEY * Key = NULL ;
if( filename==NULL ) return 0 ;
if( strlen(filename)<=0 ) return 0 ;
if( section==NULL ) return 0 ;
if( strlen(section)<=0 ) return 0 ;
if( mini_filename != NULL ) // On compare la date du fichier en mémoire avec celle du fichier sur dique
if( stat(filename, &buf) != -1 ) {
if( buf.st_mtime > mini_mtime ) {
free( mini_filename ) ;
mini_filename = NULL ;
mini_mtime = 0 ;
}
}
if( (mini_filename!=NULL)&&(!strcmp( filename, mini_filename )) ) {
if( ( Section = getSECTION( getINI( mini_Ini ), section ) ) != NULL ) {
if( ( Key = getKEY( Section, key ) ) != NULL ) {
strcpy( pStr, getvalueKEY( Key ) ) ;
return_code = 1 ;
}
}
}
else {
freeINI( &mini_Ini ) ;
if( mini_filename!=NULL ) { free(mini_filename); mini_filename=NULL;mini_mtime=0; }
mini_filename=(char*)malloc( strlen(filename)+1 ); strcpy(mini_filename,filename);
if( ( mini_Ini = newINI() ) != NULL ) {
loadINI( mini_Ini, filename ) ;
if( stat(filename, &buf) != 1 ) {
mini_mtime = buf.st_mtime ;
}
if( ( Section = getSECTION( getINI( mini_Ini ), section ) ) != NULL ) {
if( ( Key = getKEY( Section, key ) ) != NULL ) {
strcpy( pStr, getvalueKEY( Key ) ) ;
return_code = 1 ;
}
}
//freeINI( &mini_Ini ) ;
}
}
return return_code ;
}
int writeINI( const char * filename, const char * section, const char * key, const char * value ) {
int return_code = 0 ;
SINI * Ini = NULL ;
SSECTION * Section = NULL ;
SKEY * Key ;
if( filename==NULL ) return 0 ;
if( strlen(filename)<=0 ) return 0 ;
if( section==NULL ) return 0 ;
if( strlen(section)<=0 ) return 0 ;
freeINI( &mini_Ini ) ;
if( mini_filename!=NULL ) { free(mini_filename); mini_filename=NULL; }
if( ( Ini = newINI() ) != NULL ) {
loadINI( Ini, filename ) ;
if( ( Section = getSECTION( getINI( Ini ), section ) ) == NULL ) {
if( ( Section = newSECTION( section ) ) != NULL ) {
addINI( Ini, Section ) ;
}
else return 0 ;
}
if( key != NULL ) if( strlen(key)>0 ) {
if( ( Key = newKEY( key, value ) ) != NULL ) {
if( !addKEY( Section, Key ) )
{ freeKEY( &Key ) ; }
}
}
if( storeINI( Ini, filename ) )
return_code = 1 ;
freeINI( &Ini ) ;
}
return return_code ;
}
int writeINISec( const char * filename, const char * section, const char * key, const char * value ) {
int return_code = 0 ;
char * newname = NULL ;
if( (newname=(char*)malloc( strlen(filename)+5 )) == NULL ) return 0 ;
sprintf( newname, "%s.new", filename );
return_code = writeINI( newname, section, key, value ) ;
free(newname) ;
return return_code ;
}
int delINI( const char * filename, const char * section, const char * key ) {
int return_code = 0 ;
SINI * Ini = NULL ;
SSECTION * Section = NULL ;
if( filename==NULL ) return 0 ;
if( strlen(filename)<=0 ) return 0 ;
if( section==NULL ) return 0 ;
if( strlen(section)<=0 ) return 0 ;
freeINI( &mini_Ini ) ;
if( mini_filename!=NULL ) { free(mini_filename); mini_filename=NULL; }
if( ( Ini = newINI() ) != NULL ) {
loadINI( Ini, filename ) ;
if( ( Section = getSECTION( getINI( Ini ), section ) ) != NULL ) {
if( (key!=NULL) && (strlen(key)>0) ){
delKEY( Section, key ) ;
}
else {
delSECTION( getINI( Ini ), section ) ;
}
if( storeINI( Ini, filename ) )
return_code = 1 ;
}
freeINI( &Ini ) ;
}
return return_code ;
}
int delINISec( const char * filename, const char * section, const char * key ) {
int return_code = 0 ;
char * newname = NULL ;
if( (newname=(char*)malloc( strlen(filename)+5 )) == NULL ) return 0 ;
sprintf( newname, "%s.new", filename );
return_code = delINI( newname, section, key ) ;
free(newname) ;
return return_code ;
}
void destroyINI( void ) {
if(mini_filename!=NULL) { free(mini_filename) ; } mini_filename=NULL ;
freeINI( &mini_Ini ) ;
}
int ini_main( int argc, char *argv[], char *arge[] ) {
char buf[256];
//SINI * INI = newINI( ) ; loadINI( INI, "test.ini" ) ; printINI( INI ) ; freeINI( &INI ) ;
//delINI( "test.ini", "new_section", "password") ;
system( "rm test.ini" ) ;
writeINI( "test.ini", "Section1", "Name1", "Value1") ;
writeINI( "test.ini", "Section1", "Name2", "Value2") ;
system( "cat test.ini" ) ; system( "echo." ) ;
writeINI( "test.ini", "Section2", "Name1", "Value1") ;
system( "cat test.ini" ) ; system( "echo." ) ;
writeINI( "test.ini", "Section1", "Name1", "Value3") ;
system( "cat test.ini" ) ; system( "echo." ) ;
writeINI( "test.ini", "Section3", NULL, "") ;
system( "cat test.ini" ) ; system( "echo." ) ;
delINI( "test.ini", "Section2", "Name1" );
system( "cat test.ini" ) ; system( "echo." ) ;
readINI( "test.ini", "Section1", "Name1", buf); printf("Name1=%s\n",buf);
readINI( "test.ini", "Section1", "Name2", buf); printf("Name2=%s\n",buf);
char b[10];
fscanf( stdin, "%s", b) ;
readINI( "test.ini", "Section1", "Name1", buf); printf("Name1=%s\n",buf);
fscanf( stdin, "%s", b) ;
readINI( "test.ini", "Section1", "Name1", buf); printf("Name1=%s\n",buf);
destroyINI();
return 1;
}
#ifdef MAIN
int main( int argc, char *argv[], char *arge[] ) {
int return_code = 0 ;
return_code = ini_main( argc, argv, arge ) ;
#ifdef DEBUG_MODE
_leaktracker61_EnableReportLeakOnApplication_Exit("ini.leaktracker.log", 1);
_leaktracker61_DumpAllLeaks("ini.leaktracker.log", 0);
printf("Leak tracker log in ini.leaktracker.log file\n");
#endif
return return_code ;
}
#endif
| 6,696 |
9,717 | /*
* LD_PRELOAD trick to make c3pldrv handle the absolute path to /usr/{bin,lib,share)}.
* As c3pldrv is a 32 bit executable, /lib will be rewritten to /lib32.
*
* Usage:
* gcc -shared -fPIC -DOUT="$out" preload.c -o preload.so -ldl
* LD_PRELOAD=$PWD/preload.so ./c3pldrv
*/
#define _GNU_SOURCE
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <fcntl.h>
#include <dlfcn.h>
#include <limits.h>
#ifndef OUT
#error Missing OUT define - path to the installation directory.
#endif
typedef void *(*dlopen_func_t)(const char *filename, int flag);
typedef int (*open_func_t)(const char *pathname, int flags, ...);
typedef int (*execv_func_t)(const char *path, char *const argv[]);
void *dlopen(const char *filename, int flag)
{
dlopen_func_t orig_dlopen;
const char *new_filename;
char buffer[PATH_MAX];
orig_dlopen = (dlopen_func_t)dlsym(RTLD_NEXT, "dlopen");
new_filename = filename;
if (strncmp("/usr/lib", filename, 8) == 0) {
snprintf(buffer, PATH_MAX, OUT "/lib32%s", filename+8);
buffer[PATH_MAX-1] = '\0';
new_filename = buffer;
}
return orig_dlopen(new_filename, flag);
}
int open(const char *pathname, int flags, ...)
{
open_func_t orig_open;
const char *new_pathname;
char buffer[PATH_MAX];
orig_open = (open_func_t)dlsym(RTLD_NEXT, "open");
new_pathname = pathname;
if (strncmp("/usr/share", pathname, 10) == 0) {
snprintf(buffer, PATH_MAX, OUT "%s", pathname+4);
buffer[PATH_MAX-1] = '\0';
new_pathname = buffer;
}
return orig_open(new_pathname, flags);
}
int execv(const char *path, char *const argv[])
{
execv_func_t orig_execv;
const char *new_path;
char buffer[PATH_MAX];
orig_execv = (execv_func_t)dlsym(RTLD_NEXT, "execv");
new_path = path;
if (strncmp("/usr/bin", path, 8) == 0) {
snprintf(buffer, PATH_MAX, OUT "%s", path+4);
buffer[PATH_MAX-1] = '\0';
new_path = buffer;
}
return orig_execv(new_path, argv);
}
| 811 |
5,081 | <filename>app/src/main/java/com/example/jingbin/cloudreader/adapter/NavigationAdapter.java
package com.example.jingbin.cloudreader.adapter;
import com.example.jingbin.cloudreader.R;
import com.example.jingbin.cloudreader.bean.wanandroid.NaviJsonBean;
import com.example.jingbin.cloudreader.databinding.ItemNavigationBinding;
import me.jingbin.bymvvm.adapter.BaseBindingAdapter;
import me.jingbin.bymvvm.adapter.BaseBindingHolder;
/**
* Created by jingbin on 2018/10/13.
*/
public class NavigationAdapter extends BaseBindingAdapter<NaviJsonBean.DataBean, ItemNavigationBinding> {
public NavigationAdapter() {
super(R.layout.item_navigation);
}
@Override
protected void bindView(BaseBindingHolder holder, NaviJsonBean.DataBean dataBean, ItemNavigationBinding binding, int position) {
if (dataBean != null) {
binding.tvTitle.setSelected(dataBean.isSelected());
binding.setBean(dataBean);
binding.tvTitle.setOnClickListener(v -> {
if (listener != null) {
listener.onSelected(position);
}
});
}
}
private OnSelectListener listener;
public void setOnSelectListener(OnSelectListener listener) {
this.listener = listener;
}
public interface OnSelectListener {
void onSelected(int position);
}
}
| 547 |
651 | package com.ncipher.nfast.marshall;
public class M_Act_Details_NVMemOpPerms extends M_Act_Details implements Marshallable {
public static final int perms_Read = 1;
public static final int perms_Write = 2;
public static final int perms_GetACL = 1024;
public M_Act_Details_NVMemOpPerms(long var1) {
throw new RuntimeException("fake nCipher");
}
}
| 119 |
435 | <gh_stars>100-1000
{
"copyright_text": "Standard YouTube License",
"description": "",
"duration": 2322,
"language": "ita",
"recorded": "2016-06-23",
"related_urls": [],
"speakers": [
"<NAME>"
],
"tags": [],
"thumbnail_url": "https://i.ytimg.com/vi/FMAG3XOzgwg/maxresdefault.jpg",
"title": "Introduzione a MicroPython e BBC Micro Bit",
"videos": [
{
"type": "youtube",
"url": "https://www.youtube.com/watch?v=FMAG3XOzgwg"
}
]
}
| 211 |
1,025 | package com.baidu.unbiz.fluentvalidator.validator;
import com.baidu.unbiz.fluentvalidator.Validator;
import com.baidu.unbiz.fluentvalidator.ValidatorContext;
import com.baidu.unbiz.fluentvalidator.ValidatorHandler;
import com.baidu.unbiz.fluentvalidator.error.CarError;
import com.baidu.unbiz.fluentvalidator.support.MethodNameFluentValidatorPostProcessor;
/**
* @author zhangxu
*/
public class CarNotNullValidator extends ValidatorHandler implements Validator {
@Override
public boolean validate(ValidatorContext context, Object t) {
String methodName = (String) context.getAttribute(MethodNameFluentValidatorPostProcessor.KEY_METHOD_NAME);
System.out.println("MethodName = " + methodName);
if (t == null) {
context.addErrorMsg(CarError.CAR_NULL.msg());
return false;
}
return true;
}
}
| 323 |
2,338 | <reponame>jhh67/chapel
//===-- unittests/Tooling/RecursiveASTVisitorTests/CallbacksCallExpr.cpp --===//
//
// 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
//
//===----------------------------------------------------------------------===//
#include "CallbacksCommon.h"
TEST(RecursiveASTVisitor, StmtCallbacks_TraverseCallExpr) {
class RecordingVisitor : public RecordingVisitorBase<RecordingVisitor> {
public:
RecordingVisitor(ShouldTraversePostOrder ShouldTraversePostOrderValue)
: RecordingVisitorBase(ShouldTraversePostOrderValue) {}
bool TraverseCallExpr(CallExpr *CE) {
recordCallback(__func__, CE,
[&]() { RecordingVisitorBase::TraverseCallExpr(CE); });
return true;
}
bool WalkUpFromStmt(Stmt *S) {
recordCallback(__func__, S,
[&]() { RecordingVisitorBase::WalkUpFromStmt(S); });
return true;
}
};
StringRef Code = R"cpp(
void add(int, int);
void test() {
1;
2 + 3;
add(4, 5);
}
)cpp";
EXPECT_TRUE(visitorCallbackLogEqual(
RecordingVisitor(ShouldTraversePostOrder::No), Code,
R"txt(
WalkUpFromStmt CompoundStmt
WalkUpFromStmt IntegerLiteral(1)
WalkUpFromStmt BinaryOperator(+)
WalkUpFromStmt IntegerLiteral(2)
WalkUpFromStmt IntegerLiteral(3)
TraverseCallExpr CallExpr(add)
WalkUpFromStmt CallExpr(add)
WalkUpFromStmt ImplicitCastExpr
WalkUpFromStmt DeclRefExpr(add)
WalkUpFromStmt IntegerLiteral(4)
WalkUpFromStmt IntegerLiteral(5)
)txt"));
EXPECT_TRUE(visitorCallbackLogEqual(
RecordingVisitor(ShouldTraversePostOrder::Yes), Code,
R"txt(
WalkUpFromStmt IntegerLiteral(1)
WalkUpFromStmt IntegerLiteral(2)
WalkUpFromStmt IntegerLiteral(3)
WalkUpFromStmt BinaryOperator(+)
TraverseCallExpr CallExpr(add)
WalkUpFromStmt DeclRefExpr(add)
WalkUpFromStmt ImplicitCastExpr
WalkUpFromStmt IntegerLiteral(4)
WalkUpFromStmt IntegerLiteral(5)
WalkUpFromStmt CallExpr(add)
WalkUpFromStmt CompoundStmt
)txt"));
}
TEST(RecursiveASTVisitor, StmtCallbacks_TraverseCallExpr_WalkUpFromCallExpr) {
class RecordingVisitor : public RecordingVisitorBase<RecordingVisitor> {
public:
RecordingVisitor(ShouldTraversePostOrder ShouldTraversePostOrderValue)
: RecordingVisitorBase(ShouldTraversePostOrderValue) {}
bool TraverseCallExpr(CallExpr *CE) {
recordCallback(__func__, CE,
[&]() { RecordingVisitorBase::TraverseCallExpr(CE); });
return true;
}
bool WalkUpFromStmt(Stmt *S) {
recordCallback(__func__, S,
[&]() { RecordingVisitorBase::WalkUpFromStmt(S); });
return true;
}
bool WalkUpFromExpr(Expr *E) {
recordCallback(__func__, E,
[&]() { RecordingVisitorBase::WalkUpFromExpr(E); });
return true;
}
bool WalkUpFromCallExpr(CallExpr *CE) {
recordCallback(__func__, CE,
[&]() { RecordingVisitorBase::WalkUpFromCallExpr(CE); });
return true;
}
};
StringRef Code = R"cpp(
void add(int, int);
void test() {
1;
2 + 3;
add(4, 5);
}
)cpp";
EXPECT_TRUE(visitorCallbackLogEqual(
RecordingVisitor(ShouldTraversePostOrder::No), Code,
R"txt(
WalkUpFromStmt CompoundStmt
WalkUpFromExpr IntegerLiteral(1)
WalkUpFromStmt IntegerLiteral(1)
WalkUpFromExpr BinaryOperator(+)
WalkUpFromStmt BinaryOperator(+)
WalkUpFromExpr IntegerLiteral(2)
WalkUpFromStmt IntegerLiteral(2)
WalkUpFromExpr IntegerLiteral(3)
WalkUpFromStmt IntegerLiteral(3)
TraverseCallExpr CallExpr(add)
WalkUpFromCallExpr CallExpr(add)
WalkUpFromExpr CallExpr(add)
WalkUpFromStmt CallExpr(add)
WalkUpFromExpr ImplicitCastExpr
WalkUpFromStmt ImplicitCastExpr
WalkUpFromExpr DeclRefExpr(add)
WalkUpFromStmt DeclRefExpr(add)
WalkUpFromExpr IntegerLiteral(4)
WalkUpFromStmt IntegerLiteral(4)
WalkUpFromExpr IntegerLiteral(5)
WalkUpFromStmt IntegerLiteral(5)
)txt"));
EXPECT_TRUE(visitorCallbackLogEqual(
RecordingVisitor(ShouldTraversePostOrder::Yes), Code,
R"txt(
WalkUpFromExpr IntegerLiteral(1)
WalkUpFromStmt IntegerLiteral(1)
WalkUpFromExpr IntegerLiteral(2)
WalkUpFromStmt IntegerLiteral(2)
WalkUpFromExpr IntegerLiteral(3)
WalkUpFromStmt IntegerLiteral(3)
WalkUpFromExpr BinaryOperator(+)
WalkUpFromStmt BinaryOperator(+)
TraverseCallExpr CallExpr(add)
WalkUpFromExpr DeclRefExpr(add)
WalkUpFromStmt DeclRefExpr(add)
WalkUpFromExpr ImplicitCastExpr
WalkUpFromStmt ImplicitCastExpr
WalkUpFromExpr IntegerLiteral(4)
WalkUpFromStmt IntegerLiteral(4)
WalkUpFromExpr IntegerLiteral(5)
WalkUpFromStmt IntegerLiteral(5)
WalkUpFromCallExpr CallExpr(add)
WalkUpFromExpr CallExpr(add)
WalkUpFromStmt CallExpr(add)
WalkUpFromStmt CompoundStmt
)txt"));
}
TEST(RecursiveASTVisitor, StmtCallbacks_WalkUpFromCallExpr) {
class RecordingVisitor : public RecordingVisitorBase<RecordingVisitor> {
public:
RecordingVisitor(ShouldTraversePostOrder ShouldTraversePostOrderValue)
: RecordingVisitorBase(ShouldTraversePostOrderValue) {}
bool WalkUpFromStmt(Stmt *S) {
recordCallback(__func__, S,
[&]() { RecordingVisitorBase::WalkUpFromStmt(S); });
return true;
}
bool WalkUpFromExpr(Expr *E) {
recordCallback(__func__, E,
[&]() { RecordingVisitorBase::WalkUpFromExpr(E); });
return true;
}
bool WalkUpFromCallExpr(CallExpr *CE) {
recordCallback(__func__, CE,
[&]() { RecordingVisitorBase::WalkUpFromCallExpr(CE); });
return true;
}
};
StringRef Code = R"cpp(
void add(int, int);
void test() {
1;
2 + 3;
add(4, 5);
}
)cpp";
EXPECT_TRUE(visitorCallbackLogEqual(
RecordingVisitor(ShouldTraversePostOrder::No), Code,
R"txt(
WalkUpFromStmt CompoundStmt
WalkUpFromExpr IntegerLiteral(1)
WalkUpFromStmt IntegerLiteral(1)
WalkUpFromExpr BinaryOperator(+)
WalkUpFromStmt BinaryOperator(+)
WalkUpFromExpr IntegerLiteral(2)
WalkUpFromStmt IntegerLiteral(2)
WalkUpFromExpr IntegerLiteral(3)
WalkUpFromStmt IntegerLiteral(3)
WalkUpFromCallExpr CallExpr(add)
WalkUpFromExpr CallExpr(add)
WalkUpFromStmt CallExpr(add)
WalkUpFromExpr ImplicitCastExpr
WalkUpFromStmt ImplicitCastExpr
WalkUpFromExpr DeclRefExpr(add)
WalkUpFromStmt DeclRefExpr(add)
WalkUpFromExpr IntegerLiteral(4)
WalkUpFromStmt IntegerLiteral(4)
WalkUpFromExpr IntegerLiteral(5)
WalkUpFromStmt IntegerLiteral(5)
)txt"));
EXPECT_TRUE(visitorCallbackLogEqual(
RecordingVisitor(ShouldTraversePostOrder::Yes), Code,
R"txt(
WalkUpFromExpr IntegerLiteral(1)
WalkUpFromStmt IntegerLiteral(1)
WalkUpFromExpr IntegerLiteral(2)
WalkUpFromStmt IntegerLiteral(2)
WalkUpFromExpr IntegerLiteral(3)
WalkUpFromStmt IntegerLiteral(3)
WalkUpFromExpr BinaryOperator(+)
WalkUpFromStmt BinaryOperator(+)
WalkUpFromExpr DeclRefExpr(add)
WalkUpFromStmt DeclRefExpr(add)
WalkUpFromExpr ImplicitCastExpr
WalkUpFromStmt ImplicitCastExpr
WalkUpFromExpr IntegerLiteral(4)
WalkUpFromStmt IntegerLiteral(4)
WalkUpFromExpr IntegerLiteral(5)
WalkUpFromStmt IntegerLiteral(5)
WalkUpFromCallExpr CallExpr(add)
WalkUpFromExpr CallExpr(add)
WalkUpFromStmt CallExpr(add)
WalkUpFromStmt CompoundStmt
)txt"));
}
| 3,004 |
360 | /*-------------------------------------------------------------------------
*
* unaccent.c
* Text search unaccent dictionary
*
* Copyright (c) 2009-2012, PostgreSQL Global Development Group
*
* IDENTIFICATION
* contrib/unaccent/unaccent.c
*
*-------------------------------------------------------------------------
*/
#include "postgres.h"
#include "knl/knl_variable.h"
#include "catalog/namespace.h"
#include "commands/defrem.h"
#include "tsearch/ts_cache.h"
#include "tsearch/ts_locale.h"
#include "tsearch/ts_public.h"
#include "utils/builtins.h"
PG_MODULE_MAGIC;
/*
* Unaccent dictionary uses uncompressed suffix tree to find a
* character to replace. Each node of tree is an array of
* SuffixChar struct with length = 256 (n-th element of array
* corresponds to byte)
*/
typedef struct SuffixChar {
struct SuffixChar* nextChar;
char* replaceTo;
int replacelen;
} SuffixChar;
/*
* placeChar - put str into tree's structure, byte by byte.
*/
static SuffixChar* placeChar(SuffixChar* node, unsigned char* str, int lenstr, char* replaceTo, int replacelen)
{
SuffixChar* curnode = NULL;
errno_t rc;
if (!node) {
node = (SuffixChar*)palloc(sizeof(SuffixChar) * 256);
rc = memset_s(node, sizeof(SuffixChar) * 256, 0, sizeof(SuffixChar) * 256);
securec_check_c(rc, "", "");
}
curnode = node + *str;
if (lenstr == 1) {
if (curnode->replaceTo)
elog(WARNING, "duplicate TO argument, use first one");
else {
curnode->replacelen = replacelen;
curnode->replaceTo = (char*)palloc(replacelen);
rc = memcpy_s(curnode->replaceTo, replacelen, replaceTo, replacelen);
securec_check_c(rc, "", "");
}
} else {
curnode->nextChar = placeChar(curnode->nextChar, str + 1, lenstr - 1, replaceTo, replacelen);
}
return node;
}
/*
* initSuffixTree - create suffix tree from file. Function converts
* UTF8-encoded file into current encoding.
*/
static SuffixChar* initSuffixTree(char* filename)
{
SuffixChar* volatile rootSuffixTree = NULL;
MemoryContext ccxt = CurrentMemoryContext;
tsearch_readline_state trst;
volatile bool skip = false;
filename = get_tsearch_config_filename(filename, "rules");
if (!tsearch_readline_begin(&trst, filename))
ereport(
ERROR, (errcode(ERRCODE_CONFIG_FILE_ERROR), errmsg("could not open unaccent file \"%s\": %m", filename)));
do {
/*
* pg_do_encoding_conversion() (called by tsearch_readline()) will
* emit exception if it finds untranslatable characters in current
* locale. We just skip such lines, continuing with the next.
*/
skip = true;
PG_TRY();
{
char* line = NULL;
while ((line = tsearch_readline(&trst)) != NULL) {
/*
* The format of each line must be "src trg" where src and trg
* are sequences of one or more non-whitespace characters,
* separated by whitespace. Whitespace at start or end of
* line is ignored.
*/
int state;
char* ptr = NULL;
char* src = NULL;
char* trg = NULL;
int ptrlen;
int srclen = 0;
int trglen = 0;
state = 0;
for (ptr = line; *ptr; ptr += ptrlen) {
ptrlen = pg_mblen(ptr);
/* ignore whitespace, but end src or trg */
if (t_isspace(ptr)) {
if (state == 1)
state = 2;
else if (state == 3)
state = 4;
continue;
}
switch (state) {
case 0:
/* start of src */
src = ptr;
srclen = ptrlen;
state = 1;
break;
case 1:
/* continue src */
srclen += ptrlen;
break;
case 2:
/* start of trg */
trg = ptr;
trglen = ptrlen;
state = 3;
break;
case 3:
/* continue trg */
trglen += ptrlen;
break;
default:
/* bogus line format */
state = -1;
break;
}
}
if (state >= 3)
rootSuffixTree = placeChar(rootSuffixTree, (unsigned char*)src, srclen, trg, trglen);
pfree(line);
}
skip = false;
}
PG_CATCH();
{
ErrorData* errdata = NULL;
MemoryContext ecxt;
ecxt = MemoryContextSwitchTo(ccxt);
errdata = CopyErrorData();
if (errdata->sqlerrcode == ERRCODE_UNTRANSLATABLE_CHARACTER) {
FlushErrorState();
} else {
MemoryContextSwitchTo(ecxt);
PG_RE_THROW();
}
}
PG_END_TRY();
} while (skip);
tsearch_readline_end(&trst);
return rootSuffixTree;
}
/*
* findReplaceTo - find multibyte character in tree
*/
static SuffixChar* findReplaceTo(SuffixChar* node, unsigned char* src, int srclen)
{
while (node) {
node = node + *src;
if (srclen == 1)
return node;
src++;
srclen--;
node = node->nextChar;
}
return NULL;
}
PG_FUNCTION_INFO_V1(unaccent_init);
extern "C" Datum unaccent_init(PG_FUNCTION_ARGS);
Datum unaccent_init(PG_FUNCTION_ARGS)
{
List* dictoptions = (List*)PG_GETARG_POINTER(0);
SuffixChar* rootSuffixTree = NULL;
bool fileloaded = false;
ListCell* l = NULL;
foreach (l, dictoptions) {
DefElem* defel = (DefElem*)lfirst(l);
if (pg_strcasecmp("Rules", defel->defname) == 0) {
if (fileloaded)
ereport(ERROR, (errcode(ERRCODE_INVALID_PARAMETER_VALUE), errmsg("multiple Rules parameters")));
rootSuffixTree = initSuffixTree(defGetString(defel));
fileloaded = true;
} else {
ereport(ERROR,
(errcode(ERRCODE_INVALID_PARAMETER_VALUE),
errmsg("unrecognized Unaccent parameter: \"%s\"", defel->defname)));
}
}
if (!fileloaded) {
ereport(ERROR, (errcode(ERRCODE_INVALID_PARAMETER_VALUE), errmsg("missing Rules parameter")));
}
PG_RETURN_POINTER(rootSuffixTree);
}
PG_FUNCTION_INFO_V1(unaccent_lexize);
extern "C" Datum unaccent_lexize(PG_FUNCTION_ARGS);
Datum unaccent_lexize(PG_FUNCTION_ARGS)
{
SuffixChar* rootSuffixTree = (SuffixChar*)PG_GETARG_POINTER(0);
char* srcchar = (char*)PG_GETARG_POINTER(1);
int32 len = PG_GETARG_INT32(2);
char* srcstart = NULL;
char* trgchar = NULL;
int charlen;
Size tarlen = 0;
TSLexeme* res = NULL;
SuffixChar* node = NULL;
errno_t rc;
srcstart = srcchar;
while (srcchar - srcstart < len) {
charlen = pg_mblen(srcchar);
node = findReplaceTo(rootSuffixTree, (unsigned char*)srcchar, charlen);
if (node && node->replaceTo) {
if (!res) {
/* allocate res only if it's needed */
res = (TSLexeme*)palloc0(sizeof(TSLexeme) * 2);
tarlen = (Size)len * pg_database_encoding_max_length() + 1; /* \0 */
res->lexeme = trgchar = (char*)palloc(tarlen);
res->flags = TSL_FILTER;
if (srcchar != srcstart) {
rc = memcpy_s(trgchar, tarlen, srcstart, srcchar - srcstart);
securec_check_c(rc, "", "");
trgchar += (srcchar - srcstart);
tarlen -= (srcchar - srcstart);
}
}
rc = memcpy_s(trgchar, node->replaceTo, node->replacelen);
trgchar += node->replacelen;
} else if (res) {
rc = memcpy_s(trgchar, charlen, srcchar, charlen);
securec_check_c(rc, "", "");
trgchar += charlen;
tarlen -= charlen;
}
srcchar += charlen;
}
if (res)
*trgchar = '\0';
PG_RETURN_POINTER(res);
}
/*
* Function-like wrapper for dictionary
*/
PG_FUNCTION_INFO_V1(unaccent_dict);
extern "C" Datum unaccent_dict(PG_FUNCTION_ARGS);
Datum unaccent_dict(PG_FUNCTION_ARGS)
{
text* str = NULL;
int strArg;
Oid dictOid;
TSDictionaryCacheEntry* dict = NULL;
TSLexeme* res = NULL;
if (PG_NARGS() == 1) {
dictOid = get_ts_dict_oid(stringToQualifiedNameList("unaccent"), false);
strArg = 0;
} else {
dictOid = PG_GETARG_OID(0);
strArg = 1;
}
str = PG_GETARG_TEXT_P(strArg);
dict = lookup_ts_dictionary_cache(dictOid);
res = (TSLexeme*)DatumGetPointer(FunctionCall4(&(dict->lexize),
PointerGetDatum(dict->dictData),
PointerGetDatum(VARDATA(str)),
Int32GetDatum(VARSIZE(str) - VARHDRSZ),
PointerGetDatum(NULL)));
PG_FREE_IF_COPY(str, strArg);
if (res == NULL) {
PG_RETURN_TEXT_P(PG_GETARG_TEXT_P_COPY(strArg));
} else if (res->lexeme == NULL) {
pfree(res);
PG_RETURN_TEXT_P(PG_GETARG_TEXT_P_COPY(strArg));
} else {
text* txt = cstring_to_text(res->lexeme);
pfree(res->lexeme);
pfree(res);
PG_RETURN_TEXT_P(txt);
}
}
| 5,191 |
9,717 | {
"url": "https://github.com/nvim-neorg/tree-sitter-norg",
"rev": "665736e400cfd52ae92ead244ca9f5d44db98151",
"date": "2021-12-14T15:04:57+01:00",
"path": "/nix/store/crbl24rj54f8c9pjq8igadz3wqcw6qrw-tree-sitter-norg",
"sha256": "0hxar07a7n3ghqagr0qjxbz4sgzcpyxwgd4dbj1vvy4xnk07i0br",
"fetchLFS": false,
"fetchSubmodules": false,
"deepClone": false,
"leaveDotGit": false
}
| 213 |
672 | /*
* Copyright 2014-2019 Netflix, 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 com.netflix.spectator.impl.matcher;
import com.netflix.spectator.impl.AsciiSet;
import java.util.HashMap;
import java.util.Map;
/** Constants that are used by the various matchers. */
final class Constants {
private Constants() {
}
/** Position returned to indicate that there is no match. */
static final int NO_MATCH = -1;
/** Set of lower case alphabet characters. */
static final AsciiSet LOWER = AsciiSet.fromPattern("a-z");
/** Set of upper case alphabet characters. */
static final AsciiSet UPPER = AsciiSet.fromPattern("A-Z");
/** Set of all ASCII characters. */
static final AsciiSet ASCII = AsciiSet.all();
/** Set of lower and upper case alphabet characters. */
static final AsciiSet ALPHA = LOWER.union(UPPER);
/** Set of decimal digit characters. */
static final AsciiSet DIGIT = AsciiSet.fromPattern("0-9");
/** Set containing the union of {@link #ALPHA} and {@link #DIGIT}. */
static final AsciiSet ALNUM = ALPHA.union(DIGIT);
/** Set containing the common punctuation characters. */
static final AsciiSet PUNCT = AsciiSet.fromPattern("-!\"#$%&'()*+,./:;<=>?@[\\]^_`{|}~");
/**
* Set containing the visible characters ({@link #ALPHA}, {@link #DIGIT}, and {@link #PUNCT}).
*/
static final AsciiSet GRAPH = PUNCT.union(ALNUM);
/** Set containing the printable characters. */
static final AsciiSet PRINT = GRAPH.union(AsciiSet.fromPattern(" "));
/** Set containing space and tab. */
static final AsciiSet BLANK = AsciiSet.fromPattern(" \t");
/** Set containing the ASCII control characters. */
static final AsciiSet CNTRL = AsciiSet.control();
/** Set of hexadecimal digit characters. */
static final AsciiSet XDIGIT = AsciiSet.fromPattern("0-9a-fA-F");
/** Set containing the word characters. */
static final AsciiSet WORD_CHARS = AsciiSet.fromPattern("a-zA-Z_0-9");
/** Set containing the whitespace characters. */
static final AsciiSet SPACE = AsciiSet.fromPattern(" \t\n\u000B\f\r");
/** Character classes that can be looked up by name. */
static final Map<String, AsciiSet> NAMED_CHAR_CLASSES = new HashMap<>();
static {
NAMED_CHAR_CLASSES.put("Lower", LOWER);
NAMED_CHAR_CLASSES.put("Upper", UPPER);
NAMED_CHAR_CLASSES.put("ASCII", ASCII);
NAMED_CHAR_CLASSES.put("Alpha", ALPHA);
NAMED_CHAR_CLASSES.put("Digit", DIGIT);
NAMED_CHAR_CLASSES.put("Alnum", ALNUM);
NAMED_CHAR_CLASSES.put("Punct", PUNCT);
NAMED_CHAR_CLASSES.put("Graph", GRAPH);
NAMED_CHAR_CLASSES.put("Print", PRINT);
NAMED_CHAR_CLASSES.put("Blank", BLANK);
NAMED_CHAR_CLASSES.put("Cntrl", CNTRL);
NAMED_CHAR_CLASSES.put("XDigit", XDIGIT);
NAMED_CHAR_CLASSES.put("Space", SPACE);
}
}
| 1,145 |
612 | <filename>SRT/lib/xvision/functional.py<gh_stars>100-1000
# Copyright (c) Facebook, Inc. and its affiliates.
# All rights reserved.
#
# This source code is licensed under the license found in the
# LICENSE file in the root directory of this source tree.
#
#
from __future__ import division
import torch
import sys
import math
from PIL import Image, ImageOps, ImageEnhance, PILLOW_VERSION
try:
import accimage
except ImportError:
accimage = None
import numpy as np
def _is_pil_image(img):
if accimage is not None:
return isinstance(img, (Image.Image, accimage.Image))
else:
return isinstance(img, Image.Image)
def _is_tensor_image(img):
return torch.is_tensor(img) and img.ndimension() == 3
def _is_numpy_image(img):
return isinstance(img, np.ndarray) and (img.ndim in {2, 3})
def to_tensor(pic):
"""Convert a ``PIL Image`` or ``numpy.ndarray`` to tensor.
See ``ToTensor`` for more details.
Args:
pic (PIL Image or numpy.ndarray): Image to be converted to tensor.
Returns:
Tensor: Converted image.
"""
if not(_is_pil_image(pic) or _is_numpy_image(pic) or _is_tensor_image(pic)):
raise TypeError('pic should be PIL Image or ndarray or Tensor. Got {}'.format(type(pic)))
if _is_tensor_image(pic): return pic
if isinstance(pic, np.ndarray):
# handle numpy array
if pic.ndim == 2:
pic = pic[:, :, None]
img = torch.from_numpy(pic.transpose((2, 0, 1)))
# backward compatibility
if isinstance(img, torch.ByteTensor):
return img.float().div(255)
else:
return img
if accimage is not None and isinstance(pic, accimage.Image):
nppic = np.zeros([pic.channels, pic.height, pic.width], dtype=np.float32)
pic.copyto(nppic)
return torch.from_numpy(nppic)
# handle PIL Image
if pic.mode == 'I':
img = torch.from_numpy(np.array(pic, np.int32, copy=False))
elif pic.mode == 'I;16':
img = torch.from_numpy(np.array(pic, np.int16, copy=False))
elif pic.mode == 'F':
img = torch.from_numpy(np.array(pic, np.float32, copy=False))
elif pic.mode == '1':
img = 255 * torch.from_numpy(np.array(pic, np.uint8, copy=False))
else:
img = torch.ByteTensor(torch.ByteStorage.from_buffer(pic.tobytes()))
# PIL image mode: L, LA, P, I, F, RGB, YCbCr, RGBA, CMYK
if pic.mode == 'YCbCr':
nchannel = 3
elif pic.mode == 'I;16':
nchannel = 1
else:
nchannel = len(pic.mode)
img = img.view(pic.size[1], pic.size[0], nchannel)
# put it from HWC to CHW format
# yikes, this transpose takes 80% of the loading time/CPU
img = img.transpose(0, 1).transpose(0, 2).contiguous()
if isinstance(img, torch.ByteTensor):
return img.float().div(255)
else:
return img
| 1,050 |
5,169 | <reponame>Gantios/Specs<filename>Specs/3/6/2/ClaySDK/1.7.1/ClaySDK.podspec.json
{
"name": "ClaySDK",
"version": "1.7.1",
"summary": "The Clay mobile SDK make it easy to build a seamless door opening experience in your application.",
"description": "This SDK for iOS contains the most up-to-date frameworks for integrating Mobile Key technology into your own iOS applications. It will setup the necessary security to communicate with Connect API, and unlock locks with encrypted Mobile Keys returned by the Connect API. The SDK for iOS includes iOS libraries, developer documentation and a sample Xcode project to get you up and running quickly and easily.",
"homepage": "https://my-clay.com/developers/mobile-sdk-introduction/",
"license": {
"type": "MIT",
"file": "LICENSE"
},
"authors": {
"Jakov": "<EMAIL>",
"Roberto": "<EMAIL>"
},
"source": {
"git": "https://github.com/ClaySolutions/ClaySDK.git",
"tag": "1.7.1"
},
"swift_versions": "5.1.3",
"platforms": {
"ios": "11"
},
"vendored_frameworks": "ClaySDK.framework",
"dependencies": {
"VirgilSDK": [
"7.1.0"
]
},
"swift_version": "5.1.3"
}
| 426 |
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.modules.javadoc.hints;
import com.sun.source.doctree.DocCommentTree;
import com.sun.source.tree.ClassTree;
import com.sun.source.tree.CompilationUnitTree;
import com.sun.source.tree.ExpressionTree;
import com.sun.source.tree.IdentifierTree;
import com.sun.source.tree.MethodTree;
import com.sun.source.tree.Tree;
import static com.sun.source.tree.Tree.Kind.ANNOTATION_TYPE;
import static com.sun.source.tree.Tree.Kind.CLASS;
import static com.sun.source.tree.Tree.Kind.ENUM;
import static com.sun.source.tree.Tree.Kind.INTERFACE;
import static com.sun.source.tree.Tree.Kind.METHOD;
import static com.sun.source.tree.Tree.Kind.VARIABLE;
import com.sun.source.tree.TypeParameterTree;
import com.sun.source.tree.VariableTree;
import com.sun.source.util.SourcePositions;
import com.sun.source.util.TreePath;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.lang.model.SourceVersion;
import javax.lang.model.element.AnnotationMirror;
import javax.lang.model.element.Element;
import javax.lang.model.element.ElementKind;
import javax.lang.model.element.ExecutableElement;
import javax.lang.model.element.TypeElement;
import javax.lang.model.type.DeclaredType;
import javax.lang.model.type.TypeKind;
import javax.lang.model.type.TypeMirror;
import javax.swing.text.BadLocationException;
import javax.swing.text.Document;
import javax.swing.text.Position;
import javax.swing.text.StyledDocument;
import org.netbeans.api.editor.guards.GuardedSection;
import org.netbeans.api.editor.guards.GuardedSectionManager;
import org.netbeans.api.java.lexer.JavaTokenId;
import org.netbeans.api.java.queries.SourceLevelQuery;
import org.netbeans.api.java.source.ClasspathInfo.PathKind;
import org.netbeans.api.java.source.CompilationInfo;
import org.netbeans.api.java.source.TreeUtilities;
import org.netbeans.api.lexer.TokenSequence;
import org.netbeans.spi.editor.hints.Severity;
import org.openide.filesystems.FileObject;
/**
*
* @author <NAME>
*/
public class JavadocUtilities {
private static final String ERROR_IDENT = "<error>"; //NOI18N
private JavadocUtilities() {
}
public static boolean isDeprecated(CompilationInfo javac, Element elm) {
return findDeprecated(javac, elm) != null;
}
public static AnnotationMirror findDeprecated(CompilationInfo javac, Element elm) {
TypeElement deprAnn = javac.getElements().getTypeElement("java.lang.Deprecated"); //NOI18N
if (deprAnn == null) {
String msg = String.format("Even though the source level of %s" + //NOI18N
" is set to JDK5 or later, java.lang.Deprecated cannot" + //NOI18N
" be found on the bootclasspath: %s", //NOI18N
javac.getClasspathInfo().getClassPath(PathKind.SOURCE),
javac.getClasspathInfo().getClassPath(PathKind.BOOT));
Logger.getLogger(JavadocUtilities.class.getName()).warning(msg);
return null;
}
for (AnnotationMirror annotationMirror : javac.getElements().getAllAnnotationMirrors(elm)) {
if (deprAnn.equals(annotationMirror.getAnnotationType().asElement())) {
return annotationMirror;
}
}
return null;
}
public static boolean hasInheritedDoc(CompilationInfo javac, Element elm) {
return findInheritedDoc(javac, elm) != null;
}
public static DocCommentTree findInheritedDoc(CompilationInfo javac, Element elm) {
if (elm.getKind() == ElementKind.METHOD) {
TypeElement clazz = (TypeElement) elm.getEnclosingElement();
return searchInInterfaces(javac, clazz, clazz,
(ExecutableElement) elm, new HashSet<TypeElement>());
}
return null;
}
/**
* <a href="http://java.sun.com/javase/6/docs/technotes/tools/solaris/javadoc.html#inheritingcomments">
* Algorithm for Inheriting Method Comments
* </a>
* <p>Do not use MethodDoc.overriddenMethod() instead since it fails for
* interfaces!
*/
private static DocCommentTree searchInInterfaces(
CompilationInfo javac, TypeElement class2query, TypeElement overriderClass,
ExecutableElement overrider, Set<TypeElement> exclude) {
// Step 1
for (TypeMirror ifceMirror : class2query.getInterfaces()) {
if (ifceMirror.getKind() == TypeKind.DECLARED) {
TypeElement ifceEl = (TypeElement) ((DeclaredType) ifceMirror).asElement();
if (exclude.contains(ifceEl)) {
continue;
}
// check methods
DocCommentTree jdoc = searchInMethods(javac, ifceEl, overriderClass, overrider);
if (jdoc != null) {
return jdoc;
}
exclude.add(ifceEl);
}
}
// Step 2
for (TypeMirror ifceMirror : class2query.getInterfaces()) {
if (ifceMirror.getKind() == TypeKind.DECLARED) {
TypeElement ifceEl = (TypeElement) ((DeclaredType) ifceMirror).asElement();
DocCommentTree jdoc = searchInInterfaces(javac, ifceEl, overriderClass, overrider, exclude);
if (jdoc != null) {
return jdoc;
}
}
}
// Step 3
return searchInSuperclass(javac, class2query, overriderClass, overrider, exclude);
}
private static DocCommentTree searchInSuperclass(
CompilationInfo javac, TypeElement class2query, TypeElement overriderClass,
ExecutableElement overrider, Set<TypeElement> exclude) {
// Step 3a
TypeMirror superclassMirror = class2query.getSuperclass();
if (superclassMirror.getKind() != TypeKind.DECLARED) {
return null;
}
TypeElement superclass = (TypeElement) ((DeclaredType) superclassMirror).asElement();
// check methods
DocCommentTree jdoc = searchInMethods(javac, superclass, overriderClass, overrider);
if (jdoc != null) {
return jdoc;
}
// Step 3b
return searchInInterfaces(javac, superclass, overriderClass, overrider, exclude);
}
private static DocCommentTree searchInMethods(
CompilationInfo javac, TypeElement class2query,
TypeElement overriderClass, ExecutableElement overrider) {
for (Element elm : class2query.getEnclosedElements()) {
if (elm.getKind() == ElementKind.METHOD &&
javac.getElements().overrides(overrider, (ExecutableElement) elm, overriderClass)) {
DocCommentTree jdoc = javac.getDocTrees().getDocCommentTree(elm);
return (jdoc != null && !jdoc.getFullBody().isEmpty())?
jdoc: null;
}
}
return null;
}
static boolean isValid(CompilationInfo javac, TreePath path, Severity severity, Access access, int caret) {
Tree leaf = path.getLeaf();
boolean onLine = severity == Severity.HINT && caret > -1;
switch (leaf.getKind()) {
case ANNOTATION_TYPE:
case CLASS:
case ENUM:
case INTERFACE:
return access.isAccessible(javac, path, false) && (!onLine || isInHeader(javac, (ClassTree) leaf, caret));
case METHOD:
return access.isAccessible(javac, path, false) && (!onLine || isInHeader(javac, (MethodTree) leaf, caret));
case VARIABLE:
return access.isAccessible(javac, path, false);
}
return false;
}
public static boolean isGuarded(Tree node, CompilationInfo javac, Document doc) {
GuardedSectionManager guards = GuardedSectionManager.getInstance((StyledDocument) doc);
if (guards != null) {
try {
final int startOff = (int) javac.getTrees().getSourcePositions().
getStartPosition(javac.getCompilationUnit(), node);
final Position startPos = doc.createPosition(startOff);
for (GuardedSection guard : guards.getGuardedSections()) {
if (guard.contains(startPos, false)) {
return true;
}
}
} catch (BadLocationException ex) {
Logger.getLogger(Analyzer.class.getName()).log(Level.INFO, ex.getMessage(), ex);
// consider it as guarded
return true;
}
}
return false;
}
/**
* has syntax errors preventing to generate javadoc?
*/
public static boolean hasErrors(Tree leaf) {
switch (leaf.getKind()) {
case METHOD:
MethodTree mt = (MethodTree) leaf;
Tree rt = mt.getReturnType();
if (rt != null && rt.getKind() == Tree.Kind.ERRONEOUS) {
return true;
}
if (ERROR_IDENT.contentEquals(mt.getName())) {
return true;
}
for (VariableTree vt : mt.getParameters()) {
if (ERROR_IDENT.contentEquals(vt.getName())) {
return true;
}
}
for (Tree t : mt.getThrows()) {
if (t.getKind() == Tree.Kind.ERRONEOUS ||
(t.getKind() == Tree.Kind.IDENTIFIER && ERROR_IDENT.contentEquals(((IdentifierTree) t).getName()))) {
return true;
}
}
break;
case VARIABLE:
VariableTree vt = (VariableTree) leaf;
return vt.getType().getKind() == Tree.Kind.ERRONEOUS
|| ERROR_IDENT.contentEquals(vt.getName());
case ANNOTATION_TYPE:
case CLASS:
case ENUM:
case INTERFACE:
ClassTree ct = (ClassTree) leaf;
if (ERROR_IDENT.contentEquals(ct.getSimpleName())) {
return true;
}
for (TypeParameterTree tpt : ct.getTypeParameters()) {
if (ERROR_IDENT.contentEquals(tpt.getName())) {
return true;
}
}
break;
}
return false;
}
private static boolean isInHeader(CompilationInfo info, ClassTree tree, int offset) {
CompilationUnitTree cut = info.getCompilationUnit();
SourcePositions sp = info.getTrees().getSourcePositions();
long lastKnownOffsetInHeader = sp.getStartPosition(cut, tree);
List<? extends Tree> impls = tree.getImplementsClause();
List<? extends TypeParameterTree> typeparams;
if (impls != null && !impls.isEmpty()) {
lastKnownOffsetInHeader= sp.getEndPosition(cut, impls.get(impls.size() - 1));
} else if ((typeparams = tree.getTypeParameters()) != null && !typeparams.isEmpty()) {
lastKnownOffsetInHeader= sp.getEndPosition(cut, typeparams.get(typeparams.size() - 1));
} else if (tree.getExtendsClause() != null) {
lastKnownOffsetInHeader = sp.getEndPosition(cut, tree.getExtendsClause());
} else if (tree.getModifiers() != null) {
lastKnownOffsetInHeader = sp.getEndPosition(cut, tree.getModifiers());
}
TokenSequence<JavaTokenId> ts = info.getTreeUtilities().tokensFor(tree);
ts.move((int) lastKnownOffsetInHeader);
while (ts.moveNext()) {
if (ts.token().id() == JavaTokenId.LBRACE) {
return offset < ts.offset();
}
}
return false;
}
private static boolean isInHeader(CompilationInfo info, MethodTree tree, int offset) {
CompilationUnitTree cut = info.getCompilationUnit();
SourcePositions sp = info.getTrees().getSourcePositions();
long lastKnownOffsetInHeader = sp.getStartPosition(cut, tree);
List<? extends ExpressionTree> throwz;
List<? extends VariableTree> params;
List<? extends TypeParameterTree> typeparams;
if ((throwz = tree.getThrows()) != null && !throwz.isEmpty()) {
lastKnownOffsetInHeader = sp.getEndPosition(cut, throwz.get(throwz.size() - 1));
} else if ((params = tree.getParameters()) != null && !params.isEmpty()) {
lastKnownOffsetInHeader = sp.getEndPosition(cut, params.get(params.size() - 1));
} else if ((typeparams = tree.getTypeParameters()) != null && !typeparams.isEmpty()) {
lastKnownOffsetInHeader = sp.getEndPosition(cut, typeparams.get(typeparams.size() - 1));
} else if (tree.getReturnType() != null) {
lastKnownOffsetInHeader = sp.getEndPosition(cut, tree.getReturnType());
} else if (tree.getModifiers() != null) {
lastKnownOffsetInHeader = sp.getEndPosition(cut, tree.getModifiers());
}
TokenSequence<JavaTokenId> ts = info.getTreeUtilities().tokensFor(tree);
ts.move((int) lastKnownOffsetInHeader);
while (ts.moveNext()) {
if (ts.token().id() == JavaTokenId.LBRACE || ts.token().id() == JavaTokenId.SEMICOLON) {
return offset < ts.offset();
}
}
return false;
}
/**
* creates start and end positions of the tree
*/
public static int[] createSignaturePositions(final Tree t, final CompilationInfo javac) {
int[] span = null;
if (t.getKind() == Tree.Kind.METHOD) { // method + constructor
span = javac.getTreeUtilities().findNameSpan((MethodTree) t);
} else if (TreeUtilities.CLASS_TREE_KINDS.contains(t.getKind())) {
span = javac.getTreeUtilities().findNameSpan((ClassTree) t);
} else if (Tree.Kind.VARIABLE == t.getKind()) {
span = javac.getTreeUtilities().findNameSpan((VariableTree) t);
}
return span;
}
public static SourceVersion resolveSourceVersion(FileObject file) {
String sourceLevel = SourceLevelQuery.getSourceLevel(file);
if (sourceLevel == null) {
return SourceVersion.latest();
} else if (sourceLevel.startsWith("1.6")) {
return SourceVersion.RELEASE_6;
} else if (sourceLevel.startsWith("1.5")) {
return SourceVersion.RELEASE_5;
} else if (sourceLevel.startsWith("1.4")) {
return SourceVersion.RELEASE_4;
} else if (sourceLevel.startsWith("1.3")) {
return SourceVersion.RELEASE_3;
} else if (sourceLevel.startsWith("1.2")) {
return SourceVersion.RELEASE_2;
} else if (sourceLevel.startsWith("1.1")) {
return SourceVersion.RELEASE_1;
} else if (sourceLevel.startsWith("1.0")) {
return SourceVersion.RELEASE_0;
}
return SourceVersion.latest();
}
}
| 7,128 |
348 | <gh_stars>100-1000
{"nom":"<NAME>","circ":"3ème circonscription","dpt":"Dordogne","inscrits":140,"abs":70,"votants":70,"blancs":9,"nuls":1,"exp":60,"res":[{"nuance":"SOC","nom":"<NAME>","voix":33},{"nuance":"MDM","nom":"<NAME>","voix":27}]} | 101 |
376 | /*
Copyright (c) 2005, 2012, Oracle and/or its affiliates. All rights reserved.
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; version 2 of the License.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program; see the file COPYING. If not, write to the
Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston,
MA 02110-1301 USA.
*/
/* hc128.hpp defines HC128
*/
#ifndef TAO_CRYPT_HC128_HPP
#define TAO_CRYPT_HC128_HPP
#include "misc.hpp"
namespace TaoCrypt {
// HC128 encryption and decryption
class HC128 {
public:
typedef HC128 Encryption;
typedef HC128 Decryption;
HC128() {}
void Process(byte*, const byte*, word32);
void SetKey(const byte*, const byte*);
private:
word32 T_[1024]; /* P[i] = T[i]; Q[i] = T[1024 + i ]; */
word32 X_[16];
word32 Y_[16];
word32 counter1024_; /* counter1024 = i mod 1024 at the ith step */
word32 key_[8];
word32 iv_[8];
void SetIV(const byte*);
void GenerateKeystream(word32*);
void SetupUpdate();
HC128(const HC128&); // hide copy
const HC128 operator=(const HC128&); // and assign
};
} // namespace
#endif // TAO_CRYPT_HC128_HPP
| 585 |
1,442 | #ifndef POINCARE_POLYNOMIAL_H
#define POINCARE_POLYNOMIAL_H
#include <poincare/expression.h>
#include <poincare/rational.h>
namespace Poincare {
class Polynomial {
public:
static int QuadraticPolynomialRoots(Expression a, Expression b, Expression c, Expression * root1, Expression * root2, Expression * delta, Context * context, Preferences::ComplexFormat complexFormat, Preferences::AngleUnit angleUnit, bool approximateSolutions = false);
static int CubicPolynomialRoots(Expression a, Expression b, Expression c, Expression d, Expression * root1, Expression * root2, Expression * root3, Expression * delta, Context * context, Preferences::ComplexFormat complexFormat, Preferences::AngleUnit angleUnit, bool * approximateSolutions = nullptr);
private:
static constexpr int k_maxNumberOfNodesBeforeApproximatingDelta = 16;
static Expression ReducePolynomial(const Expression * coefficients, int degree, Expression parameter, ExpressionNode::ReductionContext reductionContext);
static Rational ReduceRationalPolynomial(const Rational * coefficients, int degree, Rational parameter);
static bool IsRoot(const Expression * coefficients, int degree, Expression root, ExpressionNode::ReductionContext reductionContext) { return ReducePolynomial(coefficients, degree, root, reductionContext).nullStatus(reductionContext.context()) == ExpressionNode::NullStatus::Null; }
static Expression RationalRootSearch(const Expression * coefficients, int degree, ExpressionNode::ReductionContext reductionContext);
static Expression SumRootSearch(const Expression * coefficients, int degree, int relevantCoefficient, ExpressionNode::ReductionContext reductionContext);
static Expression CardanoNumber(Expression delta0, Expression delta1, bool * approximate, ExpressionNode::ReductionContext reductionContext);
};
}
#endif
| 442 |
665 | <filename>security/keycloak/src/main/java/org/apache/isis/security/keycloak/IsisModuleSecurityKeycloak.java
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.isis.security.keycloak;
import java.util.List;
import org.apache.isis.core.config.IsisConfiguration;
import org.apache.isis.core.runtimeservices.IsisModuleCoreRuntimeServices;
import org.apache.isis.core.security.authentication.login.LoginSuccessHandlerUNUSED;
import org.apache.isis.core.webapp.IsisModuleCoreWebapp;
import org.apache.isis.security.keycloak.handler.LogoutHandlerForKeycloak;
import org.apache.isis.security.keycloak.services.KeycloakOauth2UserService;
import org.apache.isis.security.spring.IsisModuleSecuritySpring;
import org.springframework.boot.autoconfigure.security.oauth2.client.OAuth2ClientProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Import;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.config.http.SessionCreationPolicy;
import org.springframework.security.core.authority.mapping.SimpleAuthorityMapper;
import org.springframework.security.oauth2.client.web.OAuth2AuthorizationRequestRedirectFilter;
import org.springframework.security.oauth2.jwt.NimbusJwtDecoderJwkSupport;
import org.springframework.security.web.authentication.SavedRequestAwareAuthenticationSuccessHandler;
import org.springframework.security.web.authentication.logout.LogoutHandler;
import org.springframework.security.web.util.matcher.AntPathRequestMatcher;
import lombok.RequiredArgsConstructor;
import lombok.val;
/**
* Configuration Bean to support Isis Security using Keycloak.
*
* @since 2.0 {@index}
*/
@Configuration
@Import({
// modules
IsisModuleCoreRuntimeServices.class,
IsisModuleCoreWebapp.class,
// services
LogoutHandlerForKeycloak.class,
// builds on top of Spring
IsisModuleSecuritySpring.class,
})
@EnableWebSecurity
public class IsisModuleSecurityKeycloak {
@Bean
public WebSecurityConfigurerAdapter webSecurityConfigurer(
final IsisConfiguration isisConfiguration,
final KeycloakOauth2UserService keycloakOidcUserService,
final List<LoginSuccessHandlerUNUSED> loginSuccessHandlersUNUSED,
final List<LogoutHandler> logoutHandlers
) {
val realm = isisConfiguration.getSecurity().getKeycloak().getRealm();
return new KeycloakWebSecurityConfigurerAdapter(keycloakOidcUserService, logoutHandlers, isisConfiguration
);
}
// @RequiredArgsConstructor
// public static class AuthSuccessHandler extends SavedRequestAwareAuthenticationSuccessHandler {
//
// final List<LoginSuccessHandler> loginSuccessHandlers;
//
// @Override
// public void onAuthenticationSuccess(
// final HttpServletRequest request,
// final HttpServletResponse response,
// final Authentication authentication) throws ServletException, IOException {
// super.onAuthenticationSuccess(request, response, authentication);
// loginSuccessHandlers.forEach(LoginSuccessHandler::onSuccess);
// }
// }
@Bean
KeycloakOauth2UserService keycloakOidcUserService(OAuth2ClientProperties oauth2ClientProperties) {
// TODO use default JwtDecoder - where to grab?
val jwtDecoder = new NimbusJwtDecoderJwkSupport(
oauth2ClientProperties.getProvider().get("keycloak").getJwkSetUri());
val authoritiesMapper = new SimpleAuthorityMapper();
authoritiesMapper.setConvertToUpperCase(true);
return new KeycloakOauth2UserService(jwtDecoder, authoritiesMapper);
}
@RequiredArgsConstructor
public static class KeycloakWebSecurityConfigurerAdapter extends WebSecurityConfigurerAdapter {
private final KeycloakOauth2UserService keycloakOidcUserService;
private final List<LogoutHandler> logoutHandlers;
private final IsisConfiguration isisConfiguration;
@Override
public void configure(HttpSecurity http) throws Exception {
val successUrl = isisConfiguration.getSecurity().getKeycloak().getLoginSuccessUrl();
val realm = isisConfiguration.getSecurity().getKeycloak().getRealm();
val loginPage = OAuth2AuthorizationRequestRedirectFilter.DEFAULT_AUTHORIZATION_REQUEST_BASE_URI
+ "/" + realm;
val httpSecurityLogoutConfigurer =
http
.sessionManagement()
.sessionCreationPolicy(SessionCreationPolicy.IF_REQUIRED)
.and()
.authorizeRequests()
.anyRequest().authenticated()
.and()
// responsibility to propagate logout to Keycloak is performed by
// LogoutHandlerForKeycloak (called by Isis' LogoutMenu, not by Spring)
// this is to ensure that Isis can invalidate the http session eagerly and not preserve it in
// the SecurityContextPersistenceFilter (which uses http session to do its work)
.logout()
.logoutRequestMatcher(new AntPathRequestMatcher("/logout"));
logoutHandlers.forEach(httpSecurityLogoutConfigurer::addLogoutHandler);
httpSecurityLogoutConfigurer
.and()
// This is the point where OAuth2 login of Spring 5 gets enabled
.oauth2Login()
.defaultSuccessUrl(successUrl, true)
// .successHandler(new AuthSuccessHandler(loginSuccessHandlers))
.successHandler(new SavedRequestAwareAuthenticationSuccessHandler())
.userInfoEndpoint()
.oidcUserService(keycloakOidcUserService)
.and()
.loginPage(loginPage);
}
}
}
| 2,645 |
509 | <filename>core/src/main/java/com/onelogin/saml2/settings/SettingsBuilder.java
package com.onelogin.saml2.settings;
import java.io.IOException;
import java.io.InputStream;
import java.net.MalformedURLException;
import java.net.URL;
import java.security.Key;
import java.security.KeyStore;
import java.security.KeyStoreException;
import java.security.NoSuchAlgorithmException;
import java.security.PrivateKey;
import java.security.UnrecoverableKeyException;
import java.security.cert.Certificate;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.LinkedHashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Properties;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.onelogin.saml2.exception.Error;
import com.onelogin.saml2.model.Contact;
import com.onelogin.saml2.model.KeyStoreSettings;
import com.onelogin.saml2.model.Organization;
import com.onelogin.saml2.util.Util;
/**
* SettingsBuilder class of OneLogin's Java Toolkit.
*
* A class that implements the settings builder
*/
public class SettingsBuilder {
/**
* Private property to construct a logger for this class.
*/
private static final Logger LOGGER = LoggerFactory.getLogger(SettingsBuilder.class);
/**
* Private property that contains the SAML settings
*/
private Map<String, Object> samlData = new LinkedHashMap<>();
/**
* Saml2Settings object
*/
private Saml2Settings saml2Setting;
public final static String STRICT_PROPERTY_KEY = "onelogin.saml2.strict";
public final static String DEBUG_PROPERTY_KEY = "onelogin.saml2.debug";
// SP
public final static String SP_ENTITYID_PROPERTY_KEY = "onelogin.saml2.sp.entityid";
public final static String SP_ASSERTION_CONSUMER_SERVICE_URL_PROPERTY_KEY = "onelogin.saml2.sp.assertion_consumer_service.url";
public final static String SP_ASSERTION_CONSUMER_SERVICE_BINDING_PROPERTY_KEY = "onelogin.saml2.sp.assertion_consumer_service.binding";
public final static String SP_SINGLE_LOGOUT_SERVICE_URL_PROPERTY_KEY = "onelogin.saml2.sp.single_logout_service.url";
public final static String SP_SINGLE_LOGOUT_SERVICE_BINDING_PROPERTY_KEY = "onelogin.saml2.sp.single_logout_service.binding";
public final static String SP_NAMEIDFORMAT_PROPERTY_KEY = "onelogin.saml2.sp.nameidformat";
public final static String SP_X509CERT_PROPERTY_KEY = "onelogin.saml2.sp.x509cert";
public final static String SP_PRIVATEKEY_PROPERTY_KEY = "onelogin.saml2.sp.privatekey";
public final static String SP_X509CERTNEW_PROPERTY_KEY = "onelogin.saml2.sp.x509certNew";
// KeyStore
public final static String KEYSTORE_KEY = "onelogin.saml2.keystore.store";
public final static String KEYSTORE_ALIAS = "onelogin.saml2.keystore.alias";
public final static String KEYSTORE_KEY_PASSWORD = "<PASSWORD>login.saml2.keystore.key.password";
// IDP
public final static String IDP_ENTITYID_PROPERTY_KEY = "onelogin.saml2.idp.entityid";
public final static String IDP_SINGLE_SIGN_ON_SERVICE_URL_PROPERTY_KEY = "onelogin.saml2.idp.single_sign_on_service.url";
public final static String IDP_SINGLE_SIGN_ON_SERVICE_BINDING_PROPERTY_KEY = "onelogin.saml2.idp.single_sign_on_service.binding";
public final static String IDP_SINGLE_LOGOUT_SERVICE_URL_PROPERTY_KEY = "onelogin.saml2.idp.single_logout_service.url";
public final static String IDP_SINGLE_LOGOUT_SERVICE_RESPONSE_URL_PROPERTY_KEY = "onelogin.saml2.idp.single_logout_service.response.url";
public final static String IDP_SINGLE_LOGOUT_SERVICE_BINDING_PROPERTY_KEY = "onelogin.saml2.idp.single_logout_service.binding";
public final static String IDP_X509CERT_PROPERTY_KEY = "onelogin.saml2.idp.x509cert";
public final static String IDP_X509CERTMULTI_PROPERTY_KEY = "onelogin.saml2.idp.x509certMulti";
public final static String CERTFINGERPRINT_PROPERTY_KEY = "onelogin.saml2.idp.certfingerprint";
public final static String CERTFINGERPRINT_ALGORITHM_PROPERTY_KEY = "onelogin.saml2.idp.certfingerprint_algorithm";
// Security
public final static String SECURITY_NAMEID_ENCRYPTED = "onelogin.saml2.security.nameid_encrypted";
public final static String SECURITY_AUTHREQUEST_SIGNED = "onelogin.saml2.security.authnrequest_signed";
public final static String SECURITY_LOGOUTREQUEST_SIGNED = "onelogin.saml2.security.logoutrequest_signed";
public final static String SECURITY_LOGOUTRESPONSE_SIGNED = "onelogin.saml2.security.logoutresponse_signed";
public final static String SECURITY_WANT_MESSAGES_SIGNED = "onelogin.saml2.security.want_messages_signed";
public final static String SECURITY_WANT_ASSERTIONS_SIGNED = "onelogin.saml2.security.want_assertions_signed";
public final static String SECURITY_WANT_ASSERTIONS_ENCRYPTED = "onelogin.saml2.security.want_assertions_encrypted";
public final static String SECURITY_WANT_NAMEID = "onelogin.saml2.security.want_nameid";
public final static String SECURITY_WANT_NAMEID_ENCRYPTED = "onelogin.saml2.security.want_nameid_encrypted";
public final static String SECURITY_SIGN_METADATA = "onelogin.saml2.security.sign_metadata";
public final static String SECURITY_REQUESTED_AUTHNCONTEXT = "onelogin.saml2.security.requested_authncontext";
public final static String SECURITY_REQUESTED_AUTHNCONTEXTCOMPARISON = "onelogin.saml2.security.requested_authncontextcomparison";
public final static String SECURITY_WANT_XML_VALIDATION = "onelogin.saml2.security.want_xml_validation";
public final static String SECURITY_SIGNATURE_ALGORITHM = "onelogin.saml2.security.signature_algorithm";
public final static String SECURITY_DIGEST_ALGORITHM = "onelogin.saml2.security.digest_algorithm";
public final static String SECURITY_REJECT_UNSOLICITED_RESPONSES_WITH_INRESPONSETO = "onelogin.saml2.security.reject_unsolicited_responses_with_inresponseto";
public final static String SECURITY_ALLOW_REPEAT_ATTRIBUTE_NAME_PROPERTY_KEY = "onelogin.saml2.security.allow_duplicated_attribute_name";
public final static String SECURITY_REJECT_DEPRECATED_ALGORITHM = "onelogin.saml2.security.reject_deprecated_alg";
// Compress
public final static String COMPRESS_REQUEST = "onelogin.saml2.compress.request";
public final static String COMPRESS_RESPONSE = "onelogin.saml2.compress.response";
// Parsing
public final static String PARSING_TRIM_NAME_IDS = "onelogin.saml2.parsing.trim_name_ids";
public final static String PARSING_TRIM_ATTRIBUTE_VALUES = "onelogin.saml2.parsing.trim_attribute_values";
// Misc
public final static String CONTACT_TECHNICAL_GIVEN_NAME = "onelogin.saml2.contacts.technical.given_name";
public final static String CONTACT_TECHNICAL_EMAIL_ADDRESS = "onelogin.saml2.contacts.technical.email_address";
public final static String CONTACT_SUPPORT_GIVEN_NAME = "onelogin.saml2.contacts.support.given_name";
public final static String CONTACT_SUPPORT_EMAIL_ADDRESS = "onelogin.saml2.contacts.support.email_address";
public final static String ORGANIZATION_NAME = "onelogin.saml2.organization.name";
public final static String ORGANIZATION_DISPLAYNAME = "onelogin.saml2.organization.displayname";
public final static String ORGANIZATION_URL = "onelogin.saml2.organization.url";
public final static String ORGANIZATION_LANG = "onelogin.saml2.organization.lang";
public final static String UNIQUE_ID_PREFIX_PROPERTY_KEY = "onelogin.saml2.unique_id_prefix";
/**
* Load settings from the file
*
* @param propFileName OneLogin_Saml2_Settings
*
* @return the SettingsBuilder object with the settings loaded from the file
*
* @throws IOException
* @throws Error
*/
public SettingsBuilder fromFile(String propFileName) throws Error, IOException {
return fromFile(propFileName, null);
}
/**
* Load settings from the file
*
* @param propFileName OneLogin_Saml2_Settings
* @param keyStoreSetting KeyStore which have the Private/Public keys
*
* @return the SettingsBuilder object with the settings loaded from the file
*
* @throws IOException
* @throws Error
*/
public SettingsBuilder fromFile(String propFileName, KeyStoreSettings keyStoreSetting) throws Error, IOException {
ClassLoader classLoader = getClass().getClassLoader();
try (InputStream inputStream = classLoader.getResourceAsStream(propFileName)) {
if (inputStream != null) {
Properties prop = new Properties();
prop.load(inputStream);
parseProperties(prop);
LOGGER.debug("properties file '{}' loaded succesfully", propFileName);
} else {
String errorMsg = "properties file '" + propFileName + "' not found in the classpath";
LOGGER.error(errorMsg);
throw new Error(errorMsg, Error.SETTINGS_FILE_NOT_FOUND);
}
} catch (IOException e) {
String errorMsg = "properties file'" + propFileName + "' cannot be loaded.";
LOGGER.error(errorMsg, e);
throw new Error(errorMsg, Error.SETTINGS_FILE_NOT_FOUND);
}
// Parse KeyStore and set the properties for SP Cert and Key
if (keyStoreSetting != null) {
parseKeyStore(keyStoreSetting);
}
return this;
}
/**
* Loads the settings from a properties object
*
* @param prop contains the properties
*
* @return the SettingsBuilder object with the settings loaded from the prop
* object
*/
public SettingsBuilder fromProperties(Properties prop) {
parseProperties(prop);
return this;
}
/**
* Loads the settings from mapped values.
*
* @param samlData Mapped values.
*
* @return the SettingsBuilder object with the settings loaded from the prop
* object
*/
public SettingsBuilder fromValues(Map<String, Object> samlData) {
return this.fromValues(samlData, null);
}
/**
* Loads the settings from mapped values and KeyStore settings.
*
* @param samlData Mapped values.
* @param keyStoreSetting KeyStore model
*
* @return the SettingsBuilder object with the settings loaded from the prop
* object
*/
public SettingsBuilder fromValues(Map<String, Object> samlData, KeyStoreSettings keyStoreSetting) {
if (samlData != null) {
this.samlData.putAll(samlData);
}
if (keyStoreSetting != null) {
parseKeyStore(keyStoreSetting);
}
return this;
}
/**
* Builds the Saml2Settings object. Read the Properties object and set all the
* SAML settings
*
* @return the Saml2Settings object with all the SAML settings loaded
*
*/
public Saml2Settings build() {
return build(new Saml2Settings());
}
/**
* Builds the Saml2Settings object. Read the Properties object and set all the
* SAML settings
*
* @param saml2Setting an existing Saml2Settings
*
* @return the Saml2Settings object with all the SAML settings loaded
*
*/
public Saml2Settings build(Saml2Settings saml2Setting) {
this.saml2Setting = saml2Setting;
Boolean strict = loadBooleanProperty(STRICT_PROPERTY_KEY);
if (strict != null) {
saml2Setting.setStrict(strict);
}
Boolean debug = loadBooleanProperty(DEBUG_PROPERTY_KEY);
if (debug != null) {
saml2Setting.setDebug(debug);
}
this.loadSpSetting();
this.loadIdpSetting();
this.loadSecuritySetting();
this.loadCompressSetting();
this.loadParsingSetting();
List<Contact> contacts = this.loadContacts();
if (!contacts.isEmpty()) {
saml2Setting.setContacts(loadContacts());
}
Organization org = this.loadOrganization();
if (org != null) {
saml2Setting.setOrganization(org);
}
String uniqueIdPrefix = loadUniqueIDPrefix();
if (StringUtils.isNotEmpty(uniqueIdPrefix)) {
saml2Setting.setUniqueIDPrefix(uniqueIdPrefix);
} else if (saml2Setting.getUniqueIDPrefix() == null){
saml2Setting.setUniqueIDPrefix(Util.UNIQUE_ID_PREFIX);
}
return saml2Setting;
}
/**
* Loads the IdP settings from the properties file
*/
private void loadIdpSetting() {
String idpEntityID = loadStringProperty(IDP_ENTITYID_PROPERTY_KEY);
if (idpEntityID != null) {
saml2Setting.setIdpEntityId(idpEntityID);
}
URL idpSingleSignOnServiceUrl = loadURLProperty(IDP_SINGLE_SIGN_ON_SERVICE_URL_PROPERTY_KEY);
if (idpSingleSignOnServiceUrl != null) {
saml2Setting.setIdpSingleSignOnServiceUrl(idpSingleSignOnServiceUrl);
}
String idpSingleSignOnServiceBinding = loadStringProperty(IDP_SINGLE_SIGN_ON_SERVICE_BINDING_PROPERTY_KEY);
if (idpSingleSignOnServiceBinding != null) {
saml2Setting.setIdpSingleSignOnServiceBinding(idpSingleSignOnServiceBinding);
}
URL idpSingleLogoutServiceUrl = loadURLProperty(IDP_SINGLE_LOGOUT_SERVICE_URL_PROPERTY_KEY);
if (idpSingleLogoutServiceUrl != null) {
saml2Setting.setIdpSingleLogoutServiceUrl(idpSingleLogoutServiceUrl);
}
URL idpSingleLogoutServiceResponseUrl = loadURLProperty(IDP_SINGLE_LOGOUT_SERVICE_RESPONSE_URL_PROPERTY_KEY);
if (idpSingleLogoutServiceResponseUrl != null) {
saml2Setting.setIdpSingleLogoutServiceResponseUrl(idpSingleLogoutServiceResponseUrl);
}
String idpSingleLogoutServiceBinding = loadStringProperty(IDP_SINGLE_LOGOUT_SERVICE_BINDING_PROPERTY_KEY);
if (idpSingleLogoutServiceBinding != null) {
saml2Setting.setIdpSingleLogoutServiceBinding(idpSingleLogoutServiceBinding);
}
List<X509Certificate> idpX509certMulti = loadCertificateListFromProp(IDP_X509CERTMULTI_PROPERTY_KEY);
if (idpX509certMulti != null) {
saml2Setting.setIdpx509certMulti(idpX509certMulti);
}
X509Certificate idpX509cert = loadCertificateFromProp(IDP_X509CERT_PROPERTY_KEY);
if (idpX509cert != null) {
saml2Setting.setIdpx509cert(idpX509cert);
}
String idpCertFingerprint = loadStringProperty(CERTFINGERPRINT_PROPERTY_KEY);
if (idpCertFingerprint != null) {
saml2Setting.setIdpCertFingerprint(idpCertFingerprint);
}
String idpCertFingerprintAlgorithm = loadStringProperty(CERTFINGERPRINT_ALGORITHM_PROPERTY_KEY);
if (idpCertFingerprintAlgorithm != null && !idpCertFingerprintAlgorithm.isEmpty()) {
saml2Setting.setIdpCertFingerprintAlgorithm(idpCertFingerprintAlgorithm);
}
}
/**
* Loads the security settings from the properties file
*/
private void loadSecuritySetting() {
Boolean nameIdEncrypted = loadBooleanProperty(SECURITY_NAMEID_ENCRYPTED);
if (nameIdEncrypted != null)
saml2Setting.setNameIdEncrypted(nameIdEncrypted);
Boolean authnRequestsSigned = loadBooleanProperty(SECURITY_AUTHREQUEST_SIGNED);
if (authnRequestsSigned != null)
saml2Setting.setAuthnRequestsSigned(authnRequestsSigned);
Boolean logoutRequestSigned = loadBooleanProperty(SECURITY_LOGOUTREQUEST_SIGNED);
if (logoutRequestSigned != null)
saml2Setting.setLogoutRequestSigned(logoutRequestSigned);
Boolean logoutResponseSigned = loadBooleanProperty(SECURITY_LOGOUTRESPONSE_SIGNED);
if (logoutResponseSigned != null)
saml2Setting.setLogoutResponseSigned(logoutResponseSigned);
Boolean wantMessagesSigned = loadBooleanProperty(SECURITY_WANT_MESSAGES_SIGNED);
if (wantMessagesSigned != null)
saml2Setting.setWantMessagesSigned(wantMessagesSigned);
Boolean wantAssertionsSigned = loadBooleanProperty(SECURITY_WANT_ASSERTIONS_SIGNED);
if (wantAssertionsSigned != null)
saml2Setting.setWantAssertionsSigned(wantAssertionsSigned);
Boolean wantAssertionsEncrypted = loadBooleanProperty(SECURITY_WANT_ASSERTIONS_ENCRYPTED);
if (wantAssertionsEncrypted != null)
saml2Setting.setWantAssertionsEncrypted(wantAssertionsEncrypted);
Boolean wantNameId = loadBooleanProperty(SECURITY_WANT_NAMEID);
if (wantNameId != null)
saml2Setting.setWantNameId(wantNameId);
Boolean wantNameIdEncrypted = loadBooleanProperty(SECURITY_WANT_NAMEID_ENCRYPTED);
if (wantNameIdEncrypted != null)
saml2Setting.setWantNameIdEncrypted(wantNameIdEncrypted);
Boolean wantXMLValidation = loadBooleanProperty(SECURITY_WANT_XML_VALIDATION);
if (wantXMLValidation != null)
saml2Setting.setWantXMLValidation(wantXMLValidation);
Boolean signMetadata = loadBooleanProperty(SECURITY_SIGN_METADATA);
if (signMetadata != null)
saml2Setting.setSignMetadata(signMetadata);
List<String> requestedAuthnContext = loadListProperty(SECURITY_REQUESTED_AUTHNCONTEXT);
if (requestedAuthnContext != null)
saml2Setting.setRequestedAuthnContext(requestedAuthnContext);
String requestedAuthnContextComparison = loadStringProperty(SECURITY_REQUESTED_AUTHNCONTEXTCOMPARISON);
if (requestedAuthnContextComparison != null && !requestedAuthnContextComparison.isEmpty())
saml2Setting.setRequestedAuthnContextComparison(requestedAuthnContextComparison);
String signatureAlgorithm = loadStringProperty(SECURITY_SIGNATURE_ALGORITHM);
if (signatureAlgorithm != null && !signatureAlgorithm.isEmpty())
saml2Setting.setSignatureAlgorithm(signatureAlgorithm);
String digestAlgorithm = loadStringProperty(SECURITY_DIGEST_ALGORITHM);
if (digestAlgorithm != null && !digestAlgorithm.isEmpty())
saml2Setting.setDigestAlgorithm(digestAlgorithm);
Boolean rejectUnsolicitedResponsesWithInResponseTo = loadBooleanProperty(SECURITY_REJECT_UNSOLICITED_RESPONSES_WITH_INRESPONSETO);
if (rejectUnsolicitedResponsesWithInResponseTo != null) {
saml2Setting.setRejectUnsolicitedResponsesWithInResponseTo(rejectUnsolicitedResponsesWithInResponseTo);
}
Boolean allowRepeatAttributeName = loadBooleanProperty(SECURITY_ALLOW_REPEAT_ATTRIBUTE_NAME_PROPERTY_KEY);
if (allowRepeatAttributeName != null) {
saml2Setting.setAllowRepeatAttributeName(allowRepeatAttributeName);
}
Boolean rejectDeprecatedAlg = loadBooleanProperty(SECURITY_REJECT_DEPRECATED_ALGORITHM);
if (rejectDeprecatedAlg != null) {
saml2Setting.setRejectDeprecatedAlg(rejectDeprecatedAlg);
}
}
/**
* Loads the compress settings from the properties file
*/
private void loadCompressSetting() {
Boolean compressRequest = loadBooleanProperty(COMPRESS_REQUEST);
if (compressRequest != null) {
saml2Setting.setCompressRequest(compressRequest);
}
Boolean compressResponse = loadBooleanProperty(COMPRESS_RESPONSE);
if (compressResponse != null) {
saml2Setting.setCompressResponse(compressResponse);
}
}
/**
* Loads the parsing settings from the properties file
*/
private void loadParsingSetting() {
Boolean trimNameIds = loadBooleanProperty(PARSING_TRIM_NAME_IDS);
if (trimNameIds != null) {
saml2Setting.setTrimNameIds(trimNameIds);
}
Boolean trimAttributeValues = loadBooleanProperty(PARSING_TRIM_ATTRIBUTE_VALUES);
if (trimAttributeValues != null) {
saml2Setting.setTrimAttributeValues(trimAttributeValues);
}
}
/**
* Loads the organization settings from the properties file
*/
private Organization loadOrganization() {
Organization orgResult = null;
String orgName = loadStringProperty(ORGANIZATION_NAME);
String orgDisplayName = loadStringProperty(ORGANIZATION_DISPLAYNAME);
URL orgUrl = loadURLProperty(ORGANIZATION_URL);
String orgLangAttribute = loadStringProperty(ORGANIZATION_LANG);
if (StringUtils.isNotBlank(orgName) || StringUtils.isNotBlank(orgDisplayName) || orgUrl != null) {
orgResult = new Organization(orgName, orgDisplayName, orgUrl, orgLangAttribute);
}
return orgResult;
}
/**
* Loads the contacts settings from the properties file
*/
private List<Contact> loadContacts() {
List<Contact> contacts = new LinkedList<>();
String technicalGn = loadStringProperty(CONTACT_TECHNICAL_GIVEN_NAME);
String technicalEmailAddress = loadStringProperty(CONTACT_TECHNICAL_EMAIL_ADDRESS);
if ((technicalGn != null && !technicalGn.isEmpty()) || (technicalEmailAddress != null && !technicalEmailAddress.isEmpty())) {
Contact technical = new Contact("technical", technicalGn, technicalEmailAddress);
contacts.add(technical);
}
String supportGn = loadStringProperty(CONTACT_SUPPORT_GIVEN_NAME);
String supportEmailAddress = loadStringProperty(CONTACT_SUPPORT_EMAIL_ADDRESS);
if ((supportGn != null && !supportGn.isEmpty()) || (supportEmailAddress != null && !supportEmailAddress.isEmpty())) {
Contact support = new Contact("support", supportGn, supportEmailAddress);
contacts.add(support);
}
return contacts;
}
/**
* Loads the unique ID prefix. Uses default if property not set.
*/
private String loadUniqueIDPrefix() {
String uniqueIDPrefix = loadStringProperty(UNIQUE_ID_PREFIX_PROPERTY_KEY);
return uniqueIDPrefix;
}
/**
* Loads the SP settings from the properties file
*/
private void loadSpSetting() {
String spEntityID = loadStringProperty(SP_ENTITYID_PROPERTY_KEY);
if (spEntityID != null) {
saml2Setting.setSpEntityId(spEntityID);
}
URL assertionConsumerServiceUrl = loadURLProperty(SP_ASSERTION_CONSUMER_SERVICE_URL_PROPERTY_KEY);
if (assertionConsumerServiceUrl != null) {
saml2Setting.setSpAssertionConsumerServiceUrl(assertionConsumerServiceUrl);
}
String spAssertionConsumerServiceBinding = loadStringProperty(SP_ASSERTION_CONSUMER_SERVICE_BINDING_PROPERTY_KEY);
if (spAssertionConsumerServiceBinding != null) {
saml2Setting.setSpAssertionConsumerServiceBinding(spAssertionConsumerServiceBinding);
}
URL spSingleLogoutServiceUrl = loadURLProperty(SP_SINGLE_LOGOUT_SERVICE_URL_PROPERTY_KEY);
if (spSingleLogoutServiceUrl != null) {
saml2Setting.setSpSingleLogoutServiceUrl(spSingleLogoutServiceUrl);
}
String spSingleLogoutServiceBinding = loadStringProperty(SP_SINGLE_LOGOUT_SERVICE_BINDING_PROPERTY_KEY);
if (spSingleLogoutServiceBinding != null) {
saml2Setting.setSpSingleLogoutServiceBinding(spSingleLogoutServiceBinding);
}
String spNameIDFormat = loadStringProperty(SP_NAMEIDFORMAT_PROPERTY_KEY);
if (spNameIDFormat != null && !spNameIDFormat.isEmpty()) {
saml2Setting.setSpNameIDFormat(spNameIDFormat);
}
boolean keyStoreEnabled = this.samlData.get(KEYSTORE_KEY) != null && this.samlData.get(KEYSTORE_ALIAS) != null
&& this.samlData.get(KEYSTORE_KEY_PASSWORD) != null;
X509Certificate spX509cert;
PrivateKey spPrivateKey;
if (keyStoreEnabled) {
KeyStore ks = (KeyStore) this.samlData.get(KEYSTORE_KEY);
String alias = (String) this.samlData.get(KEYSTORE_ALIAS);
String password = (String) this.samlData.get(KEYSTORE_KEY_PASSWORD);
spX509cert = getCertificateFromKeyStore(ks, alias, password);
spPrivateKey = getPrivateKeyFromKeyStore(ks, alias, password);
} else {
spX509cert = loadCertificateFromProp(SP_X509CERT_PROPERTY_KEY);
spPrivateKey = loadPrivateKeyFromProp(SP_PRIVATEKEY_PROPERTY_KEY);
}
if (spX509cert != null) {
saml2Setting.setSpX509cert(spX509cert);
}
if (spPrivateKey != null) {
saml2Setting.setSpPrivateKey(spPrivateKey);
}
X509Certificate spX509certNew = loadCertificateFromProp(SP_X509CERTNEW_PROPERTY_KEY);
if (spX509certNew != null) {
saml2Setting.setSpX509certNew(spX509certNew);
}
}
/**
* Loads a property of the type String from the Properties object
*
* @param propertyKey the property name
*
* @return the value
*/
private String loadStringProperty(String propertyKey) {
Object propValue = samlData.get(propertyKey);
if (isString(propValue)) {
return StringUtils.trimToNull((String) propValue);
}
return null;
}
/**
* Loads a property of the type Boolean from the Properties object
*
* @param propertyKey the property name
*
* @return the value
*/
private Boolean loadBooleanProperty(String propertyKey) {
Object propValue = samlData.get(propertyKey);
if (isString(propValue)) {
return Boolean.parseBoolean(((String) propValue).trim());
}
if (propValue instanceof Boolean) {
return (Boolean) propValue;
}
return null;
}
/**
* Loads a property of the type List from the Properties object
*
* @param propertyKey the property name
*
* @return the value
*/
private List<String> loadListProperty(String propertyKey) {
Object propValue = samlData.get(propertyKey);
if (isString(propValue)) {
String[] values = ((String) propValue).trim().split(",");
for (int i = 0; i < values.length; i++) {
values[i] = values[i].trim();
}
return Arrays.asList(values);
}
if (propValue instanceof List) {
return (List<String>) propValue;
}
return null;
}
/**
* Loads a property of the type URL from the Properties object
*
* @param propertyKey the property name
*
* @return the value
*/
private URL loadURLProperty(String propertyKey) {
Object propValue = samlData.get(propertyKey);
if (isString(propValue)) {
try {
return new URL(((String) propValue).trim());
} catch (MalformedURLException e) {
LOGGER.error("'{}' contains malformed url.", propertyKey, e);
return null;
}
}
if (propValue instanceof URL) {
return (URL) propValue;
}
return null;
}
protected PrivateKey getPrivateKeyFromKeyStore(KeyStore keyStore, String alias, String password) {
Key key;
try {
if (keyStore.containsAlias(alias)) {
key = keyStore.getKey(alias, password.toCharArray());
if (key instanceof PrivateKey) {
return (PrivateKey) key;
}
} else {
LOGGER.error("Entry for alias {} not found in keystore", alias);
}
} catch (UnrecoverableKeyException | KeyStoreException | NoSuchAlgorithmException e) {
LOGGER.error("Error loading private key from keystore. {}", e);
}
return null;
}
protected X509Certificate getCertificateFromKeyStore(KeyStore keyStore, String alias, String password) {
try {
if (keyStore.containsAlias(alias)) {
Key key = keyStore.getKey(alias, password.toCharArray());
if (key instanceof PrivateKey) {
Certificate cert = keyStore.getCertificate(alias);
if (cert instanceof X509Certificate) {
return (X509Certificate) cert;
}
}
} else {
LOGGER.error("Entry for alias {} not found in keystore", alias);
}
} catch (KeyStoreException | UnrecoverableKeyException | NoSuchAlgorithmException e) {
LOGGER.error("Error loading certificate from keystore. {}", e);
}
return null;
}
/**
* Loads a property of the type X509Certificate from the property value
*
* @param propValue the property value
*
* @return the X509Certificate object
*/
protected X509Certificate loadCertificateFromProp(Object propValue) {
if (isString(propValue)) {
try {
return Util.loadCert(((String) propValue).trim());
} catch (CertificateException e) {
LOGGER.error("Error loading certificate from properties.", e);
return null;
}
}
if (propValue instanceof X509Certificate) {
return (X509Certificate) propValue;
}
return null;
}
/**
* Loads a property of the type X509Certificate from the Properties object
*
* @param propertyKey the property name
*
* @return the X509Certificate object
*/
protected X509Certificate loadCertificateFromProp(String propertyKey) {
return loadCertificateFromProp(samlData.get(propertyKey));
}
/**
* Loads a property of the type List of X509Certificate from the Properties
* object
*
* @param propertyKey the property name
*
* @return the X509Certificate object list
*/
private List<X509Certificate> loadCertificateListFromProp(String propertyKey) {
List<X509Certificate> list = new ArrayList<X509Certificate>();
int i = 0;
while (true) {
Object propValue = samlData.get(propertyKey + "." + i++);
if (propValue == null)
break;
list.add(loadCertificateFromProp(propValue));
}
return list;
}
/**
* Loads a property of the type X509Certificate from file
*
* @param filename the file name of the file that contains the X509Certificate
*
* @return the X509Certificate object
*/
/*
protected X509Certificate loadCertificateFromFile(String filename) {
String certString = null;
try {
certString = Util.getFileAsString(filename.trim());
} catch (URISyntaxException e) {
LOGGER.error("Error loading certificate from file.", e);
return null;
}
catch (IOException e) {
LOGGER.error("Error loading certificate from file.", e);
return null;
}
try {
return Util.loadCert(certString);
} catch (CertificateException e) {
LOGGER.error("Error loading certificate from file.", e);
return null;
} catch (UnsupportedEncodingException e) {
LOGGER.error("the certificate is not in correct format.", e);
return null;
}
}
*/
/**
* Loads a property of the type PrivateKey from the Properties object
*
* @param propertyKey the property name
*
* @return the PrivateKey object
*/
protected PrivateKey loadPrivateKeyFromProp(String propertyKey) {
Object propValue = samlData.get(propertyKey);
if (isString(propValue)) {
try {
return Util.loadPrivateKey(((String) propValue).trim());
} catch (Exception e) {
LOGGER.error("Error loading privatekey from properties.", e);
return null;
}
}
if (propValue instanceof PrivateKey) {
return (PrivateKey) propValue;
}
return null;
}
/**
* Parses properties
*
* @param properties the Properties object to be parsed
*/
private void parseProperties(Properties properties) {
if (properties != null) {
for (String propertyKey : properties.stringPropertyNames()) {
this.samlData.put(propertyKey, properties.getProperty(propertyKey));
}
}
}
/**
* Parses the KeyStore data
*
* @param setting the KeyStoreSettings object to be parsed
*/
private void parseKeyStore(KeyStoreSettings setting) {
this.samlData.put(KEYSTORE_KEY, setting.getKeyStore());
this.samlData.put(KEYSTORE_ALIAS, setting.getSpAlias());
this.samlData.put(KEYSTORE_KEY_PASSWORD, setting.getSpKeyPass());
}
/**
* Aux method that verifies if an Object is an string
*
* @param propValue the Object to be verified
*/
private boolean isString(Object propValue) {
return propValue instanceof String && StringUtils.isNotBlank((String) propValue);
}
}
| 10,417 |
1,017 | <gh_stars>1000+
package com.xiaolyuh;
import org.springframework.boot.Banner.Mode;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
public class SpringBootStudentCompletableFutureApplication {
// 标准的JAVA应用main方法,主要作用作为项目启动的入口
public static void main(String[] args) {
// SpringApplication.run(SpringBootStudentBannerApplication.class, args);
SpringApplication application = new SpringApplication(SpringBootStudentCompletableFutureApplication.class);
/*
* Mode.OFF:关闭;
* Mode.CONSOLE:控制台输出,默认方式;
* Mode.LOG:日志输出方式;
*/
application.setBannerMode(Mode.CONSOLE);
application.run(args);
}
}
| 313 |
2,338 | <filename>lld/MachO/Arch/ARM64_32.cpp
//===- ARM64_32.cpp
//----------------------------------------------------------===//
//
// 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
//
//===----------------------------------------------------------------------===//
#include "Arch/ARM64Common.h"
#include "InputFiles.h"
#include "Symbols.h"
#include "SyntheticSections.h"
#include "Target.h"
#include "lld/Common/ErrorHandler.h"
#include "llvm/ADT/SmallVector.h"
#include "llvm/ADT/StringRef.h"
#include "llvm/BinaryFormat/MachO.h"
#include "llvm/Support/Endian.h"
#include "llvm/Support/MathExtras.h"
using namespace llvm::MachO;
using namespace llvm::support::endian;
using namespace lld;
using namespace lld::macho;
namespace {
struct ARM64_32 : ARM64Common {
ARM64_32();
void writeStub(uint8_t *buf, const Symbol &) const override;
void writeStubHelperHeader(uint8_t *buf) const override;
void writeStubHelperEntry(uint8_t *buf, const DylibSymbol &,
uint64_t entryAddr) const override;
const RelocAttrs &getRelocAttrs(uint8_t type) const override;
};
} // namespace
// These are very similar to ARM64's relocation attributes, except that we don't
// have the BYTE8 flag set.
const RelocAttrs &ARM64_32::getRelocAttrs(uint8_t type) const {
static const std::array<RelocAttrs, 11> relocAttrsArray{{
#define B(x) RelocAttrBits::x
{"UNSIGNED", B(UNSIGNED) | B(ABSOLUTE) | B(EXTERN) | B(LOCAL) | B(BYTE4)},
{"SUBTRACTOR", B(SUBTRAHEND) | B(EXTERN) | B(BYTE4)},
{"BRANCH26", B(PCREL) | B(EXTERN) | B(BRANCH) | B(BYTE4)},
{"PAGE21", B(PCREL) | B(EXTERN) | B(BYTE4)},
{"PAGEOFF12", B(ABSOLUTE) | B(EXTERN) | B(BYTE4)},
{"GOT_LOAD_PAGE21", B(PCREL) | B(EXTERN) | B(GOT) | B(BYTE4)},
{"GOT_LOAD_PAGEOFF12",
B(ABSOLUTE) | B(EXTERN) | B(GOT) | B(LOAD) | B(BYTE4)},
{"POINTER_TO_GOT", B(PCREL) | B(EXTERN) | B(GOT) | B(POINTER) | B(BYTE4)},
{"TLVP_LOAD_PAGE21", B(PCREL) | B(EXTERN) | B(TLV) | B(BYTE4)},
{"TLVP_LOAD_PAGEOFF12",
B(ABSOLUTE) | B(EXTERN) | B(TLV) | B(LOAD) | B(BYTE4)},
{"ADDEND", B(ADDEND)},
#undef B
}};
assert(type < relocAttrsArray.size() && "invalid relocation type");
if (type >= relocAttrsArray.size())
return invalidRelocAttrs;
return relocAttrsArray[type];
}
// The stub code is fairly similar to ARM64's, except that we load pointers into
// 32-bit 'w' registers, instead of the 64-bit 'x' ones.
static constexpr uint32_t stubCode[] = {
0x90000010, // 00: adrp x16, __la_symbol_ptr@page
0xb9400210, // 04: ldr w16, [x16, __la_symbol_ptr@pageoff]
0xd61f0200, // 08: br x16
};
void ARM64_32::writeStub(uint8_t *buf8, const Symbol &sym) const {
::writeStub<ILP32>(buf8, stubCode, sym);
}
static constexpr uint32_t stubHelperHeaderCode[] = {
0x90000011, // 00: adrp x17, _dyld_private@page
0x91000231, // 04: add x17, x17, _dyld_private@pageoff
0xa9bf47f0, // 08: stp x16/x17, [sp, #-16]!
0x90000010, // 0c: adrp x16, dyld_stub_binder@page
0xb9400210, // 10: ldr w16, [x16, dyld_stub_binder@pageoff]
0xd61f0200, // 14: br x16
};
void ARM64_32::writeStubHelperHeader(uint8_t *buf8) const {
::writeStubHelperHeader<ILP32>(buf8, stubHelperHeaderCode);
}
static constexpr uint32_t stubHelperEntryCode[] = {
0x18000050, // 00: ldr w16, l0
0x14000000, // 04: b stubHelperHeader
0x00000000, // 08: l0: .long 0
};
void ARM64_32::writeStubHelperEntry(uint8_t *buf8, const DylibSymbol &sym,
uint64_t entryVA) const {
::writeStubHelperEntry(buf8, stubHelperEntryCode, sym, entryVA);
}
ARM64_32::ARM64_32() : ARM64Common(ILP32()) {
cpuType = CPU_TYPE_ARM64_32;
cpuSubtype = CPU_SUBTYPE_ARM64_V8;
stubSize = sizeof(stubCode);
stubHelperHeaderSize = sizeof(stubHelperHeaderCode);
stubHelperEntrySize = sizeof(stubHelperEntryCode);
}
TargetInfo *macho::createARM64_32TargetInfo() {
static ARM64_32 t;
return &t;
}
| 1,779 |
892 | {
"schema_version": "1.2.0",
"id": "GHSA-w64p-hf49-ggf8",
"modified": "2022-05-02T03:25:45Z",
"published": "2022-05-02T03:25:45Z",
"aliases": [
"CVE-2009-1508"
],
"details": "SQL injection vulnerability in the xforum_validateUser function in Common.php in X-Forum 0.6.2 allows remote attackers to execute arbitrary SQL commands, as demonstrated via the cookie_username parameter to Configure.php.",
"severity": [
],
"affected": [
],
"references": [
{
"type": "ADVISORY",
"url": "https://nvd.nist.gov/vuln/detail/CVE-2009-1508"
},
{
"type": "WEB",
"url": "https://exchange.xforce.ibmcloud.com/vulnerabilities/49537"
},
{
"type": "WEB",
"url": "https://www.exploit-db.com/exploits/8317"
},
{
"type": "WEB",
"url": "http://www.securityfocus.com/bid/34302"
}
],
"database_specific": {
"cwe_ids": [
"CWE-89"
],
"severity": "HIGH",
"github_reviewed": false
}
} | 455 |
532 | <reponame>shalupov/gradle-download-task<filename>src/main/java/de/undercouch/gradle/tasks/download/DownloadTaskPlugin.java
// Copyright 2013 <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.undercouch.gradle.tasks.download;
import org.gradle.api.Plugin;
import org.gradle.api.Project;
import org.gradle.api.plugins.ExtraPropertiesExtension;
/**
* Registers the extensions provided by this plugin
* @author <NAME>
*/
public class DownloadTaskPlugin implements Plugin<Project> {
@Override
public void apply(Project project) {
project.getExtensions().create("download", DownloadExtension.class, project);
if (project.getExtensions().findByName("verifyChecksum") == null) {
project.getExtensions().create("verifyChecksum", VerifyExtension.class, project);
}
//register top-level properties 'Download' and 'Verify' for our tasks
ExtraPropertiesExtension extraProperties =
project.getExtensions().getExtraProperties();
extraProperties.set(Download.class.getSimpleName(), Download.class);
extraProperties.set(Verify.class.getSimpleName(), Verify.class);
}
}
| 531 |
460 | #include "../../../src/scripttools/debugging/qscriptdebuggercommandexecutor_p.h"
| 28 |
348 | {"nom":"Bize-Minervois","circ":"1ère circonscription","dpt":"Aude","inscrits":913,"abs":488,"votants":425,"blancs":18,"nuls":34,"exp":373,"res":[{"nuance":"REM","nom":"<NAME>","voix":254},{"nuance":"FN","nom":"<NAME>","voix":119}]} | 91 |
1,612 | package yyydjk.com.library;
import android.content.Context;
import android.graphics.Canvas;
import android.util.AttributeSet;
import android.widget.FrameLayout;
public class CouponView extends FrameLayout {
private CouponViewHelper helper;
public CouponView(Context context) {
this(context, null);
}
public CouponView(Context context, AttributeSet attrs) {
this(context, attrs, 0);
}
public CouponView(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
helper = new CouponViewHelper(this, context, attrs, defStyle);
}
@Override
protected void onSizeChanged(int w, int h, int oldw, int oldh) {
super.onSizeChanged(w, h, oldw, oldh);
helper.onSizeChanged(w, h);
}
@Override
protected void onDraw(Canvas canvas) {
super.onDraw(canvas);
helper.onDraw(canvas);
}
public float getSemicircleGap() {
return helper.getSemicircleGap();
}
public void setSemicircleGap(float semicircleGap) {
helper.setSemicircleGap(semicircleGap);
}
public float getSemicircleRadius() {
return helper.getSemicircleRadius();
}
public void setSemicircleRadius(float semicircleRadius) {
helper.setSemicircleRadius(semicircleRadius);
}
public int getSemicircleColor() {
return helper.getSemicircleColor();
}
public void setSemicircleColor(int semicircleColor) {
helper.setSemicircleColor(semicircleColor);
}
public float getDashLineLength() {
return helper.getDashLineLength();
}
public void setDashLineLength(float dashLineLength) {
helper.setDashLineLength(dashLineLength);
}
public float getDashLineHeight() {
return helper.getDashLineHeight();
}
public void setDashLineHeight(float dashLineHeight) {
helper.setDashLineHeight(dashLineHeight);
}
public float getDashLineGap() {
return helper.getDashLineGap();
}
public void setDashLineGap(float dashLineGap) {
helper.setDashLineGap(dashLineGap);
}
public int getDashLineColor() {
return helper.getDashLineColor();
}
public void setDashLineColor(int dashLineColor) {
helper.setDashLineColor(dashLineColor);
}
public boolean isSemicircleTop() {
return helper.isSemicircleTop();
}
public void setSemicircleTop(boolean semicircleTop) {
helper.setSemicircleTop(semicircleTop);
}
public boolean isSemicircleBottom() {
return helper.isSemicircleBottom();
}
public void setSemicircleBottom(boolean semicircleBottom) {
helper.setSemicircleBottom(semicircleBottom);
}
public boolean isSemicircleLeft() {
return helper.isSemicircleLeft();
}
public void setSemicircleLeft(boolean semicircleLeft) {
helper.setSemicircleLeft(semicircleLeft);
}
public boolean isSemicircleRight() {
return helper.isSemicircleRight();
}
public void setSemicircleRight(boolean semicircleRight) {
helper.setSemicircleRight(semicircleRight);
}
public boolean isDashLineTop() {
return helper.isDashLineTop();
}
public void setDashLineTop(boolean dashLineTop) {
helper.setDashLineTop(dashLineTop);
}
public boolean DashLineBottom() {
return helper.isDashLineBottom();
}
public void setDashLineBottom(boolean dashLineBottom) {
helper.setDashLineBottom(dashLineBottom);
}
public boolean isDashLineLeft() {
return helper.isDashLineLeft();
}
public void setDashLineLeft(boolean dashLineLeft) {
helper.setDashLineLeft(dashLineLeft);
}
public boolean isDashLineRight() {
return helper.isDashLineRight();
}
public void setDashLineRight(boolean dashLineRight) {
helper.setDashLineRight(dashLineRight);
}
public float getDashLineMarginTop() {
return helper.getDashLineMarginTop();
}
public void setDashLineMarginTop(float dashLineMarginTop) {
helper.setDashLineMarginTop(dashLineMarginTop);
}
public float getDashLineMarginBottom() {
return helper.getDashLineMarginBottom();
}
public void setDashLineMarginBottom(float dashLineMarginBottom) {
helper.setDashLineMarginBottom(dashLineMarginBottom);
}
public float getDashLineMarginLeft() {
return helper.getDashLineMarginLeft();
}
public void setDashLineMarginLeft(float dashLineMarginLeft) {
helper.setDashLineMarginLeft(dashLineMarginLeft);
}
public float getDashLineMarginRight() {
return helper.getDashLineMarginRight();
}
public void setDashLineMarginRight(float dashLineMarginRight) {
helper.setDashLineMarginRight(dashLineMarginRight);
}
}
| 1,909 |
3,083 | // Copyright 2011-2016 Google LLC
//
// 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.google.security.zynamics.binnavi.API.debug;
import com.google.security.zynamics.binnavi.API.debug.raw.RegisterValues;
import com.google.security.zynamics.binnavi.API.disassembly.Address;
import com.google.security.zynamics.binnavi.debug.connection.packets.replies.SingleStepReply;
public class DebuggerSingleStepReply extends DebuggerReply {
public DebuggerSingleStepReply(final SingleStepReply reply) {
super(reply);
}
public Address getAddress() {
return new Address(((SingleStepReply) reply).getAddress().getAddress().toBigInteger());
}
public RegisterValues getRegisterValues() {
return new RegisterValues(((SingleStepReply) reply).getRegisterValues());
}
public long getThreadId() {
return ((SingleStepReply) reply).getThreadId();
}
}
| 386 |
1,233 | /*
* Copyright 2021 Netflix, 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.mantisrx.runtime.scheduler;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
import io.mantisrx.common.metrics.rx.MonitorOperator;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.TimeUnit;
import org.junit.Test;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import rx.Observable;
import rx.Subscription;
import rx.internal.util.RxThreadFactory;
public class MantisRxSingleThreadSchedulerTest {
private static final Logger logger = LoggerFactory.getLogger(MantisRxSingleThreadSchedulerTest.class);
Observable<Observable<String>> createSourceObs(int numInnerObs, int valuesPerCompletingInnerObs) {
return Observable.range(1, numInnerObs)
.map(x -> {
if (x != 1) {
return Observable.interval(10, TimeUnit.MILLISECONDS)
.map(l -> String.format("I%d: %d", x, l.intValue()))
.take(valuesPerCompletingInnerObs);
} else {
return Observable.interval(100, TimeUnit.MILLISECONDS)
.map(l -> String.format("I%d: %d", x, l.intValue()));
}
});
}
@Test
public void testObserveOnAfterOnCompleteMantisRxScheduler() throws InterruptedException {
int nThreads = 6;
final MantisRxSingleThreadScheduler[] mantisRxSingleThreadSchedulers = new MantisRxSingleThreadScheduler[nThreads];
RxThreadFactory rxThreadFactory = new RxThreadFactory("MantisRxScheduler-");
logger.info("creating {} Mantis threads", nThreads);
for (int i = 0; i < nThreads; i++) {
mantisRxSingleThreadSchedulers[i] = new MantisRxSingleThreadScheduler(rxThreadFactory);
}
int numInnerObs = 10;
int valuesPerCompletingInnerObs = 2;
int valuesToWaitFor = numInnerObs*valuesPerCompletingInnerObs + 10;
Observable<Observable<String>> oo = createSourceObs(numInnerObs, valuesPerCompletingInnerObs);
final CountDownLatch latch = new CountDownLatch(valuesToWaitFor);
Observable<String> map = oo
.lift(new MonitorOperator<>("worker_stage_outer"))
.map(observable -> observable
.groupBy(e -> System.nanoTime() % nThreads)
.flatMap(go -> go
.observeOn(mantisRxSingleThreadSchedulers[go.getKey().intValue()])
.doOnNext(x -> {
logger.info("processing {} on thread {}", x, Thread.currentThread().getName());
latch.countDown();
})
)
).flatMap(x -> x);
Subscription subscription = map.subscribe();
assertTrue(latch.await(5, TimeUnit.SECONDS));
for (int i = 0; i < nThreads; i++) {
assertFalse(mantisRxSingleThreadSchedulers[i].createWorker().isUnsubscribed());
}
subscription.unsubscribe();
}
}
| 1,519 |
427 | <reponame>TigerBSD/FreeBSD-Custom-ThinkPad
//===-- MICmdData.cpp -------------------------------------------*- C++ -*-===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
// In-house headers:
#include "MICmdData.h"
| 122 |
409 | #ifndef RAZERS_PARALLEL_MISC_H_
#define RAZERS_PARALLEL_MISC_H_
namespace seqan {
template <typename TPos, typename TSize, typename TCount>
void computeSplittersBySlotCount(String<TPos> & splitters, TSize size, TCount count)
{
resize(splitters, count + 1, Exact());
splitters[0] = 0;
TSize blockLength = size / count;
TSize rest = size % count;
for (TCount i = 1; i <= count; ++i)
{
splitters[i] = splitters[i - 1] + blockLength;
if (i <= rest)
splitters[i] += 1;
}
SEQAN_ASSERT_EQ(back(splitters), size);
}
template <typename TPos, typename TDataSize, typename TSlotSize, typename TPackageCount>
void computeSplittersBySlotSize(String<TPos> & splitters, TDataSize size, TSlotSize slotSize, TPackageCount maxPackageCount)
{
// Limit maximal number of verification packages.
if (maxPackageCount > 0 && (size / slotSize > maxPackageCount))
slotSize = size / maxPackageCount + (static_cast<TSlotSize>(size % maxPackageCount) > static_cast<TSlotSize>(0));
// Compute splitters.
unsigned count = size / slotSize + (static_cast<TSlotSize>(size % slotSize) > static_cast<TSlotSize>(0));
resize(splitters, count + 1, Exact());
splitters[0] = 0;
for (unsigned i = 1; i < count; ++i)
splitters[i] = splitters[i - 1] + slotSize;
splitters[count] = size;
SEQAN_ASSERT_LEQ(splitters[count] - splitters[count - 1], slotSize);
}
template <typename TPos, typename TDataSize, typename TSlotSize>
void computeSplittersBySlotSize(String<TPos> & splitters, TDataSize size, TSlotSize slotSize)
{
computeSplittersBySlotSize(splitters, size, slotSize, 0u);
}
} // namespace seqan
#endif // #ifndef RAZERS_PARALLEL_MISC_H_
| 669 |
5,166 | <filename>javav2/example_code/route53/src/main/java/com/example/route/DeleteHealthCheck.java
// snippet-comment:[These are tags for the AWS doc team's sample catalog. Do not remove.]
// snippet-sourcedescription:[DeleteHealthCheck.java demonstrates how to delete a health check.]
//snippet-keyword:[AWS SDK for Java v2]
// snippet-service:[Amazon Route 53]
// snippet-keyword:[Code Sample]
// snippet-sourcetype:[full-example]
// snippet-sourcedate:[09/28/2021]
// snippet-sourceauthor:[AWS - scmacdon]
/*
Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
SPDX-License-Identifier: Apache-2.0
*/
package com.example.route;
// snippet-start:[route53.java2.delete_health_check.import]
import software.amazon.awssdk.regions.Region;
import software.amazon.awssdk.services.route53.Route53Client;
import software.amazon.awssdk.services.route53.model.Route53Exception;
import software.amazon.awssdk.services.route53.model.DeleteHealthCheckRequest;
// snippet-end:[route53.java2.delete_health_check.import]
/**
* To run this Java V2 code example, ensure that you have setup your development environment, including your credentials.
*
* For information, see this documentation topic:
*
* https://docs.aws.amazon.com/sdk-for-java/latest/developer-guide/get-started.html
*/
public class DeleteHealthCheck {
public static void main(String[] args) {
final String USAGE = "\n" +
"Usage:\n" +
" <id> \n\n" +
"Where:\n" +
" id - the health check id. \n";
if (args.length != 1) {
System.out.println(USAGE);
System.exit(1);
}
String id = args[0];
Region region = Region.AWS_GLOBAL;
Route53Client route53Client = Route53Client.builder()
.region(region)
.build();
delHealthCheck(route53Client, id);
route53Client.close();
}
// snippet-start:[route53.java2.delete_health_check.main]
public static void delHealthCheck( Route53Client route53Client, String id) {
try {
DeleteHealthCheckRequest delRequest = DeleteHealthCheckRequest.builder()
.healthCheckId(id)
.build();
// Delete the Health Check
route53Client.deleteHealthCheck(delRequest);
System.out.println("The hosted zone was deleted");
} catch (Route53Exception e) {
System.err.println(e.getMessage());
System.exit(1);
}
}
// snippet-end:[route53.java2.delete_health_check.main]
}
| 1,117 |
2,603 | /***********************************************************************************************************************
* DISCLAIMER
* This software is supplied by Renesas Electronics Corporation and is only
* intended for use with Renesas products. No other uses are authorized. This
* software is owned by Renesas Electronics Corporation and is protected under
* all applicable laws, including copyright laws.
* THIS SOFTWARE IS PROVIDED "AS IS" AND RENESAS MAKES NO WARRANTIES REGARDING
* THIS SOFTWARE, WHETHER EXPRESS, IMPLIED OR STATUTORY, INCLUDING BUT NOT
* LIMITED TO WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE
* AND NON-INFRINGEMENT. ALL SUCH WARRANTIES ARE EXPRESSLY DISCLAIMED.
* TO THE MAXIMUM EXTENT PERMITTED NOT PROHIBITED BY LAW, NEITHER RENESAS
* ELECTRONICS CORPORATION NOR ANY OF ITS AFFILIATED COMPANIES SHALL BE LIABLE
* FOR ANY DIRECT, INDIRECT, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES FOR
* ANY REASON RELATED TO THIS SOFTWARE, EVEN IF RENESAS OR ITS AFFILIATES HAVE
* BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES.
* Renesas reserves the right, without notice, to make changes to this software
* and to discontinue the availability of this software. By using this software,
* you agree to the additional terms and conditions found by accessing the
* following link:
* http://www.renesas.com/disclaimer
*
* Copyright (C) 2013 Renesas Electronics Corporation. All rights reserved.
***********************************************************************************************************************/
/***********************************************************************************************************************
* File Name : r_cg_vect.h
* Version : Applilet4 for RX64M V1.00.00.00 [02 Aug 2013]
* Device(s) : R5F564MLHxFC
* Tool-Chain : CCRX
* Description : This file contains definition of vector.
* Creation Date: 07/02/2014
***********************************************************************************************************************/
#ifndef _VECT_H
#define _VECT_H
/***********************************************************************************************************************
Macro definitions (Register bit)
***********************************************************************************************************************/
/***********************************************************************************************************************
Macro definitions
***********************************************************************************************************************/
/***********************************************************************************************************************
Typedef definitions
***********************************************************************************************************************/
/***********************************************************************************************************************
Global functions
***********************************************************************************************************************/
/* Undefined */
#pragma interrupt (r_undefined_exception)
void r_undefined_exception(void);
/* Reserved */
#pragma interrupt (r_reserved_exception)
void r_reserved_exception(void);
/* NMI */
#pragma interrupt (r_nmi_exception)
void r_nmi_exception(void);
/* ICU GROUPBE0 */
#pragma interrupt (r_icua_group_be0_interrupt(vect=106))
void r_icua_group_be0_interrupt(void);
/* ICU GROUPBL0 */
#pragma interrupt (r_icua_group_bl0_interrupt(vect=110))
void r_icua_group_bl0_interrupt(void);
/* ICU GROUPBL1 */
#pragma interrupt (r_icua_group_bl1_interrupt(vect=111))
void r_icua_group_bl1_interrupt(void);
/* ICU GROUPAL0 */
#pragma interrupt (r_icua_group_al0_interrupt(vect=112))
void r_icua_group_al0_interrupt(void);
/* ICU GROUPAL1 */
#pragma interrupt (r_icua_group_al1_interrupt(vect=113))
void r_icua_group_al1_interrupt(void);
/*;<<VECTOR DATA START (POWER ON RESET)>> */
/*;Power On Reset PC */
extern void PowerON_Reset(void);
/*;<<VECTOR DATA END (POWER ON RESET)>> */
#endif | 1,113 |
544 | //
// XMLString.cpp
//
// Library: XML
// Package: XML
// Module: XMLString
//
// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH.
// and Contributors.
//
// SPDX-License-Identifier: BSL-1.0
//
#include "Poco/XML/XMLString.h"
#if defined(XML_UNICODE_WCHAR_T)
#include <stdlib.h>
#endif
namespace Poco {
namespace XML {
#if defined(XML_UNICODE_WCHAR_T)
std::string fromXMLString(const XMLString& str)
{
std::string result;
result.reserve(str.size());
for (XMLString::const_iterator it = str.begin(); it != str.end(); ++it)
{
char c;
wctomb(&c, *it);
result += c;
}
return result;
}
XMLString toXMLString(const std::string& str)
{
XMLString result;
result.reserve(str.size());
for (std::string::const_iterator it = str.begin(); it != str.end();)
{
wchar_t c;
int n = mbtowc(&c, &*it, MB_CUR_MAX);
result += c;
it += (n > 0 ? n : 1);
}
return result;
}
#endif // XML_UNICODE_WCHAR_T
} } // namespace Poco::XML
| 411 |
778 | <filename>applications/SolidMechanicsApplication/tests/material_tests/isotropic_damage_material_model/PlaneStress_FourPointShear_parameters.json
{
"model_settings" : {
"dimension" : 2,
"domain_parts_list" : ["Parts_Parts_Auto1"],
"processes_parts_list" : ["Parts_Parts_Auto1","DISPLACEMENT_Displacement_Auto1","DISPLACEMENT_Displacement_Auto2","LineLoad2D_Load_on_lines_Auto1","LineLoad2D_Load_on_lines_Auto2"]
},
"solver_settings" : {
"solver_type" : "solid_mechanics_static_solver",
"Parameters" : {
"time_integration_settings" : {
"solution_type" : "Quasi-static",
"analysis_type" : "Non-linear",
"integration_method" : "Static"
},
"solving_strategy_settings" : {
"max_iteration" : 15
},
"convergence_criterion_settings" : {
"convergence_criterion" : "And_criterion"
},
"linear_solver_settings" : {
"solver_type" : "ExternalSolversApplication.super_lu",
"scaling" : false
}
}
},
"constraints_process_list" : [{
"model_part_name" : "DISPLACEMENT_Displacement_Auto1"
},{
"model_part_name" : "DISPLACEMENT_Displacement_Auto2",
"value" : [null,0.0,0.0]
}],
"loads_process_list" : [{
"model_part_name" : "LineLoad2D_Load_on_lines_Auto1",
"variable_name" : "FORCE_LOAD",
"modulus" : "15000.0*t",
"direction" : [0.0,-1.0,0.0]
},{
"model_part_name" : "LineLoad2D_Load_on_lines_Auto2",
"variable_name" : "FORCE_LOAD",
"modulus" : "1500.0*t",
"direction" : [0.0,-1.0,0.0]
}],
"check_process_list" : [
{
"python_module" : "from_json_check_result_process",
"kratos_module" : "KratosMultiphysics",
"process_name" : "FromJsonCheckResultProcess",
"Parameters" : {
"check_variables" : ["DISPLACEMENT_X","DISPLACEMENT_Y"],
"input_file_name" : "material_tests/isotropic_damage_material_model/PlaneStress_FourPointShear_results.json",
"model_part_name" : "Parts_Parts_Auto1",
"time_frequency" : 20.00
}
}
],
"_json_output_process" : [
{
"python_module" : "json_output_process",
"kratos_module" : "KratosMultiphysics",
"process_name" : "JsonOutputProcess",
"Parameters" : {
"output_variables" : ["DISPLACEMENT_X","DISPLACEMENT_Y"],
"output_file_name" : "material_tests/isotropic_damage_material_model/PlaneStress_FourPointShear_results.json",
"model_part_name" : "Parts_Parts_Auto1",
"time_frequency" : 20.00
}
}
]
}
| 1,463 |
1,014 | <filename>Database/Equities/Countries/South Korea/Technology/_Technology Industries.json
[
"Communication Equipment",
"Computer Hardware",
"Consumer Electronics",
"Electronic Components",
"Electronics & Computer Distribution",
"Information Technology Services",
"Scientific & Technical Instruments",
"Semiconductor Equipment & Materials",
"Semiconductors",
"Software - Application"
] | 131 |
8,747 | // Copyright 2015-2019 Espressif Systems (Shanghai) PTE LTD
//
// 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.
// ESP SDIO slave link used by the ESP host to communicate with ESP SDIO slave.
#pragma once
#include "esp_err.h"
#include "esp_serial_slave_link/essl.h"
#include "freertos/FreeRTOS.h"
#include "freertos/task.h"
#include "driver/sdmmc_defs.h"
/// Configuration for the ESSL SDIO device
typedef struct {
sdmmc_card_t *card; ///< The initialized sdmmc card pointer of the slave.
int recv_buffer_size; ///< The pre-negotiated recv buffer size used by both the host and the slave.
} essl_sdio_config_t;
/**
* @brief Initialize the ESSL SDIO device and get its handle.
*
* @param out_handle Output of the handle.
* @param config Configuration for the ESSL SDIO device.
* @return
* - ESP_OK: on success
* - ESP_ERR_NO_MEM: memory exhausted.
*/
esp_err_t essl_sdio_init_dev(essl_handle_t *out_handle, const essl_sdio_config_t *config);
/**
* @brief Deinitialize and free the space used by the ESSL SDIO device.
*
* @param handle Handle of the ESSL SDIO device to deinit.
* @return
* - ESP_OK: on success
* - ESP_ERR_INVALID_ARG: wrong handle passed
*/
esp_err_t essl_sdio_deinit_dev(essl_handle_t handle);
//Please call `essl_` functions witout `sdio` instead of calling these functions directly.
/** @cond */
/**
* SDIO Initialize process of an ESSL SDIO slave device.
*
* @param arg Context of the ``essl`` component. Send to other functions later.
* @param wait_ms Time to wait before operation is done, in ms.
*
* @return
* - ESP_OK if success
* - One of the error codes from SDMMC host controller
*/
esp_err_t essl_sdio_init(void *arg, uint32_t wait_ms);
/**
* Wait for interrupt of an ESSL SDIO slave device.
*
* @param arg Context of the ``essl`` component.
* @param wait_ms Time to wait before operation is done, in ms.
*
* @return
* - ESP_OK if success
* - One of the error codes from SDMMC host controller
*/
esp_err_t essl_sdio_wait_for_ready(void *arg, uint32_t wait_ms);
/**
* Get buffer num for the host to send data to the slave. The buffers are size of ``buffer_size``.
*
* @param arg Context of the component.
*
* @return
* - ESP_OK Success
* - One of the error codes from SDMMC host controller
*/
uint32_t essl_sdio_get_tx_buffer_num(void *arg);
/** Get amount of data the ESSL SDIO slave preparing to send to host.
*
* @param arg Context of the component.
*
* @return
* - ESP_OK Success
* - One of the error codes from SDMMC host controller
*/
uint32_t essl_sdio_get_rx_data_size(void *arg);
/**
* Send a packet to the ESSL SDIO slave. The slave receive the packet into buffers whose size is ``buffer_size`` in the arg.
*
* @param arg Context of the component.
* @param start Start address of the packet to send
* @param length Length of data to send, if the packet is over-size, the it will be divided into blocks and hold into different buffers automatically.
* @param wait_ms Time to wait before timeout, in ms.
*
* @return
* - ESP_OK Success
* - ESP_ERR_TIMEOUT No buffer to use, or error ftrom SDMMC host controller
* - One of the error codes from SDMMC host controller
*/
esp_err_t essl_sdio_send_packet(void *arg, const void *start, size_t length, uint32_t wait_ms);
/**
* Get a packet from an ESSL SDIO slave.
*
* @param arg Context of the component.
* @param[out] out_data Data output address
* @param size The size of the output buffer, if the buffer is smaller than the size of data to receive from slave, the driver returns ``ESP_ERR_NOT_FINISHED``
* @param wait_ms Time to wait before timeout, in ms.
*
* @return
* - ESP_OK Success, all the data are read from the slave.
* - ESP_ERR_NOT_FINISHED Read success, while there're data remaining.
* - One of the error codes from SDMMC host controller
*/
esp_err_t essl_sdio_get_packet(void *arg, void *out_data, size_t size, uint32_t wait_ms);
/**
* Wait for the interrupt from the SDIO slave.
*
* @param arg Context of the component.
* @param wait_ms Time to wait before timeout, in ms.
* @return
* - ESP_ERR_NOT_SUPPORTED: if the interrupt line is not initialized properly.
* - ESP_OK: if interrupt happened
* - ESP_ERR_TIMEOUT: if timeout before interrupt happened.
* - or other values returned from the `io_int_wait` member of the `card->host` structure.
*/
esp_err_t essl_sdio_wait_int(void *arg, uint32_t wait_ms);
/**
* Clear interrupt bits of an ESSL SDIO slave. All the bits set in the mask will be cleared, while other bits will stay the same.
*
* @param arg Context of the component.
* @param intr_mask Mask of interrupt bits to clear.
* @param wait_ms Time to wait before timeout, in ms.
*
* @return
* - ESP_OK Success
* - One of the error codes from SDMMC host controller
*/
esp_err_t essl_sdio_clear_intr(void *arg, uint32_t intr_mask, uint32_t wait_ms);
/**
* Get interrupt bits of an ESSL SDIO slave.
*
* @param arg Context of the component.
* @param intr_raw Output of the raw interrupt bits. Set to NULL if only masked bits are read.
* @param intr_st Output of the masked interrupt bits. set to NULL if only raw bits are read.
* @param wait_ms Time to wait before timeout, in ms.
*
* @return
* - ESP_OK Success
* - ESP_INVALID_ARG if both ``intr_raw`` and ``intr_st`` are NULL.
* - One of the error codes from SDMMC host controller
*/
esp_err_t essl_sdio_get_intr(void *arg, uint32_t *intr_raw, uint32_t *intr_st, uint32_t wait_ms);
/**
* Set interrupt enable bits of an ESSL SDIO slave. The slave only sends interrupt on the line when there is a bit both the raw status and the enable are set.
*
* @param arg Context of the component.
* @param ena_mask Mask of the interrupt bits to enable.
* @param wait_ms Time to wait before timeout, in ms.
*
* @return
* - ESP_OK Success
* - One of the error codes from SDMMC host controller
*/
esp_err_t essl_sdio_set_intr_ena(void *arg, uint32_t ena_mask, uint32_t wait_ms);
/**
* Get interrupt enable bits of an ESSL SDIO slave.
*
* @param arg Context of the component.
* @param ena_mask_o Output of interrupt bit enable mask.
* @param wait_ms Time to wait before timeout, in ms.
*
* @return
* - ESP_OK Success
* - One of the error codes from SDMMC host controller
*/
esp_err_t essl_sdio_get_intr_ena(void *arg, uint32_t *ena_mask_o, uint32_t wait_ms);
/**
* Write general purpose R/W registers (8-bit) of an ESSL SDIO slave.
*
* @param arg Context of the component.
* @param addr Address of register to write. Valid address: 0-27, 32-63 (28-31 reserved).
* @param value Value to write to the register.
* @param wait_ms Time to wait before timeout, in ms.
*
* @return
* - ESP_OK Success
* - ESP_ERR_INVALID_ARG Address not valid.
* - One of the error codes from SDMMC host controller
*/
esp_err_t essl_sdio_write_reg(void *arg, uint8_t addr, uint8_t value, uint8_t *value_o, uint32_t wait_ms);
/**
* Read general purpose R/W registers (8-bit) of an ESSL SDIO slave.
*
* @param arg Context of the component.
* @param add Address of register to read. Valid address: 0-27, 32-63 (28-31 reserved, return interrupt bits on read).
* @param value Output value read from the register.
* @param wait_ms Time to wait before timeout, in ms.
*
* @return
* - ESP_OK Success
* - ESP_ERR_INVALID_ARG Address not valid.
* - One of the error codes from SDMMC host controller
*/
esp_err_t essl_sdio_read_reg(void *arg, uint8_t add, uint8_t *value_o, uint32_t wait_ms);
/**
* Send interrupts to slave. Each bit of the interrupt will be triggered.
*
* @param arg Context of the component.
* @param intr_mask Mask of interrupt bits to send to slave.
* @param wait_ms Time to wait before timeout, in ms.
*
* @return
* - ESP_OK Success
* - One of the error codes from SDMMC host controller
*/
esp_err_t essl_sdio_send_slave_intr(void *arg, uint32_t intr_mask, uint32_t wait_ms);
/**
* @brief Reset the counter on the host side.
*
* @note Only call when you know the slave has reset its counter, or there will be inconsistent between the master and the slave.
*
* @param arg Context of the component.
*/
void essl_sdio_reset_cnt(void *arg);
/** @endcond */
| 2,942 |
381 | package com.tngtech.jgiven.report.config.converter;
import java.io.File;
/**
* Total conversion function
*/
public class ToFile implements StringConverter{
public Object apply (String input) {
return new File(input);
}
} | 81 |
32,544 | <filename>core-java-modules/core-java-exceptions-3/src/main/java/com/baeldung/exceptions/classcastexception/Amphibian.java
package com.baeldung.exceptions.classcastexception;
public class Amphibian implements Animal {
@Override
public String getName() {
return "Amphibian";
}
}
| 111 |
348 | <filename>docs/data/leg-t2/053/05303093.json<gh_stars>100-1000
{"nom":"<NAME>","circ":"3ème circonscription","dpt":"Mayenne","inscrits":224,"abs":96,"votants":128,"blancs":5,"nuls":4,"exp":119,"res":[{"nuance":"UDI","nom":"M. <NAME>","voix":95},{"nuance":"REM","nom":"M. <NAME>","voix":24}]} | 123 |
416 | <filename>iPhoneOS12.4.sdk/System/Library/Frameworks/Intents.framework/Headers/INSpatialEventTrigger.h
//
// INSpatialEventTrigger.h
// Intents
//
// Copyright (c) 2016-2017 Apple Inc. All rights reserved.
//
#import <Foundation/Foundation.h>
#import <Intents/INSpatialEvent.h>
@class CLPlacemark;
NS_ASSUME_NONNULL_BEGIN
API_AVAILABLE(ios(11.0), watchos(4.0))
API_UNAVAILABLE(macosx)
@interface INSpatialEventTrigger : NSObject <NSCopying, NSSecureCoding>
- (instancetype)initWithPlacemark:(CLPlacemark *)placemark
event:(INSpatialEvent)event NS_DESIGNATED_INITIALIZER;
@property (readonly, copy, NS_NONATOMIC_IOSONLY) CLPlacemark *placemark;
@property (readonly, assign, NS_NONATOMIC_IOSONLY) INSpatialEvent event;
@end
NS_ASSUME_NONNULL_END
| 329 |
1,210 | // Boost.Geometry (aka GGL, Generic Geometry Library)
// Copyright (c) 2007-2012 <NAME>, Amsterdam, the Netherlands.
// Copyright (c) 2008-2012 <NAME>, Paris, France.
// Copyright (c) 2009-2012 <NAME>, London, UK.
// This file was modified by Oracle on 2014.
// Modifications copyright (c) 2014 Oracle and/or its affiliates.
// Contributed and/or modified by <NAME>, on behalf of Oracle
// Parts of Boost.Geometry are redesigned from Geodan's Geographic Library
// (geolib/GGL), copyright (c) 1995-2010 Geodan, Amsterdam, the Netherlands.
// Use, modification and distribution is subject to the Boost Software License,
// Version 1.0. (See accompanying file LICENSE_1_0.txt or copy at
// http://www.boost.org/LICENSE_1_0.txt)
#ifndef BOOST_GEOMETRY_UTIL_SELECT_CALCULATION_TYPE_HPP
#define BOOST_GEOMETRY_UTIL_SELECT_CALCULATION_TYPE_HPP
#include <boost/mpl/if.hpp>
#include <boost/type_traits.hpp>
#include <boost/geometry/util/select_coordinate_type.hpp>
namespace boost { namespace geometry
{
/*!
\brief Meta-function selecting the "calculation" type
\details Based on two input geometry types, and an input calculation type,
(which defaults to void in the calling function), this meta-function
selects the most appropriate:
- if calculation type is specified, that one is used,
- if it is void, the most precise of the two points is used
\ingroup utility
*/
template <typename Geometry1, typename Geometry2, typename CalculationType>
struct select_calculation_type
{
typedef typename
boost::mpl::if_
<
boost::is_void<CalculationType>,
typename select_coordinate_type
<
Geometry1,
Geometry2
>::type,
CalculationType
>::type type;
};
// alternative version supporting more than 2 Geometries
template <typename CalculationType,
typename Geometry1,
typename Geometry2 = void,
typename Geometry3 = void>
struct select_calculation_type_alt
{
typedef typename
boost::mpl::if_
<
boost::is_void<CalculationType>,
typename select_coordinate_type
<
Geometry1,
Geometry2,
Geometry3
>::type,
CalculationType
>::type type;
};
}} // namespace boost::geometry
#endif // BOOST_GEOMETRY_UTIL_SELECT_CALCULATION_TYPE_HPP
| 1,014 |
1,958 | package com.freetymekiyan.algorithms.level.medium;
import java.util.HashMap;
import java.util.Map;
import java.util.Random;
/**
* 535. Encode and Decode TinyURL
* <p>
* Note: This is a companion problem to the System Design problem: Design TinyURL.
* TinyURL is a URL shortening service where you enter a URL such as https://leetcode.com/problems/design-tinyurl and it
* returns a short URL such as http://tinyurl.com/4e9iAk.
* <p>
* Design the encode and decode methods for the TinyURL service. There is no restriction on how your encode/decode
* algorithm should work. You just need to ensure that a URL can be encoded to a tiny URL and the tiny URL can be
* decoded to the original URL.
* <p>
* Related Topics: Hash Table, Math
* Similar Questions: (M) Design TinyURL
*/
public class EncodeAndDecodeTinyURL {
public class Codec {
private static final String ALPHABET = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";
private Map<String, String> map = new HashMap<>();
// Encodes a URL to a shortened URL.
public String encode(String longUrl) {
String shortUrl;
do {
shortUrl = randomKey();
} while (map.containsKey(shortUrl)); // Make sure the key doesn't duplicate with previous keys.
map.put(shortUrl, longUrl);
return shortUrl;
}
// Decodes a shortened URL to its original URL.
public String decode(String shortUrl) {
return map.get(shortUrl);
}
/**
* Generate a random key/short url for an incoming long url.
*/
private String randomKey() {
StringBuilder sb = new StringBuilder();
Random r = new Random(System.currentTimeMillis());
for (int i = 0; i < 6; i++) {
sb.append(ALPHABET.charAt(r.nextInt(ALPHABET.length())));
}
return sb.toString();
}
}
// Your Codec object will be instantiated and called as such:
// Codec codec = new Codec();
// codec.decode(codec.encode(url));
}
| 820 |
571 | <gh_stars>100-1000
package com.handsomezhou.contactssearch.activity;
import android.support.v4.app.Fragment;
import com.handsomezhou.contactssearch.fragment.T9SearchFragment;
public class T9SearchActivity extends BaseSingleFragmentActivity{
@Override
protected Fragment createFragment() {
return new T9SearchFragment();
}
@Override
protected boolean isRealTimeLoadFragment() {
return false;
}}
| 134 |
335 | <filename>I/Intermittently_adverb.json
{
"word": "Intermittently",
"definitions": [
"At irregular intervals; not continuously or steadily."
],
"parts-of-speech": "Adverb"
} | 78 |
329 | <gh_stars>100-1000
r##"#pragma once
//for assert
#include <cassert>
//for std::abort
#include <cstdlib>
//for std::move
#include <utility>
#include "c_Foo.h"
namespace org_examples {
class Foo {
public:
using SelfType = FooOpaque *;
using CForeignType = FooOpaque;
Foo(Foo &&o) noexcept: self_(o.self_)
{
o.self_ = nullptr;
}
Foo &operator=(Foo &&o) noexcept
{
assert(this != &o);
free_mem(this->self_);
self_ = o.self_;
o.self_ = nullptr;
return *this;
}
explicit Foo(SelfType o) noexcept: self_(o) {}
FooOpaque *release() noexcept
{
FooOpaque *ret = self_;
self_ = nullptr;
return ret;
}
explicit operator SelfType() const noexcept { return self_; }
Foo(const Foo&) = delete;
Foo &operator=(const Foo&) = delete;
Foo() noexcept
{
this->self_ = Foo_new();
if (this->self_ == nullptr) {
std::abort();
}
}
void method() const noexcept;
static void static_func() noexcept;
private:
static void free_mem(SelfType &p) noexcept
{
if (p != nullptr) {
Foo_delete(p);
}
p = nullptr;
}
public:
~Foo() noexcept
{
free_mem(this->self_);
}
private:
SelfType self_;
};
inline void Foo::method() const noexcept
{
Foo_method(this->self_);
}
inline void Foo::static_func() noexcept
{
Foo_static_func();
}
} // namespace org_examples"##;
r##"#pragma once
namespace org_examples {
class Foo;
} // namespace org_examples"##;
r##"class AppError {
public:
using SelfType = AppErrorOpaque *;
using CForeignType = AppErrorOpaque;
AppError(AppError &&o) noexcept: self_(o.self_)
{
o.self_ = nullptr;
}
AppError &operator=(AppError &&o) noexcept
{
assert(this != &o);
free_mem(this->self_);
self_ = o.self_;
o.self_ = nullptr;
return *this;
}
explicit AppError(SelfType o) noexcept: self_(o) {}
AppErrorOpaque *release() noexcept
{
AppErrorOpaque *ret = self_;
self_ = nullptr;
return ret;
}
explicit operator SelfType() const noexcept { return self_; }
AppError(const AppError& o) noexcept {
if (o.self_ != nullptr) {
self_ = AppError_clone(o.self_);
} else {
self_ = nullptr;
}
}
AppError &operator=(const AppError& o) noexcept {
if (this != &o) {
free_mem(this->self_);
if (o.self_ != nullptr) {
self_ = AppError_clone(o.self_);
} else {
self_ = nullptr;
}
}
return *this;
}
private:
AppError() noexcept {}
public:
AppError clone() const noexcept;
std::string_view err_abbr() const noexcept;
private:
static void free_mem(SelfType &p) noexcept
{
if (p != nullptr) {
AppError_delete(p);
}
p = nullptr;
}
public:
~AppError() noexcept
{
free_mem(this->self_);
}
QString display() const noexcept;
private:
SelfType self_;
};"##;
| 1,572 |
521 | <filename>tests/config/base_tests.cpp
/**
* @file tests/config/base_tests.cpp
* @brief Tests for the @c address module.
* @copyright (c) 2017 Avast Software, licensed under the MIT license
*/
#include <gtest/gtest.h>
#include "retdec/config/base.h"
#include "retdec/config/functions.h"
#include "retdec/config/objects.h"
#include "retdec/config/segments.h"
using namespace ::testing;
namespace retdec {
namespace config {
namespace tests {
//
//=============================================================================
// BaseSequentialContainerTests
//=============================================================================
//
class BaseSequentialContainerTests: public Test
{
public:
BaseSequentialContainerTests() :
obj1("obj1", Storage::inMemory(0x1000)),
obj2("obj2", Storage::inRegister("reg")),
obj3("obj3", Storage::onStack(20)),
obj4("obj4", Storage::undefined())
{
EXPECT_TRUE(objs.empty());
objs.insert(obj1);
objs.insert(obj2);
objs.insert(obj3);
objs.insert(obj4);
EXPECT_EQ(4, objs.size());
}
protected:
Object obj1;
Object obj2;
Object obj3;
Object obj4;
BaseSequentialContainer<Object> objs;
};
TEST_F(BaseSequentialContainerTests, SequentialSimpleMethodsWork)
{
EXPECT_EQ(obj1, *objs.begin());
auto end = objs.end();
--end;
EXPECT_EQ(obj4, *end);
EXPECT_EQ(4, objs.size());
EXPECT_FALSE(objs.empty());
EXPECT_EQ(obj1, objs.front());
objs.clear();
EXPECT_EQ(0, objs.size());
EXPECT_TRUE(objs.empty());
}
TEST_F(BaseSequentialContainerTests, SequentialGetElementByIdWorks)
{
EXPECT_EQ(obj1, *objs.getElementById(obj1.getName()));
EXPECT_EQ(obj2, *objs.getElementById(obj2.getName()));
EXPECT_EQ(obj3, *objs.getElementById(obj3.getName()));
EXPECT_EQ(obj4, *objs.getElementById(obj4.getName()));
}
TEST_F(BaseSequentialContainerTests, SequentialInsertWorks)
{
// This object is unique -> must be added.
//
Object obj5("obj5", Storage::inMemory(0x2000));
EXPECT_EQ(4, objs.size());
objs.insert(obj5);
EXPECT_EQ(5, objs.size());
// This object is not unique -> existing object is updated.
//
Object obj6(obj1.getName(), Storage::inMemory(0x4000));
auto front = objs.front();
EXPECT_EQ(obj1.getStorage().getAddress(), front.getStorage().getAddress());
EXPECT_EQ(5, objs.size());
objs.insert(obj6);
EXPECT_EQ(5, objs.size());
front = objs.front();
EXPECT_EQ(obj6.getStorage().getAddress(), front.getStorage().getAddress());
}
TEST_F(BaseSequentialContainerTests, EmptyContainersAreEqual)
{
BaseSequentialContainer<Object> c1;
BaseSequentialContainer<Object> c2;
EXPECT_TRUE(c1 == c2);
EXPECT_FALSE(c1 != c2);
}
TEST_F(BaseSequentialContainerTests, DifferentSizedContainersAreNotEqual)
{
BaseSequentialContainer<Object> c1;
c1.insert(obj1);
c1.insert(obj2);
c1.insert(obj3);
BaseSequentialContainer<Object> c2;
c2.insert(obj1);
c2.insert(obj2);
EXPECT_FALSE(c1 == c2);
EXPECT_TRUE(c1 != c2);
}
TEST_F(BaseSequentialContainerTests, SameSizedContainersWithDifferentElementsAreNotEqual)
{
BaseSequentialContainer<Object> c1;
c1.insert(obj1);
c1.insert(obj2);
BaseSequentialContainer<Object> c2;
c2.insert(obj3);
c2.insert(obj4);
EXPECT_FALSE(c1 == c2);
EXPECT_TRUE(c1 != c2);
}
TEST_F(BaseSequentialContainerTests, SameSizedContainersWithTheSameElementsAreEqual)
{
BaseSequentialContainer<Object> c1;
c1.insert(obj1);
c1.insert(obj2);
BaseSequentialContainer<Object> c2;
c2.insert(obj1);
c2.insert(obj2);
EXPECT_TRUE(c1 == c2);
EXPECT_FALSE(c1 != c2);
}
//
//=============================================================================
// BaseAssociativeContainerTests
//=============================================================================
//
class BaseAssociativeContainerTests: public Test
{
public:
BaseAssociativeContainerTests() :
fnc1("fnc1"),
fnc2("fnc2")
{
fnc1.setStart(0x1000);
fnc1.setIsStaticallyLinked();
fnc2.setStart(0x2000);
EXPECT_TRUE(fncs.empty());
fncs.insert(fnc1);
fncs.insert(fnc2);
EXPECT_EQ(2, fncs.size());
}
protected:
Function fnc1;
Function fnc2;
BaseAssociativeContainer<std::string, Function> fncs;
};
TEST_F(BaseAssociativeContainerTests, AssociativeSimpleMethodsWork)
{
EXPECT_EQ(fnc1, fncs.begin()->second);
auto end = fncs.end();
--end;
EXPECT_EQ(fnc2, end->second);
EXPECT_EQ(2, fncs.size());
EXPECT_FALSE(fncs.empty());
fncs.clear();
EXPECT_EQ(0, fncs.size());
EXPECT_TRUE(fncs.empty());
}
TEST_F(BaseAssociativeContainerTests, AssociativeGetElementByIdWorks)
{
EXPECT_EQ(fnc1, *fncs.getElementById(fnc1.getName()));
EXPECT_EQ(fnc2, *fncs.getElementById(fnc2.getName()));
}
TEST_F(BaseAssociativeContainerTests, AssociativeInsertWorks)
{
// This object is unique -> must be added.
//
Function fnc3("fnc3");
fnc3.setStart(0x3000);
EXPECT_EQ(2, fncs.size());
fncs.insert(fnc3);
EXPECT_EQ(3, fncs.size());
// This object is not unique -> existing object is updated.
//
Function fnc4(fnc1.getName());
fnc4.setStart(0x4000);
fnc4.setIsDynamicallyLinked();
EXPECT_TRUE(fncs.getElementById(fnc1.getName())->isStaticallyLinked());
EXPECT_EQ(fnc1.getStart(), fncs.getElementById(fnc1.getName())->getStart());
EXPECT_EQ(3, fncs.size());
fncs.insert(fnc4);
EXPECT_EQ(3, fncs.size());
EXPECT_TRUE(fncs.getElementById(fnc1.getName())->isDynamicallyLinked());
EXPECT_EQ(fnc4.getStart(), fncs.getElementById(fnc1.getName())->getStart());
}
//
//=============================================================================
// BaseAssociativeContainerTests
//=============================================================================
//
class BaseSetContainerTests: public Test
{
public:
BaseSetContainerTests() :
seg1(retdec::utils::Address(0x1000)),
seg2(retdec::utils::Address(0x2000))
{
seg1.setName("seg1");
seg1.setComment("comment1");
seg2.setName("seg2");
EXPECT_TRUE(segs.empty());
segs.insert(seg1);
segs.insert(seg2);
EXPECT_EQ(2, segs.size());
}
protected:
Segment seg1;
Segment seg2;
BaseSetContainer<Segment> segs;
};
TEST_F(BaseSetContainerTests, SetSimpleMethodsWork)
{
EXPECT_EQ(seg1, *segs.begin());
auto end = segs.end();
--end;
EXPECT_EQ(seg2, *end);
EXPECT_EQ(2, segs.size());
EXPECT_FALSE(segs.empty());
segs.clear();
EXPECT_EQ(0, segs.size());
EXPECT_TRUE(segs.empty());
}
TEST_F(BaseSetContainerTests, SetInsertWorks)
{
// This object is unique -> must be added.
//
Segment seg3(retdec::utils::Address(0x3000));
seg3.setName("seg3");
EXPECT_EQ(2, segs.size());
segs.insert(seg3);
EXPECT_EQ(3, segs.size());
// This object is not unique -> existing object is updated.
//
Segment seg4(seg1.getStart());
seg4.setName("seg4");
seg4.setComment("comment4");
EXPECT_EQ(seg1.getName(), segs.find(seg1)->getName());
EXPECT_EQ(seg1.getComment(), segs.find(seg1)->getComment());
EXPECT_EQ(3, segs.size());
segs.insert(seg4);
EXPECT_EQ(3, segs.size());
EXPECT_EQ(seg4.getName(), segs.find(seg1)->getName());
EXPECT_EQ(seg4.getComment(), segs.find(seg1)->getComment());
}
} // namespace tests
} // namespace config
} // namespace retdec
| 2,878 |
568 | <reponame>GeekDaniel/bizsocket
package bizsocket.tcp;
/**
* Created by tong on 16/10/19.
*/
public interface PacketPool {
Packet pull();
void push(Packet packet);
}
| 66 |
1,558 | #ifndef AUTOCOMPLETESETTINGSEDITOR_H
#define AUTOCOMPLETESETTINGSEDITOR_H
#include <QWidget>
//#include "ui_autocompletesettingsform.h"
#include "lib/qtmaterialoverlaywidget.h"
class QtMaterialAutoComplete;
class AutoCompleteSettingsEditor : public QWidget
{
Q_OBJECT
public:
explicit AutoCompleteSettingsEditor(QWidget *parent = 0);
~AutoCompleteSettingsEditor();
protected slots:
void setupForm();
void updateWidget();
void selectColor();
private:
//Ui::AutoCompleteSettingsForm *const ui;
QtMaterialAutoComplete *const m_autocomplete;
};
#endif // AUTOCOMPLETESETTINGSEDITOR_H
| 226 |
463 | <filename>client/labml/internal/monitor/__init__.py
import typing
from typing import Optional, List, Union, Tuple
from labml.internal.util.colors import StyleCode
from .iterator import Iterator
from .loop import Loop
from .mix import Mix
from .sections import Section, OuterSection
from ..logger import logger_singleton as logger
from ..logger.types import LogPart
from ..tracker import tracker_singleton as tracker
from ...logger import Text
from ...utils.notice import labml_notice
class Monitor:
__loop_indicators: List[Union[str, Tuple[str, Optional[StyleCode]]]]
__is_looping: bool
def __init__(self):
self.__loop: Optional[Loop] = None
self.__sections: List[Section] = []
self.__is_looping = False
self.__loop_indicators = []
self.__is_silent = False
def clear(self):
self.__loop: Optional[Loop] = None
self.__sections: List[Section] = []
self.__is_looping = False
self.__loop_indicators = []
def silent(self, is_silent: bool = True):
self.__is_silent = is_silent
def mix(self, total_iterations, iterators: List[Tuple[str, typing.Sized]],
is_monit: bool):
return Mix(total_iterations=total_iterations,
iterators=iterators,
is_monit=is_monit, logger=self)
def iterate(self, name, iterable: Union[typing.Iterable, typing.Sized, int],
total_steps: Optional[int], *,
is_silent: bool,
is_children_silent: bool,
is_timed: bool,
section: Optional[Section]):
return Iterator(logger=self,
name=name,
iterable=iterable,
is_silent=is_silent,
is_timed=is_timed,
total_steps=total_steps,
is_children_silent=is_children_silent,
is_enumerate=False,
section=section)
def enum(self, name, iterable: typing.Sized, *,
is_silent: bool,
is_children_silent: bool,
is_timed: bool,
section: Optional[Section]):
return Iterator(logger=self,
name=name,
iterable=iterable,
is_silent=is_silent,
is_timed=is_timed,
total_steps=None,
is_children_silent=is_children_silent,
is_enumerate=True,
section=section)
def section(self, name, *,
is_silent: bool,
is_timed: bool,
is_partial: bool,
is_new_line: bool,
is_children_silent: bool,
total_steps: float) -> Section:
if self.__is_looping:
if len(self.__sections) != 0:
is_silent = True
section = self.__loop.get_section(name=name,
is_silent=is_silent,
is_timed=is_timed,
is_partial=is_partial,
total_steps=total_steps,
parents=[s.name for s in self.__sections])
self.__sections.append(section)
else:
if len(self.__sections) > 0:
if self.__sections[-1].is_silent or self.__sections[-1].is_children_silent:
is_silent = True
is_children_silent = True
self.__sections.append(OuterSection(monitor=self,
name=name,
is_silent=is_silent,
is_timed=is_timed,
is_partial=is_partial,
is_new_line=is_new_line,
is_children_silent=is_children_silent,
total_steps=total_steps,
level=len(self.__sections)))
return self.__sections[-1]
def progress(self, steps: float):
if len(self.__sections) == 0:
raise RuntimeError("You must be within a section to report progress")
if self.__sections[-1].progress(steps):
self.__log_line()
def set_successful(self, is_successful=True):
if len(self.__sections) == 0:
raise RuntimeError("You must be within a section to report success")
self.__sections[-1].is_successful = is_successful
self.__log_line()
def loop(self, iterator_: typing.Collection, *,
is_track: bool,
is_print_iteration_time: bool):
if len(self.__sections) != 0:
labml_notice(['LabML Loop: ', ('Starting loop inside sections', Text.key), '\n',
(
'This could be because some iterators crashed in a previous cell in a notebook.',
Text.meta)],
is_danger=False)
err = RuntimeError('Section outside loop')
for s in reversed(self.__sections):
s.__exit__(type(err), err, err.__traceback__)
# raise RuntimeError("Cannot start a loop within a section")
self.__loop = Loop(iterator=iterator_,
monitor=self,
is_track=is_track,
is_print_iteration_time=is_print_iteration_time)
return self.__loop
def start_loop(self):
self.__is_looping = True
tracker().start_loop(self.set_looping_indicators)
def finish_loop(self):
if len(self.__sections) != 0:
raise RuntimeError("Cannot be within a section when finishing the loop")
tracker().finish_loop()
self.__loop = None
self.__is_looping = False
def section_enter(self, section):
if len(self.__sections) == 0:
raise RuntimeError("Entering a section without creating a section.\n"
"Always use logger.section to create a section")
if section is not self.__sections[-1]:
raise RuntimeError("Entering a section other than the one last_created\n"
"Always user with logger.section(...):")
if len(self.__sections) > 1 and not self.__sections[-2].is_parented:
self.__sections[-2].make_parent()
if not self.__is_silent and not self.__sections[-1].is_silent:
logger().log([])
self.__log_line()
def __log_looping_line(self):
parts = [(f"{tracker().global_step :8,}: ", Text.highlight)]
parts += self.__loop.log_sections()
parts += self.__loop_indicators
parts += self.__loop.log_progress()
if not self.__is_silent:
logger().log(parts, is_new_line=False)
def __log_line(self):
if self.__is_looping:
self.__log_looping_line()
return
if len(self.__sections) == 0:
return
parts = self.__sections[-1].log()
if parts is None:
return
if not self.__is_silent:
logger().log(parts, is_new_line=False)
def set_looping_indicators(self, indicators: List[LogPart]):
self.__loop_indicators = indicators
self.__log_looping_line()
def section_exit(self, section):
if len(self.__sections) == 0:
raise RuntimeError("Impossible")
if section is not self.__sections[-1]:
raise RuntimeError("Impossible")
self.__log_line()
self.__sections.pop(-1)
_internal: Optional[Monitor] = None
def monitor_singleton() -> Monitor:
global _internal
if _internal is None:
_internal = Monitor()
return _internal
| 4,246 |
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.persistence.api.integration;
import java.util.Iterator;
import java.util.ServiceLoader;
import org.jbpm.persistence.api.integration.base.TransactionalPersistenceEventManager;
/**
* Provider of PersistenceEventManager implementation to be used.
* It does discovery via ServiceLoader and if none found returns default implementation
* which is <code>org.jbpm.persistence.api.integration.base.TransactionalPersistenceEventManager</code>
*/
public class EventManagerProvider {
private PersistenceEventManager eventManager;
private EventManagerProvider() {
ServiceLoader<PersistenceEventManager> found = ServiceLoader.load(PersistenceEventManager.class);
Iterator<PersistenceEventManager> it = found.iterator();
if (it.hasNext()) {
eventManager = it.next();
} else {
eventManager = new TransactionalPersistenceEventManager();
}
}
private static class LazyHolder {
static final EventManagerProvider INSTANCE = new EventManagerProvider();
}
public static EventManagerProvider getInstance() {
return LazyHolder.INSTANCE;
}
public PersistenceEventManager get() {
return eventManager;
}
public boolean isActive() {
return eventManager.isActive();
}
}
| 613 |
470 | #pragma once
// project header
#include "Struct/AssetManager/FAssetDependenciesInfo.h"
#include "FExternFileInfo.h"
// engine header
#include "CoreMinimal.h"
#include "FPlatformExternAssets.h"
#include "Engine/EngineTypes.h"
#include "FPatchVersionAssetDiff.generated.h"
USTRUCT(BlueprintType)
struct FPatchVersionAssetDiff
{
GENERATED_USTRUCT_BODY()
public:
FPatchVersionAssetDiff()=default;
FPatchVersionAssetDiff(const FPatchVersionAssetDiff&)=default;
UPROPERTY(EditAnywhere)
FAssetDependenciesInfo AddAssetDependInfo;
UPROPERTY(EditAnywhere)
FAssetDependenciesInfo ModifyAssetDependInfo;
UPROPERTY(EditAnywhere)
FAssetDependenciesInfo DeleteAssetDependInfo;
}; | 267 |
348 | <reponame>chamberone/Leaflet.PixiOverlay
{"nom":"Loudes","circ":"2ème circonscription","dpt":"Haute-Loire","inscrits":761,"abs":409,"votants":352,"blancs":24,"nuls":13,"exp":315,"res":[{"nuance":"LR","nom":"<NAME>","voix":206},{"nuance":"REM","nom":"<NAME>","voix":109}]} | 111 |
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 _XIMPSHAPE_HXX
#define _XIMPSHAPE_HXX
#include <com/sun/star/io/XOutputStream.hpp>
#include <com/sun/star/document/XActionLockable.hpp>
#include <com/sun/star/container/XIdentifierContainer.hpp>
#include <xmloff/xmlictxt.hxx>
#include "sdxmlimp_impl.hxx"
#include <xmloff/nmspmap.hxx>
#include <com/sun/star/drawing/XShapes.hpp>
#include <com/sun/star/text/XTextCursor.hpp>
#include <com/sun/star/awt/Point.hpp>
#include <tools/rtti.hxx>
#include "xexptran.hxx"
#include <vector>
#include <xmloff/shapeimport.hxx>
#include <xmloff/xmlmultiimagehelper.hxx>
#include <basegfx/matrix/b2dhommatrix.hxx>
//////////////////////////////////////////////////////////////////////////////
// common shape context
class SdXMLShapeContext : public SvXMLShapeContext
{
protected:
// the shape group this object should be created inside
com::sun::star::uno::Reference< com::sun::star::drawing::XShapes > mxShapes;
com::sun::star::uno::Reference< com::sun::star::text::XTextCursor > mxCursor;
com::sun::star::uno::Reference< com::sun::star::text::XTextCursor > mxOldCursor;
com::sun::star::uno::Reference< com::sun::star::xml::sax::XAttributeList> mxAttrList;
com::sun::star::uno::Reference< com::sun::star::container::XIdentifierContainer > mxGluePoints;
com::sun::star::uno::Reference< com::sun::star::document::XActionLockable > mxLockable;
rtl::OUString maDrawStyleName;
rtl::OUString maTextStyleName;
rtl::OUString maPresentationClass;
rtl::OUString maShapeName;
rtl::OUString maThumbnailURL;
/// whether to restore list context (#91964#)
bool mbListContextPushed;
sal_uInt16 mnStyleFamily;
sal_uInt16 mnClass;
sal_Bool mbIsPlaceholder;
bool mbClearDefaultAttributes;
sal_Bool mbIsUserTransformed;
sal_Int32 mnZOrder;
rtl::OUString maShapeId;
rtl::OUString maLayerName;
// #i68101#
rtl::OUString maShapeTitle;
rtl::OUString maShapeDescription;
SdXMLImExTransform2D mnTransform;
com::sun::star::awt::Size maSize;
com::sun::star::awt::Point maPosition;
basegfx::B2DHomMatrix maUsedTransformation;
bool mbVisible;
bool mbPrintable;
/** if bSupportsStyle is false, auto styles will be set but not a style */
void SetStyle( bool bSupportsStyle = true );
void SetLayer();
void SetThumbnail();
void AddShape(com::sun::star::uno::Reference< com::sun::star::drawing::XShape >& xShape);
void AddShape(const char* pServiceName );
void SetTransformation();
SvXMLImport& GetImport() { return SvXMLImportContext::GetImport(); }
const SvXMLImport& GetImport() const { return SvXMLImportContext::GetImport(); }
void addGluePoint( const com::sun::star::uno::Reference< com::sun::star::xml::sax::XAttributeList>& xAttrList );
sal_Bool isPresentationShape() const;
public:
TYPEINFO();
SdXMLShapeContext( SvXMLImport& rImport,
sal_uInt16 nPrfx,
const rtl::OUString& rLocalName,
const com::sun::star::uno::Reference< com::sun::star::xml::sax::XAttributeList>& xAttrList,
com::sun::star::uno::Reference< com::sun::star::drawing::XShapes >& rShapes,
sal_Bool bTemporaryShape);
virtual ~SdXMLShapeContext();
virtual void StartElement(const com::sun::star::uno::Reference< com::sun::star::xml::sax::XAttributeList>& xAttrList);
virtual void EndElement();
virtual SvXMLImportContext * CreateChildContext( sal_uInt16 nPrefix, const ::rtl::OUString& rLocalName,
const com::sun::star::uno::Reference< com::sun::star::xml::sax::XAttributeList>& xAttrList );
// this is called from the parent group for each unparsed attribute in the attribute list
virtual void processAttribute( sal_uInt16 nPrefix, const ::rtl::OUString& rLocalName, const ::rtl::OUString& rValue );
/// access to ShapeId for evtl. late adding
const rtl::OUString& getShapeId() const { return maShapeId; }
// allow to copy evtl. useful data from another temporary import context, e.g. used to
// support multiple images
virtual void onDemandRescueUsefulDataFromTemporary( const SvXMLImportContext& rCandidate );
};
//////////////////////////////////////////////////////////////////////////////
// draw:rect context
class SdXMLRectShapeContext : public SdXMLShapeContext
{
sal_Int32 mnRadius;
public:
TYPEINFO();
SdXMLRectShapeContext( SvXMLImport& rImport, sal_uInt16 nPrfx,
const rtl::OUString& rLocalName,
const com::sun::star::uno::Reference< com::sun::star::xml::sax::XAttributeList>& xAttrList,
com::sun::star::uno::Reference< com::sun::star::drawing::XShapes >& rShapes,
sal_Bool bTemporaryShape);
virtual ~SdXMLRectShapeContext();
virtual void StartElement(const com::sun::star::uno::Reference< com::sun::star::xml::sax::XAttributeList>& xAttrList);
// this is called from the parent group for each unparsed attribute in the attribute list
virtual void processAttribute( sal_uInt16 nPrefix, const ::rtl::OUString& rLocalName, const ::rtl::OUString& rValue );
};
//////////////////////////////////////////////////////////////////////////////
// draw:line context
class SdXMLLineShapeContext : public SdXMLShapeContext
{
sal_Int32 mnX1;
sal_Int32 mnY1;
sal_Int32 mnX2;
sal_Int32 mnY2;
public:
TYPEINFO();
SdXMLLineShapeContext( SvXMLImport& rImport, sal_uInt16 nPrfx,
const rtl::OUString& rLocalName,
const com::sun::star::uno::Reference< com::sun::star::xml::sax::XAttributeList>& xAttrList,
com::sun::star::uno::Reference< com::sun::star::drawing::XShapes >& rShapes,
sal_Bool bTemporaryShape);
virtual ~SdXMLLineShapeContext();
virtual void StartElement(const com::sun::star::uno::Reference< com::sun::star::xml::sax::XAttributeList>& xAttrList);
// this is called from the parent group for each unparsed attribute in the attribute list
virtual void processAttribute( sal_uInt16 nPrefix, const ::rtl::OUString& rLocalName, const ::rtl::OUString& rValue );
};
//////////////////////////////////////////////////////////////////////////////
// draw:ellipse and draw:circle context
class SdXMLEllipseShapeContext : public SdXMLShapeContext
{
sal_Int32 mnCX;
sal_Int32 mnCY;
sal_Int32 mnRX;
sal_Int32 mnRY;
sal_uInt16 meKind;
sal_Int32 mnStartAngle;
sal_Int32 mnEndAngle;
public:
TYPEINFO();
SdXMLEllipseShapeContext( SvXMLImport& rImport, sal_uInt16 nPrfx,
const rtl::OUString& rLocalName,
const com::sun::star::uno::Reference< com::sun::star::xml::sax::XAttributeList>& xAttrList,
com::sun::star::uno::Reference< com::sun::star::drawing::XShapes >& rShapes,
sal_Bool bTemporaryShape);
virtual ~SdXMLEllipseShapeContext();
virtual void StartElement(const com::sun::star::uno::Reference< com::sun::star::xml::sax::XAttributeList>& xAttrList);
// this is called from the parent group for each unparsed attribute in the attribute list
virtual void processAttribute( sal_uInt16 nPrefix, const ::rtl::OUString& rLocalName, const ::rtl::OUString& rValue );
};
//////////////////////////////////////////////////////////////////////////////
// draw:polyline and draw:polygon context
class SdXMLPolygonShapeContext : public SdXMLShapeContext
{
rtl::OUString maPoints;
rtl::OUString maViewBox;
sal_Bool mbClosed;
public:
TYPEINFO();
SdXMLPolygonShapeContext( SvXMLImport& rImport, sal_uInt16 nPrfx,
const rtl::OUString& rLocalName,
const com::sun::star::uno::Reference< com::sun::star::xml::sax::XAttributeList>& xAttrList,
com::sun::star::uno::Reference< com::sun::star::drawing::XShapes >& rShapes, sal_Bool bClosed, sal_Bool bTemporaryShape);
virtual ~SdXMLPolygonShapeContext();
virtual void StartElement(const com::sun::star::uno::Reference< com::sun::star::xml::sax::XAttributeList>& xAttrList);
// this is called from the parent group for each unparsed attribute in the attribute list
virtual void processAttribute( sal_uInt16 nPrefix, const ::rtl::OUString& rLocalName, const ::rtl::OUString& rValue );
};
//////////////////////////////////////////////////////////////////////////////
// draw:path context
class SdXMLPathShapeContext : public SdXMLShapeContext
{
rtl::OUString maD;
rtl::OUString maViewBox;
sal_Bool mbClosed;
public:
TYPEINFO();
SdXMLPathShapeContext( SvXMLImport& rImport, sal_uInt16 nPrfx,
const rtl::OUString& rLocalName,
const com::sun::star::uno::Reference< com::sun::star::xml::sax::XAttributeList>& xAttrList,
com::sun::star::uno::Reference< com::sun::star::drawing::XShapes >& rShapes,
sal_Bool bTemporaryShape);
virtual ~SdXMLPathShapeContext();
virtual void StartElement(const com::sun::star::uno::Reference< com::sun::star::xml::sax::XAttributeList>& xAttrList);
// this is called from the parent group for each unparsed attribute in the attribute list
virtual void processAttribute( sal_uInt16 nPrefix, const ::rtl::OUString& rLocalName, const ::rtl::OUString& rValue );
};
//////////////////////////////////////////////////////////////////////////////
// draw:text-box context
class SdXMLTextBoxShapeContext : public SdXMLShapeContext
{
sal_Int32 mnRadius;
public:
TYPEINFO();
SdXMLTextBoxShapeContext( SvXMLImport& rImport, sal_uInt16 nPrfx,
const rtl::OUString& rLocalName,
const com::sun::star::uno::Reference< com::sun::star::xml::sax::XAttributeList>& xAttrList,
com::sun::star::uno::Reference< com::sun::star::drawing::XShapes >& rShapes,
sal_Bool bTemporaryShape);
virtual ~SdXMLTextBoxShapeContext();
virtual void StartElement(const com::sun::star::uno::Reference< com::sun::star::xml::sax::XAttributeList>& xAttrList);
// this is called from the parent group for each unparsed attribute in the attribute list
virtual void processAttribute( sal_uInt16 nPrefix, const ::rtl::OUString& rLocalName, const ::rtl::OUString& rValue );
};
//////////////////////////////////////////////////////////////////////////////
// draw:control context
class SdXMLControlShapeContext : public SdXMLShapeContext
{
private:
rtl::OUString maFormId;
public:
TYPEINFO();
SdXMLControlShapeContext( SvXMLImport& rImport, sal_uInt16 nPrfx,
const rtl::OUString& rLocalName,
const com::sun::star::uno::Reference< com::sun::star::xml::sax::XAttributeList>& xAttrList,
com::sun::star::uno::Reference< com::sun::star::drawing::XShapes >& rShapes,
sal_Bool bTemporaryShape);
virtual ~SdXMLControlShapeContext();
virtual void StartElement(const com::sun::star::uno::Reference< com::sun::star::xml::sax::XAttributeList>& xAttrList);
// this is called from the parent group for each unparsed attribute in the attribute list
virtual void processAttribute( sal_uInt16 nPrefix, const ::rtl::OUString& rLocalName, const ::rtl::OUString& rValue );
};
//////////////////////////////////////////////////////////////////////////////
// draw:connector context
class SdXMLConnectorShapeContext : public SdXMLShapeContext
{
private:
::com::sun::star::awt::Point maStart;
::com::sun::star::awt::Point maEnd;
sal_uInt16 mnType;
rtl::OUString maStartShapeId;
sal_Int32 mnStartGlueId;
rtl::OUString maEndShapeId;
sal_Int32 mnEndGlueId;
sal_Int32 mnDelta1;
sal_Int32 mnDelta2;
sal_Int32 mnDelta3;
com::sun::star::uno::Any maPath;
public:
TYPEINFO();
SdXMLConnectorShapeContext( SvXMLImport& rImport, sal_uInt16 nPrfx,
const rtl::OUString& rLocalName,
const com::sun::star::uno::Reference< com::sun::star::xml::sax::XAttributeList>& xAttrList,
com::sun::star::uno::Reference< com::sun::star::drawing::XShapes >& rShapes,
sal_Bool bTemporaryShape);
virtual ~SdXMLConnectorShapeContext();
virtual void StartElement(const com::sun::star::uno::Reference< com::sun::star::xml::sax::XAttributeList>& xAttrList);
// this is called from the parent group for each unparsed attribute in the attribute list
virtual void processAttribute( sal_uInt16 nPrefix, const ::rtl::OUString& rLocalName, const ::rtl::OUString& rValue );
};
//////////////////////////////////////////////////////////////////////////////
// draw:measure context
class SdXMLMeasureShapeContext : public SdXMLShapeContext
{
private:
::com::sun::star::awt::Point maStart;
::com::sun::star::awt::Point maEnd;
public:
TYPEINFO();
SdXMLMeasureShapeContext( SvXMLImport& rImport, sal_uInt16 nPrfx,
const rtl::OUString& rLocalName,
const com::sun::star::uno::Reference< com::sun::star::xml::sax::XAttributeList>& xAttrList,
com::sun::star::uno::Reference< com::sun::star::drawing::XShapes >& rShapes,
sal_Bool bTemporaryShape);
virtual ~SdXMLMeasureShapeContext();
virtual void StartElement(const com::sun::star::uno::Reference< com::sun::star::xml::sax::XAttributeList>& xAttrList);
virtual void EndElement();
// this is called from the parent group for each unparsed attribute in the attribute list
virtual void processAttribute( sal_uInt16 nPrefix, const ::rtl::OUString& rLocalName, const ::rtl::OUString& rValue );
};
//////////////////////////////////////////////////////////////////////////////
// draw:page context
class SdXMLPageShapeContext : public SdXMLShapeContext
{
private:
sal_Int32 mnPageNumber;
public:
TYPEINFO();
SdXMLPageShapeContext( SvXMLImport& rImport, sal_uInt16 nPrfx,
const rtl::OUString& rLocalName,
const com::sun::star::uno::Reference< com::sun::star::xml::sax::XAttributeList>& xAttrList,
com::sun::star::uno::Reference< com::sun::star::drawing::XShapes >& rShapes,
sal_Bool bTemporaryShape);
virtual ~SdXMLPageShapeContext();
virtual void StartElement(const com::sun::star::uno::Reference< com::sun::star::xml::sax::XAttributeList>& xAttrList);
// this is called from the parent group for each unparsed attribute in the attribute list
virtual void processAttribute( sal_uInt16 nPrefix, const ::rtl::OUString& rLocalName, const ::rtl::OUString& rValue );
};
//////////////////////////////////////////////////////////////////////////////
// draw:caption context
class SdXMLCaptionShapeContext : public SdXMLShapeContext
{
private:
com::sun::star::awt::Point maCaptionPoint;
sal_Int32 mnRadius;
public:
TYPEINFO();
SdXMLCaptionShapeContext( SvXMLImport& rImport, sal_uInt16 nPrfx,
const rtl::OUString& rLocalName,
const com::sun::star::uno::Reference< com::sun::star::xml::sax::XAttributeList>& xAttrList,
com::sun::star::uno::Reference< com::sun::star::drawing::XShapes >& rShapes,
sal_Bool bTemporaryShape);
virtual ~SdXMLCaptionShapeContext();
virtual void StartElement(const com::sun::star::uno::Reference< com::sun::star::xml::sax::XAttributeList>& xAttrList);
// this is called from the parent group for each unparsed attribute in the attribute list
virtual void processAttribute( sal_uInt16 nPrefix, const ::rtl::OUString& rLocalName, const ::rtl::OUString& rValue );
};
//////////////////////////////////////////////////////////////////////////////
// office:image context
class SdXMLGraphicObjectShapeContext : public SdXMLShapeContext
{
private:
::rtl::OUString maURL;
::com::sun::star::uno::Reference < ::com::sun::star::io::XOutputStream > mxBase64Stream;
/// bitfield
bool mbLateAddToIdentifierMapper : 1;
public:
TYPEINFO();
SdXMLGraphicObjectShapeContext( SvXMLImport& rImport, sal_uInt16 nPrfx,
const rtl::OUString& rLocalName,
const com::sun::star::uno::Reference< com::sun::star::xml::sax::XAttributeList>& xAttrList,
com::sun::star::uno::Reference< com::sun::star::drawing::XShapes >& rShapes,
sal_Bool bTemporaryShape);
virtual ~SdXMLGraphicObjectShapeContext();
virtual void StartElement( const ::com::sun::star::uno::Reference< ::com::sun::star::xml::sax::XAttributeList >& xAttrList );
virtual void EndElement();
virtual SvXMLImportContext * CreateChildContext( sal_uInt16 nPrefix, const ::rtl::OUString& rLocalName,
const com::sun::star::uno::Reference< com::sun::star::xml::sax::XAttributeList>& xAttrList );
// this is called from the parent group for each unparsed attribute in the attribute list
virtual void processAttribute( sal_uInt16 nPrefix, const ::rtl::OUString& rLocalName, const ::rtl::OUString& rValue );
/// support for LateAddToIdentifierMapper
bool getLateAddToIdentifierMapper() const { return mbLateAddToIdentifierMapper; }
void setLateAddToIdentifierMapper(bool bNew) { mbLateAddToIdentifierMapper = bNew; }
};
//////////////////////////////////////////////////////////////////////////////
// chart:chart context
class SdXMLChartShapeContext : public SdXMLShapeContext
{
SvXMLImportContext* mpChartContext;
public:
TYPEINFO();
SdXMLChartShapeContext( SvXMLImport& rImport, sal_uInt16 nPrfx,
const rtl::OUString& rLocalName,
const com::sun::star::uno::Reference< com::sun::star::xml::sax::XAttributeList>& xAttrList,
com::sun::star::uno::Reference< com::sun::star::drawing::XShapes >& rShapes,
sal_Bool bTemporaryShape);
virtual ~SdXMLChartShapeContext();
virtual void StartElement( const ::com::sun::star::uno::Reference< ::com::sun::star::xml::sax::XAttributeList >& xAttrList );
virtual void EndElement();
virtual void Characters( const ::rtl::OUString& rChars );
virtual SvXMLImportContext * CreateChildContext( sal_uInt16 nPrefix, const ::rtl::OUString& rLocalName,
const com::sun::star::uno::Reference< com::sun::star::xml::sax::XAttributeList>& xAttrList );
};
//////////////////////////////////////////////////////////////////////////////
// draw:object and draw:object_ole context
class SdXMLObjectShapeContext : public SdXMLShapeContext
{
private:
rtl::OUString maCLSID;
rtl::OUString maHref;
// #100592#
::com::sun::star::uno::Reference < ::com::sun::star::io::XOutputStream > mxBase64Stream;
public:
TYPEINFO();
SdXMLObjectShapeContext( SvXMLImport& rImport, sal_uInt16 nPrfx,
const rtl::OUString& rLocalName,
const com::sun::star::uno::Reference< com::sun::star::xml::sax::XAttributeList>& xAttrList,
com::sun::star::uno::Reference< com::sun::star::drawing::XShapes >& rShapes,
sal_Bool bTemporaryShape);
virtual ~SdXMLObjectShapeContext();
virtual void StartElement( const ::com::sun::star::uno::Reference< ::com::sun::star::xml::sax::XAttributeList >& xAttrList );
virtual void EndElement();
// #100592#
virtual SvXMLImportContext * CreateChildContext( sal_uInt16 nPrefix, const ::rtl::OUString& rLocalName,
const com::sun::star::uno::Reference< com::sun::star::xml::sax::XAttributeList>& xAttrList );
// this is called from the parent group for each unparsed attribute in the attribute list
virtual void processAttribute( sal_uInt16 nPrefix, const ::rtl::OUString& rLocalName, const ::rtl::OUString& rValue );
};
//////////////////////////////////////////////////////////////////////////////
// draw:applet
class SdXMLAppletShapeContext : public SdXMLShapeContext
{
private:
rtl::OUString maAppletName;
rtl::OUString maAppletCode;
rtl::OUString maHref;
sal_Bool mbIsScript;
com::sun::star::uno::Sequence< com::sun::star::beans::PropertyValue > maParams;
public:
TYPEINFO();
SdXMLAppletShapeContext( SvXMLImport& rImport, sal_uInt16 nPrfx,
const rtl::OUString& rLocalName,
const com::sun::star::uno::Reference< com::sun::star::xml::sax::XAttributeList>& xAttrList,
com::sun::star::uno::Reference< com::sun::star::drawing::XShapes >& rShapes,
sal_Bool bTemporaryShape);
virtual ~SdXMLAppletShapeContext();
virtual void StartElement( const ::com::sun::star::uno::Reference< ::com::sun::star::xml::sax::XAttributeList >& xAttrList );
virtual void EndElement();
virtual SvXMLImportContext * CreateChildContext( sal_uInt16 nPrefix, const ::rtl::OUString& rLocalName,
const com::sun::star::uno::Reference< com::sun::star::xml::sax::XAttributeList>& xAttrList );
// this is called from the parent group for each unparsed attribute in the attribute list
virtual void processAttribute( sal_uInt16 nPrefix, const ::rtl::OUString& rLocalName, const ::rtl::OUString& rValue );
};
//////////////////////////////////////////////////////////////////////////////
// draw:plugin
class SdXMLPluginShapeContext : public SdXMLShapeContext
{
private:
rtl::OUString maMimeType;
rtl::OUString maHref;
bool mbMedia;
com::sun::star::uno::Sequence< com::sun::star::beans::PropertyValue > maParams;
public:
TYPEINFO();
SdXMLPluginShapeContext( SvXMLImport& rImport, sal_uInt16 nPrfx,
const rtl::OUString& rLocalName,
const com::sun::star::uno::Reference< com::sun::star::xml::sax::XAttributeList>& xAttrList,
com::sun::star::uno::Reference< com::sun::star::drawing::XShapes >& rShapes,
sal_Bool bTemporaryShape);
virtual ~SdXMLPluginShapeContext();
virtual void StartElement( const ::com::sun::star::uno::Reference< ::com::sun::star::xml::sax::XAttributeList >& xAttrList );
virtual void EndElement();
virtual SvXMLImportContext * CreateChildContext( sal_uInt16 nPrefix, const ::rtl::OUString& rLocalName,
const com::sun::star::uno::Reference< com::sun::star::xml::sax::XAttributeList>& xAttrList );
// this is called from the parent group for each unparsed attribute in the attribute list
virtual void processAttribute( sal_uInt16 nPrefix, const ::rtl::OUString& rLocalName, const ::rtl::OUString& rValue );
};
//////////////////////////////////////////////////////////////////////////////
// draw:floating-frame
class SdXMLFloatingFrameShapeContext : public SdXMLShapeContext
{
private:
rtl::OUString maFrameName;
rtl::OUString maHref;
public:
TYPEINFO();
SdXMLFloatingFrameShapeContext( SvXMLImport& rImport, sal_uInt16 nPrfx,
const rtl::OUString& rLocalName,
const com::sun::star::uno::Reference< com::sun::star::xml::sax::XAttributeList>& xAttrList,
com::sun::star::uno::Reference< com::sun::star::drawing::XShapes >& rShapes,
sal_Bool bTemporaryShape);
virtual ~SdXMLFloatingFrameShapeContext();
virtual void StartElement( const ::com::sun::star::uno::Reference< ::com::sun::star::xml::sax::XAttributeList >& xAttrList );
virtual void EndElement();
// this is called from the parent group for each unparsed attribute in the attribute list
virtual void processAttribute( sal_uInt16 nPrefix, const ::rtl::OUString& rLocalName, const ::rtl::OUString& rValue );
};
//////////////////////////////////////////////////////////////////////////////
// draw:-frame
class SdXMLFrameShapeContext : public SdXMLShapeContext, public multiImageImportHelper
{
private:
sal_Bool mbSupportsReplacement;
SvXMLImportContextRef mxImplContext;
SvXMLImportContextRef mxReplImplContext;
protected:
/// helper to get the created xShape instance, needs to be overloaded
virtual rtl::OUString getGraphicURLFromImportContext(const SvXMLImportContext& rContext) const;
virtual void removeGraphicFromImportContext(const SvXMLImportContext& rContext) const;
public:
TYPEINFO();
SdXMLFrameShapeContext( SvXMLImport& rImport, sal_uInt16 nPrfx,
const rtl::OUString& rLocalName,
const com::sun::star::uno::Reference< com::sun::star::xml::sax::XAttributeList>& xAttrList,
com::sun::star::uno::Reference< com::sun::star::drawing::XShapes >& rShapes,
sal_Bool bTemporaryShape);
virtual ~SdXMLFrameShapeContext();
virtual SvXMLImportContext * CreateChildContext( sal_uInt16 nPrefix, const ::rtl::OUString& rLocalName,
const com::sun::star::uno::Reference< com::sun::star::xml::sax::XAttributeList>& xAttrList );
virtual void StartElement( const ::com::sun::star::uno::Reference< ::com::sun::star::xml::sax::XAttributeList >& xAttrList );
virtual void EndElement();
virtual void processAttribute( sal_uInt16 nPrefix, const ::rtl::OUString& rLocalName, const ::rtl::OUString& rValue );
};
class SdXMLCustomShapeContext : public SdXMLShapeContext
{
protected :
rtl::OUString maCustomShapeEngine;
rtl::OUString maCustomShapeData;
std::vector< com::sun::star::beans::PropertyValue > maCustomShapeGeometry;
public:
TYPEINFO();
SdXMLCustomShapeContext( SvXMLImport& rImport, sal_uInt16 nPrfx, const rtl::OUString& rLocalName,
const com::sun::star::uno::Reference< com::sun::star::xml::sax::XAttributeList>& xAttrList,
com::sun::star::uno::Reference< com::sun::star::drawing::XShapes >& rShapes,
sal_Bool bTemporaryShape);
virtual ~SdXMLCustomShapeContext();
virtual void StartElement( const com::sun::star::uno::Reference< com::sun::star::xml::sax::XAttributeList>& xAttrList );
virtual void EndElement();
virtual SvXMLImportContext * CreateChildContext( sal_uInt16 nPrefix, const ::rtl::OUString& rLocalName,
const com::sun::star::uno::Reference< com::sun::star::xml::sax::XAttributeList>& xAttrList );
// this is called from the parent group for each unparsed attribute in the attribute list
virtual void processAttribute( sal_uInt16 nPrefix, const ::rtl::OUString& rLocalName, const ::rtl::OUString& rValue );
};
//////////////////////////////////////////////////////////////////////////////
// draw:table
class SdXMLTableShapeContext : public SdXMLShapeContext
{
public:
TYPEINFO();
SdXMLTableShapeContext( SvXMLImport& rImport, sal_uInt16 nPrfx,
const rtl::OUString& rLocalName,
const com::sun::star::uno::Reference< com::sun::star::xml::sax::XAttributeList>& xAttrList,
com::sun::star::uno::Reference< com::sun::star::drawing::XShapes >& rShapes );
virtual ~SdXMLTableShapeContext();
virtual void StartElement( const ::com::sun::star::uno::Reference< ::com::sun::star::xml::sax::XAttributeList >& xAttrList );
virtual void EndElement();
virtual SvXMLImportContext * CreateChildContext( sal_uInt16 nPrefix, const ::rtl::OUString& rLocalName, const com::sun::star::uno::Reference< com::sun::star::xml::sax::XAttributeList>& xAttrList );
// this is called from the parent group for each unparsed attribute in the attribute list
virtual void processAttribute( sal_uInt16 nPrefix, const ::rtl::OUString& rLocalName, const ::rtl::OUString& rValue );
private:
SvXMLImportContextRef mxTableImportContext;
rtl::OUString msTemplateStyleName;
sal_Bool maTemplateStylesUsed[6];
};
#endif // _XIMPSHAPE_HXX
| 9,075 |
585 | <reponame>KevinKecc/caffe2<gh_stars>100-1000
/**
* Copyright (c) 2016-present, Facebook, 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.
*/
#ifndef CAFFE2_OPERATORS_REDUCTION_OPS_H_
#define CAFFE2_OPERATORS_REDUCTION_OPS_H_
#include "caffe2/core/common_omp.h"
#include "caffe2/core/context.h"
#include "caffe2/core/logging.h"
#include "caffe2/core/operator.h"
#include "caffe2/utils/math.h"
namespace caffe2 {
template <typename T, class Context>
class SumElementsOp : public Operator<Context> {
public:
USE_OPERATOR_CONTEXT_FUNCTIONS;
SumElementsOp(const OperatorDef& operator_def, Workspace* ws)
: Operator<Context>(operator_def, ws),
average_(OperatorBase::GetSingleArgument<bool>("average", false)) {}
SumElementsOp(const OperatorDef& operator_def, Workspace* ws, bool average)
: Operator<Context>(operator_def, ws), average_(average) {}
~SumElementsOp() {}
bool RunOnDevice() override
// TODO: T21635002 fix float-divide-by-zero undefined behavior
#if defined(__has_feature)
#if __has_feature(__address_sanitizer__)
__attribute__((__no_sanitize__("float-divide-by-zero")))
#endif
#endif
{
auto& X = Input(0);
auto* sum = Output(0);
sum->Resize(vector<TIndex>());
T* data = sum->template mutable_data<T>();
math::Sum<T, Context>(
X.size(), X.template data<T>(), data, &context_, &scratch_);
if (average_) {
math::Scale<T, Context>(
1,
static_cast<T>(1.) / X.size(),
sum->template data<T>(),
data,
&context_);
}
return true;
}
private:
bool average_;
Tensor<Context> scratch_;
};
template <typename T, class Context>
class SumElementsGradientOp : public Operator<Context> {
public:
USE_OPERATOR_CONTEXT_FUNCTIONS;
SumElementsGradientOp(const OperatorDef& operator_def, Workspace* ws)
: Operator<Context>(operator_def, ws),
average_(OperatorBase::GetSingleArgument<bool>("average", false)) {}
SumElementsGradientOp(
const OperatorDef& operator_def,
Workspace* ws,
bool average)
: Operator<Context>(operator_def, ws), average_(average) {}
~SumElementsGradientOp() {}
bool RunOnDevice() override;
private:
bool average_;
};
template <class Context>
class SumSqrElementsOp : public Operator<Context> {
public:
USE_SIMPLE_CTOR_DTOR(SumSqrElementsOp)
USE_OPERATOR_CONTEXT_FUNCTIONS;
bool RunOnDevice() override {
return DispatchHelper<TensorTypes<float>>::call(this, Input(0));
}
template <typename T>
bool DoRunWithType() {
bool average = OperatorBase::GetSingleArgument<bool>("average", false);
auto& X = Input(0);
auto* sum = Output(0);
sum->Resize(vector<TIndex>());
math::SumSqr<T, Context>(
X.size(),
X.template data<T>(),
sum->template mutable_data<T>(),
&context_,
&scratch_);
if (average) {
math::Scale<T, Context>(
1,
float(1.) / X.size(),
sum->template data<T>(),
sum->template mutable_data<T>(),
&context_);
}
return true;
}
private:
Tensor<Context> scratch_;
};
template <typename T, class Context, bool ROWWISE>
class MaxReductionOp : public Operator<Context> {
public:
USE_SIMPLE_CTOR_DTOR(MaxReductionOp)
USE_OPERATOR_CONTEXT_FUNCTIONS;
bool RunOnDevice() override {
auto& X = Input(0);
CAFFE_ENFORCE_EQ(X.ndim(), 3);
const int batch_size = X.dim32(0);
const int M = X.dim32(1);
const int N = X.dim32(2);
auto* Y = Output(0);
ROWWISE ? Y->Resize(batch_size, M) : Y->Resize(batch_size, N);
if (ROWWISE) {
math::RowwiseMax<T, Context>(
batch_size * M,
N,
X.template data<T>(),
Y->template mutable_data<T>(),
&context_);
} else {
const int input_size = N * M;
for (int i = 0; i < batch_size; ++i) {
math::ColwiseMax<T, Context>(
M,
N,
X.template data<T>() + i * input_size,
Y->template mutable_data<T>() + i * N,
&context_);
}
}
return true;
}
};
template <typename T, class Context, bool ROWWISE>
class MaxReductionGradientOp : public Operator<Context> {
public:
USE_SIMPLE_CTOR_DTOR(MaxReductionGradientOp)
USE_OPERATOR_CONTEXT_FUNCTIONS;
bool RunOnDevice() override;
};
} // namespace caffe2
#endif
| 1,995 |
473 | <reponame>metc/especial-backend
/*
* Tester for VSCARD protocol, client side.
*
* Can be used with ccid-card-passthru.
*
* Copyright (c) 2011 Red Hat.
* Written by <NAME>.
*
* This work is licensed under the terms of the GNU LGPL, version 2.1 or later.
* See the COPYING.LIB file in the top-level directory.
*/
#ifndef _WIN32
#include <sys/socket.h>
#include <netinet/in.h>
#include <netdb.h>
#define closesocket(x) close(x)
#endif
#include "qemu-common.h"
#include "vscard_common.h"
#include "vreader.h"
#include "vcard_emul.h"
#include "vevent.h"
static int verbose;
static void
print_byte_array(
uint8_t *arrBytes,
unsigned int nSize
) {
int i;
for (i = 0; i < nSize; i++) {
printf("%02X ", arrBytes[i]);
}
printf("\n");
}
static void
print_usage(void) {
printf("vscclient [-c <certname> .. -e <emul_args> -d <level>%s] "
"<host> <port>\n",
#ifdef USE_PASSTHRU
" -p");
printf(" -p use passthrough mode\n");
#else
"");
#endif
vcard_emul_usage();
}
static GIOChannel *channel_socket;
static GByteArray *socket_to_send;
static CompatGMutex socket_to_send_lock;
static guint socket_tag;
static void
update_socket_watch(void);
static gboolean
do_socket_send(GIOChannel *source,
GIOCondition condition,
gpointer data)
{
gsize bw;
GError *err = NULL;
g_return_val_if_fail(socket_to_send->len != 0, FALSE);
g_return_val_if_fail(condition & G_IO_OUT, FALSE);
g_io_channel_write_chars(channel_socket,
(gchar *)socket_to_send->data, socket_to_send->len, &bw, &err);
if (err != NULL) {
g_error("Error while sending socket %s", err->message);
return FALSE;
}
g_byte_array_remove_range(socket_to_send, 0, bw);
if (socket_to_send->len == 0) {
update_socket_watch();
return FALSE;
}
return TRUE;
}
static gboolean
socket_prepare_sending(gpointer user_data)
{
update_socket_watch();
return FALSE;
}
static int
send_msg(
VSCMsgType type,
uint32_t reader_id,
const void *msg,
unsigned int length
) {
VSCMsgHeader mhHeader;
g_mutex_lock(&socket_to_send_lock);
if (verbose > 10) {
printf("sending type=%d id=%u, len =%u (0x%x)\n",
type, reader_id, length, length);
}
mhHeader.type = htonl(type);
mhHeader.reader_id = 0;
mhHeader.length = htonl(length);
g_byte_array_append(socket_to_send, (guint8 *)&mhHeader, sizeof(mhHeader));
g_byte_array_append(socket_to_send, (guint8 *)msg, length);
g_idle_add(socket_prepare_sending, NULL);
g_mutex_unlock(&socket_to_send_lock);
return 0;
}
static VReader *pending_reader;
static CompatGMutex pending_reader_lock;
static CompatGCond pending_reader_condition;
#define MAX_ATR_LEN 40
static gpointer
event_thread(gpointer arg)
{
unsigned char atr[MAX_ATR_LEN];
int atr_len;
VEvent *event;
unsigned int reader_id;
while (1) {
const char *reader_name;
event = vevent_wait_next_vevent();
if (event == NULL) {
break;
}
reader_id = vreader_get_id(event->reader);
if (reader_id == VSCARD_UNDEFINED_READER_ID &&
event->type != VEVENT_READER_INSERT) {
/* ignore events from readers qemu has rejected */
/* if qemu is still deciding on this reader, wait to see if need to
* forward this event */
g_mutex_lock(&pending_reader_lock);
if (!pending_reader || (pending_reader != event->reader)) {
/* wasn't for a pending reader, this reader has already been
* rejected by qemu */
g_mutex_unlock(&pending_reader_lock);
vevent_delete(event);
continue;
}
/* this reader hasn't been told its status from qemu yet, wait for
* that status */
while (pending_reader != NULL) {
g_cond_wait(&pending_reader_condition, &pending_reader_lock);
}
g_mutex_unlock(&pending_reader_lock);
/* now recheck the id */
reader_id = vreader_get_id(event->reader);
if (reader_id == VSCARD_UNDEFINED_READER_ID) {
/* this reader was rejected */
vevent_delete(event);
continue;
}
/* reader was accepted, now forward the event */
}
switch (event->type) {
case VEVENT_READER_INSERT:
/* tell qemu to insert a new CCID reader */
/* wait until qemu has responded to our first reader insert
* before we send a second. That way we won't confuse the responses
* */
g_mutex_lock(&pending_reader_lock);
while (pending_reader != NULL) {
g_cond_wait(&pending_reader_condition, &pending_reader_lock);
}
pending_reader = vreader_reference(event->reader);
g_mutex_unlock(&pending_reader_lock);
reader_name = vreader_get_name(event->reader);
if (verbose > 10) {
printf(" READER INSERT: %s\n", reader_name);
}
send_msg(VSC_ReaderAdd,
reader_id, /* currerntly VSCARD_UNDEFINED_READER_ID */
NULL, 0 /* TODO reader_name, strlen(reader_name) */);
break;
case VEVENT_READER_REMOVE:
/* future, tell qemu that an old CCID reader has been removed */
if (verbose > 10) {
printf(" READER REMOVE: %u\n", reader_id);
}
send_msg(VSC_ReaderRemove, reader_id, NULL, 0);
break;
case VEVENT_CARD_INSERT:
/* get the ATR (intended as a response to a power on from the
* reader */
atr_len = MAX_ATR_LEN;
vreader_power_on(event->reader, atr, &atr_len);
/* ATR call functions as a Card Insert event */
if (verbose > 10) {
printf(" CARD INSERT %u: ", reader_id);
print_byte_array(atr, atr_len);
}
send_msg(VSC_ATR, reader_id, atr, atr_len);
break;
case VEVENT_CARD_REMOVE:
/* Card removed */
if (verbose > 10) {
printf(" CARD REMOVE %u:\n", reader_id);
}
send_msg(VSC_CardRemove, reader_id, NULL, 0);
break;
default:
break;
}
vevent_delete(event);
}
return NULL;
}
static unsigned int
get_id_from_string(char *string, unsigned int default_id)
{
unsigned int id = atoi(string);
/* don't accidentally swith to zero because no numbers have been supplied */
if ((id == 0) && *string != '0') {
return default_id;
}
return id;
}
static int
on_host_init(VSCMsgHeader *mhHeader, VSCMsgInit *incoming)
{
uint32_t *capabilities = (incoming->capabilities);
int num_capabilities =
1 + ((mhHeader->length - sizeof(VSCMsgInit)) / sizeof(uint32_t));
int i;
incoming->version = ntohl(incoming->version);
if (incoming->version != VSCARD_VERSION) {
if (verbose > 0) {
printf("warning: host has version %d, we have %d\n",
verbose, VSCARD_VERSION);
}
}
if (incoming->magic != VSCARD_MAGIC) {
printf("unexpected magic: got %d, expected %d\n",
incoming->magic, VSCARD_MAGIC);
return -1;
}
for (i = 0 ; i < num_capabilities; ++i) {
capabilities[i] = ntohl(capabilities[i]);
}
/* Future: check capabilities */
/* remove whatever reader might be left in qemu,
* in case of an unclean previous exit. */
send_msg(VSC_ReaderRemove, VSCARD_MINIMAL_READER_ID, NULL, 0);
/* launch the event_thread. This will trigger reader adds for all the
* existing readers */
g_thread_new("vsc/event", event_thread, NULL);
return 0;
}
enum {
STATE_HEADER,
STATE_MESSAGE,
};
#define APDUBufSize 270
static gboolean
do_socket_read(GIOChannel *source,
GIOCondition condition,
gpointer data)
{
int rv;
int dwSendLength;
int dwRecvLength;
uint8_t pbRecvBuffer[APDUBufSize];
static uint8_t pbSendBuffer[APDUBufSize];
VReaderStatus reader_status;
VReader *reader = NULL;
static VSCMsgHeader mhHeader;
VSCMsgError *error_msg;
GError *err = NULL;
static gchar *buf;
static gsize br, to_read;
static int state = STATE_HEADER;
if (state == STATE_HEADER && to_read == 0) {
buf = (gchar *)&mhHeader;
to_read = sizeof(mhHeader);
}
if (to_read > 0) {
g_io_channel_read_chars(source, (gchar *)buf, to_read, &br, &err);
if (err != NULL) {
g_error("error while reading: %s", err->message);
}
buf += br;
to_read -= br;
if (to_read != 0) {
return TRUE;
}
}
if (state == STATE_HEADER) {
mhHeader.type = ntohl(mhHeader.type);
mhHeader.reader_id = ntohl(mhHeader.reader_id);
mhHeader.length = ntohl(mhHeader.length);
if (verbose) {
printf("Header: type=%d, reader_id=%u length=%d (0x%x)\n",
mhHeader.type, mhHeader.reader_id, mhHeader.length,
mhHeader.length);
}
switch (mhHeader.type) {
case VSC_APDU:
case VSC_Flush:
case VSC_Error:
case VSC_Init:
buf = (gchar *)pbSendBuffer;
to_read = mhHeader.length;
state = STATE_MESSAGE;
return TRUE;
default:
fprintf(stderr, "Unexpected message of type 0x%X\n", mhHeader.type);
return FALSE;
}
}
if (state == STATE_MESSAGE) {
switch (mhHeader.type) {
case VSC_APDU:
if (verbose) {
printf(" recv APDU: ");
print_byte_array(pbSendBuffer, mhHeader.length);
}
/* Transmit received APDU */
dwSendLength = mhHeader.length;
dwRecvLength = sizeof(pbRecvBuffer);
reader = vreader_get_reader_by_id(mhHeader.reader_id);
reader_status = vreader_xfr_bytes(reader,
pbSendBuffer, dwSendLength,
pbRecvBuffer, &dwRecvLength);
if (reader_status == VREADER_OK) {
mhHeader.length = dwRecvLength;
if (verbose) {
printf(" send response: ");
print_byte_array(pbRecvBuffer, mhHeader.length);
}
send_msg(VSC_APDU, mhHeader.reader_id,
pbRecvBuffer, dwRecvLength);
} else {
rv = reader_status; /* warning: not meaningful */
send_msg(VSC_Error, mhHeader.reader_id, &rv, sizeof(uint32_t));
}
vreader_free(reader);
reader = NULL; /* we've freed it, don't use it by accident
again */
break;
case VSC_Flush:
/* TODO: actually flush */
send_msg(VSC_FlushComplete, mhHeader.reader_id, NULL, 0);
break;
case VSC_Error:
error_msg = (VSCMsgError *) pbSendBuffer;
if (error_msg->code == VSC_SUCCESS) {
g_mutex_lock(&pending_reader_lock);
if (pending_reader) {
vreader_set_id(pending_reader, mhHeader.reader_id);
vreader_free(pending_reader);
pending_reader = NULL;
g_cond_signal(&pending_reader_condition);
}
g_mutex_unlock(&pending_reader_lock);
break;
}
printf("warning: qemu refused to add reader\n");
if (error_msg->code == VSC_CANNOT_ADD_MORE_READERS) {
/* clear pending reader, qemu can't handle any more */
g_mutex_lock(&pending_reader_lock);
if (pending_reader) {
pending_reader = NULL;
/* make sure the event loop doesn't hang */
g_cond_signal(&pending_reader_condition);
}
g_mutex_unlock(&pending_reader_lock);
}
break;
case VSC_Init:
if (on_host_init(&mhHeader, (VSCMsgInit *)pbSendBuffer) < 0) {
return FALSE;
}
break;
default:
g_assert_not_reached();
return FALSE;
}
state = STATE_HEADER;
}
return TRUE;
}
static gboolean
do_socket(GIOChannel *source,
GIOCondition condition,
gpointer data)
{
/* not sure if two watches work well with a single win32 sources */
if (condition & G_IO_OUT) {
if (!do_socket_send(source, condition, data)) {
return FALSE;
}
}
if (condition & G_IO_IN) {
if (!do_socket_read(source, condition, data)) {
return FALSE;
}
}
return TRUE;
}
static void
update_socket_watch(void)
{
gboolean out = socket_to_send->len > 0;
if (socket_tag != 0) {
g_source_remove(socket_tag);
}
socket_tag = g_io_add_watch(channel_socket,
G_IO_IN | (out ? G_IO_OUT : 0), do_socket, NULL);
}
static gboolean
do_command(GIOChannel *source,
GIOCondition condition,
gpointer data)
{
char *string;
VCardEmulError error;
static unsigned int default_reader_id;
unsigned int reader_id;
VReader *reader = NULL;
GError *err = NULL;
g_assert(condition & G_IO_IN);
reader_id = default_reader_id;
g_io_channel_read_line(source, &string, NULL, NULL, &err);
if (err != NULL) {
g_error("Error while reading command: %s", err->message);
}
if (string != NULL) {
if (strncmp(string, "exit", 4) == 0) {
/* remove all the readers */
VReaderList *list = vreader_get_reader_list();
VReaderListEntry *reader_entry;
printf("Active Readers:\n");
for (reader_entry = vreader_list_get_first(list); reader_entry;
reader_entry = vreader_list_get_next(reader_entry)) {
VReader *reader = vreader_list_get_reader(reader_entry);
vreader_id_t reader_id;
reader_id = vreader_get_id(reader);
if (reader_id == -1) {
continue;
}
/* be nice and signal card removal first (qemu probably should
* do this itself) */
if (vreader_card_is_present(reader) == VREADER_OK) {
send_msg(VSC_CardRemove, reader_id, NULL, 0);
}
send_msg(VSC_ReaderRemove, reader_id, NULL, 0);
}
exit(0);
} else if (strncmp(string, "insert", 6) == 0) {
if (string[6] == ' ') {
reader_id = get_id_from_string(&string[7], reader_id);
}
reader = vreader_get_reader_by_id(reader_id);
if (reader != NULL) {
error = vcard_emul_force_card_insert(reader);
printf("insert %s, returned %d\n",
vreader_get_name(reader), error);
} else {
printf("no reader by id %u found\n", reader_id);
}
} else if (strncmp(string, "remove", 6) == 0) {
if (string[6] == ' ') {
reader_id = get_id_from_string(&string[7], reader_id);
}
reader = vreader_get_reader_by_id(reader_id);
if (reader != NULL) {
error = vcard_emul_force_card_remove(reader);
printf("remove %s, returned %d\n",
vreader_get_name(reader), error);
} else {
printf("no reader by id %u found\n", reader_id);
}
} else if (strncmp(string, "select", 6) == 0) {
if (string[6] == ' ') {
reader_id = get_id_from_string(&string[7],
VSCARD_UNDEFINED_READER_ID);
}
if (reader_id != VSCARD_UNDEFINED_READER_ID) {
reader = vreader_get_reader_by_id(reader_id);
}
if (reader) {
printf("Selecting reader %u, %s\n", reader_id,
vreader_get_name(reader));
default_reader_id = reader_id;
} else {
printf("Reader with id %u not found\n", reader_id);
}
} else if (strncmp(string, "debug", 5) == 0) {
if (string[5] == ' ') {
verbose = get_id_from_string(&string[6], 0);
}
printf("debug level = %d\n", verbose);
} else if (strncmp(string, "list", 4) == 0) {
VReaderList *list = vreader_get_reader_list();
VReaderListEntry *reader_entry;
printf("Active Readers:\n");
for (reader_entry = vreader_list_get_first(list); reader_entry;
reader_entry = vreader_list_get_next(reader_entry)) {
VReader *reader = vreader_list_get_reader(reader_entry);
vreader_id_t reader_id;
reader_id = vreader_get_id(reader);
if (reader_id == -1) {
continue;
}
printf("%3u %s %s\n", reader_id,
vreader_card_is_present(reader) == VREADER_OK ?
"CARD_PRESENT" : " ",
vreader_get_name(reader));
}
printf("Inactive Readers:\n");
for (reader_entry = vreader_list_get_first(list); reader_entry;
reader_entry = vreader_list_get_next(reader_entry)) {
VReader *reader = vreader_list_get_reader(reader_entry);
vreader_id_t reader_id;
reader_id = vreader_get_id(reader);
if (reader_id != -1) {
continue;
}
printf("INA %s %s\n",
vreader_card_is_present(reader) == VREADER_OK ?
"CARD_PRESENT" : " ",
vreader_get_name(reader));
}
vreader_list_delete(list);
} else if (*string != 0) {
printf("valid commands:\n");
printf("insert [reader_id]\n");
printf("remove [reader_id]\n");
printf("select reader_id\n");
printf("list\n");
printf("debug [level]\n");
printf("exit\n");
}
}
vreader_free(reader);
printf("> ");
fflush(stdout);
return TRUE;
}
/* just for ease of parsing command line arguments. */
#define MAX_CERTS 100
static int
connect_to_qemu(
const char *host,
const char *port
) {
struct addrinfo hints;
struct addrinfo *server;
int ret, sock;
sock = socket(AF_INET, SOCK_STREAM, 0);
if (sock < 0) {
/* Error */
fprintf(stderr, "Error opening socket!\n");
return -1;
}
memset(&hints, 0, sizeof(struct addrinfo));
hints.ai_family = AF_UNSPEC;
hints.ai_socktype = SOCK_STREAM;
hints.ai_flags = 0;
hints.ai_protocol = 0; /* Any protocol */
ret = getaddrinfo(host, port, &hints, &server);
if (ret != 0) {
/* Error */
fprintf(stderr, "getaddrinfo failed\n");
goto cleanup_socket;
}
if (connect(sock, server->ai_addr, server->ai_addrlen) < 0) {
/* Error */
fprintf(stderr, "Could not connect\n");
goto cleanup_socket;
}
if (verbose) {
printf("Connected (sizeof Header=%zd)!\n", sizeof(VSCMsgHeader));
}
return sock;
cleanup_socket:
closesocket(sock);
return -1;
}
int
main(
int argc,
char *argv[]
) {
GMainLoop *loop;
GIOChannel *channel_stdin;
char *qemu_host;
char *qemu_port;
VCardEmulOptions *command_line_options = NULL;
char *cert_names[MAX_CERTS];
char *emul_args = NULL;
int cert_count = 0;
int c, sock;
#ifdef _WIN32
WSADATA Data;
if (WSAStartup(MAKEWORD(2, 2), &Data) != 0) {
c = WSAGetLastError();
fprintf(stderr, "WSAStartup: %d\n", c);
return 1;
}
#endif
#if !GLIB_CHECK_VERSION(2, 31, 0)
if (!g_thread_supported()) {
g_thread_init(NULL);
}
#endif
while ((c = getopt(argc, argv, "c:e:pd:")) != -1) {
switch (c) {
case 'c':
if (cert_count >= MAX_CERTS) {
printf("too many certificates (max = %d)\n", MAX_CERTS);
exit(5);
}
cert_names[cert_count++] = optarg;
break;
case 'e':
emul_args = optarg;
break;
case 'p':
print_usage();
exit(4);
break;
case 'd':
verbose = get_id_from_string(optarg, 1);
break;
}
}
if (argc - optind != 2) {
print_usage();
exit(4);
}
if (cert_count > 0) {
char *new_args;
int len, i;
/* if we've given some -c options, we clearly we want do so some
* software emulation. add that emulation now. this is NSS Emulator
* specific */
if (emul_args == NULL) {
emul_args = (char *)"db=\"/etc/pki/nssdb\"";
}
#define SOFT_STRING ",soft=(,Virtual Reader,CAC,,"
/* 2 == close paren & null */
len = strlen(emul_args) + strlen(SOFT_STRING) + 2;
for (i = 0; i < cert_count; i++) {
len += strlen(cert_names[i])+1; /* 1 == comma */
}
new_args = g_malloc(len);
strcpy(new_args, emul_args);
strcat(new_args, SOFT_STRING);
for (i = 0; i < cert_count; i++) {
strcat(new_args, cert_names[i]);
strcat(new_args, ",");
}
strcat(new_args, ")");
emul_args = new_args;
}
if (emul_args) {
command_line_options = vcard_emul_options(emul_args);
}
qemu_host = g_strdup(argv[argc - 2]);
qemu_port = g_strdup(argv[argc - 1]);
sock = connect_to_qemu(qemu_host, qemu_port);
if (sock == -1) {
fprintf(stderr, "error opening socket, exiting.\n");
exit(5);
}
socket_to_send = g_byte_array_new();
vcard_emul_init(command_line_options);
loop = g_main_loop_new(NULL, TRUE);
printf("> ");
fflush(stdout);
#ifdef _WIN32
channel_stdin = g_io_channel_win32_new_fd(STDIN_FILENO);
#else
channel_stdin = g_io_channel_unix_new(STDIN_FILENO);
#endif
g_io_add_watch(channel_stdin, G_IO_IN, do_command, NULL);
#ifdef _WIN32
channel_socket = g_io_channel_win32_new_socket(sock);
#else
channel_socket = g_io_channel_unix_new(sock);
#endif
g_io_channel_set_encoding(channel_socket, NULL, NULL);
/* we buffer ourself for thread safety reasons */
g_io_channel_set_buffered(channel_socket, FALSE);
/* Send init message, Host responds (and then we send reader attachments) */
VSCMsgInit init = {
.version = htonl(VSCARD_VERSION),
.magic = VSCARD_MAGIC,
.capabilities = {0}
};
send_msg(VSC_Init, 0, &init, sizeof(init));
g_main_loop_run(loop);
g_main_loop_unref(loop);
g_io_channel_unref(channel_stdin);
g_io_channel_unref(channel_socket);
g_byte_array_free(socket_to_send, TRUE);
closesocket(sock);
return 0;
}
| 12,088 |
626 | package org.jsmart.zerocode.integration.tests.kafka.consume.intercept;
import org.jsmart.zerocode.core.domain.Scenario;
import org.jsmart.zerocode.core.domain.TargetEnv;
import org.jsmart.zerocode.core.runner.ZeroCodeUnitRunner;
import org.junit.Test;
import org.junit.runner.RunWith;
@TargetEnv("kafka_servers/intercept/kafka_brokers.properties")
@RunWith(ZeroCodeUnitRunner.class)
public class KafkaIntegrationBddTest {
@Test
@Scenario("kafka/consume/e2e_bdd/test_kafka_e2e_integration_msg.yml")
public void testKafka_e2eBddJSON() throws Exception {
}
@Test
@Scenario("kafka/consume/e2e_bdd/test_kafka_e2e_integration_msg.json")
public void testKafka_e2eBddYML() throws Exception {
}
}
| 299 |
1,972 | package com.ramotion.garlandview.example.main.outer;
import android.content.Context;
import android.graphics.Color;
import android.text.Spannable;
import android.text.SpannableString;
import android.text.style.AbsoluteSizeSpan;
import android.text.style.ForegroundColorSpan;
import android.view.View;
import android.view.ViewGroup;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.TextView;
import com.bumptech.glide.Glide;
import com.bumptech.glide.load.resource.bitmap.CircleCrop;
import com.ramotion.garlandview.example.R;
import com.ramotion.garlandview.example.main.inner.InnerAdapter;
import com.ramotion.garlandview.example.main.inner.InnerData;
import com.ramotion.garlandview.example.utils.GlideApp;
import com.ramotion.garlandview.header.HeaderDecorator;
import com.ramotion.garlandview.header.HeaderItem;
import com.ramotion.garlandview.inner.InnerLayoutManager;
import com.ramotion.garlandview.inner.InnerRecyclerView;
import java.util.ArrayList;
import java.util.List;
import androidx.annotation.NonNull;
import androidx.core.view.ViewCompat;
import androidx.databinding.DataBindingUtil;
import androidx.recyclerview.widget.RecyclerView;
import static android.text.Spanned.SPAN_INCLUSIVE_INCLUSIVE;
public class OuterItem extends HeaderItem {
private final static float AVATAR_RATIO_START = 1f;
private final static float AVATAR_RATIO_MAX = 0.25f;
private final static float AVATAR_RATIO_DIFF = AVATAR_RATIO_START - AVATAR_RATIO_MAX;
private final static float ANSWER_RATIO_START = 0.75f;
private final static float ANSWER_RATIO_MAX = 0.35f;
private final static float ANSWER_RATIO_DIFF = ANSWER_RATIO_START - ANSWER_RATIO_MAX;
private final static float MIDDLE_RATIO_START = 0.7f;
private final static float MIDDLE_RATIO_MAX = 0.1f;
private final static float MIDDLE_RATIO_DIFF = MIDDLE_RATIO_START- MIDDLE_RATIO_MAX;
private final static float FOOTER_RATIO_START = 1.1f;
private final static float FOOTER_RATIO_MAX = 0.35f;
private final static float FOOTER_RATIO_DIFF = FOOTER_RATIO_START - FOOTER_RATIO_MAX;
private final View mHeader;
private final View mHeaderAlpha;
private final InnerRecyclerView mRecyclerView;
private final ImageView mAvatar;
private final TextView mHeaderCaption1;
private final TextView mHeaderCaption2;
private final TextView mName;
private final TextView mInfo;
private final View mMiddle;
private final View mMiddleAnswer;
private final View mFooter;
private final List<View> mMiddleCollapsible = new ArrayList<>(2);
private final int m10dp;
private final int m120dp;
private final int mTitleSize1;
private final int mTitleSize2;
private boolean mIsScrolling;
public OuterItem(View itemView, RecyclerView.RecycledViewPool pool) {
super(itemView);
// Init header
m10dp = itemView.getContext().getResources().getDimensionPixelSize(R.dimen.dp10);
m120dp = itemView.getContext().getResources().getDimensionPixelSize(R.dimen.dp120);
mTitleSize1 = itemView.getContext().getResources().getDimensionPixelSize(R.dimen.header_title2_text_size);
mTitleSize2 = itemView.getContext().getResources().getDimensionPixelSize(R.dimen.header_title2_name_text_size);
mHeader = itemView.findViewById(R.id.header);
mHeaderAlpha = itemView.findViewById(R.id.header_alpha);
mHeaderCaption1 = (TextView) itemView.findViewById(R.id.header_text_1);
mHeaderCaption2 = (TextView) itemView.findViewById(R.id.header_text_2);
mName = (TextView) itemView.findViewById(R.id.tv_name);
mInfo = (TextView) itemView.findViewById(R.id.tv_info);
mAvatar = (ImageView) itemView.findViewById(R.id.avatar);
mMiddle = itemView.findViewById(R.id.header_middle);
mMiddleAnswer= itemView.findViewById(R.id.header_middle_answer);
mFooter = itemView.findViewById(R.id.header_footer);
mMiddleCollapsible.add((View)mAvatar.getParent());
mMiddleCollapsible.add((View)mName.getParent());
// Init RecyclerView
mRecyclerView = (InnerRecyclerView) itemView.findViewById(R.id.recycler_view);
mRecyclerView.setRecycledViewPool(pool);
mRecyclerView.setAdapter(new InnerAdapter());
mRecyclerView.addOnScrollListener(new RecyclerView.OnScrollListener() {
@Override
public void onScrollStateChanged(RecyclerView recyclerView, int newState) {
mIsScrolling = newState != RecyclerView.SCROLL_STATE_IDLE;
}
@Override
public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
onItemScrolled(recyclerView, dx, dy);
}
});
mRecyclerView.addItemDecoration(new HeaderDecorator(
itemView.getContext().getResources().getDimensionPixelSize(R.dimen.inner_item_height),
itemView.getContext().getResources().getDimensionPixelSize(R.dimen.inner_item_offset)));
// Init fonts
DataBindingUtil.bind(((FrameLayout)mHeader).getChildAt(0));
}
@Override
public boolean isScrolling() {
return mIsScrolling;
}
@Override
public InnerRecyclerView getViewGroup() {
return mRecyclerView;
}
@Override
public View getHeader() {
return mHeader;
}
@Override
public View getHeaderAlphaView() {
return mHeaderAlpha;
}
void setContent(@NonNull List<InnerData> innerDataList) {
final Context context = itemView.getContext();
final InnerData header = innerDataList.subList(0, 1).get(0);
final List<InnerData> tail = innerDataList.subList(1, innerDataList.size());
mRecyclerView.setLayoutManager(new InnerLayoutManager());
((InnerAdapter)mRecyclerView.getAdapter()).addData(tail);
GlideApp.with(context)
.load(header.avatarUrl)
.placeholder(R.drawable.avatar_placeholder)
.transform(new CircleCrop())
.into(mAvatar);
final String title1 = header.title + "?";
final Spannable title2 = new SpannableString(header.title + "? - " + header.name);
title2.setSpan(new AbsoluteSizeSpan(mTitleSize1), 0, title1.length(), SPAN_INCLUSIVE_INCLUSIVE);
title2.setSpan(new AbsoluteSizeSpan(mTitleSize2), title1.length(), title2.length(), SPAN_INCLUSIVE_INCLUSIVE);
title2.setSpan(new ForegroundColorSpan(Color.argb(204, 255, 255, 255)), title1.length(), title2.length(), SPAN_INCLUSIVE_INCLUSIVE);
mHeaderCaption1.setText(title1);
mHeaderCaption2.setText(title2);
mName.setText(String.format("%s %s", header.name, context.getString(R.string.asked)));
mInfo.setText(String.format("%s %s · %s", header.age, context.getString(R.string.years), header.address));
}
void clearContent() {
Glide.with(mAvatar.getContext()).clear(mAvatar);
((InnerAdapter)mRecyclerView.getAdapter()).clearData();
}
private float computeRatio(RecyclerView recyclerView) {
final View child0 = recyclerView.getChildAt(0);
final int pos = recyclerView.getChildAdapterPosition(child0);
if (pos != 0) {
return 0;
}
final int height = child0.getHeight();
final float y = Math.max(0, child0.getY());
return y / height;
}
private void onItemScrolled(RecyclerView recyclerView, int dx, int dy) {
final float ratio = computeRatio(recyclerView);
final float footerRatio = Math.max(0, Math.min(FOOTER_RATIO_START, ratio) - FOOTER_RATIO_DIFF) / FOOTER_RATIO_MAX;
final float avatarRatio = Math.max(0, Math.min(AVATAR_RATIO_START, ratio) - AVATAR_RATIO_DIFF) / AVATAR_RATIO_MAX;
final float answerRatio = Math.max(0, Math.min(ANSWER_RATIO_START, ratio) - ANSWER_RATIO_DIFF) / ANSWER_RATIO_MAX;
final float middleRatio = Math.max(0, Math.min(MIDDLE_RATIO_START, ratio) - MIDDLE_RATIO_DIFF) / MIDDLE_RATIO_MAX;
ViewCompat.setPivotY(mFooter, 0);
ViewCompat.setScaleY(mFooter, footerRatio);
ViewCompat.setAlpha(mFooter, footerRatio);
ViewCompat.setPivotY(mMiddleAnswer, mMiddleAnswer.getHeight());
ViewCompat.setScaleY(mMiddleAnswer, 1f - answerRatio);
ViewCompat.setAlpha(mMiddleAnswer, 0.5f - answerRatio);
ViewCompat.setAlpha(mHeaderCaption1, answerRatio);
ViewCompat.setAlpha(mHeaderCaption2, 1f - answerRatio);
final View mc2 = mMiddleCollapsible.get(1);
ViewCompat.setPivotX(mc2, 0);
ViewCompat.setPivotY(mc2, mc2.getHeight() / 2);
for (final View view: mMiddleCollapsible) {
ViewCompat.setScaleX(view, avatarRatio);
ViewCompat.setScaleY(view, avatarRatio);
ViewCompat.setAlpha(view, avatarRatio);
}
final ViewGroup.LayoutParams lp = mMiddle.getLayoutParams();
lp.height = m120dp - (int)(m10dp * (1f - middleRatio));
mMiddle.setLayoutParams(lp);
}
}
| 3,731 |
14,668 | <gh_stars>1000+
/*
* Copyright 2017 Google LLC.
* 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
*
* https://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.
*/
// The class defined in this file should only be used for testing purposes.
#ifndef RLWE_TESTING_COEFFICIENT_POLYNOMIAL_H_
#define RLWE_TESTING_COEFFICIENT_POLYNOMIAL_H_
#include <cmath>
#include <cstdint>
#include <string>
#include <vector>
#include <glog/logging.h>
#include "absl/strings/str_cat.h"
#include "status_macros.h"
#include "statusor.h"
#include "testing/coefficient_polynomial.pb.h"
namespace rlwe {
namespace testing {
// A polynomial with ModularInt coefficients that is automatically reduced
// modulo <x^n + 1>, where n is the number of coefficients provided in the
// constructor.
// SHould only be used for testing.
template <typename ModularInt>
class CoefficientPolynomial {
using ModularIntParams = typename ModularInt::Params;
public:
// Copy constructor.
CoefficientPolynomial(const CoefficientPolynomial& that) = default;
// Constructor. The polynomial is initialized to the values of a vector.
CoefficientPolynomial(std::vector<ModularInt> coeffs,
const ModularIntParams* modulus_params)
: coeffs_(std::move(coeffs)), modulus_params_(modulus_params) {}
// Constructs an empty CoefficientPolynomial.
explicit CoefficientPolynomial(int len,
const ModularIntParams* modulus_params)
: CoefficientPolynomial(std::vector<ModularInt>(
len, ModularInt::ImportZero(modulus_params)),
modulus_params) {}
// Accessor for length.
int Len() const { return coeffs_.size(); }
// Accessor for coefficients.
std::vector<ModularInt> Coeffs() const { return coeffs_; }
// Accessor for Modulus Params.
const ModularIntParams* ModulusParams() const { return modulus_params_; }
// Compute the degree.
int Degree() const {
for (int i = Len() - 1; i >= 0; i--) {
if (coeffs_[i].ExportInt(modulus_params_) != 0) {
return i;
}
}
return 0;
}
// Equality.
bool operator==(const CoefficientPolynomial& that) const {
if (Degree() != that.Degree()) {
return false;
}
for (int i = 0; i <= Degree(); i++) {
if (coeffs_[i] != that.coeffs_[i]) {
return false;
}
}
return true;
}
bool operator!=(const CoefficientPolynomial& that) const {
return !(*this == that);
}
// Addition.
rlwe::StatusOr<CoefficientPolynomial> operator+(
const CoefficientPolynomial& that) const {
// Ensure the polynomials' dimensions are equal.
if (Len() != that.Len()) {
return absl::InvalidArgumentError(
"CoefficientPolynomial dimensions mismatched.");
}
// Add polynomials point-wise.
CoefficientPolynomial out(*this);
for (int i = 0; i < Len(); i++) {
out.coeffs_[i].AddInPlace(that.coeffs_[i], modulus_params_);
}
return out;
}
// Substraction.
rlwe::StatusOr<CoefficientPolynomial> operator-(
const CoefficientPolynomial& that) const {
// Ensure the polynomials' dimensions are equal.
if (Len() != that.Len()) {
return absl::InvalidArgumentError(
"CoefficientPolynomial dimensions mismatched.");
}
// Add polynomials point-wise.
CoefficientPolynomial out(*this);
for (int i = 0; i < Len(); i++) {
out.coeffs_[i].SubInPlace(that.coeffs_[i], modulus_params_);
}
return out;
}
// Scalar multiplication.
CoefficientPolynomial operator*(ModularInt c) const {
CoefficientPolynomial out(*this);
for (auto& coeff : out.coeffs_) {
coeff.MulInPlace(c, modulus_params_);
}
return out;
}
// Multiplication modulo x^N + 1.
rlwe::StatusOr<CoefficientPolynomial> operator*(
const CoefficientPolynomial& that) const {
// Ensure the polynomials' dimensions are equal.
if (Len() != that.Len()) {
return absl::InvalidArgumentError(
"CoefficientPolynomial dimensions mismatched.");
}
// Create a zero polynomial of the correct dimension.
CoefficientPolynomial out(Len(), modulus_params_);
for (int i = 0; i < Len(); i++) {
for (int j = 0; j < Len(); j++) {
if ((i + j) >= coeffs_.size()) {
// Since multiplciation is mod (x^N + 1), if the coefficient computed
// has degree k (= i + j) larger than N, it contributes to the (k -
// N)'th coefficient with a negative factor.
out.coeffs_[(i + j) - coeffs_.size()].SubInPlace(
coeffs_[i].Mul(that.coeffs_[j], modulus_params_),
modulus_params_);
} else {
// Otherwise, contributes to the k'th coefficient as normal.
out.coeffs_[i + j].AddInPlace(
coeffs_[i].Mul(that.coeffs_[j], modulus_params_),
modulus_params_);
}
}
}
return out;
}
// A more efficient multiplication by a monomial x^power, where power <
// 2*dimension.
rlwe::StatusOr<CoefficientPolynomial> MonomialMultiplication(
int power) const {
// Check that the monomial is in range.
if (0 > power || power >= 2 * Len()) {
return absl::InvalidArgumentError(
"Monomial to absorb must have non-negative degree less than 2n.");
}
CoefficientPolynomial out(*this);
// Monomial multiplication be x^{k} where n <= k < 2*n is monomial
// multiplication by -x^{k - n}.
ModularInt multiplier = ModularInt::ImportOne(modulus_params_);
if (power >= Len()) {
multiplier.NegateInPlace(modulus_params_);
power = power - Len();
}
ModularInt negative_multiplier = multiplier.Negate(modulus_params_);
for (int i = 0; i < power; i++) {
out.coeffs_[i] =
negative_multiplier.Mul(coeffs_[i - power + Len()], modulus_params_);
}
for (int i = power; i < Len(); i++) {
out.coeffs_[i] = multiplier.Mul(coeffs_[i - power], modulus_params_);
}
return out;
}
// Given a polynomial p(x), returns a polynomial p(x^a). Expects a power <
// 2n, where n is the dimension of the polynomial.
rlwe::StatusOr<CoefficientPolynomial> Substitute(const int power) const {
// Check that the substitution is in range. The power must be relatively
// prime to 2*n. Since our dimensions are always a power of two, this is
// equivalent to the power being odd.
if (0 > power || (power % 2) == 0 || power >= 2 * Len()) {
return absl::InvalidArgumentError(
absl::StrCat("Substitution power must be a non-negative odd ",
"integer less than 2*n."));
}
CoefficientPolynomial out(*this);
// The ith coefficient of the original polynomial p(x) is sent to the (i *
// power % Len())-th coefficient under the substitution. However, in the
// polynomial ring mod (x^N + 1), x^N = -1, so we multiply the i-th
// coefficient by (-1)^{(power * i) / Len()}.
// In the loop, current_index keeps track of (i * power % Len()), and
// multiplier keeps track of the power of -1 for the current coefficient.
int current_index = 0;
ModularInt multiplier = ModularInt::ImportOne(modulus_params_);
for (int i = 0; i < Len(); i++) {
out.coeffs_[current_index] = coeffs_[i].Mul(multiplier, modulus_params_);
current_index += power;
while (current_index > Len()) {
multiplier.NegateInPlace(modulus_params_);
current_index -= Len();
}
}
return out;
}
rlwe::StatusOr<SerializedCoefficientPolynomial> Serialize() const {
SerializedCoefficientPolynomial output;
RLWE_ASSIGN_OR_RETURN(
*(output.mutable_coeffs()),
ModularInt::SerializeVector(coeffs_, modulus_params_));
output.set_num_coeffs(coeffs_.size());
return output;
}
static rlwe::StatusOr<CoefficientPolynomial> Deserialize(
const SerializedCoefficientPolynomial& serialized,
const ModularIntParams* modulus_params) {
CoefficientPolynomial output(serialized.num_coeffs(), modulus_params);
RLWE_ASSIGN_OR_RETURN(
output.coeffs_,
ModularInt::DeserializeVector(serialized.num_coeffs(),
serialized.coeffs(), modulus_params));
return output;
}
private:
std::vector<ModularInt> coeffs_;
const ModularIntParams* modulus_params_;
};
} // namespace testing
} // namespace rlwe
#endif // RLWE_TESTING_COEFFICIENT_POLYNOMIAL_H_
| 3,499 |
2,843 | package com.ns.yc.lifehelper.ui.find.view.fragment;
import android.content.Context;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.widget.RecyclerView;
import android.view.View;
import com.alibaba.android.vlayout.DelegateAdapter;
import com.blankj.utilcode.util.ActivityUtils;
import com.blankj.utilcode.util.SizeUtils;
import com.ns.yc.lifehelper.R;
import com.ns.yc.lifehelper.base.adapter.BaseBannerPagerAdapter;
import com.ns.yc.lifehelper.base.adapter.BaseDelegateAdapter;
import com.ns.yc.lifehelper.ui.find.contract.FindFragmentContract;
import com.ns.yc.lifehelper.ui.find.presenter.FindFragmentPresenter;
import com.ns.yc.lifehelper.ui.guide.view.activity.SelectFollowActivity;
import com.ns.yc.lifehelper.ui.main.view.MainActivity;
import com.yc.cn.ycbannerlib.banner.BannerView;
import com.yc.configlayer.arounter.ARouterUtils;
import com.yc.configlayer.arounter.RouterConfig;
import com.yc.configlayer.constant.Constant;
import com.ycbjie.library.base.mvp.BaseFragment;
import java.util.LinkedList;
import java.util.List;
/**
* <pre>
* @author yangchong
* blog : https://github.com/yangchong211
* time : 2017/11/21
* desc : 数据页面,使用阿里巴巴Vlayout框架
* revise: v1.4 17年6月8日
* v1.5 17年10月3日修改
* </pre>
*/
public class FindFragment extends BaseFragment<FindFragmentPresenter> implements
FindFragmentContract.View {
private RecyclerView mRecyclerView;
private MainActivity activity;
private FindFragmentContract.Presenter presenter = new FindFragmentPresenter(this);
private List<DelegateAdapter.Adapter> mAdapters;
private BannerView mBanner;
@Override
public void onAttach(Context context) {
super.onAttach(context);
activity = (MainActivity) context;
presenter.bindActivity(activity);
}
@Override
public void onDetach() {
super.onDetach();
if(activity!=null){
activity = null;
}
}
@Override
public void onPause() {
super.onPause();
if(mBanner!=null){
mBanner.pause();
}
}
@Override
public void onResume() {
super.onResume();
if(mBanner!=null){
mBanner.resume();
}
}
@Override
public void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
presenter.subscribe();
}
@Override
public void onDestroy() {
super.onDestroy();
presenter.unSubscribe();
}
@Override
public int getContentView() {
return R.layout.base_recycler_view;
}
@Override
public void initView(View view) {
mRecyclerView = view.findViewById(R.id.recyclerView);
mAdapters = new LinkedList<>();
initRecyclerView();
}
@Override
public void initListener() {
}
@Override
public void initData() {
}
private void initRecyclerView() {
DelegateAdapter delegateAdapter = presenter.initRecyclerView(mRecyclerView);
//把轮播器添加到集合
BaseDelegateAdapter bannerAdapter = presenter.initBannerAdapter();
mAdapters.add(bannerAdapter);
//初始化九宫格
BaseDelegateAdapter menuAdapter = presenter.initGvMenu();
mAdapters.add(menuAdapter);
//初始化
BaseDelegateAdapter marqueeAdapter = presenter.initMarqueeView();
mAdapters.add(marqueeAdapter);
//初始化标题
BaseDelegateAdapter titleAdapter = presenter.initTitle("豆瓣分享");
mAdapters.add(titleAdapter);
//初始化list3
BaseDelegateAdapter girdAdapter3 = presenter.initList3();
mAdapters.add(girdAdapter3);
//初始化标题
titleAdapter = presenter.initTitle("猜你喜欢");
mAdapters.add(titleAdapter);
//初始化list1
BaseDelegateAdapter girdAdapter = presenter.initList1();
mAdapters.add(girdAdapter);
//初始化标题
titleAdapter = presenter.initTitle("热门新闻");
mAdapters.add(titleAdapter);
//初始化list2
BaseDelegateAdapter linearAdapter = presenter.initList2();
mAdapters.add(linearAdapter);
//初始化标题
titleAdapter = presenter.initTitle("为您精选");
mAdapters.add(titleAdapter);
//初始化list3
BaseDelegateAdapter plusAdapter = presenter.initList4();
mAdapters.add(plusAdapter);
//初始化list控件
titleAdapter = presenter.initTitle("优质新闻");
mAdapters.add(titleAdapter);
linearAdapter = presenter.initList5();
mAdapters.add(linearAdapter);
//设置适配器
delegateAdapter.setAdapters(mAdapters);
mRecyclerView.requestLayout();
}
@Override
public void setBanner(BannerView mBanner, List<Object> arrayList) {
this.mBanner = mBanner;
mBanner.setHintGravity(2);
mBanner.setAnimationDuration(1000);
mBanner.setPlayDelay(2000);
mBanner.setHintPadding(0,0,0, SizeUtils.dp2px(10));
mBanner.setAdapter(new BaseBannerPagerAdapter(activity, arrayList));
}
@Override
public void setOnclick(int position) {
//通过路由跳转到某模块的某个页面
switch (position){
case 0:
ARouterUtils.navigation(RouterConfig.Gank.ACTIVITY_GANK_ACTIVITY);
break;
case 1:
ARouterUtils.navigation(RouterConfig.Android.ACTIVITY_ANDROID_ACTIVITY);
break;
//富文本
case 2:
ARouterUtils.navigation(RouterConfig.Note.ACTIVITY_OTHER_ARTICLE);
break;
case 3:
ARouterUtils.navigation(RouterConfig.Music.ACTIVITY_MUSIC_GUIDE_ACTIVITY);
break;
case 4:
break;
case 5:
Bundle bundle1 = new Bundle();
bundle1.putString(Constant.URL,Constant.FLUTTER);
bundle1.putString(Constant.TITLE,"flutter极致体验的WanAndroid客户端");
ARouterUtils.navigation(RouterConfig.Library.ACTIVITY_LIBRARY_WEB_VIEW,bundle1);
break;
//妹子画廊
case 6:
ARouterUtils.navigation(RouterConfig.Demo.ACTIVITY_OTHER_GALLERY_ACTIVITY);
break;
//相册画廊
case 7:
ARouterUtils.navigation(RouterConfig.Demo.ACTIVITY_COVER_ACTIVITY);
break;
default:
break;
}
}
@Override
public void setMarqueeClick(int position) {
switch (position) {
case 0:
Bundle bundle1 = new Bundle();
bundle1.putString(Constant.URL,Constant.GITHUB);
bundle1.putString(Constant.TITLE,"关于更多内容");
ARouterUtils.navigation(RouterConfig.Library.ACTIVITY_LIBRARY_WEB_VIEW,bundle1);
break;
case 1:
Bundle bundle2 = new Bundle();
bundle2.putString(Constant.URL,Constant.ZHI_HU);
bundle2.putString(Constant.TITLE,"关于我的知乎");
ARouterUtils.navigation(RouterConfig.Library.ACTIVITY_LIBRARY_WEB_VIEW,bundle2);
break;
default:
break;
}
}
@Override
public void setGridClick(int position) {
switch (position){
case 0:
ARouterUtils.navigation(RouterConfig.Video.ACTIVITY_VIDEO_VIDEO);
break;
case 1:
ARouterUtils.navigation(RouterConfig.Demo.ACTIVITY_OTHER_SNAPHELPER_ACTIVITY);
break;
case 2:
ActivityUtils.startActivity(SelectFollowActivity.class);
break;
case 3:
ARouterUtils.navigation(RouterConfig.Game.ACTIVITY_BOOK_DOODLE_ACTIVITY);
break;
case 4:
ARouterUtils.navigation(RouterConfig.Game.ACTIVITY_OTHER_PIN_TU_ACTIVITY);
break;
case 5:
ARouterUtils.navigation(RouterConfig.Game.ACTIVITY_OTHER_AIR_ACTIVITY);
break;
case 6:
ARouterUtils.navigation(RouterConfig.Game.ACTIVITY_OTHER_MONKEY_ACTIVITY);
break;
case 7:
break;
default:
break;
}
}
@Override
public void setGridClickThird(int position) {
switch (position){
case 0:
ARouterUtils.navigation(RouterConfig.DouBan.ACTIVITY_DOU_MOVIE_ACTIVITY);
break;
case 1:
ARouterUtils.navigation(RouterConfig.DouBan.ACTIVITY_DOU_MUSIC_ACTIVITY);
break;
case 2:
ARouterUtils.navigation(RouterConfig.DouBan.ACTIVITY_DOU_BOOK_ACTIVITY);
break;
default:
break;
}
}
@Override
public void setGridClickFour(int position) {
switch (position){
case 0:
ARouterUtils.navigation(RouterConfig.Demo.ACTIVITY_OTHER_BANNER_LIST_ACTIVITY);
break;
case 1:
break;
case 2:
break;
default:
break;
}
}
@Override
public void setNewsList2Click(int position, String url) {
if(position>-1 && url!=null && url.length()>0){
Bundle bundle = new Bundle();
bundle.putString(Constant.URL,url);
ARouterUtils.navigation(RouterConfig.Library.ACTIVITY_LIBRARY_WEB_VIEW,bundle);
}
}
@Override
public void setNewsList5Click(int position, String url) {
if(position>-1 && url!=null && url.length()>0){
Bundle bundle = new Bundle();
bundle.putString(Constant.URL,url);
ARouterUtils.navigation(RouterConfig.Library.ACTIVITY_LIBRARY_WEB_VIEW,bundle);
}
}
}
| 5,099 |
599 | # -*- coding: utf-8 -*-
"""
Tencent is pleased to support the open source community by making 蓝鲸智云PaaS平台社区版 (BlueKing PaaS Community
Edition) available.
Copyright (C) 2017-2021 THL A29 Limited, a Tencent company. All rights reserved.
Licensed under the MIT License (the "License"); you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://opensource.org/licenses/MIT
Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on
an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the
specific language governing permissions and limitations under the License.
针对模板集的操作
"""
import json
import logging
from datetime import datetime
from itertools import groupby
from django.db.models import Q
from django.utils.translation import ugettext_lazy as _
from backend.bcs_web.audit_log import client
from backend.components import paas_cc
from backend.container_service.projects.base.constants import LIMIT_FOR_ALL_DATA
from backend.templatesets.legacy_apps.configuration.models import MODULE_DICT, Template
from backend.templatesets.legacy_apps.configuration.utils import to_bcs_res_name
from backend.templatesets.legacy_apps.instance.constants import InsState
from backend.templatesets.legacy_apps.instance.models import InstanceConfig, VersionInstance
from backend.utils.errcodes import ErrorCode
from .. import constants as app_constants
from ..base_views import BaseAPI, error_codes
from ..utils import APIResponse
logger = logging.getLogger(__name__)
SKIP_CATEGORY = ["application", "deployment"]
class TemplateNamespace(BaseAPI):
def get_cluster_env_map(self, request, project_id):
return self.get_cluster_id_env(request, project_id)
def get_entity(self, info, category):
""""""
try:
entity = json.loads(info.instance_entity)
except Exception as error:
logger.error(u"解析entity出现异常,ID:%s, 详情: %s" % (info.id, error))
return []
return entity.get(category) or []
def get_active_ns(self, muster_id, show_version_name, category, res_name):
"""获取正在使用的实例"""
tmpl_version_info = VersionInstance.objects.filter(
is_deleted=False, show_version_name=show_version_name, template_id=muster_id
)
instance_id_list = [info.id for info in tmpl_version_info]
ins_set = InstanceConfig.objects.filter(
instance_id__in=instance_id_list, is_deleted=False, is_bcs_success=True
).exclude(Q(oper_type=app_constants.DELETE_INSTANCE) | Q(ins_state=InsState.NO_INS.value))
if category != "ALL":
ins_set = ins_set.filter(category=category, name=res_name)
inst_info = ins_set.values("instance_id")
inst_active_id_list = [info["instance_id"] for info in inst_info]
# 获取namespace
ret_data = []
for info in tmpl_version_info:
if info.id in inst_active_id_list:
ret_data.append(info.ns_id)
return ret_data
def get_ns_info(self, request, project_id, ns_id_list):
"""获取ns信息"""
resp = paas_cc.get_namespace_list(request.user.token.access_token, project_id, limit=LIMIT_FOR_ALL_DATA)
if resp.get("code") != ErrorCode.NoError:
raise error_codes.APIError.f(resp.get("message"))
results = (resp.get("data") or {}).get("results") or []
return results
def get(self, request, project_id, muster_id):
"""获取命名空间"""
# 获取参数
group_by = request.GET.get('group_by') or "env_type"
category = request.GET.get("category")
show_version_name = request.GET.get('show_version_name')
res_name = request.GET.get('res_name')
perm_can_use = request.GET.get('perm_can_use')
if perm_can_use == '1':
perm_can_use = True
else:
perm_can_use = False
# 前端的category转换为后台需要的类型
if category != 'ALL':
project_kind = request.project.kind
category = to_bcs_res_name(project_kind, category)
if category != 'ALL' and category not in MODULE_DICT:
raise error_codes.CheckFailed(f'category: {category} does not exist')
# 获取被占用的ns,没有处于删除中和已删除
ns_id_list = self.get_active_ns(muster_id, show_version_name, category, res_name)
# 查询ns信息
results = self.get_ns_info(request, project_id, ns_id_list)
# 解析&排序
cluster_env_map = self.get_cluster_env_map(request, project_id)
results = filter(lambda x: x["id"] in ns_id_list, results)
results = [
{
'name': k,
'cluster_name': cluster_env_map.get(k, {}).get('cluster_name', k),
'environment_name': _("正式")
if cluster_env_map.get(k, {}).get('cluster_env_str', '') == 'prod'
else _("测试"),
'results': sorted(list(v), key=lambda x: x['id'], reverse=True),
}
for k, v in groupby(sorted(results, key=lambda x: x[group_by]), key=lambda x: x[group_by])
]
# ordering = [i.value for i in constants.EnvType]
# results = sorted(results, key=lambda x: ordering.index(x['name']))
ret_data = []
for info in results:
for item in info["results"] or []:
item["muster_id"] = muster_id
item["environment"] = cluster_env_map.get(item["cluster_id"], {}).get("cluster_env_str")
info["results"] = self.bcs_perm_handler(
request, project_id, info["results"], filter_use=perm_can_use, ns_id_flag="id", ns_name_flag="name"
)
if info["results"]:
ret_data.append(info)
return APIResponse({"data": ret_data})
class DeleteTemplateInstance(BaseAPI):
def get_muster_name(self, muster_id):
"""获取模板名称"""
muster_name_list = Template.objects.filter(id=muster_id).values("name")
if not muster_name_list:
raise error_codes.CheckFailed(_("模板集ID: {} 不存在").format(muster_id))
return muster_name_list[0]["name"]
def get_template_name(self, template_id, category):
"""获取模板名称"""
info = MODULE_DICT[category].objects.filter(id=template_id).values("name")
if not info:
raise error_codes.CheckFailed(_("模板ID: {} 不存在").format(template_id))
return info[0]["name"]
def check_project_muster(self, project_id, muster_id):
"""判断项目和集群"""
if not Template.objects.filter(project_id=project_id, id=muster_id).exists():
raise error_codes.CheckFailed(_("项目:{},模板集: {} 不存在!").format(project_id, muster_id))
def get_instance_info(self, ns_id_list, name, category=None):
"""获取实例信息"""
inst_info = InstanceConfig.objects.filter(name__in=name, namespace__in=ns_id_list, is_deleted=False).exclude(
oper_type=app_constants.DELETE_INSTANCE
)
if category:
inst_info = inst_info.filter(category=category)
ret_data = {}
for info in inst_info:
try:
conf = self.get_common_instance_conf(info)
except Exception:
continue
metadata = conf.get("metadata") or {}
namespace = metadata.get("namespace")
labels = metadata.get("labels")
cluster_id = labels.get("io.tencent.bcs.clusterid")
ret_data[info.id] = {
"cluster_id": cluster_id,
"namespace": namespace,
"instance_name": info.name,
"muster_id": labels.get("io.tencent.paas.templateid"),
"info": info,
}
return ret_data
def delete_single(self, request, data, project_id, muster_id, show_version_name, res_name, muster_name):
"""删除单个类型"""
ns_id_list = data.get("namespace_list")
category = data.get("category")
if not (ns_id_list and category):
raise error_codes.CheckFailed(_("参数不能为空!"))
project_kind = request.project.kind
category = to_bcs_res_name(project_kind, category)
if category not in MODULE_DICT:
raise error_codes.CheckFailed(f'category: {category} does not exist')
# 获取要删除的实例的信息
inst_info = self.get_instance_info(ns_id_list, [res_name], category=category)
# 获取项目信息
flag, project_kind = self.get_project_kind(request, project_id)
if not flag:
return project_kind
with client.ContextActivityLogClient(
project_id=project_id,
user=request.user.username,
resource_type="instance",
resource=res_name,
resource_id=res_name,
extra=json.dumps(
{
"muster_id": muster_id,
"show_version_name": show_version_name,
"res_name": res_name,
"category": category,
}
),
description=_("删除模板集实例"),
).log_delete():
return self.delete_handler(request, inst_info, project_id, project_kind)
def delete_all(self, request, data, project_id, muster_id, show_version_name, res_name, muster_name):
"""删除所有类型"""
ns_id_list = data.get("namespace_list")
id_list = data.get("id_list")
if not (ns_id_list and id_list):
raise error_codes.CheckFailed(_("参数不能为空!"))
# 获取项目信息
flag, project_kind = self.get_project_kind(request, project_id)
if not flag:
return project_kind
# 获取所有模板名称
tmpl_category_name_map = {}
for info in id_list:
category_name = info["id"]
tmpl_category_name_map[category_name] = info["category"]
# 获取要删除的实例信息
inst_info = self.get_instance_info(ns_id_list, tmpl_category_name_map.keys())
# instance_version_ids = [val["info"].instance_id for key, val in inst_info.items()]
with client.ContextActivityLogClient(
project_id=project_id,
user=request.user.username,
resource_type="instance",
resource=muster_name,
resource_id=muster_id,
extra=json.dumps(
{
"muster_id": muster_id,
"show_version_name": show_version_name,
"tmpl_category_name_map": tmpl_category_name_map,
}
),
description=_("删除模板集实例"),
).log_delete():
resp = self.delete_handler(request, inst_info, project_id, project_kind)
return resp
# if resp.data.get("code") != ErrorCode.NoError:
# return resp
# else:
# # 更新version instance表记录
# try:
# VersionInstance.objects.filter(id__in=instance_version_ids).update(
# is_deleted=True, deleted_time=datetime.now()
# )
# except Exception as error:
# logger.error(u"删除失败,详情: %s" % error)
# return APIResponse({
# "code": 400,
# "message": u"更新实例状态失败,已通知管理员"
# })
# return resp
def delete_handler(self, request, inst_info, project_id, project_kind):
"""删除操作"""
oper_error_inst = []
deleted_id_list = []
for inst_id, info in inst_info.items():
# 判断权限
self.bcs_single_app_perm_handler(request, project_id, info["muster_id"], info["info"].namespace)
# 针对0/0的情况先查询一次
if info["info"].category in app_constants.ALL_CATEGORY_LIST:
if not self.get_category_info(
request,
project_id,
info["cluster_id"],
project_kind,
info["instance_name"],
info["namespace"],
info["info"].category,
):
deleted_id_list.append(inst_id)
continue
resp = self.delete_instance(
request,
project_id,
info["cluster_id"],
info["namespace"],
info["instance_name"],
category=info["info"].category,
kind=project_kind,
inst_id_list=[info["info"].id],
)
if resp.data.get("code") != ErrorCode.NoError:
logger.error("删除实例ID: %s 失败, 详情: %s" % (inst_id, resp.data.get("message")))
oper_error_inst.append(
"%s::%s: %s" % (info["namespace"], info["instance_name"], resp.data.get("message"))
)
continue
# 更新状态
if info["info"].category in SKIP_CATEGORY:
self.update_instance_record_status(info["info"], app_constants.DELETE_INSTANCE, status="Deleting")
else:
self.update_instance_record_status(
info["info"],
app_constants.DELETE_INSTANCE,
status="Deleted",
category=info["info"].category,
deleted_time=datetime.now(),
)
# 如果存在0/0的情况
if deleted_id_list:
InstanceConfig.objects.filter(id__in=deleted_id_list).update(is_deleted=True, deleted_time=datetime.now())
if oper_error_inst:
return APIResponse(
{"code": 400, "message": _("存在删除失败情况,(命名空间:实例名称)详情: {}").format(";".join(oper_error_inst))}
)
return APIResponse({"message": _("操作成功!")})
def delete(self, request, project_id, muster_id):
"""删除某一个版本下命名空间和instance信息"""
show_version_name = request.GET.get('show_version_name')
res_name = request.GET.get('res_name')
# 判断项目和模板集
self.check_project_muster(project_id, muster_id)
data = dict(request.data)
muster_name = self.get_muster_name(muster_id)
if data.get("id_list") and show_version_name:
return self.delete_all(request, data, project_id, muster_id, show_version_name, res_name, muster_name)
else:
return self.delete_single(request, data, project_id, muster_id, show_version_name, res_name, muster_name)
| 7,481 |
1,139 | package com.journaldev.spring.autowiring.service;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import com.journaldev.spring.autowiring.model.Employee;
public class EmployeeAutowiredByConstructorService {
private Employee employee;
//Autowired annotation on Constructor is equivalent to autowire="constructor"
@Autowired(required=false)
public EmployeeAutowiredByConstructorService(@Qualifier("employee") Employee emp){
this.employee=emp;
}
public Employee getEmployee() {
return this.employee;
}
}
| 189 |
348 | {"nom":"Saint-Etienne","circ":"1ère circonscription","dpt":"Loire","inscrits":38678,"abs":24975,"votants":13703,"blancs":788,"nuls":292,"exp":12623,"res":[{"nuance":"REM","nom":"<NAME>","voix":6425},{"nuance":"SOC","nom":"<NAME>","voix":6198}]} | 97 |
1,103 | from hachoir_core.field import CompressedField
try:
from zlib import decompressobj, MAX_WBITS
class DeflateStream:
def __init__(self, stream, wbits=None):
if wbits:
self.gzip = decompressobj(-MAX_WBITS)
else:
self.gzip = decompressobj()
def __call__(self, size, data=None):
if data is None:
data = ''
return self.gzip.decompress(self.gzip.unconsumed_tail+data, size)
class DeflateStreamWbits(DeflateStream):
def __init__(self, stream):
DeflateStream.__init__(self, stream, True)
def Deflate(field, wbits=True):
if wbits:
CompressedField(field, DeflateStreamWbits)
else:
CompressedField(field, DeflateStream)
return field
has_deflate = True
except ImportError:
def Deflate(field, wbits=True):
return field
has_deflate = False
| 446 |
530 | from tartiflette.language.validators.query.rule import (
June2018ReleaseValidationRule,
)
from tartiflette.language.validators.query.utils import find_field_reduced_type
from tartiflette.types.type import GraphQLCompositeType
from tartiflette.utils.errors import graphql_error_from_nodes
class LeafFieldSelections(June2018ReleaseValidationRule):
"""
This validator validates that selection set are only in used
in fields that are of composite type. (Object, Interface, Union)
More details @ https://graphql.github.io/graphql-spec/June2018/#sec-Leaf-Field-Selections
"""
RULE_NAME = "leaf-field-selections"
RULE_LINK = "https://graphql.github.io/graphql-spec/June2018/#sec-Leaf-Field-Selections"
RULE_NUMBER = "5.3.3"
def validate(self, path, schema, field, parent_type_name, **__):
rtype = find_field_reduced_type(
parent_type_name, field.name.value, schema
)
if not rtype:
return (
[]
) # Handled by field_selections_on_objects_interfaces_and_unions_types rule
# TODO maybe think about rule order/dependencies
is_gql_composite_type = isinstance(rtype, GraphQLCompositeType)
if not field.selection_set and is_gql_composite_type:
return [
graphql_error_from_nodes(
message=f"Field {field.name.value} of type {rtype.name} must have a selection of subfields.",
nodes=field,
path=path,
extensions=self._extensions,
)
]
if field.selection_set and not is_gql_composite_type:
return [
graphql_error_from_nodes(
message=f"Field {field.name.value} must not have a selection since type {rtype.name} has no subfields.",
nodes=field,
path=path,
extensions=self._extensions,
)
]
return []
| 918 |
3,702 | <gh_stars>1000+
// Copyright (c) YugaByte, 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 org.yb.cql;
import org.junit.Test;
import static org.yb.AssertionWrappers.assertEquals;
import static org.yb.AssertionWrappers.fail;
import org.yb.YBTestRunner;
import org.junit.runner.RunWith;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
@RunWith(value=YBTestRunner.class)
public class TestUseKeyspace extends BaseCQLTest {
private static final Logger LOG = LoggerFactory.getLogger(TestUseKeyspace.class);
private void testCreateExistingKeyspace(String keyspace) throws Exception {
try {
createKeyspace(keyspace);
fail("CREATE KEYSPACE \"" + keyspace + "\" did not fail");
} catch (com.datastax.driver.core.exceptions.InvalidQueryException e) {
LOG.info("Expected InvalidQuery exception", e);
}
}
private void testUseKeyspace(String keyspace, boolean create) throws Exception {
if (create) {
createKeyspace(keyspace);
}
useKeyspace(keyspace);
assertEquals(keyspace, session.getLoggedKeyspace());
}
private void testUseInvalidKeyspace(String keyspace) throws Exception {
try {
useKeyspace(keyspace);
fail("USE \"" + keyspace + "\" did not fail");
} catch (com.datastax.driver.core.exceptions.InvalidQueryException e) {
LOG.info("Expected InvalidQuery exception", e);
}
}
@Test
public void testUseKeyspace() throws Exception {
LOG.info("Begin test testUseKeyspace()");
// Use existing system keyspace.
testUseKeyspace("system", false);
// Use existing system_schema keyspace.
testUseKeyspace("system_schema", false);
// Create new keyspace and use it.
testUseKeyspace("test_keyspace", true);
// Use a non-existent keyspace.
testUseInvalidKeyspace("no_such_keyspace");
LOG.info("End test testUseKeyspace()");
}
@Test
public void testKeyspaceDoubleCreation() throws Exception {
LOG.info("Begin test testKeyspaceDoubleCreation()");
// Create new keyspace and use it.
testUseKeyspace("new_keyspace", true);
// Try to create already existing keyspace.
testCreateExistingKeyspace("new_keyspace");
// Try to create already existing default test keyspace.
testCreateExistingKeyspace(DEFAULT_TEST_KEYSPACE);
LOG.info("End test testKeyspaceDoubleCreation()");
}
}
| 934 |
348 | <filename>docs/data/leg-t2/032/03201205.json<gh_stars>100-1000
{"nom":"Laveraët","circ":"1ère circonscription","dpt":"Gers","inscrits":82,"abs":39,"votants":43,"blancs":2,"nuls":4,"exp":37,"res":[{"nuance":"REM","nom":"<NAME>","voix":29},{"nuance":"SOC","nom":"<NAME>","voix":8}]} | 118 |
473 | <gh_stars>100-1000
/*
Copyright (c) 2009-2016, <NAME>
All rights reserved.
This file is part of Elemental and is under the BSD 2-Clause License,
which can be found in the LICENSE file in the root directory, or at
http://opensource.org/licenses/BSD-2-Clause
*/
#include <El.hpp>
// This driver is an adaptation of the solver described at
// http://www.stanford.edu/~boyd/papers/admm/covsel/covsel.html
// which is derived from the distributed ADMM article of Boyd et al.
//
// The experiment is described in detail in Section 4 of:
// <NAME>, <NAME>, and <NAME>,
// "First-order methods for sparse covariance selection"
typedef double Real;
typedef Real Field;
int main( int argc, char* argv[] )
{
El::Environment env( argc, argv );
try
{
const El::Int n = El::Input("--n","problem size",200);
const El::Int N = El::Input("--N","number of samples",2000);
const Real probNnz =
El::Input("--probNnz","probability of nonzero",0.01);
const Real sigma = El::Input("--sigma","scaling of noise matrix",0.0);
const El::Int maxIter =
El::Input("--maxIter","maximum # of iter's",500);
const Real lambda = El::Input("--lambda","vector l1 penalty",0.01);
const Real rho = El::Input("--rho","augmented Lagrangian param.",1.);
const Real alpha = El::Input("--alpha","over-relaxation",1.2);
const Real absTol = El::Input("--absTol","absolute tolerance",1e-5);
const Real relTol = El::Input("--relTol","relative tolerance",1e-3);
const Real shift = El::Input("--shift","shift for noisy B",1e-8);
const Real shiftScale =
El::Input("--shiftScale","scaling for shift",1.1);
const bool progress = El::Input("--progress","print progress?",true);
const bool display = El::Input("--display","display matrices?",false);
const bool print = El::Input("--print","print matrices",false);
El::ProcessInput();
El::PrintInputReport();
El::DistMatrix<Field> SInv;
El::Zeros( SInv, n, n );
for( El::Int jLoc=0; jLoc<SInv.LocalWidth(); ++jLoc )
{
const El::Int j = SInv.GlobalCol(jLoc);
for( El::Int iLoc=0; iLoc<SInv.LocalHeight(); ++iLoc )
{
const El::Int i = SInv.GlobalRow(iLoc);
if( i == j )
{
SInv.SetLocal( iLoc, jLoc, Field(1) );
}
else
{
if( El::SampleUniform<Real>() <= probNnz )
{
if( El::SampleUniform<Real>() <= 0.5 )
SInv.SetLocal( iLoc, jLoc, Field(1) );
else
SInv.SetLocal( iLoc, jLoc, Field(-1) );
}
}
}
}
El::MakeHermitian( El::LOWER, SInv );
// Shift SInv so that it is sufficiently SPD
El::DistMatrix<Field> G( SInv );
El::DistMatrix<Real,El::VR,El::STAR> w;
El::HermitianEig( El::LOWER, G, w );
Real minEig = El::MinLoc(w).value;
if( minEig <= Real(0) )
El::ShiftDiagonal( SInv, shift-shiftScale*minEig );
// Inverse SInv
El::DistMatrix<Field> S( SInv );
El::HermitianInverse( El::LOWER, S );
El::MakeHermitian( El::LOWER, S );
// Add noise and force said matrix to stay SPD
El::DistMatrix<Field> V;
El::Uniform( V, n, n );
El::MakeHermitian( El::LOWER, V );
El::DistMatrix<Field> SNoisy( S );
El::Axpy( sigma, V, SNoisy );
G = SNoisy;
El::HermitianEig( El::LOWER, G, w );
minEig = El::MinLoc(w).value;
if( minEig <= Real(0) )
El::ShiftDiagonal( SNoisy, shift-shiftScale*minEig );
// Sample from the noisy covariance matrix
El::DistMatrix<Field> D;
El::Gaussian( D, N, n );
El::Covariance( D, G );
El::ShiftDiagonal( G, Field(-1) );
const Real unitCovErrNorm = El::FrobeniusNorm( G );
G = SNoisy;
El::Cholesky( El::LOWER, G );
El::Trmm
( El::RIGHT, El::LOWER, El::TRANSPOSE, El::NON_UNIT, Field(1), G, D );
El::Covariance( D, G );
G -= SNoisy;
const Real SNorm = El::FrobeniusNorm( S );
const Real SNoisyNorm = El::FrobeniusNorm( SNoisy );
const Real covErrNorm = El::FrobeniusNorm( G );
if( print )
{
El::Print( SInv, "SInv" );
El::Print( S, "S" );
El::Print( SNoisy, "SNoisy" );
El::Print( D, "D" );
}
if( display )
{
El::Display( SInv, "SInv" );
El::Display( S, "S" );
El::Display( SNoisy, "SNoisy" );
El::Display( D, "D" );
}
if( El::mpi::Rank() == 0 )
El::Output
("|| S ||_F = ",SNorm,"\n",
"|| SNoisy ||_F = ",SNoisyNorm,"\n",
"|| cov(Omega)-I ||_F = ",unitCovErrNorm,"\n",
"|| cov(D)-SNoisy ||_F / || S ||_F = ",covErrNorm/SNorm,"\n");
El::SparseInvCovCtrl<El::Base<Field>> ctrl;
ctrl.rho = rho;
ctrl.alpha = alpha;
ctrl.maxIter = maxIter;
ctrl.absTol = absTol;
ctrl.relTol = relTol;
ctrl.progress = progress;
El::Timer timer;
El::DistMatrix<Field> Z;
if( El::mpi::Rank() == 0 )
timer.Start();
El::SparseInvCov( D, lambda, Z, ctrl );
if( El::mpi::Rank() == 0 )
timer.Stop();
const Real SInvNorm = El::FrobeniusNorm( SInv );
G = Z;
G -= SInv;
const Real ZErrNorm = El::FrobeniusNorm( G );
if( print )
El::Print( Z, "Z" );
if( El::mpi::Rank() == 0 )
{
El::Output("SparseInvCov time: ",timer.Total()," secs");
El::Output
("|| SInv ||_F = ",SInvNorm,"\n",
"|| Z - SInv ||_F = ",ZErrNorm/SInvNorm,"\n");
}
}
catch( std::exception& e ) { El::ReportException(e); }
return 0;
}
| 3,139 |
309 | /*
This example demonstrates the usage of the vtNamedColor class.
*/
#include <vtkActor.h>
#include <vtkAlgorithm.h>
#include <vtkBandedPolyDataContourFilter.h>
#include <vtkConeSource.h>
#include <vtkElevationFilter.h>
#include <vtkLookupTable.h>
#include <vtkNamedColors.h>
#include <vtkPolyData.h>
#include <vtkPolyDataMapper.h>
#include <vtkProperty.h>
#include <vtkRenderWindow.h>
#include <vtkRenderWindowInteractor.h>
#include <vtkRenderer.h>
#include <vtkSmartPointer.h>
#include <algorithm>
#include <iostream>
#include <regex>
#include <sstream>
#include <vector>
namespace {
// Get the color names.
std::vector<std::string> GetColorNames(vtkNamedColors* namedColors);
// Get the synonyms.
std::vector<std::vector<std::string>> GetSynonyms(vtkNamedColors* namedColors);
// Print out the colors.
void PrintColors(vtkNamedColors* namedColors);
// Print out the synonyms.
void PrintSynonyms(vtkNamedColors* namedColors);
// Find any synonyms for a specified color.
std::vector<std::string> FindSynonyms(const std::string& color,
vtkNamedColors* namedColors);
} // namespace
// Create a cone, contour it using the banded contour filter and
// color it with the primary additive and subtractive colors.
int main(int, char*[])
{
auto namedColors = vtkSmartPointer<vtkNamedColors>::New();
// We can print out the variables.
// The color name and RGBA values are displayed.
// namedColors->PrintSelf(std::cout,vtkIndent(2));
// Here we just print out the colors and any
// synonyms.
PrintColors(namedColors);
PrintSynonyms(namedColors);
// Create a cone
auto coneSource = vtkSmartPointer<vtkConeSource>::New();
coneSource->SetCenter(0.0, 0.0, 0.0);
coneSource->SetRadius(5.0);
coneSource->SetHeight(10);
coneSource->SetDirection(0, 1, 0);
coneSource->SetResolution(6);
coneSource->Update();
double bounds[6];
coneSource->GetOutput()->GetBounds(bounds);
auto elevation = vtkSmartPointer<vtkElevationFilter>::New();
elevation->SetInputConnection(coneSource->GetOutputPort());
elevation->SetLowPoint(0, bounds[2], 0);
elevation->SetHighPoint(0, bounds[3], 0);
auto bcf = vtkSmartPointer<vtkBandedPolyDataContourFilter>::New();
bcf->SetInputConnection(elevation->GetOutputPort());
bcf->SetScalarModeToValue();
bcf->GenerateContourEdgesOn();
bcf->GenerateValues(7, elevation->GetScalarRange());
double rgba[4];
// Test setting and getting colors here.
// We are also modifying alpha.
namedColors->GetColor("Red", rgba);
// Make it semitransparent.
rgba[3] = 0.5;
namedColors->SetColor("My Red", rgba);
// Does "My Red" match anything?
// Demonstrates how to find synonyms.
auto matchingColors = FindSynonyms("My Red", namedColors);
if (!matchingColors.empty())
{
std::cout << "Matching colors to My Red: ";
size_t i = 1;
for (auto p : matchingColors)
{
std::cout << p;
if (i < matchingColors.size())
{
std::cout << ", ";
i = 1;
}
++i;
}
std::cout << std::endl;
}
// Build a simple lookup table of
// primary additive and subtractive colors.
auto lut = vtkSmartPointer<vtkLookupTable>::New();
lut->SetNumberOfTableValues(7);
lut->SetTableValue(0, namedColors->GetColor4d("My Red").GetData());
// Let's make the dark green one partially transparent.
namedColors->GetColor("Lime", rgba);
rgba[3] = 0.3;
lut->SetTableValue(1, rgba);
lut->SetTableValue(2, namedColors->GetColor4d("Blue").GetData());
lut->SetTableValue(3, namedColors->GetColor4d("Cyan").GetData());
lut->SetTableValue(4, namedColors->GetColor4d("Magenta").GetData());
lut->SetTableValue(5, namedColors->GetColor4d("Yellow").GetData());
lut->SetTableValue(6, namedColors->GetColor4d("White").GetData());
lut->SetTableRange(elevation->GetScalarRange());
lut->Build();
auto mapper = vtkSmartPointer<vtkPolyDataMapper>::New();
mapper->SetInputConnection(bcf->GetOutputPort());
mapper->SetScalarRange(elevation->GetScalarRange());
mapper->SetLookupTable(lut);
mapper->SetScalarModeToUseCellData();
auto contourLineMapper = vtkSmartPointer<vtkPolyDataMapper>::New();
contourLineMapper->SetInputData(bcf->GetContourEdgesOutput());
contourLineMapper->SetScalarRange(elevation->GetScalarRange());
contourLineMapper->SetResolveCoincidentTopologyToPolygonOffset();
auto actor = vtkSmartPointer<vtkActor>::New();
actor->SetMapper(mapper);
auto contourLineActor = vtkSmartPointer<vtkActor>::New();
contourLineActor->SetMapper(contourLineMapper);
contourLineActor->GetProperty()->SetColor(
namedColors->GetColor3d("Black").GetData());
auto renderer = vtkSmartPointer<vtkRenderer>::New();
auto renderWindow = vtkSmartPointer<vtkRenderWindow>::New();
renderWindow->AddRenderer(renderer);
auto renderWindowInteractor =
vtkSmartPointer<vtkRenderWindowInteractor>::New();
renderWindowInteractor->SetRenderWindow(renderWindow);
renderer->AddActor(actor);
renderer->AddActor(contourLineActor);
renderer->SetBackground2(namedColors->GetColor3d("RoyalBlue").GetData());
renderer->SetBackground(namedColors->GetColor3d("MistyRose").GetData());
renderer->GradientBackgroundOn();
renderWindow->SetSize(600, 600);
renderWindow->Render();
renderWindow->SetWindowName("NamedColors");
renderWindow->Render();
renderWindowInteractor->Start();
return EXIT_SUCCESS;
}
namespace {
std::vector<std::string> GetColorNames(vtkNamedColors* namedColors)
{
std::stringstream ss(namedColors->GetColorNames());
std::string color;
std::vector<std::string> cn;
while (std::getline(ss, color, '\n'))
{
cn.push_back(std::move(color));
}
return cn;
}
std::vector<std::vector<std::string>> GetSynonyms(vtkNamedColors* namedColors)
{
auto ncsyn = namedColors->GetSynonyms();
std::stringstream ss(std::regex_replace(ncsyn, std::regex("\n\n"), "*"));
std::string synonyms;
std::vector<std::vector<std::string>> sn;
while (std::getline(ss, synonyms, '*'))
{
std::vector<std::string> syns;
std::stringstream ss1(synonyms);
std::string color;
while (std::getline(ss1, color, '\n'))
{
syns.push_back(std::move(color));
}
sn.push_back(std::move(syns));
}
return sn;
}
std::vector<std::string> FindSynonyms(const std::string& color,
vtkNamedColors* namedColors)
{
auto availableColors = GetColorNames(namedColors);
// We will be matching on RGB only.
auto myColor = namedColors->GetColor3ub(color);
// Colors are all stored as lower case, so convert color to lower case.
std::string lcColor;
std::transform(color.begin(), color.end(), std::back_inserter(lcColor),
(int (*)(int))std::tolower);
std::vector<std::string> synonyms;
for (auto p : availableColors)
{
auto c = namedColors->GetColor3ub(p);
if (myColor.Compare(c, 1))
{
synonyms.push_back(p);
}
}
return synonyms;
}
void PrintColors(vtkNamedColors* namedColors)
{
// Get the available colors:
auto colors = GetColorNames(namedColors);
std::cout << "There are " << colors.size() << " colors:" << std::endl;
auto max_str =
std::max_element(colors.begin(), colors.end(),
[](std::string const& a, std::string const& b) {
return a.size() < b.size();
});
auto max_str_len = max_str->size();
auto n = 0;
std::ostringstream os;
for (auto const p : colors)
{
++n;
if (n % 5 == 0)
{
os << std::left << p << std::endl;
}
else
{
os << std::left << std::setw(max_str_len) << p << " ";
}
}
std::string s = std::regex_replace(os.str(), std::regex("\\s+$"), "\n");
std::cout << s << std::endl;
}
void PrintSynonyms(vtkNamedColors* namedColors)
{
// Get the synonyms:
auto synonyms = GetSynonyms(namedColors);
std::cout << "There are " << synonyms.size() << " synonyms:" << std::endl;
// Get the size of the longest synonym name.
size_t max_str_len = 0;
for (auto const p : synonyms)
{
auto max_str = std::max_element(
p.begin(), p.end(), [](std::string const& a, std::string const& b) {
return a.size() < b.size();
});
max_str_len =
(max_str_len < max_str->size()) ? max_str->size() : max_str_len;
}
for (auto const p : synonyms)
{
size_t n = 0;
for (auto const q : p)
{
++n;
if (n < p.size())
{
std::cout << std::left << std::setw(max_str_len) << q << " ";
}
else
{
std::cout << q << std::endl;
}
}
}
std::cout << std::endl;
}
} // namespace
| 3,393 |
6,989 | #include <library/cpp/iterator/functools.h>
#include <library/cpp/testing/gtest/gtest.h>
#include <util/generic/vector.h>
#include <util/generic/xrange.h>
#include <util/generic/adaptor.h>
#include <set>
// default-win-x86_64-release compiler can't decompose tuple to structure binding (02.03.2019)
#ifndef _WINDOWS
# define FOR_DISPATCH_2(i, j, r) \
for (auto [i, j] : r)
# define FOR_DISPATCH_3(i, j, k, r) \
for (auto [i, j, k] : r)
#else
# define FOR_DISPATCH_2(i, j, r) \
for (auto __t_##i##_##j : r) \
if (auto& i = std::get<0>(__t_##i##_##j); true) \
if (auto& j = std::get<1>(__t_##i##_##j); true)
# define FOR_DISPATCH_3(i, j, k, r) \
for (auto __t_##i##_##j##_##k : r) \
if (auto& i = std::get<0>(__t_##i##_##j##_##k); true) \
if (auto& j = std::get<1>(__t_##i##_##j##_##k); true) \
if (auto& k = std::get<2>(__t_##i##_##j##_##k); true)
#endif
using namespace NFuncTools;
template <typename TContainer>
auto ToVector(TContainer&& container) {
return std::vector{container.begin(), container.end()};
}
template <typename TContainerObjOrRef>
void TestViewCompileability(TContainerObjOrRef&& container) {
using TContainer = std::decay_t<TContainerObjOrRef>;
using TIterator = typename TContainer::iterator;
static_assert(std::is_same_v<decltype(container.begin()), TIterator>);
// iterator_traits must work!
using difference_type = typename std::iterator_traits<TIterator>::difference_type;
using value_type = typename std::iterator_traits<TIterator>::value_type;
using reference = typename std::iterator_traits<TIterator>::reference;
using pointer = typename std::iterator_traits<TIterator>::pointer;
{
// operator assignment
auto it = container.begin();
it = container.end();
it = std::move(container.begin());
// operator copying
auto it2 = it;
Y_UNUSED(it2);
auto it3 = std::move(it);
Y_UNUSED(it3);
Y_UNUSED(*it3);
EXPECT_TRUE(it3 == it3);
EXPECT_FALSE(it3 != it3);
// const TIterator
const auto it4 = it3;
Y_UNUSED(*it4);
EXPECT_TRUE(it4 == it4);
EXPECT_FALSE(it4 != it4);
EXPECT_TRUE(it3 == it4);
EXPECT_TRUE(it4 == it3);
EXPECT_FALSE(it3 != it4);
EXPECT_FALSE(it4 != it3);
}
auto it = container.begin();
// sanity check for types
using TConstReference = const std::remove_reference_t<reference>&;
TConstReference ref = *it;
Y_UNUSED(ref);
(void) static_cast<value_type>(*it);
(void) static_cast<difference_type>(1);
if constexpr (std::is_reference_v<decltype(*it)>) {
pointer ptr = &*it;
Y_UNUSED(ptr);
}
// std compatibility
ToVector(container);
// const iterators
[](const auto& cont) {
auto constBeginIterator = cont.begin();
auto constEndIterator = cont.end();
static_assert(std::is_same_v<decltype(constBeginIterator), typename TContainer::const_iterator>);
Y_UNUSED(constBeginIterator);
Y_UNUSED(constEndIterator);
}(container);
}
struct TTestSentinel {};
struct TTestIterator {
int operator*() {
return X;
}
void operator++() {
++X;
}
bool operator!=(const TTestSentinel&) const {
return X < 3;
}
int X;
};
// container with minimal interface
auto MakeMinimalisticContainer() {
return MakeIteratorRange(TTestIterator{}, TTestSentinel{});
}
TEST(FuncTools, CompileRange) {
TestViewCompileability(Range(19));
TestViewCompileability(Range(10, 19));
TestViewCompileability(Range(10, 19, 2));
}
TEST(FuncTools, Enumerate) {
TVector<size_t> a = {1, 2, 4};
TVector<size_t> b;
TVector<size_t> c = {1};
for (auto& v : {a, b, c}) {
size_t j = 0;
FOR_DISPATCH_2(i, x, Enumerate(v)) {
EXPECT_EQ(v[i], x);
EXPECT_EQ(i, j++);
EXPECT_LT(i, v.size());
}
EXPECT_EQ(j, v.size());
}
TVector<size_t> d = {0, 0, 0};
FOR_DISPATCH_2(i, x, Enumerate(d)) {
x = i;
}
EXPECT_THAT(
d,
testing::ElementsAre(0u, 1u, 2u)
);
}
TEST(FuncTools, EnumerateTemporary) {
TVector<size_t> a = {1, 2, 4};
TVector<size_t> b;
TVector<size_t> c = {1};
for (auto& v : {a, b, c}) {
size_t j = 0;
FOR_DISPATCH_2(i, x, Enumerate(TVector(v))) {
EXPECT_EQ(v[i], x);
EXPECT_EQ(i, j++);
EXPECT_LT(i, v.size());
}
EXPECT_EQ(j, v.size());
}
FOR_DISPATCH_2(i, x, Enumerate(TVector<size_t>{1, 2, 3})) {
EXPECT_EQ(i + 1, x);
}
}
TEST(FuncTools, CompileEnumerate) {
auto container = std::vector{1, 2, 3};
TestViewCompileability(Enumerate(container));
const auto constContainer = std::vector{1, 2, 3};
TestViewCompileability(Enumerate(constContainer));
const int arrayContainer[] = {1, 2, 3};
TestViewCompileability(Enumerate(arrayContainer));
std::vector<std::pair<int, int>> res;
FOR_DISPATCH_2(i, x, Enumerate(MakeMinimalisticContainer())) {
res.push_back({i, x});
}
EXPECT_EQ(res, (std::vector<std::pair<int, int>>{
{0, 0}, {1, 1}, {2, 2},
}));
}
TEST(FuncTools, Zip) {
TVector<std::pair<TVector<size_t>, TVector<size_t>>> ts = {
{{1, 2, 3}, {4, 5, 6}},
{{1, 2, 3}, {4, 5, 6, 7}},
{{1, 2, 3, 4}, {4, 5, 6}},
{{1, 2, 3, 4}, {}},
};
FOR_DISPATCH_2(a, b, ts) {
size_t k = 0;
FOR_DISPATCH_2(i, j, Zip(a, b)) {
EXPECT_EQ(++k, i);
EXPECT_EQ(i + 3, j);
}
EXPECT_EQ(k, Min(a.size(), b.size()));
}
}
TEST(FuncTools, ZipReference) {
TVector a = {0, 1, 2};
TVector b = {2, 1, 0, -1};
FOR_DISPATCH_2(ai, bi, Zip(a, b)) {
ai = bi;
}
EXPECT_THAT(
a,
testing::ElementsAre(2u, 1u, 0u)
);
}
TEST(FuncTools, Zip3) {
TVector<std::tuple<TVector<i32>, TVector<i32>, TVector<i32>>> ts = {
{{1, 2, 3}, {4, 5, 6}, {11, 3}},
{{1, 2, 3}, {4, 5, 6, 7}, {9, 0}},
{{1, 2, 3, 4}, {9}, {4, 5, 6}},
{{1, 2, 3, 4}, {1}, {}},
{{}, {1}, {1, 2, 3, 4}},
};
FOR_DISPATCH_3(a, b, c, ts) {
TVector<std::tuple<i32, i32, i32>> e;
for (size_t j = 0; j < a.size() && j < b.size() && j < c.size(); ++j) {
e.push_back({a[j], b[j], c[j]});
}
TVector<std::tuple<i32, i32, i32>> f;
FOR_DISPATCH_3(ai, bi, ci, Zip(a, b, c)) {
f.push_back({ai, bi, ci});
}
EXPECT_EQ(e, f);
}
}
TEST(FuncTools, CompileZip) {
auto container = std::vector{1, 2, 3};
TestViewCompileability(Zip(container));
TestViewCompileability(Zip(container, container, container));
const auto constContainer = std::vector{1, 2, 3};
TestViewCompileability(Zip(constContainer, constContainer));
const int arrayContainer[] = {1, 2, 3};
TestViewCompileability(Zip(arrayContainer, arrayContainer));
std::vector<std::pair<int, int>> res;
FOR_DISPATCH_2(a, b, Zip(MakeMinimalisticContainer(), container)) {
res.push_back({a, b});
}
EXPECT_EQ(res, (std::vector<std::pair<int, int>>{
{0, 1}, {1, 2}, {2, 3},
}));
}
TEST(FuncTools, Filter) {
TVector<TVector<i32>> ts = {
{},
{1},
{2},
{1, 2},
{2, 1},
{1, 2, 3, 4, 5, 6, 7},
};
auto pred = [](i32 x) -> bool { return x & 1; };
for (auto& a : ts) {
TVector<i32> b;
for (i32 x : a) {
if (pred(x)) {
b.push_back(x);
}
}
TVector<i32> c;
for (i32 x : Filter(pred, a)) {
c.push_back(x);
}
EXPECT_EQ(b, c);
}
}
TEST(FuncTools, CompileFilter) {
auto container = std::vector{1, 2, 3};
auto isOdd = [](int x) { return bool(x & 1); };
TestViewCompileability(Filter(isOdd, container));
const int arrayContainer[] = {1, 2, 3};
TestViewCompileability(Filter(isOdd, arrayContainer));
}
TEST(FuncTools, Map) {
TVector<TVector<i32>> ts = {
{},
{1},
{1, 2},
{1, 2, 3, 4, 5, 6, 7},
};
auto f = [](i32 x) { return x * x; };
for (auto& a : ts) {
TVector<i32> b;
for (i32 x : a) {
b.push_back(f(x));
}
TVector<i32> c;
for (i32 x : Map(f, a)) {
c.push_back(x);
}
EXPECT_EQ(b, c);
}
TVector floats = {1.4, 4.1, 13.9};
TVector ints = {1, 4, 13};
TVector<float> roundedFloats = {1, 4, 13};
TVector<int> res;
TVector<float> resFloat;
for (auto i : Map<int>(floats)) {
res.push_back(i);
}
for (auto i : Map<float>(Map<int>(floats))) {
resFloat.push_back(i);
}
EXPECT_EQ(ints, res);
EXPECT_EQ(roundedFloats, resFloat);
}
TEST(FuncTools, CompileMap) {
auto container = std::vector{1, 2, 3};
auto sqr = [](int x) { return x * x; };
TestViewCompileability(Map(sqr, container));
const int arrayContainer[] = {1, 2, 3};
TestViewCompileability(Map(sqr, arrayContainer));
}
TEST(FuncTools, MapRandomAccess) {
auto sqr = [](int x) { return x * x; };
{
auto container = std::vector{1, 2, 3};
auto mapped = Map(sqr, container);
static_assert(
std::is_same_v<decltype(mapped)::iterator::iterator_category, std::random_access_iterator_tag>
);
}
{
auto container = std::set<int>{1, 2, 3};
auto mapped = Map(sqr, container);
static_assert(
std::is_same_v<decltype(mapped)::iterator::iterator_category, std::input_iterator_tag>
);
}
}
TEST(FuncTools, CartesianProduct) {
TVector<std::pair<TVector<i32>, TVector<i32>>> ts = {
{{1, 2, 3}, {4, 5, 6}},
{{1, 2, 3}, {4, 5, 6, 7}},
{{1, 2, 3, 4}, {4, 5, 6}},
{{1, 2, 3, 4}, {}},
{{}, {1, 2, 3, 4}},
};
for (auto [a, b] : ts) {
TVector<std::pair<i32, i32>> c;
for (auto ai : a) {
for (auto bi : b) {
c.push_back({ai, bi});
}
}
TVector<std::pair<i32, i32>> d;
FOR_DISPATCH_2(ai, bi, CartesianProduct(a, b)) {
d.push_back({ai, bi});
}
EXPECT_EQ(c, d);
}
{
TVector<TVector<int>> g = {{}, {}};
TVector h = {10, 11, 12};
FOR_DISPATCH_2(gi, i, CartesianProduct(g, h)) {
gi.push_back(i);
}
EXPECT_EQ(g[0], h);
EXPECT_EQ(g[1], h);
}
}
TEST(FuncTools, CartesianProduct3) {
TVector<std::tuple<TVector<i32>, TVector<i32>, TVector<i32>>> ts = {
{{1, 2, 3}, {4, 5, 6}, {11, 3}},
{{1, 2, 3}, {4, 5, 6, 7}, {9}},
{{1, 2, 3, 4}, {9}, {4, 5, 6}},
{{1, 2, 3, 4}, {1}, {}},
{{}, {1}, {1, 2, 3, 4}},
};
FOR_DISPATCH_3(a, b, c, ts) {
TVector<std::tuple<i32, i32, i32>> e;
for (auto ai : a) {
for (auto bi : b) {
for (auto ci : c) {
e.push_back({ai, bi, ci});
}
}
}
TVector<std::tuple<i32, i32, i32>> f;
FOR_DISPATCH_3(ai, bi, ci, CartesianProduct(a, b, c)) {
f.push_back({ai, bi, ci});
}
EXPECT_EQ(e, f);
}
}
TEST(FuncTools, CompileCartesianProduct) {
auto container = std::vector{1, 2, 3};
TestViewCompileability(CartesianProduct(container, container));
const auto constContainer = std::vector{1, 2, 3};
TestViewCompileability(CartesianProduct(constContainer, constContainer));
const int arrayContainer[] = {1, 2, 3};
TestViewCompileability(CartesianProduct(arrayContainer, arrayContainer));
std::vector<std::pair<int, int>> res;
FOR_DISPATCH_2(a, b, CartesianProduct(MakeMinimalisticContainer(), MakeMinimalisticContainer())) {
res.push_back({a, b});
}
EXPECT_EQ(res, (std::vector<std::pair<int, int>>{
{0, 0}, {0, 1}, {0, 2},
{1, 0}, {1, 1}, {1, 2},
{2, 0}, {2, 1}, {2, 2},
}));
}
TEST(FuncTools, Concatenate2) {
TVector<std::pair<TVector<i32>, TVector<i32>>> ts = {
{{1, 2, 3}, {4, 5, 6}},
{{1, 2, 3}, {4, 5, 6, 7}},
{{1, 2, 3, 4}, {4, 5, 6}},
{{1, 2, 3, 4}, {}},
{{}, {1, 2, 3, 4}},
};
for (auto [a, b] : ts) {
TVector<i32> c;
for (auto ai : a) {
c.push_back(ai);
}
for (auto bi : b) {
c.push_back(bi);
}
TVector<i32> d;
for (auto x : Concatenate(a, b)) {
d.push_back(x);
}
EXPECT_EQ(c, d);
}
{
TVector<i32> a = {1, 2, 3, 4};
TVector<i32> c;
for (auto x : Concatenate(a, TVector<i32>{5, 6})) {
c.push_back(x);
}
EXPECT_EQ(c, (TVector<i32>{1, 2, 3, 4, 5, 6}));
}
}
TEST(FuncTools, CompileConcatenate) {
auto container = std::vector{1, 2, 3};
TestViewCompileability(Concatenate(container, container));
const auto constContainer = std::vector{1, 2, 3};
TestViewCompileability(Concatenate(constContainer, constContainer));
const int arrayContainer[] = {1, 2, 3};
TestViewCompileability(Concatenate(arrayContainer, arrayContainer));
std::vector<int> res;
for (auto a : Concatenate(MakeMinimalisticContainer(), MakeMinimalisticContainer())) {
res.push_back(a);
}
EXPECT_EQ(res, (std::vector{0, 1, 2, 0, 1, 2}));
}
TEST(FuncTools, Combo) {
FOR_DISPATCH_2(i, j, Enumerate(xrange(10u))) {
EXPECT_EQ(i, j);
}
FOR_DISPATCH_2(i, jk, Enumerate(Enumerate(xrange(10u)))) {
EXPECT_EQ(i, std::get<0>(jk));
EXPECT_EQ(std::get<0>(jk), std::get<1>(jk));
}
TVector<size_t> a = {0, 1, 2};
FOR_DISPATCH_2(i, j, Enumerate(Reversed(a))) {
EXPECT_EQ(i, 2 - j);
}
FOR_DISPATCH_2(i, j, Enumerate(Map<float>(a))) {
EXPECT_EQ(i, (size_t)j);
}
FOR_DISPATCH_2(i, j, Zip(a, Map<float>(a))) {
EXPECT_EQ(i, (size_t)j);
}
auto mapper = [](auto&& x) {
return std::get<0>(x) + std::get<1>(x);
};
FOR_DISPATCH_2(i, j, Zip(a, Map(mapper, Zip(a, a)))) {
EXPECT_EQ(j, 2 * i);
}
}
TEST(FuncTools, CopyIterator) {
TVector a = {1, 2, 3, 4};
TVector b = {4, 5, 6, 7};
// calls f on 2nd, 3d and 4th positions (numeration from 1st)
auto testIterator = [](auto it, auto f) {
++it;
auto it2 = it;
++it2;
++it2;
auto it3 = it;
++it3;
f(*it, *it3, *it2);
};
{
auto iterable = Enumerate(a);
testIterator(std::begin(iterable),
[](auto p2, auto p3, auto p4) {
EXPECT_EQ(std::get<0>(p2), 1u);
EXPECT_EQ(std::get<1>(p2), 2);
EXPECT_EQ(std::get<0>(p3), 2u);
EXPECT_EQ(std::get<1>(p3), 3);
EXPECT_EQ(std::get<0>(p4), 3u);
EXPECT_EQ(std::get<1>(p4), 4);
});
}
{
auto iterable = Map([](i32 x) { return x*x; }, a);
testIterator(std::begin(iterable),
[](auto p2, auto p3, auto p4) {
EXPECT_EQ(p2, 4);
EXPECT_EQ(p3, 9);
EXPECT_EQ(p4, 16);
});
}
{
auto iterable = Zip(a, b);
testIterator(std::begin(iterable),
[](auto p2, auto p3, auto p4) {
EXPECT_EQ(std::get<0>(p2), 2);
EXPECT_EQ(std::get<1>(p2), 5);
EXPECT_EQ(std::get<0>(p3), 3);
EXPECT_EQ(std::get<1>(p3), 6);
EXPECT_EQ(std::get<0>(p4), 4);
EXPECT_EQ(std::get<1>(p4), 7);
});
}
{
auto c = {1, 2, 3, 4, 5, 6, 7, 8};
auto iterable = Filter([](i32 x) { return !(x & 1); }, c);
testIterator(std::begin(iterable),
[](auto p2, auto p3, auto p4) {
EXPECT_EQ(p2, 4);
EXPECT_EQ(p3, 6);
EXPECT_EQ(p4, 8);
});
}
{
auto iterable = CartesianProduct(TVector{0, 1}, TVector{2, 3});
// (0, 2), (0, 3), (1, 2), (1, 3)
testIterator(std::begin(iterable),
[](auto p2, auto p3, auto p4) {
EXPECT_EQ(std::get<0>(p2), 0);
EXPECT_EQ(std::get<1>(p2), 3);
EXPECT_EQ(std::get<0>(p3), 1);
EXPECT_EQ(std::get<1>(p3), 2);
EXPECT_EQ(std::get<0>(p4), 1);
EXPECT_EQ(std::get<1>(p4), 3);
});
}
}
| 10,824 |
3,627 | #ifndef OLC_OPENLOCATIONCODE_H_
#define OLC_OPENLOCATIONCODE_H_
#include <stdlib.h>
#define OLC_VERSION_MAJOR 1
#define OLC_VERSION_MINOR 0
#define OLC_VERSION_PATCH 0
// OLC version number: 2.3.4 => 2003004
// Useful for checking against a particular version or above:
//
// #if OLC_VERSION_NUM < OLC_MAKE_VERSION_NUM(1, 0, 2)
// #error UNSUPPORTED OLC VERSION
// #endif
#define OLC_MAKE_VERSION_NUM(major, minor, patch) \
((major * 1000 + minor) * 1000 + patch)
// OLC version string: 2.3.4 => "2.3.4"
#define OLC_MAKE_VERSION_STR_IMPL(major, minor, patch) \
(#major "." #minor "." #patch)
#define OLC_MAKE_VERSION_STR(major, minor, patch) \
OLC_MAKE_VERSION_STR_IMPL(major, minor, patch)
// Current version, as a number and a string
#define OLC_VERSION_NUM \
OLC_MAKE_VERSION_NUM(OLC_VERSION_MAJOR, OLC_VERSION_MINOR, OLC_VERSION_PATCH)
#define OLC_VERSION_STR \
OLC_MAKE_VERSION_STR(OLC_VERSION_MAJOR, OLC_VERSION_MINOR, OLC_VERSION_PATCH)
// A pair of doubles representing latitude / longitude
typedef struct OLC_LatLon {
double lat;
double lon;
} OLC_LatLon;
// An area defined by two corners (lo and hi) and a code length
typedef struct OLC_CodeArea {
OLC_LatLon lo;
OLC_LatLon hi;
size_t len;
} OLC_CodeArea;
// Get the center coordinates for an area
void OLC_GetCenter(const OLC_CodeArea* area, OLC_LatLon* center);
// Get the effective length for a code
size_t OLC_CodeLength(const char* code, size_t size);
// Check for the three obviously-named conditions
int OLC_IsValid(const char* code, size_t size);
int OLC_IsShort(const char* code, size_t size);
int OLC_IsFull(const char* code, size_t size);
// Encode location with given code length (indicates precision) into an OLC
// Return the string length of the code
int OLC_Encode(const OLC_LatLon* location, size_t code_length, char* code,
int maxlen);
// Encode location with default code length into an OLC
// Return the string length of the code
int OLC_EncodeDefault(const OLC_LatLon* location, char* code, int maxlen);
// Decode OLC into the original location
int OLC_Decode(const char* code, size_t size, OLC_CodeArea* decoded);
// Compute a (shorter) OLC for a given code and a reference location
int OLC_Shorten(const char* code, size_t size, const OLC_LatLon* reference,
char* buf, int maxlen);
// Given shorter OLC and reference location, compute original (full length) OLC
int OLC_RecoverNearest(const char* short_code, size_t size,
const OLC_LatLon* reference, char* code, int maxlen);
#endif
| 950 |
1,338 | <reponame>Kirishikesan/haiku<filename>headers/private/kernel/platform/atari_m68k/MFP.h
/*
* Copyright 2008, Haiku Inc. All rights reserved.
* Distributed under the terms of the MIT License.
*
* Authors:
* <NAME> <<EMAIL>>
*/
#ifndef _MFP_H
#define _MFP_H
/*
* references:
* http://alive.atari.org/hosting/docs/atari/st/MFP.htm
*/
#define MFP_GPDR 0x01
#define MFP_AER 0x03
#define MFP_DDR 0x05
#define MFP_IERA 0x07
#define MFP_IERB 0x09
#define MFP_IPRA 0x0b
#define MFP_IPRB 0x0d
#define MFP_ISRA 0x0f
#define MFP_ISRB 0x11
#define MFP_IMRA 0x13
#define MFP_IMRB 0x15
#define MFP_VR 0x17
#define MFP_TACR 0x19
#define MFP_TBCR 0x1b
#define MFP_TCDCR 0x1d
#define MFP_TADR 0x1f
#define MFP_TBDR 0x21
#define MFP_TCDR 0x23
#define MFP_TDDR 0x25
//XXX
#endif /* _MFP_H */
| 388 |
14,668 | <reponame>chromium/chromium<filename>chrome/browser/ui/views/tabs/tab_close_button.cc
// Copyright 2017 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "chrome/browser/ui/views/tabs/tab_close_button.h"
#include <map>
#include <memory>
#include <vector>
#include "base/hash/hash.h"
#include "chrome/app/vector_icons/vector_icons.h"
#include "chrome/browser/ui/layout_constants.h"
#include "chrome/browser/ui/views/tabs/tab.h"
#include "chrome/browser/ui/views/tabs/tab_controller.h"
#include "components/strings/grit/components_strings.h"
#include "ui/base/l10n/l10n_util.h"
#include "ui/base/metadata/metadata_impl_macros.h"
#include "ui/base/pointer/touch_ui_controller.h"
#include "ui/gfx/canvas.h"
#include "ui/gfx/color_utils.h"
#include "ui/gfx/geometry/insets.h"
#include "ui/gfx/geometry/skia_conversions.h"
#include "ui/gfx/image/image_skia_operations.h"
#include "ui/gfx/paint_vector_icon.h"
#include "ui/views/animation/ink_drop.h"
#include "ui/views/controls/focus_ring.h"
#include "ui/views/controls/highlight_path_generator.h"
#include "ui/views/layout/layout_provider.h"
#include "ui/views/rect_based_targeting_utils.h"
#include "ui/views/view_class_properties.h"
#if defined(USE_AURA)
#include "ui/aura/env.h"
#endif
namespace {
constexpr int kGlyphSize = 16;
constexpr int kTouchGlyphSize = 24;
} // namespace
TabCloseButton::TabCloseButton(PressedCallback pressed_callback,
MouseEventCallback mouse_event_callback)
: views::ImageButton(std::move(pressed_callback)),
mouse_event_callback_(std::move(mouse_event_callback)) {
SetEventTargeter(std::make_unique<views::ViewTargeter>(this));
SetAccessibleName(l10n_util::GetStringUTF16(IDS_ACCNAME_CLOSE));
SetFocusBehavior(FocusBehavior::ACCESSIBLE_ONLY);
views::InkDrop::Get(this)->SetMode(views::InkDropHost::InkDropMode::ON);
views::InkDrop::Get(this)->SetHighlightOpacity(0.16f);
views::InkDrop::Get(this)->SetVisibleOpacity(0.14f);
// Disable animation so that the hover indicator shows up immediately to help
// avoid mis-clicks.
SetAnimationDuration(base::TimeDelta());
views::InkDrop::Get(this)->GetInkDrop()->SetHoverHighlightFadeDuration(
base::TimeDelta());
// The ink drop highlight path is the same as the focus ring highlight path,
// but needs to be explicitly mirrored for RTL.
// TODO(http://crbug.com/1056490): Make ink drops in RTL work the same way as
// focus rings.
auto ink_drop_highlight_path =
std::make_unique<views::CircleHighlightPathGenerator>(gfx::Insets());
ink_drop_highlight_path->set_use_contents_bounds(true);
ink_drop_highlight_path->set_use_mirrored_rect(true);
views::HighlightPathGenerator::Install(this,
std::move(ink_drop_highlight_path));
SetInstallFocusRingOnFocus(true);
// TODO(http://crbug.com/1056490): Once this bug is solved and explicit
// mirroring for ink drops is not needed, we can combine these two.
auto ring_highlight_path =
std::make_unique<views::CircleHighlightPathGenerator>(gfx::Insets());
ring_highlight_path->set_use_contents_bounds(true);
views::FocusRing::Get(this)->SetPathGenerator(std::move(ring_highlight_path));
// Always have a value on this property so we can modify it directly without
// a heap allocation.
SetProperty(views::kInternalPaddingKey, gfx::Insets());
}
TabCloseButton::~TabCloseButton() {}
// static
int TabCloseButton::GetGlyphSize() {
return ui::TouchUiController::Get()->touch_ui() ? kTouchGlyphSize
: kGlyphSize;
}
TabStyle::TabColors TabCloseButton::GetColors() const {
return colors_;
}
void TabCloseButton::SetColors(TabStyle::TabColors colors) {
if (colors == colors_)
return;
colors_ = std::move(colors);
views::InkDrop::Get(this)->SetBaseColor(
color_utils::GetColorWithMaxContrast(colors_.background_color));
OnPropertyChanged(&colors_, views::kPropertyEffectsPaint);
}
void TabCloseButton::SetButtonPadding(const gfx::Insets& padding) {
*GetProperty(views::kInternalPaddingKey) = padding;
}
views::View* TabCloseButton::GetTooltipHandlerForPoint(
const gfx::Point& point) {
// Tab close button has no children, so tooltip handler should be the same
// as the event handler. In addition, a hit test has to be performed for the
// point (as GetTooltipHandlerForPoint() is responsible for it).
if (!HitTestPoint(point))
return nullptr;
return GetEventHandlerForPoint(point);
}
bool TabCloseButton::OnMousePressed(const ui::MouseEvent& event) {
mouse_event_callback_.Run(this, event);
bool handled = ImageButton::OnMousePressed(event);
// Explicitly mark midle-mouse clicks as non-handled to ensure the tab
// sees them.
return !event.IsMiddleMouseButton() && handled;
}
void TabCloseButton::OnMouseReleased(const ui::MouseEvent& event) {
mouse_event_callback_.Run(this, event);
Button::OnMouseReleased(event);
}
void TabCloseButton::OnMouseMoved(const ui::MouseEvent& event) {
mouse_event_callback_.Run(this, event);
Button::OnMouseMoved(event);
}
void TabCloseButton::OnGestureEvent(ui::GestureEvent* event) {
// Consume all gesture events here so that the parent (Tab) does not
// start consuming gestures.
ImageButton::OnGestureEvent(event);
event->SetHandled();
}
gfx::Insets TabCloseButton::GetInsets() const {
return ImageButton::GetInsets() + *GetProperty(views::kInternalPaddingKey);
}
gfx::Size TabCloseButton::CalculatePreferredSize() const {
const int glyph_size = GetGlyphSize();
return gfx::Size(glyph_size, glyph_size) + GetInsets().size();
}
void TabCloseButton::PaintButtonContents(gfx::Canvas* canvas) {
cc::PaintFlags flags;
constexpr float kStrokeWidth = 1.5f;
float touch_scale = static_cast<float>(GetGlyphSize()) / kGlyphSize;
float size = (kGlyphSize - 8) * touch_scale - kStrokeWidth;
gfx::RectF glyph_bounds(GetContentsBounds());
glyph_bounds.ClampToCenteredSize(gfx::SizeF(size, size));
flags.setAntiAlias(true);
flags.setStrokeWidth(kStrokeWidth);
flags.setStrokeCap(cc::PaintFlags::kRound_Cap);
flags.setColor(colors_.foreground_color);
canvas->DrawLine(glyph_bounds.origin(), glyph_bounds.bottom_right(), flags);
canvas->DrawLine(glyph_bounds.bottom_left(), glyph_bounds.top_right(), flags);
}
views::View* TabCloseButton::TargetForRect(views::View* root,
const gfx::Rect& rect) {
CHECK_EQ(root, this);
if (!views::UsePointBasedTargeting(rect))
return ViewTargeterDelegate::TargetForRect(root, rect);
// Ignore the padding set on the button.
gfx::Rect contents_bounds = GetMirroredRect(GetContentsBounds());
#if defined(USE_AURA)
// Include the padding in hit-test for touch events.
// TODO(pkasting): It seems like touch events would generate rects rather
// than points and thus use the TargetForRect() call above. If this is
// reached, it may be from someone calling GetEventHandlerForPoint() while a
// touch happens to be occurring. In such a case, maybe we don't want this
// code to run? It's possible this block should be removed, or maybe this
// whole function deleted. Note that in these cases, we should probably
// also remove the padding on the close button bounds (see Tab::Layout()),
// as it will be pointless.
if (aura::Env::GetInstance()->is_touch_down())
contents_bounds = GetLocalBounds();
#endif
return contents_bounds.Intersects(rect) ? this : parent();
}
bool TabCloseButton::GetHitTestMask(SkPath* mask) const {
// We need to define this so hit-testing won't include the border region.
mask->addRect(gfx::RectToSkRect(GetMirroredRect(GetContentsBounds())));
return true;
}
BEGIN_METADATA(TabCloseButton, views::ImageButton)
ADD_PROPERTY_METADATA(TabStyle::TabColors, Colors)
END_METADATA
| 2,788 |
4,140 | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.hadoop.hive.ql.parse;
import static org.junit.Assert.*;
import java.util.HashMap;
import java.util.Map;
import org.apache.hadoop.hive.common.type.Date;
import org.apache.hadoop.hive.conf.HiveConf;
import org.apache.hadoop.hive.ql.QueryState;
import org.apache.hadoop.hive.ql.security.HadoopDefaultAuthenticator;
import org.apache.hadoop.hive.ql.session.SessionState;
import org.apache.hadoop.hive.serde2.io.DateWritableV2;
import org.junit.Test;
public class TestSemanticAnalyzer {
@Test
public void testNormalizeColSpec() throws Exception {
// Hive normalizes partition spec for dates to yyyy-mm-dd format. Some versions of Java will
// accept other formats for Date.valueOf, e.g. yyyy-m-d, and who knows what else in the future;
// some will not accept other formats, so we cannot test normalization with them - type check
// will fail before it can ever happen. Thus, test in isolation.
checkNormalization("date", "2010-01-01", "2010-01-01", Date.valueOf("2010-01-01"));
checkNormalization("date", "2010-1-01", "2010-01-01", Date.valueOf("2010-01-01"));
checkNormalization("date", "2010-1-1", "2010-01-01", Date.valueOf("2010-01-01"));
checkNormalization("string", "2010-1-1", "2010-1-1", "2010-1-1");
try {
checkNormalization("date", "foo", "", "foo"); // Bad format.
fail("should throw");
} catch (SemanticException ex) {
}
try {
checkNormalization("date", "2010-01-01", "2010-01-01", "2010-01-01"); // Bad value type.
fail("should throw");
} catch (SemanticException ex) {
}
}
public void checkNormalization(String colType, String originalColSpec,
String result, Object colValue) throws SemanticException {
final String colName = "col";
Map<String, String> partSpec = new HashMap<String, String>();
partSpec.put(colName, originalColSpec);
BaseSemanticAnalyzer.normalizeColSpec(partSpec, colName, colType, originalColSpec, colValue);
assertEquals(result, partSpec.get(colName));
if (colValue instanceof Date) {
DateWritableV2 dw = new DateWritableV2((Date)colValue);
BaseSemanticAnalyzer.normalizeColSpec(partSpec, colName, colType, originalColSpec, dw);
assertEquals(result, partSpec.get(colName));
}
}
@Test
public void testUnescapeSQLString() {
assertEquals("abcdefg", BaseSemanticAnalyzer.unescapeSQLString("\"abcdefg\""));
// String enclosed by single quotes.
assertEquals("C0FFEE", BaseSemanticAnalyzer.unescapeSQLString("\'C0FFEE\'"));
// Strings including single escaped characters.
assertEquals("\u0000", BaseSemanticAnalyzer.unescapeSQLString("'\\0'"));
assertEquals("\'", BaseSemanticAnalyzer.unescapeSQLString("\"\\'\""));
assertEquals("\"", BaseSemanticAnalyzer.unescapeSQLString("'\\\"'"));
assertEquals("\b", BaseSemanticAnalyzer.unescapeSQLString("\"\\b\""));
assertEquals("\n", BaseSemanticAnalyzer.unescapeSQLString("'\\n'"));
assertEquals("\r", BaseSemanticAnalyzer.unescapeSQLString("\"\\r\""));
assertEquals("\t", BaseSemanticAnalyzer.unescapeSQLString("'\\t'"));
assertEquals("\u001A", BaseSemanticAnalyzer.unescapeSQLString("\"\\Z\""));
assertEquals("\\", BaseSemanticAnalyzer.unescapeSQLString("'\\\\'"));
assertEquals("\\%", BaseSemanticAnalyzer.unescapeSQLString("\"\\%\""));
assertEquals("\\_", BaseSemanticAnalyzer.unescapeSQLString("'\\_'"));
// String including '\000' style literal characters.
assertEquals("3 + 5 = \u0038", BaseSemanticAnalyzer.unescapeSQLString("'3 + 5 = \\070'"));
assertEquals("\u0000", BaseSemanticAnalyzer.unescapeSQLString("\"\\000\""));
// String including invalid '\000' style literal characters.
assertEquals("256", BaseSemanticAnalyzer.unescapeSQLString("\"\\256\""));
// String including a '\u0000' style literal characters (\u732B is a cat in Kanji).
assertEquals("How cute \u732B are",
BaseSemanticAnalyzer.unescapeSQLString("\"How cute \\u732B are\""));
// String including a surrogate pair character
// (\uD867\uDE3D is Okhotsk atka mackerel in Kanji).
assertEquals("\uD867\uDE3D is a fish",
BaseSemanticAnalyzer.unescapeSQLString("\"\\uD867\uDE3D is a fish\""));
}
@Test
public void testSkipAuthorization() throws Exception {
HiveConf hiveConf = new HiveConf();
hiveConf.setBoolVar(HiveConf.ConfVars.HIVE_AUTHORIZATION_ENABLED, true);
hiveConf.setVar(HiveConf.ConfVars.HIVE_SERVER2_SERVICE_USERS, "u1,u2");
SessionState ss = new SessionState(hiveConf);
ss.setIsHiveServerQuery(true);
ss.setAuthenticator(new HadoopDefaultAuthenticator() {
@Override
public String getUserName() {
return "u3";
}
});
SessionState.setCurrentSessionState(ss);
BaseSemanticAnalyzer analyzer = new BaseSemanticAnalyzer(new QueryState.Builder()
.withHiveConf(hiveConf).nonIsolated().build(), null) {
@Override
public void analyzeInternal(ASTNode ast) throws SemanticException {
// no op
}
};
assertFalse(analyzer.skipAuthorization());
hiveConf.setVar(HiveConf.ConfVars.HIVE_SERVER2_SERVICE_USERS, "u1,u2,u3");
assertTrue(analyzer.skipAuthorization());
}
}
| 2,112 |
2,086 | #ifndef NEWSBOAT_GLOBALS_H_
#define NEWSBOAT_GLOBALS_H_
#include <string>
namespace newsboat {
const std::string LOCK_SUFFIX(".lock");
}
#endif /* NEWSBOAT_GLOBALS_H_ */
| 75 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.