max_stars_count
int64 301
224k
| text
stringlengths 6
1.05M
| token_count
int64 3
727k
|
---|---|---|
675 | /*
* Copyright 2016 The Bazel Authors. All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.idea.blaze.base.run;
import com.google.common.collect.ImmutableSet;
import com.google.idea.blaze.base.command.BlazeCommandName;
import com.google.idea.blaze.base.dependencies.TargetInfo;
import com.google.idea.blaze.base.model.BlazeProjectData;
import com.google.idea.blaze.base.model.primitives.Label;
import com.google.idea.blaze.base.model.primitives.RuleType;
import com.google.idea.blaze.base.run.state.BlazeCommandRunConfigurationCommonState;
import com.google.idea.blaze.base.run.targetfinder.TargetFinder;
import com.intellij.execution.configurations.ConfigurationFactory;
import com.intellij.execution.configurations.RunConfiguration;
import com.intellij.openapi.project.Project;
import javax.annotation.Nullable;
/**
* A factory creating run configurations based on BUILD file targets. Runs last, as a fallback for
* the case where no more specialized factory handles the target.
*/
public class BlazeBuildTargetRunConfigurationFactory extends BlazeRunConfigurationFactory {
// The rule types we auto-create run configurations for during sync.
private static final ImmutableSet<RuleType> HANDLED_RULE_TYPES =
ImmutableSet.of(RuleType.TEST, RuleType.BINARY);
@Override
public boolean handlesTarget(Project project, BlazeProjectData projectData, Label label) {
return findProjectTarget(project, label) != null;
}
@Nullable
private static TargetInfo findProjectTarget(Project project, Label label) {
TargetInfo targetInfo = TargetFinder.findTargetInfo(project, label);
if (targetInfo == null) {
return null;
}
return HANDLED_RULE_TYPES.contains(targetInfo.getRuleType()) ? targetInfo : null;
}
@Override
protected ConfigurationFactory getConfigurationFactory() {
return BlazeCommandRunConfigurationType.getInstance().getFactory();
}
@Override
public void setupConfiguration(RunConfiguration configuration, Label label) {
BlazeCommandRunConfiguration blazeConfig = (BlazeCommandRunConfiguration) configuration;
TargetInfo target = findProjectTarget(configuration.getProject(), label);
blazeConfig.setTargetInfo(target);
if (target == null) {
return;
}
BlazeCommandRunConfigurationCommonState state =
blazeConfig.getHandlerStateIfType(BlazeCommandRunConfigurationCommonState.class);
if (state != null) {
state.getCommandState().setCommand(commandForRuleType(target.getRuleType()));
}
blazeConfig.setGeneratedName();
}
private static BlazeCommandName commandForRuleType(RuleType ruleType) {
switch (ruleType) {
case BINARY:
return BlazeCommandName.RUN;
case TEST:
return BlazeCommandName.TEST;
default:
return BlazeCommandName.BUILD;
}
}
}
| 1,011 |
348 | <reponame>chamberone/Leaflet.PixiOverlay
{"nom":"Fontaine-la-Guyon","circ":"3ème circonscription","dpt":"Eure-et-Loir","inscrits":1083,"abs":562,"votants":521,"blancs":36,"nuls":13,"exp":472,"res":[{"nuance":"LR","nom":"<NAME>","voix":252},{"nuance":"RDG","nom":"<NAME>","voix":220}]} | 119 |
32,544 | package com.baeldung.quarkus;
import io.quarkus.test.common.QuarkusTestResource;
import io.quarkus.test.h2.H2DatabaseTestResource;
import io.quarkus.test.junit.NativeImageTest;
@NativeImageTest
@QuarkusTestResource(H2DatabaseTestResource.class)
public class NativeHelloResourceIT extends HelloResourceUnitTest {
// Execute the same tests but in native mode.
} | 119 |
441 | <reponame>mrdziuban/basex
package org.basex.index.path;
import static org.basex.util.Token.*;
import java.io.*;
import java.util.*;
import org.basex.core.*;
import org.basex.data.*;
import org.basex.index.*;
import org.basex.index.query.*;
import org.basex.index.stats.*;
import org.basex.io.in.DataInput;
import org.basex.io.out.DataOutput;
import org.basex.query.util.index.*;
import org.basex.util.*;
import org.basex.util.list.*;
/**
* This class stores the path summary of a database.
* It contains all unique location paths.
*
* @author BaseX Team 2005-21, BSD License
* @author <NAME>
*/
public final class PathIndex implements Index {
/** Node stack for building the summary. */
private final ArrayList<PathNode> stack = new ArrayList<>();
/** Data reference. */
private Data data;
/** Root node. */
private PathNode root;
/**
* Constructor.
* The {@link Data} reference must be set in a second step via {@link #data(Data)}.
*/
public PathIndex() {
init();
}
/**
* Constructor, specifying a data reference.
* @param data data reference
*/
public PathIndex(final Data data) {
this();
this.data = data;
}
/**
* Constructor, specifying an input file.
* @param data data reference
* @param in input stream
* @throws IOException I/O exception
*/
public PathIndex(final Data data, final DataInput in) throws IOException {
root = in.readBool() ? new PathNode(in, null) : new PathNode();
this.data = data;
}
/**
* Writes the path summary to the specified output.
* @param out output stream
* @throws IOException I/O exception
*/
public void write(final DataOutput out) throws IOException {
out.writeBool(root != null);
if(root != null) root.write(out, data.meta);
}
/**
* Sets the data reference.
* @param dt reference
*/
public void data(final Data dt) {
data = dt;
}
/**
* Initializes the index.
*/
public void init() {
root = new PathNode();
stack.clear();
stack.add(root);
}
@Override
public void close() { }
// Build Index ==================================================================================
/**
* Adds an element or document node.
* @param name name id ({@code 0} for nodes other than elements and attributes)
* @param kind node kind
* @param level current level
*/
public void index(final int name, final byte kind, final int level) {
index(name, kind, level, null, null);
}
/**
* Adds an entry, including its value.
* @param name name id ({@code 0} for nodes other than elements and attributes)
* @param kind node kind
* @param level current level
* @param value value ({@code null} for element or document nodes)
* @param meta meta data (ignored if value is {@code null})
*/
public void index(final int name, final byte kind, final int level, final byte[] value,
final MetaData meta) {
if(level == 0) {
final Stats stats = root.stats;
if(value != null) stats.add(value, meta);
stats.count++;
} else {
while(level >= stack.size()) stack.add(null);
stack.set(level, stack.get(level - 1).index(name, kind, value, meta));
}
}
// Traverse Index ===============================================================================
/**
* Returns the root node.
* @return root node
*/
public ArrayList<PathNode> root() {
final ArrayList<PathNode> out = new ArrayList<>();
out.add(root);
return out;
}
/**
* Returns all parents of the specified nodes.
* Called by the query optimizer.
* @param nodes input nodes
* @return parent nodes
*/
public static ArrayList<PathNode> parent(final ArrayList<PathNode> nodes) {
final ArrayList<PathNode> out = new ArrayList<>();
for(final PathNode node : nodes) {
if(!out.contains(node.parent)) out.add(node.parent);
}
return out;
}
/**
* Returns all children or descendants of the specified nodes.
* Called by the query parser and optimizer.
* @param nodes input nodes
* @param desc if false, return only children
* @return descendant nodes
*/
public static ArrayList<PathNode> desc(final ArrayList<PathNode> nodes, final boolean desc) {
final ArrayList<PathNode> list = new ArrayList<>();
for(final PathNode node : nodes) {
for(final PathNode child : node.children) {
if(desc) child.addDesc(list);
else if(!list.contains(child)) list.add(child);
}
}
return list;
}
/**
* Returns all descendants with the specified element name.
* Called by the query optimizer.
* @param name local name
* @return descendant nodes
*/
public ArrayList<PathNode> desc(final byte[] name) {
final int id = data.elemNames.id(name);
final ArrayList<PathNode> list = new ArrayList<>();
for(final PathNode child : root.children) child.addDesc(list, id);
return list;
}
/**
* Returns descendant element and attribute names for the specified start key.
* Called by the GUI.
* @param name input key
* @param desc if false, return only children
* @param occ true/false: sort by occurrence/lexicographically
* @return names
*/
public TokenList desc(final byte[] name, final boolean desc, final boolean occ) {
final TokenList names = new TokenList();
if(name.length != 0) names.add(name);
return desc(names, desc, occ);
}
/**
* Returns descendant element and attribute names for the specified descendant path.
* Called by the GUI.
* @param names input steps
* @param desc if false, return only children
* @param occ true/false: sort by occurrence/lexicographically
* @return children
*/
public TokenList desc(final TokenList names, final boolean desc, final boolean occ) {
// follow the specified descendant/child steps
ArrayList<PathNode> nodes = desc(root(), true);
for(final byte[] name : names) {
final boolean attr = startsWith(name, '@');
final byte kind = attr ? Data.ATTR : Data.ELEM;
final int id = attr ? data.attrNames.id(substring(name, 1)) : data.elemNames.id(name);
final ArrayList<PathNode> list = new ArrayList<>();
for(final PathNode node : nodes) {
if(node.name != id || node.kind != kind) continue;
for(final PathNode child : node.children) {
if(desc) child.addDesc(list);
else list.add(child);
}
}
nodes = list;
}
// sort by number of occurrences
final int ns = nodes.size();
final int[] tmp = new int[ns];
for(int i = 0; i < ns; ++i) tmp[i] = nodes.get(i).stats.count;
final int[] occs = Array.createOrder(tmp, false);
// remove non-text/attribute nodes
final TokenList tl = new TokenList();
for(int n = 0; n < ns; n++) {
final PathNode node = nodes.get(occ ? occs[n] : n);
final byte[] name = node.token(data);
if(name.length != 0 && !tl.contains(name) && !contains(name, '(')) tl.add(name);
}
if(!occ) tl.sort(false);
return tl;
}
// Info =========================================================================================
@Override
public byte[] info(final MainOptions options) {
return root != null ? chop(root.info(data, 0), 1 << 20) : EMPTY;
}
// Unsupported methods ==========================================================================
@Override
public boolean drop() {
throw Util.notExpected();
}
@Override
public IndexIterator iter(final IndexSearch search) {
throw Util.notExpected();
}
@Override
public IndexCosts costs(final IndexSearch search) {
throw Util.notExpected();
}
@Override
public EntryIterator entries(final IndexEntries entries) {
throw Util.notExpected();
}
@Override
public String toString() {
return string(info(null));
}
}
| 2,630 |
14,668 | <gh_stars>1000+
// Copyright 2021 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 <string>
#include "base/bind.h"
#include "base/files/file_path.h"
#include "base/path_service.h"
#include "base/test/metrics/histogram_tester.h"
#include "build/build_config.h"
#include "chrome/common/chrome_paths.h"
#include "chrome/test/base/chrome_test_utils.h"
#include "content/public/test/browser_test.h"
#include "content/public/test/browser_test_utils.h"
#include "content/public/test/prerender_test_util.h"
#include "net/dns/mock_host_resolver.h"
#include "net/test/embedded_test_server/embedded_test_server.h"
#include "testing/gtest/include/gtest/gtest.h"
#include "third_party/blink/public/mojom/web_feature/web_feature.mojom.h"
#if defined(OS_ANDROID)
#include "chrome/test/base/android/android_browser_test.h"
#else
#include "chrome/test/base/in_process_browser_test.h"
#endif
namespace {
namespace {
// This is equal to content::PrerenderHost::FinalStatus::kActivated.
// TODO(crbug.com/1274021): Replace this with the FinalStatus enum value
// once it is exposed.
const int kFinalStatusActivated = 0;
} // namespace
class PrerenderBrowserTest : public PlatformBrowserTest {
public:
PrerenderBrowserTest()
: prerender_helper_(
base::BindRepeating(&PrerenderBrowserTest::GetActiveWebContents,
base::Unretained(this))) {}
void SetUp() override {
prerender_helper_.SetUp(embedded_test_server());
PlatformBrowserTest::SetUp();
}
void SetUpOnMainThread() override {
host_resolver()->AddRule("*", "127.0.0.1");
embedded_test_server()->ServeFilesFromDirectory(
base::PathService::CheckedGet(chrome::DIR_TEST_DATA));
ASSERT_TRUE(embedded_test_server()->Start());
}
void TearDownOnMainThread() override {
ASSERT_TRUE(embedded_test_server()->ShutdownAndWaitUntilComplete());
}
content::WebContents* GetActiveWebContents() {
return chrome_test_utils::GetActiveWebContents(this);
}
content::test::PrerenderTestHelper& prerender_helper() {
return prerender_helper_;
}
private:
content::test::PrerenderTestHelper prerender_helper_;
};
// An end-to-end test of prerendering and activating.
IN_PROC_BROWSER_TEST_F(PrerenderBrowserTest, PrerenderAndActivate) {
base::HistogramTester histogram_tester;
// Navigate to an initial page.
GURL url = embedded_test_server()->GetURL("/empty.html");
ASSERT_TRUE(content::NavigateToURL(GetActiveWebContents(), url));
// Start a prerender.
GURL prerender_url = embedded_test_server()->GetURL("/simple.html");
prerender_helper().AddPrerender(prerender_url);
// Activate.
content::TestNavigationManager navigation_manager(GetActiveWebContents(),
prerender_url);
ASSERT_TRUE(
content::ExecJs(GetActiveWebContents()->GetMainFrame(),
content::JsReplace("location = $1", prerender_url)));
navigation_manager.WaitForNavigationFinished();
EXPECT_TRUE(navigation_manager.was_prerendered_page_activation());
EXPECT_TRUE(navigation_manager.was_successful());
histogram_tester.ExpectUniqueSample(
"Prerender.Experimental.PrerenderHostFinalStatus.SpeculationRule",
kFinalStatusActivated, 1);
}
// An end-to-end test of prerendering triggered by an embedder and activation.
IN_PROC_BROWSER_TEST_F(PrerenderBrowserTest,
PrerenderTriggeredByEmbedderAndActivate) {
base::HistogramTester histogram_tester;
GURL prerender_url = embedded_test_server()->GetURL("/simple.html");
// Start embedder triggered prerendering.
std::unique_ptr<content::PrerenderHandle> prerender_handle =
GetActiveWebContents()->StartPrerendering(
prerender_url, content::PrerenderTriggerType::kEmbedder,
"DirectURLInput");
EXPECT_TRUE(prerender_handle);
content::test::PrerenderTestHelper::WaitForPrerenderLoadCompletion(
*GetActiveWebContents(), prerender_url);
// Activate.
content::TestNavigationManager navigation_manager(GetActiveWebContents(),
prerender_url);
// Simulate a browser-initiated navigation.
GetActiveWebContents()->OpenURL(content::OpenURLParams(
prerender_url, content::Referrer(), WindowOpenDisposition::CURRENT_TAB,
ui::PageTransitionFromInt(ui::PAGE_TRANSITION_TYPED |
ui::PAGE_TRANSITION_FROM_ADDRESS_BAR),
/*is_renderer_initiated=*/false));
navigation_manager.WaitForNavigationFinished();
EXPECT_TRUE(navigation_manager.was_prerendered_page_activation());
EXPECT_TRUE(navigation_manager.was_successful());
histogram_tester.ExpectUniqueSample(
"Prerender.Experimental.PrerenderHostFinalStatus.Embedder_DirectURLInput",
kFinalStatusActivated, 1);
}
// Tests that UseCounter for SpeculationRules-triggered prerender is recorded.
// This cannot be tested in content/ as SpeculationHostImpl records the usage
// with ContentBrowserClient::LogWebFeatureForCurrentPage() that is not
// implemented in content/.
IN_PROC_BROWSER_TEST_F(PrerenderBrowserTest, UseCounter) {
base::HistogramTester histogram_tester;
// Navigate to an initial page.
GURL url = embedded_test_server()->GetURL("/empty.html");
ASSERT_TRUE(content::NavigateToURL(GetActiveWebContents(), url));
histogram_tester.ExpectBucketCount(
"Blink.UseCounter.Features",
blink::mojom::WebFeature::kSpeculationRulesPrerender, 0);
// Start a prerender. The API call should be recorded.
GURL prerender_url = embedded_test_server()->GetURL("/simple.html");
prerender_helper().AddPrerender(prerender_url);
histogram_tester.ExpectBucketCount(
"Blink.UseCounter.Features",
blink::mojom::WebFeature::kSpeculationRulesPrerender, 1);
// The API call should be recorded only one time per page.
prerender_helper().AddPrerender(prerender_url);
histogram_tester.ExpectBucketCount(
"Blink.UseCounter.Features",
blink::mojom::WebFeature::kSpeculationRulesPrerender, 1);
}
} // namespace
| 2,230 |
480 | /*
* Copyright [2013-2021], Alibaba Group Holding Limited
*
* 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.
*/
/*
* 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.alibaba.polardbx.executor.mpp.execution;
import com.google.common.base.Preconditions;
import com.alibaba.polardbx.common.utils.logger.Logger;
import com.alibaba.polardbx.common.utils.logger.LoggerFactory;
import com.alibaba.polardbx.executor.mpp.Session;
import com.alibaba.polardbx.optimizer.context.ExecutionContext;
import com.alibaba.polardbx.optimizer.memory.MemoryManager;
import com.alibaba.polardbx.optimizer.memory.MemoryPool;
import com.alibaba.polardbx.optimizer.memory.QueryMemoryPool;
import com.alibaba.polardbx.optimizer.spill.QuerySpillSpaceMonitor;
import com.alibaba.polardbx.optimizer.workload.WorkloadUtil;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ScheduledExecutorService;
public final class QueryContext {
private static final Logger log = LoggerFactory.getLogger(QueryContext.class);
private final String queryId;
private final ScheduledExecutorService yieldExecutor;
private QueryMemoryPool queryMemoryPool;
private QuerySpillSpaceMonitor querySpillSpaceMonitor;
private final Map<String, MemoryPool> taskMemoryPools = new ConcurrentHashMap<>();
protected boolean reNewQueryPool;
public QueryContext(
ScheduledExecutorService yieldExecutor,
String queryId) {
this.yieldExecutor = yieldExecutor;
this.queryId = queryId;
}
public QueryMemoryPool getQueryMemoryPool() {
return queryMemoryPool;
}
public QuerySpillSpaceMonitor getQuerySpillSpaceMonitor() {
return querySpillSpaceMonitor;
}
public String getQueryId() {
return queryId;
}
public TaskContext createTaskContext(
TaskStateMachine taskStateMachine, Session session) {
TaskContext taskContext = new TaskContext(yieldExecutor, taskStateMachine, session.getClientContext(),
taskStateMachine.getTaskId());
taskStateMachine.addStateChangeListener(newState -> {
if (newState.isDone()) {
taskContext.end();
}
});
return taskContext;
}
public QueryMemoryPool createQueryMemoryPool(String schema, ExecutionContext executionContext) {
if (this.queryMemoryPool == null) {
Preconditions.checkArgument(executionContext.getWorkloadType() != null, "Workload is null!");
//String workerQueryPoolName = queryId + WORKER_QUERY_POOL_SUFFIX;
//如果server和worker处于一个进程,query进来的时候会在server创建queryPool,所以为了区分worker端创建的queryPool
//名称定为workerQueryPoolName
boolean ap = WorkloadUtil.isApWorkload(executionContext.getWorkloadType());
if (ap) {
this.reNewQueryPool = !MemoryManager.getInstance().getApMemoryPool().getChildren().containsKey(
executionContext.getTraceId());
} else {
this.reNewQueryPool = !MemoryManager.getInstance().getTpMemoryPool().getChildren().containsKey(
executionContext.getTraceId());
}
this.queryMemoryPool = (QueryMemoryPool) MemoryManager.getInstance().createQueryMemoryPool(
ap,
executionContext.getTraceId(), executionContext.getExtraCmds());
}
return this.queryMemoryPool;
}
public QuerySpillSpaceMonitor createQuerySpillSpaceMonitor() {
if (this.querySpillSpaceMonitor == null) {
this.querySpillSpaceMonitor = new QuerySpillSpaceMonitor(queryId);
}
return this.querySpillSpaceMonitor;
}
public void registerTaskMemoryPool(MemoryPool taskMemoryPool) {
taskMemoryPools.put(taskMemoryPool.getName(), taskMemoryPool);
}
public synchronized void destroyQueryMemoryPool() {
taskMemoryPools.clear();
if (queryMemoryPool != null && reNewQueryPool) {
try {
queryMemoryPool.destroy();
} catch (Exception e) {
log.error("destroyMemoryAndStat queryMemoryPool: " + queryId, e);
}
}
try {
if (querySpillSpaceMonitor != null) {
querySpillSpaceMonitor.close();
}
} catch (Exception e) {
log.error("close querySpillSpaceMonitor: " + queryId, e);
}
}
}
| 2,057 |
1,067 | {
"version": 2,
"build": {
"env": {
"REACT_APP_STRIPE_PUBLIC_KEY_TEST": "@react_app_stripe_public_key_test",
"REACT_APP_STRIPE_PUBLIC_KEY_LIVE": "@react_app_stripe_public_key_live",
"REACT_APP_PROVIDER_STRIPE_CLIENT_ID_DEV": "@react_app_provider_stripe_client_id_dev",
"REACT_APP_PROVIDER_STRIPE_CLIENT_ID_PRD": "@react_app_provider_stripe_client_id_prd",
"REACT_APP_PROVIDER_GITHUB_CLIENT_ID_DEV": "@react_app_provider_github_client_id_dev",
"REACT_APP_PROVIDER_GITHUB_CLIENT_ID_PRD": "@react_app_provider_github_client_id_prd",
"REACT_APP_PROVIDER_SPOTIFY_CLIENT_ID_DEV": "@react_app_provider_spotify_client_id_dev",
"REACT_APP_PROVIDER_SPOTIFY_CLIENT_ID_PRD": "@react_app_provider_spotify_client_id_prd",
"REACT_APP_CUBEJS_TOKEN": "@react_app_cubejs_token",
"SKIP_PREFLIGHT_CHECK": "true",
"REACT_APP_GA": "UA-148982321-2"
}
},
"headers": [
{
"source": "/(.*)\\.(jpg|jpeg|png|webp|svg|js|css)",
"headers": [
{
"key": "Cache-Control",
"value": "public, immutable, s-maxage=31536000, max-age=31536000, stale-while-revalidate=60"
}
]
}
]
}
| 595 |
1,144 | // SPDX-License-Identifier: GPL-2.0+
/*
*
* Copyright (C) 2004-2007, 2012 Freescale Semiconductor, Inc.
* <NAME> (<EMAIL>)
*/
/* CPU specific interrupt routine */
#include <common.h>
#include <asm/immap.h>
#include <asm/io.h>
int interrupt_init(void)
{
int0_t *intp = (int0_t *) (CONFIG_SYS_INTR_BASE);
/* Make sure all interrupts are disabled */
setbits_be32(&intp->imrh0, 0xffffffff);
setbits_be32(&intp->imrl0, 0xffffffff);
enable_interrupts();
return 0;
}
#if defined(CONFIG_SLTTMR)
void dtimer_intr_setup(void)
{
int0_t *intp = (int0_t *) (CONFIG_SYS_INTR_BASE);
out_8(&intp->icr0[CONFIG_SYS_TMRINTR_NO], CONFIG_SYS_TMRINTR_PRI);
clrbits_be32(&intp->imrh0, CONFIG_SYS_TMRINTR_MASK);
}
#endif
| 322 |
702 | <filename>consensus/qbft/src/test/java/org/hyperledger/besu/consensus/qbft/validator/TransactionValidatorProviderTest.java
/*
* Copyright ConsenSys AG.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on
* an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the
* specific language governing permissions and limitations under the License.
*
* SPDX-License-Identifier: Apache-2.0
*/
package org.hyperledger.besu.consensus.qbft.validator;
import static java.util.Collections.emptyList;
import static org.assertj.core.api.Assertions.assertThat;
import static org.hyperledger.besu.consensus.qbft.validator.ValidatorTestUtils.createContractForkSpec;
import static org.hyperledger.besu.ethereum.core.InMemoryKeyValueStorageProvider.createInMemoryBlockchain;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.verifyNoMoreInteractions;
import static org.mockito.Mockito.when;
import org.hyperledger.besu.config.QbftConfigOptions;
import org.hyperledger.besu.consensus.common.ForksSchedule;
import org.hyperledger.besu.datatypes.Address;
import org.hyperledger.besu.datatypes.Hash;
import org.hyperledger.besu.ethereum.chain.MutableBlockchain;
import org.hyperledger.besu.ethereum.core.AddressHelpers;
import org.hyperledger.besu.ethereum.core.Block;
import org.hyperledger.besu.ethereum.core.BlockBody;
import org.hyperledger.besu.ethereum.core.BlockHeaderTestFixture;
import java.util.Collection;
import java.util.List;
import java.util.stream.Collectors;
import com.google.common.collect.Lists;
import org.apache.tuweni.bytes.Bytes;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.Mock;
import org.mockito.junit.MockitoJUnitRunner;
@RunWith(MockitoJUnitRunner.class)
public class TransactionValidatorProviderTest {
@Mock private ValidatorContractController validatorContractController;
protected MutableBlockchain blockChain;
protected Block genesisBlock;
protected Block block_1;
protected Block block_2;
private Block block_3;
private ForksSchedule<QbftConfigOptions> forksSchedule;
private final BlockHeaderTestFixture headerBuilder = new BlockHeaderTestFixture();
private static final Address CONTRACT_ADDRESS = Address.fromHexString("1");
@Before
public void setup() {
forksSchedule = new ForksSchedule<>(List.of(createContractForkSpec(0L, CONTRACT_ADDRESS)));
genesisBlock = createEmptyBlock(0, Hash.ZERO);
blockChain = createInMemoryBlockchain(genesisBlock);
headerBuilder.extraData(Bytes.wrap(new byte[32]));
block_1 = createEmptyBlock(1, genesisBlock.getHeader().getHash());
block_2 = createEmptyBlock(2, block_1.getHeader().getHash());
block_3 = createEmptyBlock(3, block_2.getHeader().getHash());
blockChain.appendBlock(block_1, emptyList());
blockChain.appendBlock(block_2, emptyList());
blockChain.appendBlock(block_3, emptyList());
}
private Block createEmptyBlock(final long blockNumber, final Hash parentHash) {
headerBuilder.number(blockNumber).parentHash(parentHash).coinbase(AddressHelpers.ofValue(0));
return new Block(headerBuilder.buildHeader(), new BlockBody(emptyList(), emptyList()));
}
@Test
public void validatorsAfterBlockAreRetrievedUsingContractController() {
final List<Address> validatorsAt2 =
Lists.newArrayList(Address.fromHexString("5"), Address.fromHexString("6"));
final List<Address> validatorsAt3 =
Lists.newArrayList(
Address.fromHexString("5"), Address.fromHexString("6"), Address.fromHexString("7"));
when(validatorContractController.getValidators(2, CONTRACT_ADDRESS)).thenReturn(validatorsAt2);
when(validatorContractController.getValidators(3, CONTRACT_ADDRESS)).thenReturn(validatorsAt3);
final TransactionValidatorProvider validatorProvider =
new TransactionValidatorProvider(blockChain, validatorContractController, forksSchedule);
assertThat(validatorProvider.getValidatorsAfterBlock(block_2.getHeader()))
.containsExactlyElementsOf(validatorsAt2);
assertThat(validatorProvider.getValidatorsAfterBlock(block_3.getHeader()))
.containsExactlyElementsOf(validatorProvider.getValidatorsAfterBlock(block_3.getHeader()));
}
@Test
public void validatorsForBlockAreRetrievedUsingContractController() {
final List<Address> validatorsAt2 =
Lists.newArrayList(Address.fromHexString("5"), Address.fromHexString("6"));
final List<Address> validatorsAt3 =
Lists.newArrayList(
Address.fromHexString("5"), Address.fromHexString("6"), Address.fromHexString("7"));
when(validatorContractController.getValidators(2, CONTRACT_ADDRESS)).thenReturn(validatorsAt2);
when(validatorContractController.getValidators(3, CONTRACT_ADDRESS)).thenReturn(validatorsAt3);
final TransactionValidatorProvider validatorProvider =
new TransactionValidatorProvider(blockChain, validatorContractController, forksSchedule);
assertThat(validatorProvider.getValidatorsForBlock(block_2.getHeader()))
.containsExactlyElementsOf(validatorsAt2);
assertThat(validatorProvider.getValidatorsForBlock(block_3.getHeader()))
.containsExactlyElementsOf(validatorProvider.getValidatorsForBlock(block_3.getHeader()));
}
@Test
public void validatorsAtHeadAreRetrievedUsingContractController() {
final List<Address> validators =
Lists.newArrayList(Address.fromHexString("5"), Address.fromHexString("6"));
when(validatorContractController.getValidators(3, CONTRACT_ADDRESS)).thenReturn(validators);
final TransactionValidatorProvider validatorProvider =
new TransactionValidatorProvider(blockChain, validatorContractController, forksSchedule);
assertThat(validatorProvider.getValidatorsAtHead()).containsExactlyElementsOf(validators);
}
@Test
public void validatorsAtHeadContractCallIsCached() {
final List<Address> validators =
Lists.newArrayList(Address.fromHexString("5"), Address.fromHexString("6"));
when(validatorContractController.getValidators(3, CONTRACT_ADDRESS)).thenReturn(validators);
final TransactionValidatorProvider validatorProvider =
new TransactionValidatorProvider(blockChain, validatorContractController, forksSchedule);
assertThat(validatorProvider.getValidatorsAtHead()).containsExactlyElementsOf(validators);
verify(validatorContractController).getValidators(3, CONTRACT_ADDRESS);
assertThat(validatorProvider.getValidatorsAtHead()).containsExactlyElementsOf(validators);
verifyNoMoreInteractions(validatorContractController);
}
@Test
public void validatorsAfterBlockContractCallIsCached() {
final List<Address> validators =
Lists.newArrayList(Address.fromHexString("5"), Address.fromHexString("6"));
when(validatorContractController.getValidators(2, CONTRACT_ADDRESS)).thenReturn(validators);
final TransactionValidatorProvider validatorProvider =
new TransactionValidatorProvider(blockChain, validatorContractController, forksSchedule);
final Collection<Address> result =
validatorProvider.getValidatorsAfterBlock(block_2.getHeader());
assertThat(result).containsExactlyElementsOf(validators);
verify(validatorContractController).getValidators(2, CONTRACT_ADDRESS);
final Collection<Address> resultCached =
validatorProvider.getValidatorsAfterBlock(block_2.getHeader());
assertThat(resultCached).containsExactlyElementsOf(validators);
verifyNoMoreInteractions(validatorContractController);
}
@Test
public void getValidatorsAfterBlock_and_getValidatorsForBlock_useDifferentCaches() {
final List<Address> validators =
Lists.newArrayList(Address.fromHexString("5"), Address.fromHexString("6"));
when(validatorContractController.getValidators(2, CONTRACT_ADDRESS)).thenReturn(validators);
final TransactionValidatorProvider validatorProvider =
new TransactionValidatorProvider(blockChain, validatorContractController, forksSchedule);
validatorProvider.getValidatorsAfterBlock(block_2.getHeader()); // cache miss
verify(validatorContractController, times(1)).getValidators(2, CONTRACT_ADDRESS);
validatorProvider.getValidatorsAfterBlock(block_2.getHeader()); // cache hit
verifyNoMoreInteractions(validatorContractController);
validatorProvider.getValidatorsForBlock(block_2.getHeader()); // cache miss
verify(validatorContractController, times(2)).getValidators(2, CONTRACT_ADDRESS);
validatorProvider.getValidatorsAfterBlock(block_2.getHeader()); // cache hit
verifyNoMoreInteractions(validatorContractController);
}
@Test
public void validatorsMustBeSorted() {
final List<Address> validators =
Lists.newArrayList(
Address.fromHexString("9"), Address.fromHexString("8"), Address.fromHexString("7"));
when(validatorContractController.getValidators(3, CONTRACT_ADDRESS)).thenReturn(validators);
final TransactionValidatorProvider validatorProvider =
new TransactionValidatorProvider(blockChain, validatorContractController, forksSchedule);
final Collection<Address> result = validatorProvider.getValidatorsAtHead();
final List<Address> expectedValidators =
validators.stream().sorted().collect(Collectors.toList());
assertThat(result).containsExactlyElementsOf(expectedValidators);
}
@Test
public void voteProviderIsEmpty() {
TransactionValidatorProvider transactionValidatorProvider =
new TransactionValidatorProvider(blockChain, validatorContractController, forksSchedule);
assertThat(transactionValidatorProvider.getVoteProviderAtHead()).isEmpty();
}
}
| 3,144 |
348 | <gh_stars>100-1000
{"nom":"Avilley","circ":"3ème circonscription","dpt":"Doubs","inscrits":123,"abs":47,"votants":76,"blancs":9,"nuls":2,"exp":65,"res":[{"nuance":"LR","nom":"<NAME>","voix":43},{"nuance":"REM","nom":"M. <NAME>","voix":22}]} | 99 |
1,724 | <gh_stars>1000+
/*
* Copyright 2008-present MongoDB, 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.mongodb.internal;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.Arguments;
import org.junit.jupiter.params.provider.MethodSource;
import org.junit.jupiter.params.provider.ValueSource;
import java.util.concurrent.TimeUnit;
import java.util.stream.Stream;
import static java.util.concurrent.TimeUnit.NANOSECONDS;
import static org.junit.jupiter.api.Assertions.assertAll;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertNotEquals;
import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.junit.jupiter.api.Assertions.assertTrue;
import static org.junit.jupiter.api.Assertions.assertFalse;
final class TimeoutTest {
@Test
void isInfinite() {
assertAll(
() -> assertTrue(Timeout.infinite().isInfinite()),
() -> assertFalse(Timeout.immediate().isInfinite()),
() -> assertFalse(Timeout.startNow(1).isInfinite()));
}
@Test
void isImmediate() {
assertAll(
() -> assertTrue(Timeout.immediate().isImmediate()),
() -> assertFalse(Timeout.infinite().isImmediate()),
() -> assertFalse(Timeout.startNow(1).isImmediate()));
}
@Test
void startNow() {
assertAll(
() -> assertEquals(Timeout.infinite(), Timeout.startNow(-1)),
() -> assertEquals(Timeout.immediate(), Timeout.startNow(0)),
() -> assertNotEquals(Timeout.infinite(), Timeout.startNow(1)),
() -> assertNotEquals(Timeout.immediate(), Timeout.startNow(1)),
() -> assertNotEquals(Timeout.infinite(), Timeout.startNow(Long.MAX_VALUE - 1)),
() -> assertEquals(Timeout.infinite(), Timeout.startNow(Long.MAX_VALUE)));
}
@ParameterizedTest
@MethodSource("durationArguments")
void startNowConvertsUnits(final long duration, final TimeUnit unit) {
if (duration < 0) {
assertTrue(Timeout.startNow(duration, unit).isInfinite());
} else if (duration == 0) {
assertTrue(Timeout.startNow(duration, unit).isImmediate());
} else {
assertEquals(unit.toNanos(duration), Timeout.startNow(duration, unit).durationNanos());
}
}
private static Stream<Arguments> durationArguments() {
return Stream.of(TimeUnit.values())
.flatMap(unit -> Stream.of(
Arguments.of(-7, unit),
Arguments.of(0, unit),
Arguments.of(7, unit)));
}
@Test
void remainingNanosTrivialCases() {
assertAll(
() -> assertThrows(UnsupportedOperationException.class, () -> Timeout.infinite().remaining(NANOSECONDS)),
() -> assertTrue(Timeout.infinite().remainingOrInfinite(NANOSECONDS) < 0),
() -> assertEquals(0, Timeout.immediate().remaining(NANOSECONDS)),
() -> assertEquals(0, Timeout.immediate().remainingOrInfinite(NANOSECONDS)));
}
@ParameterizedTest
@ValueSource(longs = {1, 7, Long.MAX_VALUE / 2, Long.MAX_VALUE - 1})
void remainingNanos(final long durationNanos) {
Timeout timeout = Timeout.startNow(durationNanos);
long startNanos = timeout.startNanos();
assertEquals(durationNanos, timeout.remainingNanos(startNanos));
assertEquals(Math.max(0, durationNanos - 1), timeout.remainingNanos(startNanos + 1));
assertEquals(0, timeout.remainingNanos(startNanos + durationNanos));
assertEquals(0, timeout.remainingNanos(startNanos + durationNanos + 1));
assertEquals(0, timeout.remainingNanos(startNanos + Long.MAX_VALUE));
assertEquals(0, timeout.remainingNanos(startNanos + Long.MAX_VALUE + 1));
assertEquals(0, timeout.remainingNanos(startNanos + Long.MAX_VALUE + Long.MAX_VALUE));
}
@Test
void expired() {
assertAll(
() -> assertFalse(Timeout.infinite().expired()),
() -> assertTrue(Timeout.immediate().expired()),
() -> assertTrue(Timeout.expired(0)),
() -> assertFalse(Timeout.expired(Long.MIN_VALUE)),
() -> assertFalse(Timeout.expired(-1)),
() -> assertFalse(Timeout.expired(1)),
() -> assertFalse(Timeout.expired(Long.MAX_VALUE)));
}
@Test
void convertRoundUp() {
assertAll(
() -> assertEquals(1, Timeout.convertRoundUp(1, NANOSECONDS)),
() -> assertEquals(0, Timeout.convertRoundUp(0, TimeUnit.MILLISECONDS)),
() -> assertEquals(1, Timeout.convertRoundUp(1, TimeUnit.MILLISECONDS)),
() -> assertEquals(1, Timeout.convertRoundUp(999_999, TimeUnit.MILLISECONDS)),
() -> assertEquals(1, Timeout.convertRoundUp(1_000_000, TimeUnit.MILLISECONDS)),
() -> assertEquals(2, Timeout.convertRoundUp(1_000_001, TimeUnit.MILLISECONDS)),
() -> assertEquals(1, Timeout.convertRoundUp(1, TimeUnit.DAYS)));
}
@ParameterizedTest
@ValueSource(longs = {1, 7, 10, 100, 1000})
void usesRealClock(final long durationNanos) {
long startNanosLowerBound = System.nanoTime();
Timeout timeout = Timeout.startNow(durationNanos);
long startNanosUpperBound = System.nanoTime();
assertTrue(timeout.startNanos() - startNanosLowerBound >= 0, "started too early");
assertTrue(timeout.startNanos() - startNanosUpperBound <= 0, "started too late");
while (!timeout.expired()) {
long remainingNanosUpperBound = Math.max(0, durationNanos - (System.nanoTime() - startNanosUpperBound));
long remainingNanos = timeout.remaining(NANOSECONDS);
long remainingNanosLowerBound = Math.max(0, durationNanos - (System.nanoTime() - startNanosLowerBound));
assertTrue(remainingNanos >= remainingNanosLowerBound, "remaining nanos is too low");
assertTrue(remainingNanos <= remainingNanosUpperBound, "remaining nanos is too high");
Thread.yield();
}
assertTrue(System.nanoTime() - startNanosLowerBound >= durationNanos, "expired too early");
}
private TimeoutTest() {
}
}
| 2,881 |
482 | <filename>code/implementation/host-api/src/main/java/io/cattle/platform/host/api/HostApiProxyToken.java
package io.cattle.platform.host.api;
public interface HostApiProxyToken {
public String getReportedUuid();
public String getToken();
public String getUrl();
}
| 92 |
1,473 | <reponame>ljmf00/autopsy
/*
* Autopsy Forensic Browser
*
* Copyright 2019-2019 Basis Technology Corp. Contact: carrier <at> sleuthkit
* <dot> org
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations under
* the License.
*/
package org.sleuthkit.autopsy.experimental.autoingest;
import java.awt.event.ActionEvent;
import org.openide.util.NbBundle;
import org.sleuthkit.autopsy.casemodule.multiusercases.CaseNodeData;
import org.sleuthkit.autopsy.coreutils.MessageNotifyUtil;
import org.sleuthkit.autopsy.progress.ProgressIndicator;
/**
* An action that completely deletes one or more multi-user cases. Only the
* components created by the application are deleted: the case output and the
* coordination service nodes. Note that manifest file coordination service
* nodes are only marked as deleted by setting the processing status field for
* the corresponding auto ingest job to DELETED. This is done to avoid imposing
* the requirement that the manifests be deleted before deleting the cases,
* since at this time manifests are not considered to be case components created
* by the application.
*/
final class DeleteCaseAction extends DeleteCaseComponentsAction {
private static final long serialVersionUID = 1L;
/**
* Constructs action that completely deletes one or more multi-user cases.
* Only the components created by the application are deleted: the case
* output and the coordination service nodes. Note that manifest file
* coordination service nodes are only marked as deleted by setting the
* processing status field for the corresponding auto ingest job to DELETED.
* This is done to avoid imposing the requirement that the manifests be
* deleted before deleting the cases, since at this time manifests are not
* considered to be case components created by the application.
*/
@NbBundle.Messages({
"DeleteCaseAction.menuItemText=Delete Case(s)",
"DeleteCaseAction.progressDisplayName=Delete Case(s)",
"DeleteCaseAction.taskName=app-input-and-output"
})
DeleteCaseAction() {
super(Bundle.DeleteCaseAction_menuItemText(), Bundle.DeleteCaseAction_progressDisplayName(), Bundle.DeleteCaseAction_taskName());
}
@NbBundle.Messages({
"DeleteCaseAction.confirmationText=Are you sure you want to delete the following for the case(s):\n\tManifest file znodes\n\tCase database\n\tCore.properties file\n\tCase directory\n\tCase znodes"
})
@Override
public void actionPerformed(ActionEvent event) {
if (MessageNotifyUtil.Message.confirm(Bundle.DeleteCaseAction_confirmationText())) {
super.actionPerformed(event);
}
}
@Override
DeleteCaseTask getTask(CaseNodeData caseNodeData, ProgressIndicator progress) {
return new DeleteCaseTask(caseNodeData, DeleteCaseTask.DeleteOptions.DELETE_CASE, progress);
}
}
| 988 |
4,054 | // Copyright Yahoo. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
#pragma once
#include "btreeaggregator.h"
namespace vespalib::btree {
template <typename KeyT, typename DataT, typename AggrT,
size_t INTERNAL_SLOTS, size_t LEAF_SLOTS, class AggrCalcT>
AggrT
BTreeAggregator<KeyT, DataT, AggrT, INTERNAL_SLOTS, LEAF_SLOTS, AggrCalcT>::aggregate(const LeafNodeType &node, AggrCalcT aggrCalc)
{
AggrT a;
for (uint32_t i = 0, ie = node.validSlots(); i < ie; ++i) {
if constexpr (AggrCalcT::aggregate_over_values()) {
aggrCalc.add(a, aggrCalc.getVal(node.getData(i)));
} else {
aggrCalc.add(a, aggrCalc.getVal(node.getKey(i)));
}
}
return a;
}
template <typename KeyT, typename DataT, typename AggrT,
size_t INTERNAL_SLOTS, size_t LEAF_SLOTS, class AggrCalcT>
AggrT
BTreeAggregator<KeyT, DataT, AggrT, INTERNAL_SLOTS, LEAF_SLOTS, AggrCalcT>::aggregate(const InternalNodeType &node, const NodeAllocatorType &allocator, AggrCalcT aggrCalc)
{
AggrT a;
for (uint32_t i = 0, ie = node.validSlots(); i < ie; ++i) {
const BTreeNode::Ref childRef = node.getChild(i);
const AggrT &ca(allocator.getAggregated(childRef));
aggrCalc.add(a, ca);
}
return a;
}
template <typename KeyT, typename DataT, typename AggrT,
size_t INTERNAL_SLOTS, size_t LEAF_SLOTS, class AggrCalcT>
void
BTreeAggregator<KeyT, DataT, AggrT, INTERNAL_SLOTS, LEAF_SLOTS, AggrCalcT>::
recalc(LeafNodeType &node, const AggrCalcT &aggrCalc)
{
node.getAggregated() = aggregate(node, aggrCalc);
}
template <typename KeyT, typename DataT, typename AggrT,
size_t INTERNAL_SLOTS, size_t LEAF_SLOTS, class AggrCalcT>
void
BTreeAggregator<KeyT, DataT, AggrT, INTERNAL_SLOTS, LEAF_SLOTS, AggrCalcT>::
recalc(InternalNodeType &node,
const NodeAllocatorType &allocator,
const AggrCalcT &aggrCalc)
{
node.getAggregated() = aggregate(node, allocator, aggrCalc);
}
template <typename KeyT, typename DataT, typename AggrT,
size_t INTERNAL_SLOTS, size_t LEAF_SLOTS, class AggrCalcT>
typename BTreeAggregator<KeyT, DataT, AggrT, INTERNAL_SLOTS, LEAF_SLOTS,
AggrCalcT>::AggregatedType
BTreeAggregator<KeyT, DataT, AggrT, INTERNAL_SLOTS, LEAF_SLOTS, AggrCalcT>::
recalc(LeafNodeType &node,
LeafNodeType &splitNode,
const AggrCalcT &aggrCalc)
{
AggrT a;
recalc(node, aggrCalc);
recalc(splitNode, aggrCalc);
a = node.getAggregated();
aggrCalc.add(a, splitNode.getAggregated());
return a;
}
template <typename KeyT, typename DataT, typename AggrT,
size_t INTERNAL_SLOTS, size_t LEAF_SLOTS, class AggrCalcT>
typename BTreeAggregator<KeyT, DataT, AggrT, INTERNAL_SLOTS, LEAF_SLOTS,
AggrCalcT>::AggregatedType
BTreeAggregator<KeyT, DataT, AggrT, INTERNAL_SLOTS, LEAF_SLOTS, AggrCalcT>::
recalc(InternalNodeType &node,
InternalNodeType &splitNode,
const NodeAllocatorType &allocator,
const AggrCalcT &aggrCalc)
{
AggrT a;
recalc(node, allocator, aggrCalc);
recalc(splitNode, allocator, aggrCalc);
a = node.getAggregated();
aggrCalc.add(a, splitNode.getAggregated());
return a;
}
}
| 1,551 |
11,356 | // examples/serialise.hpp
// Copyright (c) 2007-2009 <NAME> (http://www.benhanson.net/)
//
// Distributed under the Boost Software License, Version 1.0. (See accompanying
// file licence_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
#ifndef BOOST_LEXER_SERIALISE_HPP
#define BOOST_LEXER_SERIALISE_HPP
#include "internals.hpp"
#include "state_machine.hpp"
#include <boost/serialization/vector.hpp>
namespace boost
{
namespace lexer
{
// IMPORTANT! This won't work if you don't enable RTTI!
template<typename CharT, class Archive>
void serialise (basic_state_machine<CharT> &sm_, Archive &ar_,
unsigned int version_ = 1)
{
detail::internals &internals_ = const_cast<detail::internals &>
(sm_.data ());
ar_ & version_;
ar_ & *internals_._lookup;
ar_ & internals_._dfa_alphabet;
ar_ & *internals_._dfa;
ar_ & internals_._seen_BOL_assertion;
ar_ & internals_._seen_EOL_assertion;
}
}
}
#endif
| 376 |
434 | <filename>TerraForge3D/src/Shading/ShaderNodes/FloatNode.cpp<gh_stars>100-1000
#include "Shading/ShaderNodes/FloatNode.h"
#include <iostream>
void FloatNode::OnEvaluate(GLSLFunction *function, GLSLLine *line)
{
line->line = SDATA(0);
}
void FloatNode::Load(nlohmann::json data)
{
x = data["x"];
}
nlohmann::json FloatNode::Save()
{
nlohmann::json data;
data["type"] = "Float";
data["x"] = x;
return data;
}
void FloatNode::UpdateShaders()
{
sharedData->d0 = x;
}
void FloatNode::OnRender()
{
DrawHeader("Float Value");
ImGui::PushItemWidth(100);
if(ImGui::DragFloat("X", &x, 0.01f))
{
sharedData->d0 = x;
}
ImGui::SameLine();
outputPins[0]->Render();
ImGui::PopItemWidth();
}
FloatNode::FloatNode(GLSLHandler *handler)
:SNENode(handler)
{
name = "Float Value";
x = 0.0f;
headerColor = ImColor(SHADER_VALUE_NODE_COLOR);
outputPins.push_back(new SNEPin(NodeEditorPinType::Output, SNEPinType::SNEPinType_Float));
}
FloatNode::~FloatNode()
{
} | 410 |
1,088 | import click
import json
import os
from xdg import XDG_CONFIG_HOME
class InvalidDataDirException(Exception):
pass
def get_data_dir():
if os.environ.get('NLGEVAL_DATA'):
if not os.path.exists(os.environ.get('NLGEVAL_DATA')):
click.secho("NLGEVAL_DATA variable is set but points to non-existent path.", fg='red', err=True)
raise InvalidDataDirException()
return os.environ.get('NLGEVAL_DATA')
else:
try:
cfg_file = os.path.join(XDG_CONFIG_HOME, 'nlgeval', 'rc.json')
with open(cfg_file, 'rt') as f:
rc = json.load(f)
if not os.path.exists(rc['data_path']):
click.secho("Data path found in {} does not exist: {} " % (cfg_file, rc['data_path']), fg='red', err=True)
click.secho("Run `nlg-eval --setup DATA_DIR' to download or set $NLGEVAL_DATA to an existing location",
fg='red', err=True)
raise InvalidDataDirException()
return rc['data_path']
except:
click.secho("Could not determine location of data.", fg='red', err=True)
click.secho("Run `nlg-eval --setup DATA_DIR' to download or set $NLGEVAL_DATA to an existing location", fg='red',
err=True)
raise InvalidDataDirException()
| 654 |
619 | <gh_stars>100-1000
/*
* Copyright 2010 <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.javakaffee.web.msm.serializer.kryo;
import com.esotericsoftware.kryo.Kryo;
import com.esotericsoftware.kryo.Serializer;
import com.esotericsoftware.kryo.serializers.FieldSerializer;
import org.apache.wicket.Component;
import org.objenesis.strategy.StdInstantiatorStrategy;
/**
* A {@link KryoCustomization} that creates a {@link FieldSerializer} as
* serializer for subclasses of {@link Component}. This is required, as the {@link Component}
* constructor invokes {@link org.apache.wicket.Application#get()} to tell the application
* to {@link org.apache.wicket.Application#notifyComponentInstantiationListeners()}. This will
* lead to NullpointerExceptions if the application is not yet bound to the current thread
* because the session is e.g. accessed from within a servlet filter. If the component is created
* via the constructor for serialization, this problem does not occur.
*
* This also enables references and configures the StdInstantiatorStrategy as fallback for the default strategy.
*
* @author <a href="mailto:<EMAIL>"><NAME></a>
*/
public class ComponentSerializerFactory implements KryoBuilderConfiguration, KryoCustomization {
@Override
public KryoBuilder configure(KryoBuilder kryoBuilder) {
return kryoBuilder
.withInstantiatorStrategy(
new Kryo.DefaultInstantiatorStrategy(new StdInstantiatorStrategy()))
.withReferences(true);
}
@Override
public void customize(Kryo kryo) {
kryo.addDefaultSerializer(Component.class, new com.esotericsoftware.kryo.factories.SerializerFactory() {
@Override
public Serializer makeSerializer(Kryo kryo, Class<?> type) {
final FieldSerializer result = new FieldSerializer<Component>(kryo, type);
result.setIgnoreSyntheticFields(false);
return result;
}
});
}
}
| 855 |
369 | /* ----------------------------------------------------------------------------
* SAM Software Package License
* ----------------------------------------------------------------------------
* Copyright (c) 2011, Atmel Corporation
*
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* - Redistributions of source code must retain the above copyright notice,
* this list of conditions and the disclaimer below.
*
* Atmel's name may not be used to endorse or promote products derived from
* this software without specific prior written permission.
*
* DISCLAIMER: THIS SOFTWARE IS PROVIDED BY ATMEL "AS IS" AND ANY EXPRESS OR
* IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT ARE
* DISCLAIMED. IN NO EVENT SHALL ATMEL BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA,
* OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
* LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
* NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE,
* EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
* ----------------------------------------------------------------------------
*/
/** \addtogroup usart_module Working with USART
* The USART driver provides the interface to configure and use the USART peripheral.\n
*
* The USART supports several kinds of comminication modes such as full-duplex asynchronous/
* synchronous serial commnunication,RS485 with driver control signal,ISO7816,SPI and Test modes.
*
* To start a USART transfer with \ref dmad_module "DMA" support, the user could follow these steps:
* <ul>
* <li> Configure USART with expected mode and baudrate(see \ref USART_Configure), which could be done by:
* -# Resetting and disabling transmitter and receiver by setting US_CR(Control Register). </li>
* -# Conifguring the USART in a specific mode by setting USART_MODE bits in US_MR(Mode Register) </li>
* -# Setting baudrate which is different from mode to mode.
</li>
* <li> Enable transmitter or receiver respectively by set US_CR_TXEN or US_CR_RXEN in US_CR.</li>
* <li> Read from or write to the peripheral with \ref dmad_module </li>
* </ul>
*
* For more accurate information, please look at the USART section of the
* Datasheet.
*
* Related files :\n
* \ref usart.c\n
* \ref usart.h\n
*/
/**
* \file
*
* Implementation of USART (Universal Synchronous Asynchronous Receiver Transmitter)
* controller.
*
*/
/*------------------------------------------------------------------------------
* Headers
*------------------------------------------------------------------------------*/
#include "chip.h"
#include <assert.h>
#include <string.h>
/*------------------------------------------------------------------------------
* Exported functions
*------------------------------------------------------------------------------*/
/**
* \brief Configures an USART peripheral with the specified parameters.
*
*
* \param usart Pointer to the USART peripheral to configure.
* \param mode Desired value for the USART mode register (see the datasheet).
* \param baudrate Baudrate at which the USART should operate (in Hz).
* \param masterClock Frequency of the system master clock (in Hz).
*/
void USART_Configure(Usart *usart,
uint32_t mode,
uint32_t baudrate,
uint32_t masterClock)
{
uint32_t maxClock;
uint32_t id = ID_USART0;
maxClock = masterClock;
/* Reset and disable receiver & transmitter*/
usart->US_CR = US_CR_RSTRX | US_CR_RSTTX
| US_CR_RXDIS | US_CR_TXDIS;
if ((uint32_t)usart == (uint32_t)USART0) id = ID_USART0;
else if ((uint32_t)usart == (uint32_t)USART1) id = ID_USART1;
else if ((uint32_t)usart == (uint32_t)USART2) id = ID_USART2;
else if ((uint32_t)usart == (uint32_t)USART3) id = ID_USART3;
/* Configure mode*/
usart->US_MR = mode;
maxClock = PMC_SetPeriMaxClock(id, masterClock);
/* Configure baudrate*/
/* Asynchronous, no oversampling*/
if (((mode & US_MR_SYNC) == 0)
&& ((mode & US_MR_OVER) == 0))
{
usart->US_BRGR = (maxClock / baudrate) / 16;
}
if( ((mode & US_MR_USART_MODE_SPI_MASTER) == US_MR_USART_MODE_SPI_MASTER)
|| ((mode & US_MR_SYNC) == US_MR_SYNC))
{
if( (mode & US_MR_USCLKS_Msk) == US_MR_USCLKS_MCK)
{
usart->US_BRGR = maxClock / baudrate;
}
else
{
if ( (mode & US_MR_USCLKS_DIV) == US_MR_USCLKS_DIV)
{
usart->US_BRGR = maxClock / baudrate / 8;
}
}
}
/* TODO other modes*/
}
/**
* \brief Enables or disables the transmitter of an USART peripheral.
*
*
* \param usart Pointer to an USART peripheral
* \param enabled If true, the transmitter is enabled; otherwise it is
* disabled.
*/
void USART_SetTransmitterEnabled(Usart *usart, uint8_t enabled)
{
if (enabled) {
usart->US_CR = US_CR_TXEN;
}
else {
usart->US_CR = US_CR_TXDIS;
}
}
/**
* \brief Enables or disables the receiver of an USART peripheral
*
*
* \param usart Pointer to an USART peripheral
* \param enabled If true, the receiver is enabled; otherwise it is disabled.
*/
void USART_SetReceiverEnabled(Usart *usart, uint8_t enabled)
{
if (enabled) {
usart->US_CR = US_CR_RXEN;
}
else {
usart->US_CR = US_CR_RXDIS;
}
}
/**
* \brief Enables or disables the Request To Send (RTS) of an USART peripheral
*
*
* \param usart Pointer to an USART peripheral
* \param enabled If true, the RTS is enabled (0); otherwise it is disabled.
*/
void USART_SetRTSEnabled( Usart *usart, uint8_t enabled)
{
if (enabled) {
usart->US_CR = US_CR_RTSEN;
}
else {
usart->US_CR = US_CR_RTSDIS;
}
}
/**
* \brief Sends one packet of data through the specified USART peripheral. This
* function operates synchronously, so it only returns when the data has been
* actually sent.
*
*
* \param usart Pointer to an USART peripheral.
* \param data Data to send including 9nth bit and sync field if necessary (in
* the same format as the US_THR register in the datasheet).
* \param timeOut Time out value (0 = no timeout).
*/
void USART_Write( Usart *usart, uint16_t data, volatile uint32_t timeOut)
{
if (timeOut == 0) {
while ((usart->US_CSR & US_CSR_TXEMPTY) == 0);
}
else {
while ((usart->US_CSR & US_CSR_TXEMPTY) == 0) {
if (timeOut == 0) {
TRACE_ERROR("USART_Write: Timed out.\n\r");
return;
}
timeOut--;
}
}
usart->US_THR = data;
}
/**
* \brief Reads and return a packet of data on the specified USART peripheral. This
* function operates asynchronously, so it waits until some data has been
* received.
*
* \param usart Pointer to an USART peripheral.
* \param timeOut Time out value (0 -> no timeout).
*/
uint16_t USART_Read( Usart *usart, volatile uint32_t timeOut)
{
if (timeOut == 0) {
while ((usart->US_CSR & US_CSR_RXRDY) == 0);
}
else {
while ((usart->US_CSR & US_CSR_RXRDY) == 0) {
if (timeOut == 0) {
TRACE_ERROR( "USART_Read: Timed out.\n\r" ) ;
return 0;
}
timeOut--;
}
}
return usart->US_RHR;
}
/**
* \brief Returns 1 if some data has been received and can be read from an USART;
* otherwise returns 0.
*
* \param usart Pointer to an Usart instance.
*/
uint8_t USART_IsDataAvailable(Usart *usart)
{
if ((usart->US_CSR & US_CSR_RXRDY) != 0) {
return 1;
}
else {
return 0;
}
}
/**
* \brief Sets the filter value for the IRDA demodulator.
*
* \param pUsart Pointer to an Usart instance.
* \param filter Filter value.
*/
void USART_SetIrdaFilter(Usart *pUsart, uint8_t filter)
{
assert( pUsart != NULL ) ;
pUsart->US_IF = filter;
}
/**
* \brief Sends one packet of data through the specified USART peripheral. This
* function operates synchronously, so it only returns when the data has been
* actually sent.
*
* \param usart Pointer to an USART peripheral.
* \param c Character to send
*/
void USART_PutChar( Usart *usart, uint8_t c)
{
/* Wait for the transmitter to be ready*/
while ((usart->US_CSR & US_CSR_TXEMPTY) == 0);
/* Send character*/
usart->US_THR = c;
/* Wait for the transfer to complete*/
while ((usart->US_CSR & US_CSR_TXEMPTY) == 0);
}
/**
* \brief Return 1 if a character can be read in USART
* \param usart Pointer to an USART peripheral.
*/
uint32_t USART_IsRxReady(Usart *usart)
{
return (usart->US_CSR & US_CSR_RXRDY);
}
/**
* \brief Get present status
* \param usart Pointer to an USART peripheral.
*/
uint32_t USART_GetStatus(Usart *usart)
{
return usart->US_CSR;
}
/**
* \brief Enable interrupt
* \param usart Pointer to an USART peripheral.
* \param mode Interrupt mode.
*/
void USART_EnableIt(Usart *usart,uint32_t mode)
{
usart->US_IER = mode;
}
/**
* \brief Disable interrupt
* \param usart Pointer to an USART peripheral.
* \param mode Interrupt mode.
*/
void USART_DisableIt(Usart *usart,uint32_t mode)
{
usart->US_IDR = mode;
}
/**
* \brief Return interrupt mask
* \param usart Pointer to an USART peripheral.
*/
uint32_t USART_GetItMask(Usart *usart)
{
return usart->US_IMR;
}
/**
* \brief Reads and returns a character from the USART.
*
* \note This function is synchronous (i.e. uses polling).
* \param usart Pointer to an USART peripheral.
* \return Character received.
*/
uint8_t USART_GetChar(Usart *usart)
{
while ((usart->US_CSR & US_CSR_RXRDY) == 0);
return usart->US_RHR;
}
| 3,879 |
1,444 |
package mage.cards.t;
import java.util.UUID;
import mage.abilities.Ability;
import mage.abilities.effects.OneShotEffect;
import mage.abilities.effects.common.search.SearchLibraryPutInHandEffect;
import mage.cards.CardImpl;
import mage.cards.CardSetInfo;
import mage.constants.CardType;
import mage.constants.Outcome;
import mage.constants.SubType;
import mage.filter.FilterCard;
import mage.filter.common.FilterLandPermanent;
import mage.game.Game;
import mage.target.common.TargetCardInLibrary;
import mage.target.common.TargetOpponent;
/**
*
* @author emerald000
*/
public final class Tithe extends CardImpl {
public Tithe(UUID ownerId, CardSetInfo setInfo) {
super(ownerId,setInfo,new CardType[]{CardType.INSTANT},"{W}");
// Search your library for a Plains card. If target opponent controls more lands than you, you may search your library for an additional Plains card. Reveal those cards and put them into your hand. Then shuffle your library.
this.getSpellAbility().addEffect(new TitheEffect());
this.getSpellAbility().addTarget(new TargetOpponent());
}
private Tithe(final Tithe card) {
super(card);
}
@Override
public Tithe copy() {
return new Tithe(this);
}
}
class TitheEffect extends OneShotEffect {
private static final FilterCard filter = new FilterCard("Plains");
static {
filter.add(SubType.PLAINS.getPredicate());
}
TitheEffect() {
super(Outcome.Benefit);
this.staticText = "Search your library for a Plains card. If target opponent controls more lands than you, you may search your library for an additional Plains card. Reveal those cards, put them into your hand, then shuffle";
}
TitheEffect(final TitheEffect effect) {
super(effect);
}
@Override
public TitheEffect copy() {
return new TitheEffect(this);
}
@Override
public boolean apply(Game game, Ability source) {
int numYourLands = game.getBattlefield().countAll(new FilterLandPermanent(), source.getControllerId(), game);
int numOpponentLands = game.getBattlefield().countAll(new FilterLandPermanent(), this.getTargetPointer().getFirst(game, source), game);
new SearchLibraryPutInHandEffect(new TargetCardInLibrary(0, (numOpponentLands > numYourLands ? 2 : 1), filter), true).apply(game, source);
return true;
}
}
| 798 |
5,300 | #pragma once
#include <drogon/HttpSimpleController.h>
#include <drogon/IOThreadStorage.h>
using namespace drogon;
struct Fortune
{
Fortune(string_view &&id, string_view &&message)
: id_(std::move(id)), message_(std::move(message))
{
}
Fortune() = default;
string_view id_;
string_view message_;
};
class FortuneCtrlRaw : public drogon::HttpSimpleController<FortuneCtrlRaw>
{
public:
FortuneCtrlRaw()
: bodyTemplate_(DrTemplateBase::newTemplate("fortune_raw.csp"))
{
}
virtual void asyncHandleHttpRequest(
const HttpRequestPtr &req,
std::function<void(const HttpResponsePtr &)> &&callback) override;
PATH_LIST_BEGIN
// list path definitions here;
PATH_LIST_END
private:
IOThreadStorage<orm::DbClientPtr> dbClient_;
std::shared_ptr<drogon::DrTemplateBase> bodyTemplate_;
};
| 328 |
5,169 | {
"name": "TTTAttributedLabel",
"version": "1.1.0",
"platforms": {
"ios": null
},
"summary": "A drop-in replacement for UILabel that supports NSAttributedStrings.",
"homepage": "https://github.com/mattt/TTTAttributedLabel",
"authors": {
"<NAME>": "<EMAIL>"
},
"source": {
"git": "https://github.com/mattt/TTTAttributedLabel.git",
"tag": "1.1.0"
},
"license": {
"type": "MIT",
"file": "LICENSE"
},
"description": "TTTAttributedLabel is a drop-in replacement for UILabel that supports NSAttributedStrings. NSAttributedString is pretty rad. When it was ported into iOS 4 from Mac OS, iPhone developers everywhere rejoiced. Unfortunately, as of iOS 4 none of the standard controls in UIKit support it. Bummer. TTTAttributedLabel was created to be a drop-in replacement for UILabel, that provided a simple API to styling text with NSAttributedString while remaining performant. As a bonus, it also supports link embedding, both automatically with UIDataDetectorTypes and manually by specifying a range for a URL, address, phone number, or event.",
"source_files": "TTTAttributedLabel.{h,m}",
"requires_arc": false
}
| 367 |
310 | // by 8bitbubsy
#ifdef _WIN32
#define WIN32_LEAN_AND_MEAN
#include <windows.h>
#include <shlwapi.h>
#endif
#include <stdio.h>
#include <string.h> // stricmp()
#include <stdlib.h> // atoi()
#include <ctype.h> // toupper()
#include <stdint.h>
#include <stdbool.h>
// if compiling for Windows, you need to link shlwapi.lib (for PathRemoveFileSpecW())
#define CLAMP(x, low, high) (((x) > (high)) ? (high) : (((x) < (low)) ? (low) : (x)))
#define IO_BUF_SIZE 4096
#define MAX_NAME_LEN 64
#define DATA_NAME "hdata" // this has to be a legal C variable name
#define BYTES_PER_LINE 24
#define MAX_MEGABYTES_IN 8
#define MIN_BYTES_PER_LINE 1
#define MAX_BYTES_PER_LINE 64
static const char hex2ch[16] = { '0','1','2','3','4','5','6','7','8','9','A','B','C','D','E','F' };
static char fileNameOut[MAX_NAME_LEN + 8], dataType[32];
static char dataName[MAX_NAME_LEN + 1], dataNameUpper[MAX_NAME_LEN + 1];
static bool useConstFlag = true, addZeroFlag;
static size_t fileSize, bytesPerLine = BYTES_PER_LINE, dataNameLen;
#ifdef _WIN32
static void setDirToExecutablePath(void);
#endif
static void setNewDataName(const char *name);
static bool handleArguments(int argc, char *argv[]);
static bool compareFileNames(const char *path1, const char *path2);
static bool setAndTestFileSize(FILE *f);
static bool writeHeader(FILE *f);
int main(int argc, char *argv[])
{
uint8_t byte, readBuffer[IO_BUF_SIZE], writeBuffer[IO_BUF_SIZE * 6]; // don't mess with the sizes here
size_t lineEntry, readLength, writeLength, bytesWritten;
FILE *fIn, *fOut;
#ifdef _WIN32 // path is not set to cwd in XP (with VS2017 runtime) for some reason
setDirToExecutablePath();
#endif
strcpy(dataType, "uint8_t");
setNewDataName(DATA_NAME);
printf("bin2h v0.3 - by 8bitbubsy 2018-2020 - Converts a binary to a C include file\n");
printf("===========================================================================\n");
// handle input arguments
if (!handleArguments(argc, argv))
return -1;
// test if the output file is the same as the input file (illegal)
if (compareFileNames(argv[1], fileNameOut))
{
printf("Error: Output file can't be the same as input file!\n");
return 1;
}
// open input file
fIn = fopen(argv[1], "rb");
if (fIn == NULL)
{
printf("Error: Could not open input file for reading!\n");
return 1;
}
// get filesize and test if it's 0 or too high
if (!setAndTestFileSize(fIn))
{
fclose(fIn);
return 1;
}
// open output file
fOut = fopen(fileNameOut, "w");
if (fOut == NULL)
{
fclose(fIn);
printf("Error: Could not open data.h for writing!\n");
return 1;
}
// write .h header
if (!writeHeader(fOut))
goto IOError;
// write main data
printf("Reading/writing from/to files...\n");
bytesWritten = 0;
while (!feof(fIn))
{
readLength = fread(readBuffer, 1, IO_BUF_SIZE, fIn);
writeLength = 0;
for (size_t i = 0; i < readLength; i++)
{
lineEntry = bytesWritten % bytesPerLine;
// put tab if we're at the start of a line
if (lineEntry == 0)
writeBuffer[writeLength++] = '\t';
// write table entry
byte = readBuffer[i];
if (bytesWritten == fileSize-1)
{
// last byte in table
if (addZeroFlag) // fileSize is increased by one if addZeroFlag = true
{
writeBuffer[writeLength++] = '\0';
}
else
{
// "0xXX"
writeBuffer[writeLength++] = '0';
writeBuffer[writeLength++] = 'x';
writeBuffer[writeLength++] = hex2ch[byte >> 4];
writeBuffer[writeLength++] = hex2ch[byte & 15];
}
}
else
{
// "0xXX,"
writeBuffer[writeLength++] = '0';
writeBuffer[writeLength++] = 'x';
writeBuffer[writeLength++] = hex2ch[byte >> 4];
writeBuffer[writeLength++] = hex2ch[byte & 15];
writeBuffer[writeLength++] = ',';
}
// put linefeed if we're at the end of a line (or at the last byte entry)
if (lineEntry == bytesPerLine-1 || bytesWritten == fileSize-1)
writeBuffer[writeLength++] = '\n';
bytesWritten++;
}
if (fwrite(writeBuffer, 1, writeLength, fOut) != writeLength)
goto IOError;
}
if (bytesWritten != fileSize)
goto IOError;
// write .h footer
if (fprintf(fOut, "};\n") < 0) goto IOError;
fclose(fOut);
fclose(fIn);
printf("%d bytes sucessfully written to \"%s\".\n", fileSize, fileNameOut);
return 0;
IOError:
fclose(fOut);
fclose(fIn);
printf("Error: General I/O fault during reading/writing!\n");
return 1;
}
#ifdef _WIN32
static void setDirToExecutablePath(void)
{
WCHAR path[MAX_PATH];
GetModuleFileNameW(GetModuleHandleW(NULL), path, MAX_PATH);
PathRemoveFileSpecW(path);
SetCurrentDirectoryW(path);
// we don't care if this fails or not, so no error checking for now
}
#endif
static bool dataNameIsValid(const char *s, size_t len)
{
bool charIsValid;
for (size_t i = 0; i < len; i++)
{
if (i == 0 && (s[i] >= '0' && s[i] <= '9'))
return false; // a C variable can't start with a digit
charIsValid = (s[i] >= '0' && s[i] <= '9') ||
(s[i] >= 'a' && s[i] <= 'z') ||
(s[i] >= 'A' && s[i] <= 'Z');
if (!charIsValid)
return false;
}
return true;
}
static void setNewDataName(const char *name)
{
size_t i;
strncpy(dataName, name, sizeof (dataName)-1);
dataNameLen = strlen(dataName);
sprintf(fileNameOut, "%s.h", dataName);
// maker upper case version of dataName
for (i = 0; i < dataNameLen; i++)
dataNameUpper[i] = (char)toupper(dataName[i]);
dataNameUpper[i] = '\0';
// test if dataName is valid for use in a C header
if (!dataNameIsValid(dataName, dataNameLen))
{
strcpy(dataName, DATA_NAME);
printf("Warning: Data name was illegal and was set to default (%s).\n", DATA_NAME);
}
}
static bool handleArguments(int argc, char *argv[])
{
if (argc < 2)
{
printf("Usage: bin2h <binary> [options]\n");
printf("\n");
printf("Options:\n");
printf(" --no-const Don't declare data as const\n");
printf(" --signed Declare data as signed instead of unsigned\n");
printf(" --terminate Insert a zero after the data (also increases length constant by 1)\n");
printf(" -n <name> Set data name (max %d chars, a-zA-Z0-9_, default = %s)\n", MAX_NAME_LEN, DATA_NAME);
printf(" -b <num> Set amount of bytes per line in data table (%d..%d, default = %d)\n",
MIN_BYTES_PER_LINE, MAX_BYTES_PER_LINE, BYTES_PER_LINE);
return false;
}
else
{
for (int32_t i = 0; i < argc; i++)
{
if (!_stricmp(argv[i], "--no-const"))
{
useConstFlag = false;
}
if (!_stricmp(argv[i], "--terminate"))
{
addZeroFlag = true;
}
if (!_stricmp(argv[i], "--signed"))
{
strcpy(dataType, "int8_t");
}
else if (!_stricmp(argv[i], "-n"))
{
if (i < argc-1)
setNewDataName(argv[i+1]);
}
else if (!_stricmp(argv[i], "-b"))
{
if (i < argc-1)
bytesPerLine = CLAMP(atoi(argv[i+1]), MIN_BYTES_PER_LINE, MAX_BYTES_PER_LINE);
}
}
}
return true;
}
// compares two filenames (mixed full path or not, case insensitive)
static bool compareFileNames(const char *path1, const char *path2)
{
char sep;
const char *p1, *p2;
size_t l1, l2;
if (path1 == NULL || path2 == NULL)
return false; // error
#ifdef _WIN32
sep = '\\';
#else
sep = '/';
#endif
// set pointers to first occurrences of separator in paths
p1 = strrchr(path1, sep);
p2 = strrchr(path2, sep);
if (p1 == NULL)
{
// separator not found, point to start of path
p1 = path1;
l1 = strlen(p1);
}
else
{
// separator found, increase pointer by 1 if we have room
l1 = strlen(p1);
if (l1 > 0)
{
p1++;
l1--;
}
}
if (p2 == NULL)
{
// separator not found, point to start of path
p2 = path2;
l2 = strlen(p2);
}
else
{
// separator found, increase pointer by 1 if we have room
l2 = strlen(p2);
if (l2 > 0)
{
p2++;
l2--;
}
}
if (l1 != l2)
return false; // definitely not the same
// compare strings
for (size_t i = 0; i < l1; i++)
{
if (tolower(p1[i]) != tolower(p2[i]))
return false; // not the same
}
return true; // both filenames are the same
}
static bool setAndTestFileSize(FILE *f)
{
fseek(f, 0, SEEK_END);
fileSize = ftell(f);
rewind(f);
if (fileSize == 0)
{
printf("Error: Input file is empty!\n");
return false;
}
if (fileSize > MAX_MEGABYTES_IN*(1024UL*1024))
{
printf("Error: The input filesize is over %dMB. This program is meant for small files!\n", MAX_MEGABYTES_IN);
return false;
}
if (addZeroFlag)
fileSize++; // make room for zero
return true;
}
static bool writeHeader(FILE *f)
{
if (fprintf(f, "#pragma once\n") < 0) return false;
if (fprintf(f, "\n") < 0) return false;
if (fprintf(f, "#include <stdint.h>\n") < 0) return false;
if (fprintf(f, "\n") < 0) return false;
if (fprintf(f, "#define %s_LENGTH %d\n", dataNameUpper, fileSize) < 0) return false;
if (fprintf(f, "\n") < 0) return false;
if (useConstFlag)
{
if (fprintf(f, "const %s %s[%s_LENGTH] =\n", dataType, dataName, dataNameUpper) < 0)
return false;
}
else
{
if (fprintf(f, "%s %s[%s_LENGTH] =\n", dataType, dataName, dataNameUpper) < 0)
return false;
}
if (fprintf(f, "{\n") < 0)
return false;
return true;
}
| 3,833 |
1,442 | #include <escher/scroll_view.h>
#include <escher/palette.h>
#include <new>
extern "C" {
#include <assert.h>
}
#include <algorithm>
namespace Escher {
ScrollView::ScrollView(View * contentView, ScrollViewDataSource * dataSource) :
View(),
m_contentView(contentView),
m_dataSource(dataSource),
m_topMargin(0),
m_rightMargin(0),
m_bottomMargin(0),
m_leftMargin(0),
m_excessWidth(0),
m_excessHeight(0),
m_innerView(this),
m_decorators(),
m_backgroundColor(Palette::WallScreen)
{
assert(m_dataSource != nullptr);
setDecoratorType(Decorator::Type::Bars);
}
ScrollView::ScrollView(ScrollView&& other) :
m_contentView(other.m_contentView),
m_dataSource(other.m_dataSource),
m_topMargin(other.m_topMargin),
m_rightMargin(other.m_rightMargin),
m_bottomMargin(other.m_bottomMargin),
m_leftMargin(other.m_leftMargin),
m_excessWidth(other.m_excessWidth),
m_excessHeight(other.m_excessHeight),
m_innerView(this),
m_backgroundColor(other.m_backgroundColor)
{
setDecoratorType(other.m_decoratorType);
}
KDSize ScrollView::minimalSizeForOptimalDisplay() const {
KDSize contentSize = m_contentView->minimalSizeForOptimalDisplay();
KDCoordinate width = contentSize.width() + m_leftMargin + m_rightMargin;
KDCoordinate height = contentSize.height() + m_topMargin + m_bottomMargin;
/* Crop right or bottom margins if content fits without a portion of them.
* With a 0.0 tolerance, right and bottom margin is never cropped.
* With a 0.8 tolerance, at most 80% of right or bottom margin can be cropped.
* With a 1.0 tolerance, right or bottom margin can be entirely cropped. */
KDCoordinate excessWidth = width - m_frame.width();
if (excessWidth > 0 && excessWidth <= marginPortionTolerance() * m_rightMargin) {
width -= excessWidth;
m_excessWidth = excessWidth;
}
KDCoordinate excessHeight = height - m_frame.height();
if (excessHeight > 0 && excessHeight <= marginPortionTolerance() * m_bottomMargin) {
height -= excessHeight;
m_excessHeight = excessHeight;
}
return KDSize(width, height);
}
void ScrollView::setMargins(KDCoordinate top, KDCoordinate right, KDCoordinate bottom, KDCoordinate left) {
m_topMargin = top;
m_rightMargin = right;
m_bottomMargin = bottom;
m_leftMargin = left;
}
void ScrollView::scrollToContentPoint(KDPoint p, bool allowOverscroll) {
if (!allowOverscroll && !m_contentView->bounds().contains(p)) {
return;
}
KDRect visibleRect = visibleContentRect();
if (visibleRect.width() < 0 || visibleRect.height() < 0) {
return;
}
KDCoordinate offsetX = 0;
KDCoordinate offsetY = 0;
if (visibleRect.left() > p.x()) {
offsetX = p.x() - visibleRect.left();
}
if (visibleRect.right() < p.x()) {
offsetX = p.x() - visibleRect.right();
}
if (visibleRect.top() > p.y()) {
offsetY = p.y() - visibleRect.top();
}
if (visibleRect.bottom() < p.y()) {
offsetY = p.y() - visibleRect.bottom();
}
if (offsetX != 0 || offsetY != 0) {
setContentOffset(contentOffset().translatedBy(KDPoint(offsetX, offsetY)));
}
// Handle cases when the size of the view has decreased.
setContentOffset(KDPoint(
std::min(
contentOffset().x(),
std::max<KDCoordinate>(
minimalSizeForOptimalDisplay().width() - bounds().width(),
KDCoordinate(0))),
std::min(
contentOffset().y(),
std::max<KDCoordinate>(
minimalSizeForOptimalDisplay().height() - bounds().height(),
KDCoordinate(0)))));
}
void ScrollView::scrollToContentRect(KDRect rect, bool allowOverscroll) {
KDPoint tl = rect.topLeft();
KDPoint br = rect.bottomRight();
KDRect visibleRect = visibleContentRect();
/* We first check that we can display the whole rect. If we can't, we focus
* the scroll to the closest part of the rect. */
if (visibleRect.height() < rect.height()) {
// The visible rect is too small to display 'rect'
if (rect.top() >= visibleRect.top()) {
// We scroll to display the top part of rect
br = KDPoint(br.x(), rect.top() + visibleRect.height());
} else {
// We scroll to display the bottom part of rect
tl = KDPoint(tl.x(), rect.bottom() - visibleRect.height());
}
}
if (visibleRect.width() < rect.width()) {
// The visible rect is too small to display 'rect'
if (rect.left() >= visibleRect.left()) {
// We scroll to display the left part of rect
br = KDPoint(rect.left() + visibleRect.width(), br.y());
} else {
// We scroll to display the right part of rect
tl = KDPoint(rect.right() - visibleRect.width(), tl.y());
}
}
scrollToContentPoint(tl, allowOverscroll);
scrollToContentPoint(br, allowOverscroll);
}
KDRect ScrollView::visibleContentRect() {
return KDRect(
contentOffset().x(),
contentOffset().y(),
m_frame.width() - m_leftMargin - m_rightMargin + m_excessWidth,
m_frame.height() - m_topMargin - m_bottomMargin + m_excessHeight);
}
void ScrollView::layoutSubviews(bool force) {
if (bounds().isEmpty()) {
return;
}
KDRect r1 = KDRectZero;
KDRect r2 = KDRectZero;
KDRect innerFrame = decorator()->layoutIndicators(minimalSizeForOptimalDisplay(), contentOffset(), bounds(), &r1, &r2, force);
if (!r1.isEmpty()) {
markRectAsDirty(r1);
}
if (!r2.isEmpty()) {
markRectAsDirty(r2);
}
m_innerView.setFrame(innerFrame, force);
KDPoint absoluteOffset = contentOffset().opposite().translatedBy(KDPoint(m_leftMargin - innerFrame.x(), m_topMargin - innerFrame.y()));
KDRect contentFrame = KDRect(absoluteOffset, contentSize());
m_contentView->setFrame(contentFrame, force);
}
void ScrollView::setContentOffset(KDPoint offset, bool forceRelayout) {
if (m_dataSource->setOffset(offset) || forceRelayout) {
layoutSubviews();
}
}
void ScrollView::InnerView::drawRect(KDContext * ctx, KDRect rect) const {
KDCoordinate height = bounds().height();
KDCoordinate width = bounds().width();
KDCoordinate offsetX = m_scrollView->contentOffset().x() + m_frame.x();
KDCoordinate offsetY = m_scrollView->contentOffset().y() + m_frame.y();
KDCoordinate contentHeight = m_scrollView->m_contentView->bounds().height();
KDCoordinate contentWidth = m_scrollView->m_contentView->bounds().width();
ctx->fillRect(KDRect(0, 0, width, m_scrollView->m_topMargin-offsetY), m_scrollView->m_backgroundColor);
ctx->fillRect(KDRect(0, contentHeight+m_scrollView->m_topMargin-offsetY, width, height - contentHeight - m_scrollView->m_topMargin + offsetY), m_scrollView->m_backgroundColor);
ctx->fillRect(KDRect(0, 0, m_scrollView->m_leftMargin-offsetX, height), m_scrollView->m_backgroundColor);
ctx->fillRect(KDRect(contentWidth + m_scrollView->m_leftMargin - offsetX, 0, width - contentWidth - m_scrollView->m_leftMargin + offsetX, height), m_scrollView->m_backgroundColor);
}
View * ScrollView::BarDecorator::indicatorAtIndex(int index) {
if (index == 1) {
return &m_verticalBar;
}
assert(index == 2);
return &m_horizontalBar;
}
KDRect ScrollView::BarDecorator::layoutIndicators(KDSize content, KDPoint offset, KDRect frame, KDRect * dirtyRect1, KDRect * dirtyRect2, bool force) {
bool hBarWasVisible = m_horizontalBar.visible();
bool hBarIsVisible = m_horizontalBar.update(content.width(), offset.x(), frame.width());
bool vBarWasVisible = m_verticalBar.visible();
bool vBarIsVisible = m_verticalBar.update(content.height(), offset.y(), frame.height());
KDCoordinate hBarFrameBreadth = k_barsFrameBreadth * hBarIsVisible;
KDCoordinate vBarFrameBreadth = k_barsFrameBreadth * vBarIsVisible;
// Mark the vertical and horizontal rects as dirty id needed
*dirtyRect1 = hBarWasVisible == hBarIsVisible ? KDRectZero : KDRect(frame.width() - k_barsFrameBreadth, 0, k_barsFrameBreadth, frame.height());
*dirtyRect2 = vBarWasVisible == vBarIsVisible ? KDRectZero : KDRect(0, frame.height() - k_barsFrameBreadth, frame.width(), k_barsFrameBreadth);
/* If the two indicators are visible, we leave an empty rectangle in the right
* bottom corner. Otherwise, the only indicator uses all the height/width. */
m_verticalBar.setFrame(KDRect(
frame.width() - vBarFrameBreadth, 0,
vBarFrameBreadth, frame.height() - hBarFrameBreadth),
force);
m_horizontalBar.setFrame(KDRect(
0, frame.height() - hBarFrameBreadth,
frame.width() - vBarFrameBreadth, hBarFrameBreadth),
force);
return frame;
}
View * ScrollView::ArrowDecorator::indicatorAtIndex(int index) {
switch(index) {
case 1:
return &m_topArrow;
case 2:
return &m_rightArrow;
case 3:
return &m_bottomArrow;
default:
assert(index == 4);
return &m_leftArrow;
}
}
KDRect ScrollView::ArrowDecorator::layoutIndicators(KDSize content, KDPoint offset, KDRect frame, KDRect * dirtyRect1, KDRect * dirtyRect2, bool force) {
// There is no need to dirty the rects
KDSize arrowSize = KDFont::LargeFont->glyphSize();
KDCoordinate topArrowFrameBreadth = arrowSize.height() * m_topArrow.update(0 < offset.y());
KDCoordinate rightArrowFrameBreadth = arrowSize.width() * m_rightArrow.update(offset.x() + frame.width() < content.width());
KDCoordinate bottomArrowFrameBreadth = arrowSize.height() * m_bottomArrow.update(offset.y() + frame.height() < content.height());
KDCoordinate leftArrowFrameBreadth = arrowSize.width() * m_leftArrow.update(0 < offset.x());
m_topArrow.setFrame(KDRect(
0, 0,
frame.width(), topArrowFrameBreadth),
force);
m_rightArrow.setFrame(KDRect(
frame.width() - rightArrowFrameBreadth, 0,
rightArrowFrameBreadth, frame.height()),
force);
m_bottomArrow.setFrame(KDRect(
0, frame.height() - bottomArrowFrameBreadth,
frame.width(), bottomArrowFrameBreadth),
force);
m_leftArrow.setFrame(KDRect(
0, 0,
leftArrowFrameBreadth, frame.height()),
force);
return KDRect(
frame.x() + leftArrowFrameBreadth,
frame.y() + topArrowFrameBreadth,
frame.width() - leftArrowFrameBreadth - rightArrowFrameBreadth,
frame.height() - topArrowFrameBreadth - bottomArrowFrameBreadth
);
}
void ScrollView::ArrowDecorator::setBackgroundColor(KDColor c) {
const int indicatorsCount = numberOfIndicators();
for (int index = 1; index <= indicatorsCount; index++) {
static_cast<ScrollViewArrow *>(indicatorAtIndex(index))->setBackgroundColor(c);
}
}
ScrollView::Decorators::Decorators() {
/* We need to initiate the Union at construction to avoid destructing an
* uninitialized object when changing the decorator type. */
new (this) Decorator();
}
ScrollView::Decorators::~Decorators() {
activeDecorator()->~Decorator();
}
void ScrollView::Decorators::setActiveDecorator(Decorator::Type t) {
/* Decorator destructor is virtual so calling ~Decorator() on a Decorator
* pointer will call the appropriate destructor. */
activeDecorator()->~Decorator();
switch (t) {
case Decorator::Type::Bars:
new (&m_bars) BarDecorator();
break;
case Decorator::Type::Arrows:
new (&m_arrows) ArrowDecorator();
break;
default:
assert(t == Decorator::Type::None);
new (&m_none) Decorator();
}
}
#if ESCHER_VIEW_LOGGING
const char * ScrollView::className() const {
return "ScrollView";
}
void ScrollView::logAttributes(std::ostream &os) const {
View::logAttributes(os);
os << " offset=\"" << (int)contentOffset().x << "," << (int)contentOffset().y << "\"";
}
#endif
}
| 4,213 |
2,151 | // Copyright 2016 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#ifndef THIRD_PARTY_BLINK_RENDERER_MODULES_NOTIFICATIONS_NOTIFICATION_IMAGE_LOADER_H_
#define THIRD_PARTY_BLINK_RENDERER_MODULES_NOTIFICATIONS_NOTIFICATION_IMAGE_LOADER_H_
#include <memory>
#include "base/memory/scoped_refptr.h"
#include "third_party/blink/renderer/core/loader/threadable_loader.h"
#include "third_party/blink/renderer/core/loader/threadable_loader_client.h"
#include "third_party/blink/renderer/modules/modules_export.h"
#include "third_party/blink/renderer/platform/heap/handle.h"
#include "third_party/blink/renderer/platform/shared_buffer.h"
#include "third_party/blink/renderer/platform/wtf/functional.h"
#include "third_party/skia/include/core/SkBitmap.h"
namespace blink {
class ExecutionContext;
class KURL;
class ResourceError;
// Asynchronously downloads an image when given a url, decodes the loaded data,
// and passes the bitmap to the given callback.
class MODULES_EXPORT NotificationImageLoader final
: public GarbageCollectedFinalized<NotificationImageLoader>,
public ThreadableLoaderClient {
public:
// Type names are used in UMAs, so do not rename.
enum class Type { kImage, kIcon, kBadge, kActionIcon };
// The bitmap may be empty if the request failed or the image data could not
// be decoded.
using ImageCallback = base::OnceCallback<void(const SkBitmap&)>;
explicit NotificationImageLoader(Type type);
~NotificationImageLoader() override;
// Scales down |image| according to its type and returns result. If it is
// already small enough, |image| is returned unchanged.
static SkBitmap ScaleDownIfNeeded(const SkBitmap& image, Type type);
// Asynchronously downloads an image from the given url, decodes the loaded
// data, and passes the bitmap to the callback. Times out if the load takes
// too long and ImageCallback is invoked with an empty bitmap.
void Start(ExecutionContext* context,
const KURL& url,
ImageCallback image_callback);
// Cancels the pending load, if there is one. The |m_imageCallback| will not
// be run.
void Stop();
// ThreadableLoaderClient interface.
void DidReceiveData(const char* data, unsigned length) override;
void DidFinishLoading(unsigned long resource_identifier) override;
void DidFail(const ResourceError& error) override;
void DidFailRedirectCheck() override;
void Trace(blink::Visitor* visitor) { visitor->Trace(threadable_loader_); }
private:
void RunCallbackWithEmptyBitmap();
Type type_;
bool stopped_;
double start_time_;
scoped_refptr<SharedBuffer> data_;
ImageCallback image_callback_;
Member<ThreadableLoader> threadable_loader_;
};
} // namespace blink
#endif // THIRD_PARTY_BLINK_RENDERER_MODULES_NOTIFICATIONS_NOTIFICATION_IMAGE_LOADER_H_
| 913 |
456 | <filename>presto-cassandra/src/main/java/com/facebook/presto/cassandra/RetryPolicyType.java
/*
* 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.facebook.presto.cassandra;
import com.datastax.driver.core.policies.DefaultRetryPolicy;
import com.datastax.driver.core.policies.DowngradingConsistencyRetryPolicy;
import com.datastax.driver.core.policies.FallthroughRetryPolicy;
import com.datastax.driver.core.policies.RetryPolicy;
import static com.google.common.base.Preconditions.checkNotNull;
public enum RetryPolicyType
{
DEFAULT(DefaultRetryPolicy.INSTANCE),
BACKOFF(BackoffRetryPolicy.INSTANCE),
DOWNGRADING_CONSISTENCY(DowngradingConsistencyRetryPolicy.INSTANCE),
FALLTHROUGH(FallthroughRetryPolicy.INSTANCE);
private final RetryPolicy policy;
RetryPolicyType(RetryPolicy policy)
{
this.policy = checkNotNull(policy, "policy is null");
}
public RetryPolicy getPolicy()
{
return policy;
}
}
| 483 |
5,903 | /*! ******************************************************************************
*
* Pentaho Data Integration
*
* Copyright (C) 2002-2017 by <NAME> : http://www.pentaho.com
*
*******************************************************************************
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
******************************************************************************/
package org.pentaho.di.core;
import junit.framework.TestCase;
/**
* Test class for counter functionality.
*
* @author <NAME>
*/
public class CounterTest extends TestCase {
/**
* Constructor test 1.
*/
public void testConstructor1() {
Counter cnt1 = new Counter();
assertEquals( 1L, cnt1.getCounter() );
assertEquals( 1L, cnt1.getIncrement() );
assertEquals( 0L, cnt1.getMaximum() );
assertEquals( 1L, cnt1.getStart() );
assertFalse( cnt1.isLoop() );
Counter cnt2 = new Counter( 2L );
assertEquals( 2L, cnt2.getCounter() );
assertEquals( 1L, cnt2.getIncrement() );
assertEquals( 0L, cnt2.getMaximum() );
assertEquals( 2L, cnt2.getStart() );
assertFalse( cnt2.isLoop() );
Counter cnt3 = new Counter( 3L, 2L );
assertEquals( 3L, cnt3.getCounter() );
assertEquals( 2L, cnt3.getIncrement() );
assertEquals( 0L, cnt3.getMaximum() );
assertEquals( 3L, cnt3.getStart() );
assertFalse( cnt3.isLoop() );
Counter cnt4 = new Counter( 5L, 2L, 20L );
assertEquals( 5L, cnt4.getCounter() );
assertEquals( 2L, cnt4.getIncrement() );
assertEquals( 20L, cnt4.getMaximum() );
assertEquals( 5L, cnt4.getStart() );
assertTrue( cnt4.isLoop() );
}
/**
* Test the setting of stuff.
*/
public void testSets() {
Counter cnt1 = new Counter();
cnt1.setCounter( 5L );
assertEquals( 5L, cnt1.getCounter() );
cnt1.setIncrement( 2L );
assertEquals( 2L, cnt1.getIncrement() );
cnt1.setLoop( true );
assertTrue( cnt1.isLoop() );
cnt1.setMaximum( 100L );
assertEquals( 100L, cnt1.getMaximum() );
}
/**
* Test next().
*/
public void testNext() {
Counter cnt1 = new Counter();
cnt1.setCounter( 2L );
assertEquals( 2L, cnt1.next() );
assertEquals( 3L, cnt1.next() );
assertEquals( 4L, cnt1.next() );
assertEquals( 5L, cnt1.next() );
assertEquals( 6L, cnt1.next() );
assertEquals( 7L, cnt1.next() );
assertEquals( 8L, cnt1.next() );
assertEquals( 9L, cnt1.next() );
assertEquals( 10L, cnt1.next() );
Counter cnt2 = new Counter();
cnt2.setCounter( 1L );
cnt2.setIncrement( 3L );
cnt2.setMaximum( 10L );
assertEquals( 1L, cnt2.next() );
assertEquals( 4L, cnt2.next() );
assertEquals( 7L, cnt2.next() );
assertEquals( 10L, cnt2.next() );
assertEquals( 13L, cnt2.next() );
Counter cnt3 = new Counter();
cnt3.setCounter( 1L );
cnt3.setIncrement( 3L );
cnt3.setMaximum( 11L );
cnt3.setLoop( true );
assertEquals( 1L, cnt3.next() );
assertEquals( 4L, cnt3.next() );
assertEquals( 7L, cnt3.next() );
assertEquals( 10L, cnt3.next() );
assertEquals( 1L, cnt3.next() );
assertEquals( 4L, cnt3.next() );
assertEquals( 7L, cnt3.next() );
assertEquals( 10L, cnt3.next() );
assertEquals( 1L, cnt3.next() );
cnt3.setCounter( 10L );
assertEquals( 10L, cnt3.next() );
}
}
| 1,504 |
407 | import operator as op
from functools import reduce
import numpy as np
def combination_Cnr(n, r):
r = min(r, n - r)
numer = reduce(op.mul, range(n, n - r, -1), 1)
denom = reduce(op.mul, range(1, r + 1), 1)
return numer / denom
def fisher_test_pValue_by_formula(ts_len, g_f):
a = int((ts_len - 1) / 2)
x = g_f # observed value of the test statistic
b = int(1 / x)
pValue = 0.0
for k in range(1, b + 1):
try:
cak = combination_Cnr(a, k)
except OverflowError:
cak = 1e300
expo = (1 - k * x)**(a - 1)
curr = (-1)**(k - 1) * cak * expo
pValue += curr
return pValue
def fisher_test_critical_value(ts_len, alpha_th):
# return g_f, alpha
if ts_len < 10 or ts_len > 4097: # 41-4001
raise ValueError('only support 41<=ts_len<=4096')
N = ts_len
n = int((N - 1) / 2)
Set_n = [5, 20, 30, 50, 100, 500, 1000, 2000, 2100]
if alpha_th == 0.05:
alpha_precision_th = 1e-3
# Set_g_f is critical value for fisher_test based on papers
Set_g_f = [
0.684, 0.270, 0.198, 0.131, 0.0443 / 0.6, 0.011 / 0.6,
0.00592 / 0.6, 0.00317 / 0.6, 0.0050473
]
elif alpha_th == 0.01:
alpha_precision_th = 1e-4
Set_g_f = [
0.789, 0.330, 0.241, 0.160, 0.0533 / 0.6, 0.0129 / 0.6,
0.00687 / 0.6, 0.00365 / 0.6, 0.005819
]
else:
raise ValueError('only support alpha_th = 0.05 or 0.01')
for idx in range(len(Set_n)):
if Set_n[idx] <= n < Set_n[idx + 1]:
# binaray search
g_f_high = Set_g_f[idx]
g_f_low = Set_g_f[idx + 1]
while g_f_low <= g_f_high:
g_f = g_f_low + (g_f_high - g_f_low) / 2
alpha = fisher_test_pValue_by_formula(ts_len, g_f)
if np.abs(alpha - alpha_th) < alpha_precision_th:
return g_f, alpha
elif alpha > alpha_th:
g_f_low = g_f
else:
g_f_high = g_f
def fisher_test(periodogram_input, ts_len, alph_th=1e-50):
# based on paper "Statistical power of Fisher test for the detection
# of short periodic gene expression profiles"
# formula 1-4. tested, the following
# periodogram_values, ts_len = fft_periodogram(input_data)
# period_candi, pValue, observed_g =
# fisher_g_test(periodogram_values, ts_len)
# observed_g, pValue, 1/period_candi (when there is period)
# is the same as
# https://rdrr.io/cran/ptest/man/ptestg.html
# import rpy2.robjects as robjects
# from rpy2.robjects.packages import importr
# from rpy2.robjects import pandas2ri
# pandas2ri.activate()
# ptest=importr('ptest')
# ptestg=robjects.r('ptestg')
# Fisher = ptestg(input_data,method="Fisher")
# print(Fisher)
periodogram_values = periodogram_input.copy()
periodogram_values[:2] = 0 # do not consider 0,1-> DC and T != N
max_p_value = np.max(periodogram_values)
max_p_idx = np.argmax(periodogram_values)
sum_p_values = np.sum(periodogram_values)
# handle zero case
if sum_p_values == 0.0:
sum_p_values = 1.0
observed_g = max_p_value / sum_p_values
# handle zero case
if observed_g == 0.0:
observed_g = 1.0
x = observed_g
a = int((ts_len - 1) / 2)
b = int(1 / x)
pValue = 0.0
for k in range(1, b + 1):
try:
cak = combination_Cnr(a, k)
except OverflowError:
cak = 1e300
expo = (1 - k * x)**(a - 1)
curr = (-1)**(k - 1) * cak * expo
pValue += curr
# special processing for non-period signal
if max_p_idx == 0 or max_p_idx == 1:
period_candi = 0
period_range = None
per_T = 0
else:
per_T = np.round(ts_len / max_p_idx).astype(int)
if pValue <= alph_th:
period_candi = per_T
# calculate period_range
N = ts_len
k = max_p_idx
low = int((N / (k + 1) + N / k) / 2 - 1)
high = int((N / k + N / (k - 1)) / 2 + 1)
period_range = np.arange(low, high + 1)
else: # period_candi=0 indicate no period
period_candi = 0
period_range = None
# output
return period_candi, period_range, per_T, pValue, observed_g
def siegel_test_alpha_by_formula(ts_len, g_f, t, lamb=0.6):
# passed only for n<=50
N = ts_len
n = int((N - 1) / 2)
pValue = 0.0
for ell in range(1, n + 1): # 1 ~ n
for k in range(0, ell): # 0 ~ ell-1
c_nl = combination_Cnr(n, ell)
c_lk = combination_Cnr(ell - 1, k)
c_nk = combination_Cnr(n - 1, k)
comb = c_nl * c_lk * c_nk
pos_part = 1 - ell * lamb * g_f - t
pos_part = max(pos_part, 0)**(n - k - 1)
curr = (-1)**(k + ell + 1) * comb * (t**k) * pos_part
pValue += curr
return pValue
def siegel_test_critical_value(ts_len, alpha_th, lamb=0.6):
# return g_f, alpha
if ts_len < 13 or ts_len > 4097: # 41-4001
raise ValueError('only support 13<=ts_len<=4096')
if lamb != 0.6:
raise ValueError('only support lamb=0.6')
N = ts_len
n = int((N - 1) / 2)
alpha = 100
if ts_len > 100:
t_6 = siegel_test_critical_value_by_interpolation(ts_len, alpha_th)
return t_6, alpha
else:
Set_n = [5, 10, 20, 30, 50]
if alpha_th == 0.05:
alpha_precision_th = 1e-3
# Set_g_f is critical value for fisher_test based on papers
Set_t_6 = [0.274, 0.181, 0.116, 0.088, 0.0616]
elif alpha_th == 0.01:
alpha_precision_th = 1e-4
Set_t_6 = [0.315, 0.214, 0.134, 0.0993, 0.0673]
else:
raise ValueError('only support alpha_th = 0.05 or 0.01')
g_f, alpha_tmp = fisher_test_critical_value(ts_len, alpha_th)
for idx in range(len(Set_n)):
if Set_n[idx] <= n < Set_n[idx + 1]:
# binaray search
t_6_high = Set_t_6[idx]
t_6_low = Set_t_6[idx + 1]
while t_6_low <= t_6_high:
t_6 = t_6_low + (t_6_high - t_6_low) / 2
alpha = siegel_test_alpha_by_formula(ts_len, g_f, t_6)
if np.abs(alpha - alpha_th) < alpha_precision_th:
return t_6, alpha
elif alpha > alpha_th:
t_6_low = t_6
else:
t_6_high = t_6
def siegel_test_critical_value_by_interpolation(ts_len, alpha_th):
# this one fixed lambda=0.6
if ts_len < 41 or ts_len > 4097: # 41-4001
raise ValueError('only support 41<=ts_len<=4096')
N = ts_len
m = int((N - 1) / 2)
if alpha_th == 0.05:
critical_value = 1.033 * (m**(-0.72356))
elif alpha_th == 0.01:
critical_value = 1.4987 * (m**(-0.79695))
else:
raise ValueError('only support alpha_th = 0.05 or 0.01')
return critical_value
| 3,787 |
2,266 | <reponame>XmanAZC/EasyLogger
#ifndef CPUUSAGE_H
#define CPUUSAGE_H
static void cpu_usage_idle_hook(void);
void cpu_usage_get(rt_uint8_t *major, rt_uint8_t *minor);
void cpu_usage_init(void);
#endif
| 97 |
1,056 | <reponame>timfel/netbeans<filename>java/performance/mobility/test/qa-functional/src/org/netbeans/performance/mobility/dialogs/NewConfigurationDialogTest.java<gh_stars>1000+
/*
* 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.performance.mobility.dialogs;
import org.netbeans.modules.performance.utilities.PerformanceTestCase;
import org.netbeans.performance.mobility.setup.MobilitySetup;
import org.netbeans.jellytools.NbDialogOperator;
import org.netbeans.jellytools.ProjectsTabOperator;
import org.netbeans.jellytools.actions.ActionNoBlock;
import org.netbeans.jellytools.nodes.Node;
import org.netbeans.jemmy.operators.ComponentOperator;
import org.netbeans.junit.NbTestSuite;
import org.netbeans.junit.NbModuleSuite;
/**
*
* @author Administrator
*/
public class NewConfigurationDialogTest extends PerformanceTestCase {
private Node testNode;
private String targetProject;
public NewConfigurationDialogTest(String testName) {
super(testName);
expectedTime = WINDOW_OPEN;
targetProject = "MobileApplicationVisualMIDlet";
}
public NewConfigurationDialogTest(String testName, String performanceDataName) {
super(testName, performanceDataName);
expectedTime = WINDOW_OPEN;
targetProject = "MobileApplicationVisualMIDlet";
}
public static NbTestSuite suite() {
NbTestSuite suite = new NbTestSuite();
suite.addTest(NbModuleSuite.create(NbModuleSuite.createConfiguration(MobilitySetup.class)
.addTest(NewConfigurationDialogTest.class)
.enableModules(".*").clusters(".*")));
return suite;
}
public void testNewConfigurationDialog() {
doMeasurement();
}
@Override
public void initialize() {
String projectConfNodeName = org.netbeans.jellytools.Bundle.getString("org.netbeans.modules.mobility.project.ui.Bundle", "LBL_ProjectConfigurations");
testNode = new Node(new ProjectsTabOperator().getProjectRootNode(targetProject),projectConfNodeName);
testNode.select();
}
public void prepare() {
testNode.select();
}
public ComponentOperator open() {
String cmdName = org.netbeans.jellytools.Bundle.getString("org.netbeans.modules.mobility.project.ui.customizer.Bundle", "LBL_VCS_AddConfiguration");
new ActionNoBlock(null,cmdName).performPopup(testNode);
return new NbDialogOperator(cmdName);
}
@Override
public void close() {
if(testedComponentOperator != null) {
((NbDialogOperator)testedComponentOperator).close();
}
}
}
| 1,167 |
365 | <reponame>ThyeeZz/towhee<filename>towhee/models/layers/activations/tanh.py
# Copyright 2021 <NAME> and Zilliz. All rights reserved. #
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
import torch
from torch import nn
def tanh(x: torch.Tensor, inplace: bool = False) -> torch.Tensor:
return x.tanh_() if inplace else x.tanh()
class Tanh(nn.Module):
"""
Tanh activiation layer.
A layer applies a tangnet function to the input.
Args:
inplace(`Bool`):
whether use inplace version.
Returns:
(`torch.Tensor`)
output tensor after activation.
"""
def __init__(self, inplace: bool = False) -> None:
super().__init__()
self.inplace = inplace
def forward(self, x: torch.Tensor) -> torch.Tensor:
return x.tanh_() if self.inplace else x.tanh()
| 473 |
789 | <reponame>AmatorAVG/django-helpdesk-atoria
# Generated by Django 3.2.7 on 2021-10-05 10:21
from django.db import migrations, models
import helpdesk.models
import helpdesk.validators
class Migration(migrations.Migration):
dependencies = [
('helpdesk', '0035_alter_email_on_ticket_change'),
]
operations = [
migrations.AlterField(
model_name='followupattachment',
name='file',
field=models.FileField(max_length=1000, upload_to=helpdesk.models.attachment_path, validators=[helpdesk.validators.validate_file_extension], verbose_name='File'),
),
migrations.AlterField(
model_name='kbiattachment',
name='file',
field=models.FileField(max_length=1000, upload_to=helpdesk.models.attachment_path, validators=[helpdesk.validators.validate_file_extension], verbose_name='File'),
),
]
| 382 |
918 | /*
* 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.gobblin.data.management.retention.version;
import java.io.IOException;
import com.google.common.base.Preconditions;
import lombok.extern.slf4j.Slf4j;
import org.apache.gobblin.data.management.retention.dataset.CleanableDataset;
import org.apache.gobblin.data.management.version.DatasetVersion;
/**
* An abstraction for cleaning a {@link DatasetVersion} of a {@link CleanableDataset}.
*/
@Slf4j
public abstract class VersionCleaner {
protected final CleanableDataset cleanableDataset;
protected final DatasetVersion datasetVersion;
public VersionCleaner(DatasetVersion datasetVersion, CleanableDataset cleanableDataset) {
Preconditions.checkNotNull(cleanableDataset);
Preconditions.checkNotNull(datasetVersion);
this.cleanableDataset = cleanableDataset;
this.datasetVersion = datasetVersion;
}
/**
* Action to perform before cleaning a {@link DatasetVersion} of a {@link CleanableDataset}.
* @throws IOException
*/
public abstract void preCleanAction() throws IOException;
/**
* Cleans the {@link DatasetVersion} of a {@link CleanableDataset}.
* @throws IOException
*/
public abstract void clean() throws IOException;
/**
* Action to perform after cleaning a {@link DatasetVersion} of a {@link CleanableDataset}.
* @throws IOException
*/
public abstract void postCleanAction() throws IOException;
}
| 642 |
848 | <gh_stars>100-1000
/*
* Copyright 2019 Xilinx 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.
*/
#include <algorithm>
#include <iostream>
#include <numeric>
#include "vart/op_imp.h"
#include "vart/runner_helper.hpp"
using namespace std;
namespace {
class TopK_OpImp : public vart::OpImp {
public:
explicit TopK_OpImp(const xir::Op* op, xir::Attrs * attrs);
virtual ~TopK_OpImp();
TopK_OpImp(const TopK_OpImp& other) = delete;
TopK_OpImp& operator=(const TopK_OpImp& rhs) = delete;
public:
virtual int calculate(const std::vector<vart::OpImpArg>& inputs,
vart::TensorBuffer* output) override;
};
TopK_OpImp::TopK_OpImp(const xir::Op* op, xir::Attrs * attrs) : vart::OpImp(op){};
TopK_OpImp::~TopK_OpImp() {}
static std::vector<std::pair<int, float>> topk(float* begin, float* output,
int size, int K) {
auto indices = std::vector<int>(size);
std::iota(indices.begin(), indices.end(), 0);
std::partial_sort(indices.begin(), indices.begin() + K, indices.end(),
[begin](int a, int b) { return begin[a] > begin[b]; });
auto ret = std::vector<std::pair<int, float>>(K);
for (auto i = 0; i < K; ++i) {
output[i * 2] = (float)indices[i];
output[i * 2 + 1] = begin[indices[i]];
}
return ret;
}
int TopK_OpImp::calculate(const std::vector<vart::OpImpArg>& inputs,
vart::TensorBuffer* output_tensor_buffer) {
CHECK_EQ(inputs.size(), 1u);
auto& input = inputs[0];
CHECK_EQ(input.args.size(), 1u);
auto& input_tensor_buffer = input.args[0];
auto input_shape = input_tensor_buffer->get_tensor()->get_shape();
auto output_shape = output_tensor_buffer->get_tensor()->get_shape();
auto num_of_dims = input_shape.size();
CHECK_EQ(num_of_dims, output_shape.size());
for (auto dim = 0u; dim < num_of_dims - 1; ++dim) {
CHECK_EQ(input_shape[dim], output_shape[dim]);
}
auto dim_index = vart::get_index_zeros(input_tensor_buffer->get_tensor());
auto buf_input = vart::get_tensor_buffer_data(input_tensor_buffer, dim_index);
auto buf_output =
vart::get_tensor_buffer_data(output_tensor_buffer, dim_index);
CHECK_EQ(buf_input.size / sizeof(float),
input_tensor_buffer->get_tensor()->get_element_num())
<< "only support float to float, continuous region";
CHECK_EQ(buf_output.size / sizeof(float),
output_tensor_buffer->get_tensor()->get_element_num())
<< "only support float to float, continuous region";
auto channels = input_shape[num_of_dims - 1];
auto k = output_shape[num_of_dims - 1] / 2;
for (auto i = 0u, j = 0u; i < buf_input.size / sizeof(float);
i = i + channels, j = j + k) {
auto input = (float*)buf_input.data;
auto output = (float*)buf_output.data;
topk(&input[i], &output[j], channels, k);
}
return 0;
}
} // namespace
extern "C" vart_op_imp_t vart_init_op_imp(const xir_op_t op) {
return vart::make_vart_opt_imp<TopK_OpImp>();
}
| 1,402 |
4,294 | <gh_stars>1000+
import logging
from apscheduler.schedulers.sync import Scheduler
from apscheduler.triggers.interval import IntervalTrigger
from apscheduler.workers.sync import Worker
def say_hello():
print('Hello!')
logging.basicConfig(level=logging.DEBUG)
try:
with Scheduler() as scheduler, Worker(scheduler.data_store, portal=scheduler.portal):
scheduler.add_schedule(say_hello, IntervalTrigger(seconds=1))
scheduler.wait_until_stopped()
except (KeyboardInterrupt, SystemExit):
pass
| 184 |
8,092 | #
# Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The ASF licenses this file
# to you under the Apache License, Version 2.0 (the
# "License"); you may not use this file except in compliance
# with the License. You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing,
# software distributed under the License is distributed on an
# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
# KIND, either express or implied. See the License for the
# specific language governing permissions and limitations
# under the License.
import pytest
from airflow.decorators import task
from airflow.utils.state import State
class Test_BranchPythonDecoratedOperator:
@pytest.mark.parametrize("branch_task_name", ["task_1", "task_2"])
def test_branch_one(self, dag_maker, branch_task_name):
@task
def dummy_f():
pass
@task
def task_1():
pass
@task
def task_2():
pass
@task.branch(task_id="branching")
def branch_operator():
return branch_task_name
with dag_maker():
branchoperator = branch_operator()
df = dummy_f()
task_1 = task_1()
task_2 = task_2()
df.set_downstream(branchoperator)
branchoperator.set_downstream(task_1)
branchoperator.set_downstream(task_2)
dr = dag_maker.create_dagrun()
df.operator.run(start_date=dr.execution_date, end_date=dr.execution_date, ignore_ti_state=True)
branchoperator.operator.run(
start_date=dr.execution_date, end_date=dr.execution_date, ignore_ti_state=True
)
task_1.operator.run(start_date=dr.execution_date, end_date=dr.execution_date, ignore_ti_state=True)
task_2.operator.run(start_date=dr.execution_date, end_date=dr.execution_date, ignore_ti_state=True)
tis = dr.get_task_instances()
for ti in tis:
if ti.task_id == "dummy_f":
assert ti.state == State.SUCCESS
if ti.task_id == "branching":
assert ti.state == State.SUCCESS
if ti.task_id == "task_1" and branch_task_name == "task_1":
assert ti.state == State.SUCCESS
elif ti.task_id == "task_1":
assert ti.state == State.SKIPPED
if ti.task_id == "task_2" and branch_task_name == "task_2":
assert ti.state == State.SUCCESS
elif ti.task_id == "task_2":
assert ti.state == State.SKIPPED
| 1,193 |
454 | <reponame>zwkjhx/vertx-zero<gh_stars>100-1000
package io.vertx.up.uca.registry;
import io.vertx.up.exception.web._500InternalServerException;
import io.vertx.up.util.Ut;
import java.util.Objects;
public class Uddi {
/*
* Registry interface connect
*/
public static UddiRegistry registry(final Class<?> caller) {
final Class<?> componentCls = UddiConfig.registry();
if (Objects.isNull(componentCls)) {
return Ut.singleton(UddiEmpty.class);
} else {
return Ut.singleton(componentCls, caller);
}
}
/*
* Discovery
*/
public static UddiJet discovery(final Class<?> caller) {
final Class<?> componentCls = UddiConfig.jet();
if (Objects.isNull(componentCls) || !Ut.isImplement(componentCls, UddiJet.class)) {
throw new _500InternalServerException(caller, "Null or not UddiJet");
} else {
return Ut.instance(componentCls);
}
}
/*
* Client
*/
public static UddiClient client(final Class<?> caller) {
final Class<?> componentCls = UddiConfig.client();
if (Objects.isNull(componentCls) || !Ut.isImplement(componentCls, UddiClient.class)) {
throw new _500InternalServerException(caller, "Null or not UddiClient");
} else {
return Ut.instance(componentCls, caller);
}
}
}
| 608 |
2,151 | //===----- FileOffset.h - Offset in a file ----------------------*- C++ -*-===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
#ifndef LLVM_CLANG_EDIT_FILEOFFSET_H
#define LLVM_CLANG_EDIT_FILEOFFSET_H
#include "clang/Basic/SourceLocation.h"
namespace clang {
namespace edit {
class FileOffset {
FileID FID;
unsigned Offs;
public:
FileOffset() : Offs(0) { }
FileOffset(FileID fid, unsigned offs) : FID(fid), Offs(offs) { }
bool isInvalid() const { return FID.isInvalid(); }
FileID getFID() const { return FID; }
unsigned getOffset() const { return Offs; }
FileOffset getWithOffset(unsigned offset) const {
FileOffset NewOffs = *this;
NewOffs.Offs += offset;
return NewOffs;
}
friend bool operator==(FileOffset LHS, FileOffset RHS) {
return LHS.FID == RHS.FID && LHS.Offs == RHS.Offs;
}
friend bool operator!=(FileOffset LHS, FileOffset RHS) {
return !(LHS == RHS);
}
friend bool operator<(FileOffset LHS, FileOffset RHS) {
return std::tie(LHS.FID, LHS.Offs) < std::tie(RHS.FID, RHS.Offs);
}
friend bool operator>(FileOffset LHS, FileOffset RHS) {
return RHS < LHS;
}
friend bool operator>=(FileOffset LHS, FileOffset RHS) {
return !(LHS < RHS);
}
friend bool operator<=(FileOffset LHS, FileOffset RHS) {
return !(RHS < LHS);
}
};
}
} // end namespace clang
#endif
| 571 |
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.xml.multiview;
import org.netbeans.core.spi.multiview.CloseOperationState;
import org.netbeans.core.spi.multiview.MultiViewFactory;
import org.netbeans.modules.xml.multiview.ui.TreePanelDesignEditor;
import org.openide.loaders.DataObject;
import org.openide.util.WeakListeners;
import org.openide.util.lookup.ProxyLookup;
import java.beans.PropertyChangeEvent;
import java.beans.PropertyChangeListener;
import java.beans.PropertyVetoException;
/**
* XmlMultiviewElement.java
*
* Created on October 5, 2004, 1:35 PM
* @author mkuchtiak
*/
public abstract class TreePanelMultiViewElement extends AbstractMultiViewElement {
private TreePanelDesignEditor editor;
private PropertyChangeListener listener = new PropertyChangeListener() {
public void propertyChange(PropertyChangeEvent evt) {
if (DataObject.PROP_MODIFIED.equals(evt.getPropertyName()) && editor != null) {
Utils.runInAwtDispatchThread(new Runnable() {
public void run() {
callback.getTopComponent().setDisplayName(dObj.getEditorSupport().messageName());
callback.getTopComponent().setHtmlDisplayName(dObj.getEditorSupport().messageHtmlName());
callback.getTopComponent().setToolTipText(dObj.getEditorSupport().messageToolTip());
}
});
}
}
};
public TreePanelMultiViewElement(final XmlMultiViewDataObject dObj) {
super(dObj);
dObj.addPropertyChangeListener(WeakListeners.propertyChange(listener, dObj));
}
protected void setVisualEditor(TreePanelDesignEditor editor) {
this.editor=editor;
}
public CloseOperationState canCloseElement() {
try {
editor.fireVetoableChange(TreePanelDesignEditor.PROPERTY_FLUSH_DATA, this, null);
} catch (PropertyVetoException e) {
return MultiViewFactory.createUnsafeCloseState(TreePanelDesignEditor.PROPERTY_FLUSH_DATA, null, null);
}
return super.canCloseElement();
}
public void componentActivated() {
editor.componentActivated();
}
public void componentClosed() {
editor.componentClosed();
}
public void componentDeactivated() {
editor.componentDeactivated();
}
public void componentHidden() {
editor.componentHidden();
dObj.setActiveMultiViewElement(null);
}
public void componentOpened() {
editor.componentOpened();
}
public void componentShowing() {
editor.componentShowing();
dObj.setActiveMultiViewElement(this);
}
public org.openide.util.Lookup getLookup() {
return new ProxyLookup(new org.openide.util.Lookup[] {
dObj.getNodeDelegate().getLookup()
});
}
public javax.swing.JComponent getToolbarRepresentation() {
//return editor.getStructureView();
return new javax.swing.JPanel();
}
public javax.swing.JComponent getVisualRepresentation() {
return editor;
}
}
| 1,451 |
563 | package com.gentics.mesh.core.data.dao;
import java.util.function.Predicate;
import com.gentics.mesh.context.InternalActionContext;
import com.gentics.mesh.core.data.branch.HibBranch;
import com.gentics.mesh.core.data.page.Page;
import com.gentics.mesh.core.data.perm.InternalPermission;
import com.gentics.mesh.core.data.project.HibProject;
import com.gentics.mesh.core.data.user.HibUser;
import com.gentics.mesh.core.rest.branch.BranchResponse;
import com.gentics.mesh.core.result.Result;
import com.gentics.mesh.event.EventQueueBatch;
import com.gentics.mesh.parameter.PagingParameters;
/**
* DAO to access {@link HibBranch}
*/
// TODO move the contents of this to BranchDao once migration is done
public interface BranchDaoWrapper extends BranchDao, DaoTransformable<HibBranch, BranchResponse>, DaoWrapper<HibBranch> {
/**
* Load all branches.
*
* @param project
* @return
*/
Result<? extends HibBranch> findAll(HibProject project);
/**
* Load a page of branches.
*
* @param project
* @param ac
* @param pagingInfo
* @return
*/
Page<? extends HibBranch> findAll(HibProject project, InternalActionContext ac, PagingParameters pagingInfo);
/**
* Load a page of branches.
*
* @param project
* @param ac
* @param pagingInfo
* @param extraFilter
* @return
*/
Page<? extends HibBranch> findAll(HibProject project, InternalActionContext ac, PagingParameters pagingInfo, Predicate<HibBranch> extraFilter);
/**
* Load the branch of the project.
*
* @param project
* @param ac
* @param uuid
* @param perm
* @return
*/
HibBranch loadObjectByUuid(HibProject project, InternalActionContext ac, String uuid, InternalPermission perm);
/**
* Load the branch by uuid.
*
* @param project
* @param ac
* @param uuid
* @param perm
* @param errorIfNotFound
* @return
*/
HibBranch loadObjectByUuid(HibProject project, InternalActionContext ac, String uuid, InternalPermission perm, boolean errorIfNotFound);
/**
* Find the branch of the project by uuid.
*
* @param project
* @param uuid
*/
HibBranch findByUuid(HibProject project, String uuid);
/**
* Return the branch by name.
*
* @param project
* @param name
* @return
*/
HibBranch findByName(HibProject project, String name);
/**
* Return the etag for the branch.
*
* @param branch
* @param ac
* @return
*/
String getETag(HibBranch branch, InternalActionContext ac);
/**
* Return the API path for the given branch.
*
* @param branch
* @param ac
* @return
*/
String getAPIPath(HibBranch branch, InternalActionContext ac);
/**
* Update the branch.
*
* @param branch
* @param ac
* @param batch
* @return
*/
boolean update(HibBranch branch, InternalActionContext ac, EventQueueBatch batch);
/**
* Create the branch.
*
* @param project
* @param name
* @param user
* @param batch
* @return
*/
HibBranch create(HibProject project, String name, HibUser user, EventQueueBatch batch);
/**
* Create the branch.
*
* @param project
* @param ac
* @param batch
* @param uuid
* @return
*/
HibBranch create(HibProject project, InternalActionContext ac, EventQueueBatch batch, String uuid);
/**
* Create the branch.
*
* @param project
* @param name
* @param creator
* @param uuid
* @param setLatest
* @param baseBranch
* @param batch
* @return
*/
HibBranch create(HibProject project, String name, HibUser creator, String uuid, boolean setLatest, HibBranch baseBranch, EventQueueBatch batch);
/**
* Return the latest branch for the project.
*
* @param project
* @return
*/
HibBranch getLatestBranch(HibProject project);
}
| 1,269 |
1,144 | <gh_stars>1000+
/*****************************************************************************
**
** Name: app_services.h
**
** Description: Bluetooth Services functions
**
** Copyright (c) 2009-2011, Broadcom Corp., All Rights Reserved.
** Broadcom Bluetooth Core. Proprietary and confidential.
**
*****************************************************************************/
/*******************************************************************************
**
** Function app_service_id_to_string
**
** Description This function is used to convert a service ID to a string
**
** Parameters
**
** Returns Pointer to string containing the service in human format
**
*******************************************************************************/
const char *app_service_id_to_string(tBSA_SERVICE_ID serviceId);
/*******************************************************************************
**
** Function app_service_mask_to_string
**
** Description This function is used to convert a service ID Mask to a string
**
** Parameters
**
** Returns Pointer to string containing the services in human format
**
*******************************************************************************/
char *app_service_mask_to_string(tBSA_SERVICE_MASK serviceMask);
| 318 |
6,989 | #include "spinlock.h"
| 9 |
528 | #!/usr/bin/env python
'''
Disclaimer - This is a solution to the below problem given the content we have
discussed in class. It is not necessarily the best solution to the problem.
In other words, I generally only use things we have covered up to this point
in the class (with some exceptions which I will usually note).
Python for Network Engineers
https://pynet.twb-tech.com
Learning Python
1. Use the split method to divide the following IPv6 address into
groups of 4 hex digits (i.e. split on the ":")
FE80:0000:0000:0000:0101:A3EF:EE1E:1719
2. Use the join method to reunite your split IPv6 address back to
its original value.
'''
ipv6_addr = 'FE80:0000:0000:0000:0101:A3EF:EE1E:1719'
ipv6_sections = ipv6_addr.split(":")
print
print "IPv6 address split:"
print ipv6_sections
print
ipv6_new = ":".join(ipv6_sections)
print "IPv6 address re-joined:"
print ipv6_new
print
| 295 |
2,151 | // Copyright 2016 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#ifndef SKIA_EXT_SKIA_HISTOGRAM_H_
#define SKIA_EXT_SKIA_HISTOGRAM_H_
#include <cstdint>
// This file exposes Chrome's histogram functionality to Skia, without bringing
// in any Chrome specific headers. To achieve the same level of optimization as
// is present in Chrome, we need to use an inlined atomic pointer. This macro
// defines a placeholder atomic which will be inlined into the call-site. This
// placeholder is passed to the actual histogram logic in Chrome.
#define SK_HISTOGRAM_POINTER_HELPER(function, ...) \
do { \
static intptr_t atomic_histogram_pointer = 0; \
function(&atomic_histogram_pointer, __VA_ARGS__); \
} while (0)
#define SK_HISTOGRAM_BOOLEAN(name, sample) \
SK_HISTOGRAM_POINTER_HELPER(skia::HistogramBoolean, "Skia." name, sample)
#define SK_HISTOGRAM_ENUMERATION(name, sample, boundary_value) \
SK_HISTOGRAM_POINTER_HELPER(skia::HistogramEnumeration, "Skia." name, \
sample, boundary_value)
namespace skia {
void HistogramBoolean(intptr_t* atomic_histogram_pointer,
const char* name,
bool sample);
void HistogramEnumeration(intptr_t* atomic_histogram_pointer,
const char* name,
int sample,
int boundary_value);
} // namespace skia
#endif // SKIA_EXT_SKIA_HISTOGRAM_H_
| 675 |
607 | <gh_stars>100-1000
{
"name": "opencvjs",
"version": "1.0.0",
"description": "JavaScript Bindings for OpenCV",
"main": "build/cv.js",
"scripts": {
"build": "python make.py",
"test": "open test/tests.html"
},
"homepage": "https://github.com/ucisysarch/opencvjs",
"repository": "https://github.com/ucisysarch/opencvjs",
"bugs": "https://github.com/ucisysarch/opencvjs/issues",
"license": "BSD-4-Clause"
}
| 179 |
1,668 | <filename>src/ralph/trade_marks/migrations/0010_auto_20210702_1129.py
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('trade_marks', '0009_auto_20210630_1719'),
]
operations = [
migrations.RemoveField(
model_name='design',
name='type',
),
migrations.RemoveField(
model_name='patent',
name='type',
),
migrations.AddField(
model_name='design',
name='database_link',
field=models.URLField(max_length=255, blank=True, null=True),
),
migrations.AddField(
model_name='patent',
name='database_link',
field=models.URLField(max_length=255, blank=True, null=True),
),
migrations.AddField(
model_name='trademark',
name='database_link',
field=models.URLField(max_length=255, blank=True, null=True),
),
migrations.AlterField(
model_name='design',
name='classes',
field=models.CharField(max_length=255),
),
migrations.AlterField(
model_name='design',
name='number',
field=models.CharField(max_length=255),
),
migrations.AlterField(
model_name='patent',
name='classes',
field=models.CharField(max_length=255),
),
migrations.AlterField(
model_name='patent',
name='number',
field=models.CharField(max_length=255),
),
migrations.AlterField(
model_name='trademark',
name='classes',
field=models.CharField(max_length=255),
),
migrations.AlterField(
model_name='trademark',
name='number',
field=models.CharField(max_length=255),
),
migrations.AlterField(
model_name='trademark',
name='type',
field=models.PositiveIntegerField(verbose_name='Trade Mark type', default=2, choices=[(1, 'Word'), (2, 'Figurative'), (3, 'Word - Figurative')]),
),
]
| 1,147 |
445 | #!/usr/bin/env python
import youku
import bilibili
import acfun
import iask
import ku6
import pptv
import iqiyi
import tudou
import sohu
import w56
import cntv
import yinyuetai
import ifeng
from common import *
import re
def url_to_module(url):
site = r1(r'http://([^/]+)/', url)
assert site, 'invalid url: ' + url
if site.endswith('.com.cn'):
site = site[:-3]
domain = r1(r'(\.[^.]+\.[^.]+)$', site)
assert domain, 'not supported url: ' + url
k = r1(r'([^.]+)', domain)
downloads = {
'youku':youku,
'bilibili':bilibili,
'kankanews':bilibili,
'smgbb':bilibili,
'acfun':acfun,
'iask':iask,
'sina':iask,
'ku6':ku6,
'pptv':pptv,
'iqiyi':iqiyi,
'tudou':tudou,
'sohu':sohu,
'56':w56,
'cntv':cntv,
'yinyuetai':yinyuetai,
'ifeng':ifeng,
}
if k in downloads:
return downloads[k]
else:
raise NotImplementedError(url)
def any_download(url, merge=True):
m = url_to_module(url)
m.download(url, merge=merge)
def any_download_playlist(url, create_dir=False, merge=True):
m = url_to_module(url)
m.download_playlist(url, create_dir=create_dir, merge=merge)
def main():
script_main('video_lixian', any_download, any_download_playlist)
if __name__ == '__main__':
main()
| 573 |
30,023 | """The geo_rss_events component."""
| 11 |
348 | <filename>docs/data/leg-t2/087/08701153.json
{"nom":"Saint-Julien-le-Petit","circ":"1ère circonscription","dpt":"Haute-Vienne","inscrits":284,"abs":116,"votants":168,"blancs":7,"nuls":12,"exp":149,"res":[{"nuance":"FI","nom":"<NAME>","voix":83},{"nuance":"REM","nom":"Mme <NAME>","voix":66}]} | 119 |
4,535 | <reponame>redoclag/plaidml
// Copyright 2018, Intel Corporation
#pragma once
#include <map>
#include <string>
#include "tile/codegen/alias.h"
#include "tile/codegen/codegen.pb.h"
#include "tile/codegen/compile_pass.h"
#include "tile/stripe/stripe.h"
namespace vertexai {
namespace tile {
namespace codegen {
class FixStridesPass final : public CompilePass {
public:
explicit FixStridesPass(const proto::FixStridesPass& options) : options_{options} {}
void Apply(CompilerState* state) const final;
private:
proto::FixStridesPass options_;
};
} // namespace codegen
} // namespace tile
} // namespace vertexai
| 210 |
14,668 | <gh_stars>1000+
// Copyright 2019 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
package org.chromium.chrome.browser.omnibox.suggestions;
import org.chromium.ui.base.PageTransition;
/**
* Provides the additional functionality to trigger and interact with autocomplete suggestions.
*/
public interface AutocompleteDelegate extends UrlBarDelegate {
/**
* Notified that the URL text has changed.
*/
void onUrlTextChanged();
/**
* Notified that suggestions have changed.
* @param autocompleteText The inline autocomplete text that can be appended to the
* currently entered user text.
* @param defaultMatchIsSearch Whether the default match is a search (as opposed to a URL).
* This is true if there are no suggestions.
*/
void onSuggestionsChanged(String autocompleteText, boolean defaultMatchIsSearch);
/**
* Requests the keyboard visibility update.
*
* @param shouldShow When true, keyboard should be made visible.
* @param delayHide when true, hiding will commence after brief delay.
*/
void setKeyboardVisibility(boolean shouldShow, boolean delayHide);
/**
* @return Reports whether keyboard (whether software or hardware) is active.
* Software keyboard is reported as active whenever it is visible on screen; hardware keyboard
* is reported as active when it is connected.
*/
boolean isKeyboardActive();
/**
* Requests that the given URL be loaded in the current tab.
*
* @param url The URL to be loaded.
* @param transition The transition type associated with the url load.
* @param inputStart The time the input started for the load request.
*/
void loadUrl(String url, @PageTransition int transition, long inputStart);
/**
* Requests that the given URL be loaded in the current tab.
*
* @param url The URL to be loaded.
* @param transition The transition type associated with the url load.
* @param inputStart The time the input started for the load request.
* @param postDataType postData type.
* @param postData Post-data to include in the tab URL's request body, ex. bitmap when
* image search.
*/
void loadUrlWithPostData(String url, @PageTransition int transition, long inputStart,
String postDataType, byte[] postData);
/**
* @return Whether the omnibox was focused via the NTP fakebox.
*/
boolean didFocusUrlFromFakebox();
/**
* @return Whether the URL currently has focus.
*/
boolean isUrlBarFocused();
}
| 877 |
1,721 | //
// JPVideoPlayerAudioViewController.h
// JPVideoPlayerDemo
//
// Created by NewPan on 2018/5/25.
// Copyright © 2018年 NewPan. All rights reserved.
//
#import <UIKit/UIKit.h>
@interface JPVideoPlayerAudioViewController : UIViewController
@end
| 86 |
1,781 | <gh_stars>1000+
package chapter1.section3;
import java.util.Iterator;
/**
* Created by <NAME> on 14/11/17.
*/
public class DoublyLinkedListCircular<Item> implements Iterable<Item> {
public class DoubleNode {
public Item item;
DoubleNode previous;
DoubleNode next;
}
private int size;
private DoubleNode first;
private DoubleNode last;
public boolean isEmpty() {
return size == 0;
}
public int size() {
return size;
}
public DoubleNode first() {
return first;
}
public DoubleNode last() {
return last;
}
public Item get(int index) {
if (isEmpty()) {
return null;
}
if (index < 0 || index >= size) {
throw new IllegalArgumentException("Index must be between 0 and " + (size() - 1));
}
DoubleNode current = first;
int count = 0;
while (count != index) {
current = current.next;
count++;
}
return current.item;
}
public void insertNodeAtTheBeginning(DoubleNode doubleNode) {
DoubleNode oldFirst = first;
first = doubleNode;
first.next = oldFirst;
if (!isEmpty()) {
first.previous = oldFirst.previous;
oldFirst.previous = first;
} else {
last = first;
first.previous = last;
}
last.next = first;
size++;
}
public void insertNodeAtTheEnd(DoubleNode doubleNode) {
DoubleNode oldLast = last;
last = doubleNode;
last.previous = oldLast;
if (!isEmpty()) {
last.next = oldLast.next;
oldLast.next = last;
} else {
first = last;
last.next = first;
}
first.previous = last;
size++;
}
public void insertAtTheBeginning(Item item) {
DoubleNode oldFirst = first;
first = new DoubleNode();
first.item = item;
first.next = oldFirst;
if (!isEmpty()) {
first.previous = oldFirst.previous;
oldFirst.previous = first;
} else {
last = first;
first.previous = last;
}
last.next = first;
size++;
}
public void insertAtTheEnd(Item item) {
DoubleNode oldLast = last;
last = new DoubleNode();
last.item = item;
last.previous = oldLast;
if (!isEmpty()) {
last.next = oldLast.next;
oldLast.next = last;
} else {
first = last;
last.next = first;
}
first.previous = last;
size++;
}
public void insertBeforeNode(Item beforeItem, Item item) {
if (isEmpty()) {
return;
}
DoubleNode currentNode;
for(currentNode = first; currentNode != last; currentNode = currentNode.next) {
if (currentNode.item.equals(beforeItem)) {
break;
}
}
if (currentNode == last && last.item != beforeItem) {
return;
}
DoubleNode newNode = new DoubleNode();
newNode.item = item;
DoubleNode previousNode = currentNode.previous;
currentNode.previous = newNode;
newNode.next = currentNode;
newNode.previous = previousNode;
if (newNode.previous == last) {
// This is the first node
first = newNode;
}
newNode.previous.next = newNode;
size++;
}
public void insertAfterNode(Item afterNode, Item item) {
if (isEmpty()) {
return;
}
DoubleNode currentNode;
for(currentNode = first; currentNode != last; currentNode = currentNode.next) {
if (currentNode.item.equals(afterNode)) {
break;
}
}
if (currentNode == last && last.item != afterNode) {
return;
}
DoubleNode newNode = new DoubleNode();
newNode.item = item;
DoubleNode nextNode = currentNode.next;
currentNode.next = newNode;
newNode.previous = currentNode;
newNode.next = nextNode;
if (newNode.next == first) {
// This is the last node
last = newNode;
}
newNode.next.previous = newNode;
size++;
}
public void insertLinkedListAtTheEnd(DoublyLinkedListCircular<Item> doublyLinkedListCircular) {
if (!doublyLinkedListCircular.isEmpty()) {
doublyLinkedListCircular.first().previous = last;
doublyLinkedListCircular.last().next = first;
}
if (!isEmpty()) {
last.next = doublyLinkedListCircular.first();
first.previous = doublyLinkedListCircular.last();
} else {
first = doublyLinkedListCircular.first();
}
last = doublyLinkedListCircular.last();
size += doublyLinkedListCircular.size;
}
public Item removeFromTheBeginning() {
if (isEmpty()) {
return null;
}
Item item = first.item;
if (size() > 1) {
first.next.previous = first.previous;
first.previous.next = first.next;
first = first.next;
} else { // There is only 1 element in the list
first = null;
last = null;
}
size--;
return item;
}
public Item removeFromTheEnd() {
if (isEmpty()) {
return null;
}
Item item = last.item;
if (size() > 1) {
last.previous.next = last.next;
last.next.previous = last.previous;
last = last.previous;
} else { // There is only 1 element in the list
first = null;
last = null;
}
size--;
return item;
}
public void removeItem(Item item) {
if (isEmpty()) {
return;
}
DoubleNode currentNode = first;
while (currentNode != last) {
if (currentNode.item.equals(item)) {
removeItemWithNode(currentNode);
return;
}
currentNode = currentNode.next;
}
if (currentNode.item == item) {
removeFromTheEnd();
}
}
public void removeItemWithNode(DoubleNode doubleNode) {
if (doubleNode == null) {
throw new IllegalArgumentException("Node cannot be null");
}
// Base case 1: empty list
if (isEmpty()) {
return;
}
// Base case 2: size 1 list
if (doubleNode == first && first == last) {
first = null;
last = null;
return;
}
DoubleNode previousNode = doubleNode.previous;
DoubleNode nextNode = doubleNode.next;
previousNode.next = nextNode;
nextNode.previous = previousNode;
if (doubleNode == first) {
first = nextNode;
}
if (doubleNode == last) {
last = previousNode;
}
size--;
}
public Item removeItemWithIndex(int nodeIndex) {
if (isEmpty()) {
return null;
}
if (nodeIndex < 0 || nodeIndex >= size) {
throw new IllegalArgumentException("Index must be between 0 and " + (size() - 1));
}
boolean startFromTheBeginning = nodeIndex <= size() / 2;
int index = startFromTheBeginning ? 0 : size() - 1;
DoubleNode currentNode = startFromTheBeginning? first : last;
while (true) {
if (nodeIndex == index) {
break;
}
if (startFromTheBeginning) {
index++;
} else {
index--;
}
currentNode = startFromTheBeginning ? currentNode.next : currentNode.previous;
}
@SuppressWarnings("ConstantConditions") // If we got here, the node exists
Item item = currentNode.item;
removeItemWithNode(currentNode);
return item;
}
@Override
public Iterator<Item> iterator() {
return new DoublyLinkedListCircularIterator();
}
private class DoublyLinkedListCircularIterator implements Iterator<Item> {
int index = 0;
DoubleNode currentNode = first;
@Override
public boolean hasNext() {
return index < size();
}
@Override
public Item next() {
Item item = currentNode.item;
currentNode = currentNode.next;
index++;
return item;
}
}
}
| 4,159 |
373 | {
"jcr:primaryType": "cq:Page",
"jcr:content": {
"jcr:primaryType": "cq:PageContent",
"jcr:title": "assets",
"cq:template": "/apps/acs-commons/templates/utilities/asset-packager",
"preview": "true",
"sling:resourceType": "acs-commons/components/utilities/packager/asset-packager",
"cq:designPath": "/etc/designs/acs-commons",
"configuration": {
"jcr:primaryType": "nt:unstructured",
"pageExclusions": "",
"packageACLHandling": "Overwrite",
"assetExclusions": "",
"packageDescription": "Asset Package initially defined by a ACS AEM Commons - Asset Packager configuration.",
"packageVersion": "1.0.0",
"packageGroupName": "Assets",
"pagePath": "/content/we-retail/language-masters/en/experience",
"packageName": "assets",
"assetPrefix": "/content/dam/we-retail/en/experiences",
"sling:resourceType": "acs-commons/components/utilities/packager/asset-packager/configuration",
"conflictResolution": "IncrementVersion"
}
}
}
| 415 |
317 | <filename>test/com/googlecode/totallylazy/collections/TrieTest.java
package com.googlecode.totallylazy.collections;
import org.junit.Test;
import static com.googlecode.totallylazy.Option.none;
import static com.googlecode.totallylazy.Option.some;
import static com.googlecode.totallylazy.Segment.constructors.characters;
import static com.googlecode.totallylazy.collections.PersistentSortedMap.constructors;
import static com.googlecode.totallylazy.collections.Trie.trie;
import static com.googlecode.totallylazy.matchers.Matchers.is;
import static org.hamcrest.MatcherAssert.assertThat;
public class TrieTest {
@Test
public void get() throws Exception {
Trie<Character, String> trie = trie(none(String.class), constructors.<Character, Trie<Character, String>>sortedMap('a', trie(none(String.class), constructors.<Character, Trie<Character, String>>sortedMap('b', trie(some("Foo"), constructors.<Character, Trie<Character, String>>emptySortedMap())))));
assertThat(trie.get(characters("ab")).get(), is("Foo"));
}
@Test
public void put() throws Exception {
Trie<Character, String> trie = Trie.<Character, String>trie().put(characters("ab"), "Foo");
assertThat(trie.get(characters("ab")).get(), is("Foo"));
}
@Test
public void contains() throws Exception {
Trie<Character, String> trie = Trie.<Character, String>trie().put(characters("ab"), "Foo");
assertThat(trie.contains(characters("ab")), is(true));
assertThat(trie.contains(characters("a")), is(false));
assertThat(trie.contains(characters("b")), is(false));
assertThat(trie.contains(characters("")), is(false));
}
@Test
public void remove() throws Exception {
Trie<Character, String> trie = Trie.<Character, String>trie().put(characters("ab"), "Foo").put(characters("aa"), "Bar").remove(characters("ab"));
assertThat(trie.contains(characters("ab")), is(false));
assertThat(trie.contains(characters("aa")), is(true));
}
}
| 744 |
496 | import sys
import imdb
imdb_object = imdb.IMDb()
if len(sys.argv) != 2:
print("Please provide movie name in proper format!!!")
sys.exit()
movie_name = sys.argv[1].replace('_', ' ')
try:
search_result = imdb_object.search_movie(movie_name, 1)
movie_data = search_result[0].__dict__
vote_details = imdb_object.get_movie_vote_details(movie_data["movieID"])
movie_rating_stats = vote_details["data"]["demographics"]["imdb users"]
print("Rating: %s, based on %s votes" % (movie_rating_stats["rating"], movie_rating_stats["votes"]))
except KeyError:
print("Movie ratings data is not available")
sys.exit()
| 240 |
396 | package com.ljy.devring.cache;
import android.app.Application;
import android.content.Context;
import android.content.SharedPreferences;
import android.os.Process;
import androidx.collection.SimpleArrayMap;
import com.ljy.devring.cache.support.DiskCache;
import com.ljy.devring.cache.support.MemoryCache;
import com.ljy.devring.cache.support.SpCache;
import com.ljy.devring.util.FileUtil;
import java.io.File;
import javax.inject.Inject;
import javax.inject.Singleton;
import dagger.Lazy;
/**
* author: ljy
* date: 2018/3/16
* description: 缓存管理者
*/
@Singleton
public class CacheManager {
private static final long DEFAULT_DISK_CACHE_MAX_SIZE = Long.MAX_VALUE;
private static final int DEFAULT_DISK_CACHE_MAX_COUNT = Integer.MAX_VALUE;
private static final String DEFAULT_SP_NAME = "default_sp_name_";
@Inject
Application mContext;
@Inject
CacheConfig mCacheConfig;
@Inject
SimpleArrayMap<String, SpCache> mMapSpCache;
@Inject
SimpleArrayMap<String, DiskCache> mMapDiskCache;
@Inject
Lazy<MemoryCache> mMemoryCache;
@Inject
public CacheManager() {
}
public DiskCache diskCache(String cacheName) {
File cacheDir;
if (isSpace(cacheName)) cacheName = "cache_default";
if (mCacheConfig.getDiskCacheFolder() != null && mCacheConfig.getDiskCacheFolder().isDirectory()) {
cacheDir = new File(mCacheConfig.getDiskCacheFolder(), cacheName);
} else {
cacheDir = new File(FileUtil.getCacheDir(mContext), cacheName);
}
String cacheKey = cacheDir.getAbsoluteFile() + "_" + Process.myPid();
DiskCache cache = mMapDiskCache.get(cacheKey);
if (cache == null) {
long maxSize = mCacheConfig.getDiskCacheMaxSize() > 0 ? mCacheConfig.getDiskCacheMaxSize() : DEFAULT_DISK_CACHE_MAX_SIZE;
int maxCount = mCacheConfig.getDiskCacheMaxCount() > 0 ? mCacheConfig.getDiskCacheMaxCount() : DEFAULT_DISK_CACHE_MAX_COUNT;
cache = new DiskCache(mContext, cacheDir, maxSize, maxCount);
mMapDiskCache.put(cacheKey, cache);
}
return cache;
}
private boolean isSpace(final String s) {
if (s == null) return true;
for (int i = 0, len = s.length(); i < len; ++i) {
if (!Character.isWhitespace(s.charAt(i))) {
return false;
}
}
return true;
}
public MemoryCache memoryCache() {
return mMemoryCache.get();
}
/**
* 返回默认提供的sp,Mode默认为Context.MODE_PRIVATE
*/
public SpCache spCache() {
return spCache(DEFAULT_SP_NAME, Context.MODE_PRIVATE);
}
/**
* 返回默认提供的sp,Mode为指定的类型
*/
public SpCache spCache(int mode) {
return spCache(DEFAULT_SP_NAME, mode);
}
/**
* 返回指定的Sp,Mode默认为Context.MODE_PRIVATE
*/
public SpCache spCache(String spName) {
return spCache(spName, Context.MODE_PRIVATE);
}
/**
* 返回指定的Sp,Mode为指定的类型
*/
public SpCache spCache(String spName, int mode) {
SpCache spCache = mMapSpCache.get(spName + mode);
if (spCache == null) {
SharedPreferences defaultSp = mContext.getSharedPreferences(spName, mode);
spCache = new SpCache(defaultSp);
mMapSpCache.put(spName + mode, spCache);
}
return spCache;
}
}
| 1,527 |
1,428 | <gh_stars>1000+
# BHASKARA
from math import sqrt
a = float(input('Informe o valor de "a": '))
b = float(input('Informe o valor de "b": '))
c = float(input('Informe o valor de "c": '))
delta = pow(b, 2) - 4 * a * c
deltart = sqrt(delta)
x1 = ((-b) + deltart) / (2 * a)
x2 = ((-b) - deltart) / (2 * a)
print('\033[30mO valor de x1 =\033[m \033[31m{}\033[m\033[30m e x2 =\033[m \033[34m{}\033[m'.format(x1, x2))
| 216 |
2,690 | # Copyright ClusterHQ Inc. See LICENSE file for details.
"""
Tests for ``flocker.provision._install``.
"""
import yaml
from pyrsistent import freeze, thaw
from textwrap import dedent
from .._install import (
task_configure_flocker_agent,
task_enable_flocker_agent,
run, put, run_from_args,
get_repository_url, UnsupportedDistribution, get_installable_version,
get_repo_options,
_remove_dataset_fields, _remove_private_key,
UnknownAction, DistributionNotSupported)
from .._ssh import Put
from .._effect import sequence
from ...node.backends import backend_loader
from ...testtools import TestCase
from ... import __version__ as flocker_version
THE_AGENT_YML_PATH = b"/etc/flocker/agent.yml"
BASIC_AGENT_YML = freeze({
"version": 1,
"control-service": {
"hostname": "192.0.2.42",
"port": 4524,
},
"dataset": {
"backend": "zfs",
},
"logging": {
"version": 1,
"formatters": {
"timestamped": {
"datefmt": "%Y-%m-%d %H:%M:%S",
"format": "%(asctime)s %(message)s"
},
},
},
})
class ConfigureFlockerAgentTests(TestCase):
"""
Tests for ``task_configure_flocker_agent``.
"""
def test_agent_yml(self):
"""
```task_configure_flocker_agent`` writes a ``/etc/flocker/agent.yml``
file which contains the backend configuration passed to it.
"""
control_address = BASIC_AGENT_YML["control-service"]["hostname"]
expected_pool = u"some-test-pool"
expected_backend_configuration = dict(pool=expected_pool)
commands = task_configure_flocker_agent(
control_node=control_address,
dataset_backend=backend_loader.get(
BASIC_AGENT_YML["dataset"]["backend"]
),
dataset_backend_configuration=expected_backend_configuration,
logging_config=thaw(BASIC_AGENT_YML["logging"]),
)
[put_agent_yml] = list(
effect.intent
for effect in
commands.intent.effects
if isinstance(effect.intent, Put)
)
# Seems like transform should be usable here but I don't know how.
expected_agent_config = BASIC_AGENT_YML.set(
"dataset",
BASIC_AGENT_YML["dataset"].update(expected_backend_configuration)
)
self.assertEqual(
put(
content=yaml.safe_dump(thaw(expected_agent_config)),
path=THE_AGENT_YML_PATH,
log_content_filter=_remove_dataset_fields,
).intent,
put_agent_yml,
)
class EnableFlockerAgentTests(TestCase):
"""
Tests for ``task_enable_flocker_agent``.
"""
def test_centos_sequence(self):
"""
``task_enable_flocker_agent`` for the 'centos-7' distribution returns
a sequence of systemctl enable and start commands for each agent.
"""
distribution = u"centos-7"
commands = task_enable_flocker_agent(
distribution=distribution,
)
expected_sequence = sequence([
run(command="systemctl enable flocker-dataset-agent"),
run(command="systemctl start flocker-dataset-agent"),
])
self.assertEqual(commands, expected_sequence)
def test_centos_sequence_managed(self):
"""
``task_enable_flocker_agent`` for the 'centos-7' distribution
returns a sequence of 'service restart' commands for each agent
when the action passed down is "restart" (used for managed provider).
"""
distribution = u"centos-7"
commands = task_enable_flocker_agent(
distribution=distribution,
action="restart"
)
expected_sequence = sequence([
run(command="systemctl enable flocker-dataset-agent"),
run(command="systemctl restart flocker-dataset-agent"),
])
self.assertEqual(commands, expected_sequence)
def test_ubuntu_sequence(self):
"""
``task_enable_flocker_agent`` for the 'ubuntu-14.04' distribution
returns a sequence of 'service start' commands for each agent.
"""
distribution = u"ubuntu-14.04"
commands = task_enable_flocker_agent(
distribution=distribution,
)
expected_sequence = sequence([
run(command="service flocker-dataset-agent start"),
])
self.assertEqual(commands, expected_sequence)
def test_ubuntu_sequence_managed(self):
"""
``task_enable_flocker_agent`` for the 'ubuntu-14.04' distribution
returns a sequence of 'service restart' commands for each agent
when the action passed down is "restart" (used for managed provider).
"""
distribution = u"ubuntu-14.04"
commands = task_enable_flocker_agent(
distribution=distribution,
action="restart"
)
expected_sequence = sequence([
run(command="service flocker-dataset-agent restart"),
])
self.assertEqual(commands, expected_sequence)
def test_sequence_invalid_action(self):
"""
``task_enable_flocker_agent`` for a valid distribution
but an invalid action raises a ``UnknownAction``.
"""
distribution = u"ubuntu-14.04"
self.assertRaises(UnknownAction,
task_enable_flocker_agent,
distribution=distribution,
action="stop")
def test_sequence_invalid_distro(self):
"""
``task_enable_flocker_agent`` for a non supported
distribution raises a ``DistributionNotSupported``.
"""
distribution = u"RedHat"
self.assertRaises(DistributionNotSupported,
task_enable_flocker_agent,
distribution=distribution,
action="restart")
def _centos7_install_commands(version):
"""
Construct the command sequence expected for installing Flocker on CentOS 7.
:param str version: A Flocker native OS package version (a package name
suffix) like ``"-1.2.3-1"``.
:return: The sequence of commands expected for installing Flocker on
CentOS7.
"""
installable_version = get_installable_version(flocker_version)
return sequence([
run(command="yum clean all"),
run(command="yum install -y {}".format(get_repository_url(
distribution='centos-7',
flocker_version=installable_version,
))),
run_from_args(
['yum', 'install'] + get_repo_options(installable_version) +
['-y', 'clusterhq-flocker-node' + version])
])
class GetRepoOptionsTests(TestCase):
"""
Tests for ``get_repo_options``.
"""
def test_marketing_release(self):
"""
No extra repositories are enabled if the latest installable version
is a marketing release.
"""
self.assertEqual(get_repo_options(flocker_version='0.3.0'), [])
def test_development_release(self):
"""
Enabling a testing repository is enabled if the latest installable
version is not a marketing release.
"""
self.assertEqual(
get_repo_options(flocker_version='0.3.0.dev1'),
['--enablerepo=clusterhq-testing'])
class GetRepositoryURLTests(TestCase):
"""
Tests for ``get_repository_url``.
"""
def test_centos_7(self):
"""
It is possible to get a repository URL for CentOS 7 packages.
"""
expected = ("https://clusterhq-archive.s3.amazonaws.com/centos/"
"clusterhq-release$(rpm -E %dist).noarch.rpm")
self.assertEqual(
get_repository_url(
distribution='centos-7',
flocker_version='0.3.0'),
expected
)
def test_ubuntu_14_04(self):
"""
It is possible to get a repository URL for Ubuntu 14.04 packages.
"""
expected = ("https://clusterhq-archive.s3.amazonaws.com/ubuntu/"
"$(lsb_release --release --short)/\\$(ARCH)")
self.assertEqual(
get_repository_url(
distribution='ubuntu-14.04',
flocker_version='0.3.0'),
expected
)
def test_unsupported_distribution(self):
"""
An ``UnsupportedDistribution`` error is thrown if a repository for the
desired distribution cannot be found.
"""
self.assertRaises(
UnsupportedDistribution,
get_repository_url, 'unsupported-os', '0.3.0',
)
def test_non_release_ubuntu(self):
"""
The operating system key for ubuntu has the suffix ``-testing`` for
non-marketing releases.
"""
expected = ("https://clusterhq-archive.s3.amazonaws.com/"
"ubuntu-testing/"
"$(lsb_release --release --short)/\\$(ARCH)")
self.assertEqual(
get_repository_url(
distribution='ubuntu-14.04',
flocker_version='0.3.0.dev1'),
expected
)
def test_non_release_centos(self):
"""
The operating system key for centos stays the same non-marketing
releases.
"""
expected = ("https://clusterhq-archive.s3.amazonaws.com/centos/"
"clusterhq-release$(rpm -E %dist).noarch.rpm")
self.assertEqual(
get_repository_url(
distribution='centos-7',
flocker_version='0.3.0.dev1'),
expected
)
class PrivateKeyLoggingTest(TestCase):
"""
Test removal of private keys from logs.
"""
def test_private_key_removed(self):
"""
A private key is removed for logging.
"""
key = dedent('''
-----BEGIN PRIVATE KEY-----
MFDkDKSLDDSf
MFSENSITIVED
MDKODSFJOEWe
-----END PRIVATE KEY-----
''')
self.assertEqual(
dedent('''
-----BEGIN PRIVATE KEY-----
MFDk...REMOVED...OEWe
-----END PRIVATE KEY-----
'''),
_remove_private_key(key))
def test_non_key_kept(self):
"""
Non-key data is kept for logging.
"""
key = 'some random data, not a key'
self.assertEqual(key, _remove_private_key(key))
def test_short_key_kept(self):
"""
A key that is suspiciously short is kept for logging.
"""
key = dedent('''
-----BEGIN PRIVATE KEY-----
short
-----END PRIVATE KEY-----
''')
self.assertEqual(key, _remove_private_key(key))
def test_no_end_key_removed(self):
"""
A missing end tag does not prevent removal working.
"""
key = dedent('''
-----BEGIN PRIVATE KEY-----
MFDkDKSLDDSf
MFSENSITIVED
MDKODSFJOEWe
''')
self.assertEqual(
'\n-----BEGIN PRIVATE KEY-----\nMFDk...REMOVED...OEWe\n',
_remove_private_key(key))
class DatasetLoggingTest(TestCase):
"""
Test removal of sensitive information from logged configuration files.
"""
def test_dataset_logged_safely(self):
"""
Values are either the same or replaced by 'REMOVED'.
"""
config = {
'dataset': {
'secret': 'SENSITIVE',
'zone': 'keep'
}
}
content = yaml.safe_dump(config)
logged = _remove_dataset_fields(content)
self.assertEqual(
yaml.safe_load(logged),
{'dataset': {'secret': 'REMOVED', 'zone': 'keep'}})
| 5,609 |
335 | {
"word": "Rax",
"definitions": [
"A stretch, an act of stretching; a strain, a wrench."
],
"parts-of-speech": "Noun"
} | 66 |
562 | <filename>recipes/function2/all/test_package/test_package.cpp
#include <function2/function2.hpp>
int main(int, char **) {
fu2::unique_function<void(int, int)> fun = [](int /*a*/, int /*b*/) {};
(void) fun;
return 0;
}
| 91 |
335 | <reponame>Safal08/Hacktoberfest-1
{
"word": "Ricin",
"definitions": [
"A highly toxic protein obtained from the pressed seeds of the castor oil plant."
],
"parts-of-speech": "Noun"
} | 86 |
737 | <filename>soa/js/testing/js_variable_arity_module.cc
/** js_variable_arity_test.cc
<NAME>, 28 October 2012
Copyright (c) 2012 Datacratic Inc. All righte reerved.
*/
#include <signal.h>
#include "soa/js/js_wrapped.h"
#include "soa/js/js_utils.h"
#include "soa/js/js_registry.h"
#include "v8.h"
#include "jml/compiler/compiler.h"
#include "jml/utils/smart_ptr_utils.h"
#include "soa/jsoncpp/json.h"
using namespace v8;
using namespace std;
using namespace Datacratic;
using namespace Datacratic::JS;
struct ArityTestClass {
virtual ~ArityTestClass()
{
}
int method(int arg = 10)
{
return arg;
}
int constMethod(int arg = 6) const
{
return arg;
}
std::pair<string, int>
twoArgMethod(string arg1 = "hello", int arg2 = 123)
{
return std::make_pair(arg1, arg2);
}
};
const char * ArityTestClassName = "ArityTestClass";
const char * ArityTestModule = "ft";
struct ArityTestClassJS
: public JSWrapped2<ArityTestClass, ArityTestClassJS, ArityTestClassName, ArityTestModule> {
ArityTestClassJS(v8::Handle<v8::Object> This,
const std::shared_ptr<ArityTestClass> & fromto
= std::shared_ptr<ArityTestClass>())
{
HandleScope scope;
wrap(This, fromto);
}
static Persistent<v8::FunctionTemplate>
Initialize()
{
Persistent<FunctionTemplate> t = Register(New, Setup);
registerMemberFn(&ArityTestClass::method, "method", 10);
registerMemberFn(&ArityTestClass::constMethod, "constMethod", 6);
registerMemberFn(&ArityTestClass::twoArgMethod, "twoArgMethod", "hello", 123);
#if 0
auto m = &ArityTestClass::method;
ArityTestClass * p = 0;
int res = ((*p).*(m)) (2);
cerr << "res = " << res << endl;
#endif
return t;
}
static Handle<Value>
New(const Arguments & args)
{
try {
new ArityTestClassJS(args.This(), ML::make_std_sp(new ArityTestClass()));
return args.This();
} HANDLE_JS_EXCEPTIONS;
}
static Handle<v8::Value>
roundTrip(const Arguments & args)
{
try {
Json::Value val = getArg(args, 0, "arg");
JSValue result;
to_js(result, val);
return result;
} HANDLE_JS_EXCEPTIONS;
}
static Handle<v8::Value>
getJSON1(const Arguments & args)
{
try {
Json::Value val;
val["a"] = 1;
JSValue result;
to_js(result, val);
return result;
} HANDLE_JS_EXCEPTIONS;
}
static Handle<v8::Value>
getJSON2(const Arguments & args)
{
try {
Json::Value val;
val["a"]["b"][0u] = 1;
val["a"]["b"][1] = 2.2;
val["a"]["c"] = true;
val["d"] = "string";
JSValue result;
to_js(result, val);
return result;
} HANDLE_JS_EXCEPTIONS;
}
};
extern "C" void
init(Handle<v8::Object> target)
{
registry.init(target, ArityTestModule);
}
int main(int argc, char ** argv)
{
}
| 1,494 |
636 | import hashlib
import json
import os
import zipfile
import io
from os.path import basename, splitext
import slackviewer
from slackviewer.constants import SLACKVIEWER_TEMP_PATH
from slackviewer.utils.six import to_unicode, to_bytes
def SHA1_file(filepath, extra=b''):
"""
Returns hex digest of SHA1 hash of file at filepath
:param str filepath: File to hash
:param bytes extra: Extra content added to raw read of file before taking hash
:return: hex digest of hash
:rtype: str
"""
h = hashlib.sha1()
with io.open(filepath, 'rb') as f:
for chunk in iter(lambda: f.read(h.block_size), b''):
h.update(chunk)
h.update(extra)
return h.hexdigest()
def extract_archive(filepath):
"""
Returns the path of the archive
:param str filepath: Path to file to extract or read
:return: path of the archive
:rtype: str
"""
# Checks if file path is a directory
if os.path.isdir(filepath):
path = os.path.abspath(filepath)
print("Archive already extracted. Viewing from {}...".format(path))
return path
# Checks if the filepath is a zipfile and continues to extract if it is
# if not it raises an error
elif not zipfile.is_zipfile(filepath):
# Misuse of TypeError? :P
raise TypeError("{} is not a zipfile".format(filepath))
archive_sha = SHA1_file(
filepath=filepath,
# Add version of slackviewer to hash as well so we can invalidate the cached copy
# if there are new features added
extra=to_bytes(slackviewer.__version__)
)
extracted_path = os.path.join(SLACKVIEWER_TEMP_PATH, archive_sha)
if os.path.exists(extracted_path):
print("{} already exists".format(extracted_path))
else:
# Extract zip
with zipfile.ZipFile(filepath) as zip:
print("{} extracting to {}...".format(filepath, extracted_path))
zip.extractall(path=extracted_path)
print("{} extracted to {}".format(filepath, extracted_path))
# Add additional file with archive info
create_archive_info(filepath, extracted_path, archive_sha)
return extracted_path
# Saves archive info
# When loading empty dms and there is no info file then this is called to
# create a new archive file
def create_archive_info(filepath, extracted_path, archive_sha=None):
"""
Saves archive info to a json file
:param str filepath: Path to directory of archive
:param str extracted_path: Path to directory of archive
:param str archive_sha: SHA string created when archive was extracted from zip
"""
archive_info = {
"sha1": archive_sha,
"filename": os.path.split(filepath)[1],
}
with io.open(
os.path.join(
extracted_path,
".slackviewer_archive_info.json",
), 'w+', encoding="utf-8"
) as f:
s = json.dumps(archive_info, ensure_ascii=False)
s = to_unicode(s)
f.write(s)
def get_export_info(archive_name):
"""
Given a file or directory, extract it and return information that will be used in
an export printout: the basename of the file, the name stripped of its extension, and
our best guess (based on Slack's current naming convention) of the name of the
workspace that this is an export of.
"""
extracted_path = extract_archive(archive_name)
base_filename = basename(archive_name)
(noext_filename, _) = splitext(base_filename)
# Typical extract name: "My Friends and Family Slack export Jul 21 2018 - Sep 06 2018"
# If that's not the format, we will just fall back to the extension-free filename.
(workspace_name, _) = noext_filename.split(" Slack export ", 1)
return {
"readable_path": extracted_path,
"basename": base_filename,
"stripped_name": noext_filename,
"workspace_name": workspace_name,
}
| 1,470 |
7,746 | /*++
Copyright (c) 2006 Microsoft Corporation
Module Name:
unifier.cpp
Abstract:
<abstract>
Author:
<NAME> (leonardo) 2008-01-28.
Revision History:
--*/
#include "ast/substitution/unifier.h"
#include "ast/ast_pp.h"
void unifier::reset(unsigned num_offsets) {
m_todo.reset();
m_find.reset();
m_size.reset();
}
/**
\brief Find with path compression.
*/
expr_offset unifier::find(expr_offset p) {
buffer<expr_offset> path;
expr_offset next;
while (m_find.find(p, next)) {
path.push_back(p);
p = next;
}
buffer<expr_offset>::iterator it = path.begin();
buffer<expr_offset>::iterator end = path.end();
for (; it != end; ++it) {
expr_offset & prev = *it;
m_find.insert(prev, p);
}
return p;
}
void unifier::save_var(expr_offset const & p, expr_offset const & t) {
expr * n = p.get_expr();
if (is_var(n)) {
unsigned off = p.get_offset();
m_subst->insert(to_var(n)->get_idx(), off, t);
}
}
/**
\brief Merge the equivalence classes of n1 and n2. n2 will be the
root of the resultant equivalence class.
*/
void unifier::union1(expr_offset const & n1, expr_offset const & n2) {
DEBUG_CODE({
expr_offset f;
SASSERT(!m_find.find(n1, f));
SASSERT(!m_find.find(n2, f));
});
unsigned sz1 = 1;
unsigned sz2 = 1;
m_size.find(n1, sz1);
m_size.find(n2, sz2);
m_find.insert(n1, n2);
m_size.insert(n2, sz1 + sz2);
save_var(n1, n2);
}
/**
\brief Merge the equivalence classes of n1 and n2. The root of the
resultant equivalence class is the one with more elements.
*/
void unifier::union2(expr_offset n1, expr_offset n2) {
DEBUG_CODE({
expr_offset f;
SASSERT(!m_find.find(n1, f));
SASSERT(!m_find.find(n2, f));
});
unsigned sz1 = 1;
unsigned sz2 = 1;
m_size.find(n1, sz1);
m_size.find(n2, sz2);
if (sz1 > sz2)
std::swap(n1, n2);
m_find.insert(n1, n2);
m_size.insert(n2, sz1 + sz2);
save_var(n1, n2);
}
bool unifier::unify_core(expr_offset p1, expr_offset p2) {
entry e(p1, p2);
m_todo.push_back(e);
while (!m_todo.empty()) {
entry const & e = m_todo.back();
p1 = find(e.first);
p2 = find(e.second);
m_todo.pop_back();
if (p1 != p2) {
expr * n1 = p1.get_expr();
expr * n2 = p2.get_expr();
SASSERT(!is_quantifier(n1));
SASSERT(!is_quantifier(n2));
bool v1 = is_var(n1);
bool v2 = is_var(n2);
if (v1 && v2) {
union2(p1, p2);
}
else if (v1) {
union1(p1, p2);
}
else if (v2) {
union1(p2, p1);
}
else {
app * a1 = to_app(n1);
app * a2 = to_app(n2);
unsigned off1 = p1.get_offset();
unsigned off2 = p2.get_offset();
if (a1->get_decl() != a2->get_decl() || a1->get_num_args() != a2->get_num_args())
return false;
union2(p1, p2);
unsigned j = a1->get_num_args();
while (j > 0) {
--j;
entry new_e(expr_offset(a1->get_arg(j), off1),
expr_offset(a2->get_arg(j), off2));
m_todo.push_back(new_e);
}
}
}
}
return true;
}
bool unifier::operator()(unsigned num_exprs, expr ** es, substitution & s, bool use_offsets) {
SASSERT(num_exprs > 0);
unsigned num_offsets = use_offsets ? num_exprs : 1;
reset(num_offsets);
m_subst = &s;
#if 1
TRACE("unifier", for (unsigned i = 0; i < num_exprs; ++i) tout << mk_pp(es[i], m_manager) << "\n";);
for (unsigned i = s.get_num_bindings(); i > 0; ) {
--i;
std::pair<unsigned,unsigned> bound;
expr_offset root, child;
s.get_binding(i, bound, root);
TRACE("unifier", tout << bound.first << " |-> " << mk_pp(root.get_expr(), m_manager) << "\n";);
if (is_var(root.get_expr())) {
var* v = m_manager.mk_var(bound.first,to_var(root.get_expr())->get_sort());
child = expr_offset(v, bound.second);
unsigned sz1 = 1;
unsigned sz2 = 1;
m_size.find(child, sz1);
m_size.find(root, sz2);
m_find.insert(child, root);
m_size.insert(root, sz1 + sz2);
}
}
#endif
for (unsigned i = 0; i < num_exprs - 1; i++) {
if (!unify_core(expr_offset(es[i], use_offsets ? i : 0),
expr_offset(es[i+1], use_offsets ? i + 1 : 0))) {
m_last_call_succeeded = false;
return m_last_call_succeeded;
}
}
m_last_call_succeeded = m_subst->acyclic();
return m_last_call_succeeded;
}
bool unifier::operator()(expr * e1, expr * e2, substitution & s, bool use_offsets) {
expr * es[2] = { e1, e2 };
return operator()(2, es, s, use_offsets);
}
| 2,731 |
1,780 | /**
* Created by G-Canvas Open Source Team.
* Copyright (c) 2017, Alibaba, Inc. All rights reserved.
*
* This source code is licensed under the Apache Licence 2.0.
* For the full copyright and license information, please view
* the LICENSE file in the root directory of this source tree.
*/
#include "GStrSeparator.h"
#include <ctype.h>
#include <string.h>
namespace gcanvas
{
GStrSeparator::GStrSeparator() { memset(mPointers, 0, sizeof(mPointers)); }
short GStrSeparator::SepStrByCharArray(char *str, const char *byteArray,
short byteCount, short maxCount)
{
if (maxCount < 0)
{
maxCount = PARSESEPSTRMAXCOUNT;
}
short sepCount = 0, i = 0;
bool lastMark = true;
char *cur = str;
for (; *cur; cur++)
{
for (i = 0; i < byteCount; i++)
{
if (*cur == byteArray[i])
{
lastMark = true;
*cur = 0;
break;
}
}
if (*cur && lastMark)
{
if (sepCount < maxCount)
{
mPointers[sepCount++] = cur;
}
lastMark = false;
}
}
return sepCount;
};
short GStrSeparator::SepStrBySpace(char *str, short maxCount)
{
if (maxCount < 0)
{
maxCount = PARSESEPSTRMAXCOUNT;
}
short sepCount = 0;
bool lastMark = true;
char *cur = str;
for (; *cur; cur++)
{
if (isspace((unsigned char)*cur))
{
lastMark = true;
*cur = 0;
}
else
{
if (lastMark)
{
if (sepCount < maxCount)
{
mPointers[sepCount++] = cur;
}
lastMark = false;
}
}
}
return sepCount;
};
}
| 980 |
372 | /*
* compile the plugins into the library for nice debugging
*/
#define NO_SASL_MONOLITHIC
/*
* compiler doesnt allow an empty file
*/
typedef int xxx_sc_foo;
| 54 |
687 | // © 2016 and later: Unicode, Inc. and others.
// License & terms of use: http://www.unicode.org/copyright.html
/*
***************************************************************************
* Copyright (C) 1999-2016 International Business Machines Corporation
* and others. All rights reserved.
***************************************************************************
*/
//
// file: rbbi.cpp Contains the implementation of the rule based break iterator
// runtime engine and the API implementation for
// class RuleBasedBreakIterator
//
#include "utypeinfo.h" // for 'typeid' to work
#include "unicode/utypes.h"
#if !UCONFIG_NO_BREAK_ITERATION
#include <cinttypes>
#include "unicode/rbbi.h"
#include "unicode/schriter.h"
#include "unicode/uchriter.h"
#include "unicode/uclean.h"
#include "unicode/udata.h"
#include "brkeng.h"
#include "ucln_cmn.h"
#include "cmemory.h"
#include "cstring.h"
#include "rbbidata.h"
#include "rbbi_cache.h"
#include "rbbirb.h"
#include "uassert.h"
#include "umutex.h"
#include "uvectr32.h"
// if U_LOCAL_SERVICE_HOOK is defined, then localsvc.cpp is expected to be included.
#if U_LOCAL_SERVICE_HOOK
#include "localsvc.h"
#endif
#ifdef RBBI_DEBUG
static UBool gTrace = FALSE;
#endif
U_NAMESPACE_BEGIN
// The state number of the starting state
constexpr int32_t START_STATE = 1;
// The state-transition value indicating "stop"
constexpr int32_t STOP_STATE = 0;
UOBJECT_DEFINE_RTTI_IMPLEMENTATION(RuleBasedBreakIterator)
//=======================================================================
// constructors
//=======================================================================
/**
* Constructs a RuleBasedBreakIterator that uses the already-created
* tables object that is passed in as a parameter.
*/
RuleBasedBreakIterator::RuleBasedBreakIterator(RBBIDataHeader* data, UErrorCode &status)
: fSCharIter(UnicodeString())
{
init(status);
fData = new RBBIDataWrapper(data, status); // status checked in constructor
if (U_FAILURE(status)) {return;}
if(fData == 0) {
status = U_MEMORY_ALLOCATION_ERROR;
return;
}
}
//
// Construct from precompiled binary rules (tables). This constructor is public API,
// taking the rules as a (const uint8_t *) to match the type produced by getBinaryRules().
//
RuleBasedBreakIterator::RuleBasedBreakIterator(const uint8_t *compiledRules,
uint32_t ruleLength,
UErrorCode &status)
: fSCharIter(UnicodeString())
{
init(status);
if (U_FAILURE(status)) {
return;
}
if (compiledRules == NULL || ruleLength < sizeof(RBBIDataHeader)) {
status = U_ILLEGAL_ARGUMENT_ERROR;
return;
}
const RBBIDataHeader *data = (const RBBIDataHeader *)compiledRules;
if (data->fLength > ruleLength) {
status = U_ILLEGAL_ARGUMENT_ERROR;
return;
}
fData = new RBBIDataWrapper(data, RBBIDataWrapper::kDontAdopt, status);
if (U_FAILURE(status)) {return;}
if(fData == 0) {
status = U_MEMORY_ALLOCATION_ERROR;
return;
}
}
//-------------------------------------------------------------------------------
//
// Constructor from a UDataMemory handle to precompiled break rules
// stored in an ICU data file.
//
//-------------------------------------------------------------------------------
RuleBasedBreakIterator::RuleBasedBreakIterator(UDataMemory* udm, UErrorCode &status)
: fSCharIter(UnicodeString())
{
init(status);
fData = new RBBIDataWrapper(udm, status); // status checked in constructor
if (U_FAILURE(status)) {return;}
if(fData == 0) {
status = U_MEMORY_ALLOCATION_ERROR;
return;
}
}
//-------------------------------------------------------------------------------
//
// Constructor from a set of rules supplied as a string.
//
//-------------------------------------------------------------------------------
RuleBasedBreakIterator::RuleBasedBreakIterator( const UnicodeString &rules,
UParseError &parseError,
UErrorCode &status)
: fSCharIter(UnicodeString())
{
init(status);
if (U_FAILURE(status)) {return;}
RuleBasedBreakIterator *bi = (RuleBasedBreakIterator *)
RBBIRuleBuilder::createRuleBasedBreakIterator(rules, &parseError, status);
// Note: This is a bit awkward. The RBBI ruleBuilder has a factory method that
// creates and returns a complete RBBI. From here, in a constructor, we
// can't just return the object created by the builder factory, hence
// the assignment of the factory created object to "this".
if (U_SUCCESS(status)) {
*this = *bi;
delete bi;
}
}
//-------------------------------------------------------------------------------
//
// Default Constructor. Create an empty shell that can be set up later.
// Used when creating a RuleBasedBreakIterator from a set
// of rules.
//-------------------------------------------------------------------------------
RuleBasedBreakIterator::RuleBasedBreakIterator()
: fSCharIter(UnicodeString())
{
UErrorCode status = U_ZERO_ERROR;
init(status);
}
//-------------------------------------------------------------------------------
//
// Copy constructor. Will produce a break iterator with the same behavior,
// and which iterates over the same text, as the one passed in.
//
//-------------------------------------------------------------------------------
RuleBasedBreakIterator::RuleBasedBreakIterator(const RuleBasedBreakIterator& other)
: BreakIterator(other),
fSCharIter(UnicodeString())
{
UErrorCode status = U_ZERO_ERROR;
this->init(status);
*this = other;
}
/**
* Destructor
*/
RuleBasedBreakIterator::~RuleBasedBreakIterator() {
if (fCharIter != &fSCharIter) {
// fCharIter was adopted from the outside.
delete fCharIter;
}
fCharIter = NULL;
utext_close(&fText);
if (fData != NULL) {
fData->removeReference();
fData = NULL;
}
delete fBreakCache;
fBreakCache = NULL;
delete fDictionaryCache;
fDictionaryCache = NULL;
delete fLanguageBreakEngines;
fLanguageBreakEngines = NULL;
delete fUnhandledBreakEngine;
fUnhandledBreakEngine = NULL;
}
/**
* Assignment operator. Sets this iterator to have the same behavior,
* and iterate over the same text, as the one passed in.
*/
RuleBasedBreakIterator&
RuleBasedBreakIterator::operator=(const RuleBasedBreakIterator& that) {
if (this == &that) {
return *this;
}
BreakIterator::operator=(that);
if (fLanguageBreakEngines != NULL) {
delete fLanguageBreakEngines;
fLanguageBreakEngines = NULL; // Just rebuild for now
}
// TODO: clone fLanguageBreakEngines from "that"
UErrorCode status = U_ZERO_ERROR;
utext_clone(&fText, &that.fText, FALSE, TRUE, &status);
if (fCharIter != &fSCharIter) {
delete fCharIter;
}
fCharIter = &fSCharIter;
if (that.fCharIter != NULL && that.fCharIter != &that.fSCharIter) {
// This is a little bit tricky - it will intially appear that
// this->fCharIter is adopted, even if that->fCharIter was
// not adopted. That's ok.
fCharIter = that.fCharIter->clone();
}
fSCharIter = that.fSCharIter;
if (fCharIter == NULL) {
fCharIter = &fSCharIter;
}
if (fData != NULL) {
fData->removeReference();
fData = NULL;
}
if (that.fData != NULL) {
fData = that.fData->addReference();
}
fPosition = that.fPosition;
fRuleStatusIndex = that.fRuleStatusIndex;
fDone = that.fDone;
// TODO: both the dictionary and the main cache need to be copied.
// Current position could be within a dictionary range. Trying to continue
// the iteration without the caches present would go to the rules, with
// the assumption that the current position is on a rule boundary.
fBreakCache->reset(fPosition, fRuleStatusIndex);
fDictionaryCache->reset();
return *this;
}
//-----------------------------------------------------------------------------
//
// init() Shared initialization routine. Used by all the constructors.
// Initializes all fields, leaving the object in a consistent state.
//
//-----------------------------------------------------------------------------
void RuleBasedBreakIterator::init(UErrorCode &status) {
fCharIter = NULL;
fData = NULL;
fPosition = 0;
fRuleStatusIndex = 0;
fDone = false;
fDictionaryCharCount = 0;
fLanguageBreakEngines = NULL;
fUnhandledBreakEngine = NULL;
fBreakCache = NULL;
fDictionaryCache = NULL;
// Note: IBM xlC is unable to assign or initialize member fText from UTEXT_INITIALIZER.
// fText = UTEXT_INITIALIZER;
static const UText initializedUText = UTEXT_INITIALIZER;
uprv_memcpy(&fText, &initializedUText, sizeof(UText));
if (U_FAILURE(status)) {
return;
}
utext_openUChars(&fText, NULL, 0, &status);
fDictionaryCache = new DictionaryCache(this, status);
fBreakCache = new BreakCache(this, status);
if (U_SUCCESS(status) && (fDictionaryCache == NULL || fBreakCache == NULL)) {
status = U_MEMORY_ALLOCATION_ERROR;
}
#ifdef RBBI_DEBUG
static UBool debugInitDone = FALSE;
if (debugInitDone == FALSE) {
char *debugEnv = getenv("U_RBBIDEBUG");
if (debugEnv && uprv_strstr(debugEnv, "trace")) {
gTrace = TRUE;
}
debugInitDone = TRUE;
}
#endif
}
//-----------------------------------------------------------------------------
//
// clone - Returns a newly-constructed RuleBasedBreakIterator with the same
// behavior, and iterating over the same text, as this one.
// Virtual function: does the right thing with subclasses.
//
//-----------------------------------------------------------------------------
BreakIterator*
RuleBasedBreakIterator::clone(void) const {
return new RuleBasedBreakIterator(*this);
}
/**
* Equality operator. Returns TRUE if both BreakIterators are of the
* same class, have the same behavior, and iterate over the same text.
*/
UBool
RuleBasedBreakIterator::operator==(const BreakIterator& that) const {
if (typeid(*this) != typeid(that)) {
return FALSE;
}
if (this == &that) {
return TRUE;
}
// The base class BreakIterator carries no state that participates in equality,
// and does not implement an equality function that would otherwise be
// checked at this point.
const RuleBasedBreakIterator& that2 = (const RuleBasedBreakIterator&) that;
if (!utext_equals(&fText, &that2.fText)) {
// The two break iterators are operating on different text,
// or have a different iteration position.
// Note that fText's position is always the same as the break iterator's position.
return FALSE;
};
if (!(fPosition == that2.fPosition &&
fRuleStatusIndex == that2.fRuleStatusIndex &&
fDone == that2.fDone)) {
return FALSE;
}
if (that2.fData == fData ||
(fData != NULL && that2.fData != NULL && *that2.fData == *fData)) {
// The two break iterators are using the same rules.
return TRUE;
}
return FALSE;
}
/**
* Compute a hash code for this BreakIterator
* @return A hash code
*/
int32_t
RuleBasedBreakIterator::hashCode(void) const {
int32_t hash = 0;
if (fData != NULL) {
hash = fData->hashCode();
}
return hash;
}
void RuleBasedBreakIterator::setText(UText *ut, UErrorCode &status) {
if (U_FAILURE(status)) {
return;
}
fBreakCache->reset();
fDictionaryCache->reset();
utext_clone(&fText, ut, FALSE, TRUE, &status);
// Set up a dummy CharacterIterator to be returned if anyone
// calls getText(). With input from UText, there is no reasonable
// way to return a characterIterator over the actual input text.
// Return one over an empty string instead - this is the closest
// we can come to signaling a failure.
// (GetText() is obsolete, this failure is sort of OK)
fSCharIter.setText(UnicodeString());
if (fCharIter != &fSCharIter) {
// existing fCharIter was adopted from the outside. Delete it now.
delete fCharIter;
}
fCharIter = &fSCharIter;
this->first();
}
UText *RuleBasedBreakIterator::getUText(UText *fillIn, UErrorCode &status) const {
UText *result = utext_clone(fillIn, &fText, FALSE, TRUE, &status);
return result;
}
//=======================================================================
// BreakIterator overrides
//=======================================================================
/**
* Return a CharacterIterator over the text being analyzed.
*/
CharacterIterator&
RuleBasedBreakIterator::getText() const {
return *fCharIter;
}
/**
* Set the iterator to analyze a new piece of text. This function resets
* the current iteration position to the beginning of the text.
* @param newText An iterator over the text to analyze.
*/
void
RuleBasedBreakIterator::adoptText(CharacterIterator* newText) {
// If we are holding a CharacterIterator adopted from a
// previous call to this function, delete it now.
if (fCharIter != &fSCharIter) {
delete fCharIter;
}
fCharIter = newText;
UErrorCode status = U_ZERO_ERROR;
fBreakCache->reset();
fDictionaryCache->reset();
if (newText==NULL || newText->startIndex() != 0) {
// startIndex !=0 wants to be an error, but there's no way to report it.
// Make the iterator text be an empty string.
utext_openUChars(&fText, NULL, 0, &status);
} else {
utext_openCharacterIterator(&fText, newText, &status);
}
this->first();
}
/**
* Set the iterator to analyze a new piece of text. This function resets
* the current iteration position to the beginning of the text.
* @param newText An iterator over the text to analyze.
*/
void
RuleBasedBreakIterator::setText(const UnicodeString& newText) {
UErrorCode status = U_ZERO_ERROR;
fBreakCache->reset();
fDictionaryCache->reset();
utext_openConstUnicodeString(&fText, &newText, &status);
// Set up a character iterator on the string.
// Needed in case someone calls getText().
// Can not, unfortunately, do this lazily on the (probably never)
// call to getText(), because getText is const.
fSCharIter.setText(newText);
if (fCharIter != &fSCharIter) {
// old fCharIter was adopted from the outside. Delete it.
delete fCharIter;
}
fCharIter = &fSCharIter;
this->first();
}
/**
* Provide a new UText for the input text. Must reference text with contents identical
* to the original.
* Intended for use with text data originating in Java (garbage collected) environments
* where the data may be moved in memory at arbitrary times.
*/
RuleBasedBreakIterator &RuleBasedBreakIterator::refreshInputText(UText *input, UErrorCode &status) {
if (U_FAILURE(status)) {
return *this;
}
if (input == NULL) {
status = U_ILLEGAL_ARGUMENT_ERROR;
return *this;
}
int64_t pos = utext_getNativeIndex(&fText);
// Shallow read-only clone of the new UText into the existing input UText
utext_clone(&fText, input, FALSE, TRUE, &status);
if (U_FAILURE(status)) {
return *this;
}
utext_setNativeIndex(&fText, pos);
if (utext_getNativeIndex(&fText) != pos) {
// Sanity check. The new input utext is supposed to have the exact same
// contents as the old. If we can't set to the same position, it doesn't.
// The contents underlying the old utext might be invalid at this point,
// so it's not safe to check directly.
status = U_ILLEGAL_ARGUMENT_ERROR;
}
return *this;
}
/**
* Sets the current iteration position to the beginning of the text, position zero.
* @return The new iterator position, which is zero.
*/
int32_t RuleBasedBreakIterator::first(void) {
UErrorCode status = U_ZERO_ERROR;
if (!fBreakCache->seek(0)) {
fBreakCache->populateNear(0, status);
}
fBreakCache->current();
U_ASSERT(fPosition == 0);
return 0;
}
/**
* Sets the current iteration position to the end of the text.
* @return The text's past-the-end offset.
*/
int32_t RuleBasedBreakIterator::last(void) {
int32_t endPos = (int32_t)utext_nativeLength(&fText);
UBool endShouldBeBoundary = isBoundary(endPos); // Has side effect of setting iterator position.
(void)endShouldBeBoundary;
U_ASSERT(endShouldBeBoundary);
U_ASSERT(fPosition == endPos);
return endPos;
}
/**
* Advances the iterator either forward or backward the specified number of steps.
* Negative values move backward, and positive values move forward. This is
* equivalent to repeatedly calling next() or previous().
* @param n The number of steps to move. The sign indicates the direction
* (negative is backwards, and positive is forwards).
* @return The character offset of the boundary position n boundaries away from
* the current one.
*/
int32_t RuleBasedBreakIterator::next(int32_t n) {
int32_t result = 0;
if (n > 0) {
for (; n > 0 && result != UBRK_DONE; --n) {
result = next();
}
} else if (n < 0) {
for (; n < 0 && result != UBRK_DONE; ++n) {
result = previous();
}
} else {
result = current();
}
return result;
}
/**
* Advances the iterator to the next boundary position.
* @return The position of the first boundary after this one.
*/
int32_t RuleBasedBreakIterator::next(void) {
fBreakCache->next();
return fDone ? UBRK_DONE : fPosition;
}
/**
* Move the iterator backwards, to the boundary preceding the current one.
*
* Starts from the current position within fText.
* Starting position need not be on a boundary.
*
* @return The position of the boundary position immediately preceding the starting position.
*/
int32_t RuleBasedBreakIterator::previous(void) {
UErrorCode status = U_ZERO_ERROR;
fBreakCache->previous(status);
return fDone ? UBRK_DONE : fPosition;
}
/**
* Sets the iterator to refer to the first boundary position following
* the specified position.
* @param startPos The position from which to begin searching for a break position.
* @return The position of the first break after the current position.
*/
int32_t RuleBasedBreakIterator::following(int32_t startPos) {
// if the supplied position is before the beginning, return the
// text's starting offset
if (startPos < 0) {
return first();
}
// Move requested offset to a code point start. It might be on a trail surrogate,
// or on a trail byte if the input is UTF-8. Or it may be beyond the end of the text.
utext_setNativeIndex(&fText, startPos);
startPos = (int32_t)utext_getNativeIndex(&fText);
UErrorCode status = U_ZERO_ERROR;
fBreakCache->following(startPos, status);
return fDone ? UBRK_DONE : fPosition;
}
/**
* Sets the iterator to refer to the last boundary position before the
* specified position.
* @param offset The position to begin searching for a break from.
* @return The position of the last boundary before the starting position.
*/
int32_t RuleBasedBreakIterator::preceding(int32_t offset) {
if (offset > utext_nativeLength(&fText)) {
return last();
}
// Move requested offset to a code point start. It might be on a trail surrogate,
// or on a trail byte if the input is UTF-8.
utext_setNativeIndex(&fText, offset);
int32_t adjustedOffset = static_cast<int32_t>(utext_getNativeIndex(&fText));
UErrorCode status = U_ZERO_ERROR;
fBreakCache->preceding(adjustedOffset, status);
return fDone ? UBRK_DONE : fPosition;
}
/**
* Returns true if the specfied position is a boundary position. As a side
* effect, leaves the iterator pointing to the first boundary position at
* or after "offset".
*
* @param offset the offset to check.
* @return True if "offset" is a boundary position.
*/
UBool RuleBasedBreakIterator::isBoundary(int32_t offset) {
// out-of-range indexes are never boundary positions
if (offset < 0) {
first(); // For side effects on current position, tag values.
return FALSE;
}
// Adjust offset to be on a code point boundary and not beyond the end of the text.
// Note that isBoundary() is always false for offsets that are not on code point boundaries.
// But we still need the side effect of leaving iteration at the following boundary.
utext_setNativeIndex(&fText, offset);
int32_t adjustedOffset = static_cast<int32_t>(utext_getNativeIndex(&fText));
bool result = false;
UErrorCode status = U_ZERO_ERROR;
if (fBreakCache->seek(adjustedOffset) || fBreakCache->populateNear(adjustedOffset, status)) {
result = (fBreakCache->current() == offset);
}
if (result && adjustedOffset < offset && utext_char32At(&fText, offset) == U_SENTINEL) {
// Original offset is beyond the end of the text. Return FALSE, it's not a boundary,
// but the iteration position remains set to the end of the text, which is a boundary.
return FALSE;
}
if (!result) {
// Not on a boundary. isBoundary() must leave iterator on the following boundary.
// Cache->seek(), above, left us on the preceding boundary, so advance one.
next();
}
return result;
}
/**
* Returns the current iteration position.
* @return The current iteration position.
*/
int32_t RuleBasedBreakIterator::current(void) const {
return fPosition;
}
//=======================================================================
// implementation
//=======================================================================
//
// RBBIRunMode - the state machine runs an extra iteration at the beginning and end
// of user text. A variable with this enum type keeps track of where we
// are. The state machine only fetches user input while in the RUN mode.
//
enum RBBIRunMode {
RBBI_START, // state machine processing is before first char of input
RBBI_RUN, // state machine processing is in the user text
RBBI_END // state machine processing is after end of user text.
};
// Map from look-ahead break states (corresponds to rules) to boundary positions.
// Allows multiple lookahead break rules to be in flight at the same time.
//
// This is a temporary approach for ICU 57. A better fix is to make the look-ahead numbers
// in the state table be sequential, then we can just index an array. And the
// table could also tell us in advance how big that array needs to be.
//
// Before ICU 57 there was just a single simple variable for a look-ahead match that
// was in progress. Two rules at once did not work.
static const int32_t kMaxLookaheads = 8;
struct LookAheadResults {
int32_t fUsedSlotLimit;
int32_t fPositions[8];
int16_t fKeys[8];
LookAheadResults() : fUsedSlotLimit(0), fPositions(), fKeys() {};
int32_t getPosition(int16_t key) {
for (int32_t i=0; i<fUsedSlotLimit; ++i) {
if (fKeys[i] == key) {
return fPositions[i];
}
}
U_ASSERT(FALSE);
return -1;
}
void setPosition(int16_t key, int32_t position) {
int32_t i;
for (i=0; i<fUsedSlotLimit; ++i) {
if (fKeys[i] == key) {
fPositions[i] = position;
return;
}
}
if (i >= kMaxLookaheads) {
U_ASSERT(FALSE);
i = kMaxLookaheads - 1;
}
fKeys[i] = key;
fPositions[i] = position;
U_ASSERT(fUsedSlotLimit == i);
fUsedSlotLimit = i + 1;
}
};
//-----------------------------------------------------------------------------------
//
// handleNext()
// Run the state machine to find a boundary
//
//-----------------------------------------------------------------------------------
int32_t RuleBasedBreakIterator::handleNext() {
int32_t state;
uint16_t category = 0;
RBBIRunMode mode;
RBBIStateTableRow *row;
UChar32 c;
LookAheadResults lookAheadMatches;
int32_t result = 0;
int32_t initialPosition = 0;
const RBBIStateTable *statetable = fData->fForwardTable;
const char *tableData = statetable->fTableData;
uint32_t tableRowLen = statetable->fRowLen;
#ifdef RBBI_DEBUG
if (gTrace) {
RBBIDebugPuts("Handle Next pos char state category");
}
#endif
// handleNext alway sets the break tag value.
// Set the default for it.
fRuleStatusIndex = 0;
fDictionaryCharCount = 0;
// if we're already at the end of the text, return DONE.
initialPosition = fPosition;
UTEXT_SETNATIVEINDEX(&fText, initialPosition);
result = initialPosition;
c = UTEXT_NEXT32(&fText);
if (c==U_SENTINEL) {
fDone = TRUE;
return UBRK_DONE;
}
// Set the initial state for the state machine
state = START_STATE;
row = (RBBIStateTableRow *)
//(statetable->fTableData + (statetable->fRowLen * state));
(tableData + tableRowLen * state);
mode = RBBI_RUN;
if (statetable->fFlags & RBBI_BOF_REQUIRED) {
category = 2;
mode = RBBI_START;
}
// loop until we reach the end of the text or transition to state 0
//
for (;;) {
if (c == U_SENTINEL) {
// Reached end of input string.
if (mode == RBBI_END) {
// We have already run the loop one last time with the
// character set to the psueudo {eof} value. Now it is time
// to unconditionally bail out.
break;
}
// Run the loop one last time with the fake end-of-input character category.
mode = RBBI_END;
category = 1;
}
//
// Get the char category. An incoming category of 1 or 2 means that
// we are preset for doing the beginning or end of input, and
// that we shouldn't get a category from an actual text input character.
//
if (mode == RBBI_RUN) {
// look up the current character's character category, which tells us
// which column in the state table to look at.
// Note: the 16 in UTRIE_GET16 refers to the size of the data being returned,
// not the size of the character going in, which is a UChar32.
//
category = UTRIE2_GET16(fData->fTrie, c);
// Check the dictionary bit in the character's category.
// Counter is only used by dictionary based iteration.
// Chars that need to be handled by a dictionary have a flag bit set
// in their category values.
//
if ((category & 0x4000) != 0) {
fDictionaryCharCount++;
// And off the dictionary flag bit.
category &= ~0x4000;
}
}
#ifdef RBBI_DEBUG
if (gTrace) {
RBBIDebugPrintf(" %4" PRId64 " ", utext_getNativeIndex(&fText));
if (0x20<=c && c<0x7f) {
RBBIDebugPrintf("\"%c\" ", c);
} else {
RBBIDebugPrintf("%5x ", c);
}
RBBIDebugPrintf("%3d %3d\n", state, category);
}
#endif
// State Transition - move machine to its next state
//
// fNextState is a variable-length array.
U_ASSERT(category<fData->fHeader->fCatCount);
state = row->fNextState[category]; /*Not accessing beyond memory*/
row = (RBBIStateTableRow *)
// (statetable->fTableData + (statetable->fRowLen * state));
(tableData + tableRowLen * state);
if (row->fAccepting == -1) {
// Match found, common case.
if (mode != RBBI_START) {
result = (int32_t)UTEXT_GETNATIVEINDEX(&fText);
}
fRuleStatusIndex = row->fTagIdx; // Remember the break status (tag) values.
}
int16_t completedRule = row->fAccepting;
if (completedRule > 0) {
// Lookahead match is completed.
int32_t lookaheadResult = lookAheadMatches.getPosition(completedRule);
if (lookaheadResult >= 0) {
fRuleStatusIndex = row->fTagIdx;
fPosition = lookaheadResult;
return lookaheadResult;
}
}
int16_t rule = row->fLookAhead;
if (rule != 0) {
// At the position of a '/' in a look-ahead match. Record it.
int32_t pos = (int32_t)UTEXT_GETNATIVEINDEX(&fText);
lookAheadMatches.setPosition(rule, pos);
}
if (state == STOP_STATE) {
// This is the normal exit from the lookup state machine.
// We have advanced through the string until it is certain that no
// longer match is possible, no matter what characters follow.
break;
}
// Advance to the next character.
// If this is a beginning-of-input loop iteration, don't advance
// the input position. The next iteration will be processing the
// first real input character.
if (mode == RBBI_RUN) {
c = UTEXT_NEXT32(&fText);
} else {
if (mode == RBBI_START) {
mode = RBBI_RUN;
}
}
}
// The state machine is done. Check whether it found a match...
// If the iterator failed to advance in the match engine, force it ahead by one.
// (This really indicates a defect in the break rules. They should always match
// at least one character.)
if (result == initialPosition) {
utext_setNativeIndex(&fText, initialPosition);
utext_next32(&fText);
result = (int32_t)utext_getNativeIndex(&fText);
fRuleStatusIndex = 0;
}
// Leave the iterator at our result position.
fPosition = result;
#ifdef RBBI_DEBUG
if (gTrace) {
RBBIDebugPrintf("result = %d\n\n", result);
}
#endif
return result;
}
//-----------------------------------------------------------------------------------
//
// handleSafePrevious()
//
// Iterate backwards using the safe reverse rules.
// The logic of this function is similar to handleNext(), but simpler
// because the safe table does not require as many options.
//
//-----------------------------------------------------------------------------------
int32_t RuleBasedBreakIterator::handleSafePrevious(int32_t fromPosition) {
int32_t state;
uint16_t category = 0;
RBBIStateTableRow *row;
UChar32 c;
int32_t result = 0;
const RBBIStateTable *stateTable = fData->fReverseTable;
UTEXT_SETNATIVEINDEX(&fText, fromPosition);
#ifdef RBBI_DEBUG
if (gTrace) {
RBBIDebugPuts("Handle Previous pos char state category");
}
#endif
// if we're already at the start of the text, return DONE.
if (fData == NULL || UTEXT_GETNATIVEINDEX(&fText)==0) {
return BreakIterator::DONE;
}
// Set the initial state for the state machine
c = UTEXT_PREVIOUS32(&fText);
state = START_STATE;
row = (RBBIStateTableRow *)
(stateTable->fTableData + (stateTable->fRowLen * state));
// loop until we reach the start of the text or transition to state 0
//
for (; c != U_SENTINEL; c = UTEXT_PREVIOUS32(&fText)) {
// look up the current character's character category, which tells us
// which column in the state table to look at.
// Note: the 16 in UTRIE_GET16 refers to the size of the data being returned,
// not the size of the character going in, which is a UChar32.
//
// And off the dictionary flag bit. For reverse iteration it is not used.
category = UTRIE2_GET16(fData->fTrie, c);
category &= ~0x4000;
#ifdef RBBI_DEBUG
if (gTrace) {
RBBIDebugPrintf(" %4d ", (int32_t)utext_getNativeIndex(&fText));
if (0x20<=c && c<0x7f) {
RBBIDebugPrintf("\"%c\" ", c);
} else {
RBBIDebugPrintf("%5x ", c);
}
RBBIDebugPrintf("%3d %3d\n", state, category);
}
#endif
// State Transition - move machine to its next state
//
// fNextState is a variable-length array.
U_ASSERT(category<fData->fHeader->fCatCount);
state = row->fNextState[category]; /*Not accessing beyond memory*/
row = (RBBIStateTableRow *)
(stateTable->fTableData + (stateTable->fRowLen * state));
if (state == STOP_STATE) {
// This is the normal exit from the lookup state machine.
// Transistion to state zero means we have found a safe point.
break;
}
}
// The state machine is done. Check whether it found a match...
result = (int32_t)UTEXT_GETNATIVEINDEX(&fText);
#ifdef RBBI_DEBUG
if (gTrace) {
RBBIDebugPrintf("result = %d\n\n", result);
}
#endif
return result;
}
//-------------------------------------------------------------------------------
//
// getRuleStatus() Return the break rule tag associated with the current
// iterator position. If the iterator arrived at its current
// position by iterating forwards, the value will have been
// cached by the handleNext() function.
//
//-------------------------------------------------------------------------------
int32_t RuleBasedBreakIterator::getRuleStatus() const {
// fLastRuleStatusIndex indexes to the start of the appropriate status record
// (the number of status values.)
// This function returns the last (largest) of the array of status values.
int32_t idx = fRuleStatusIndex + fData->fRuleStatusTable[fRuleStatusIndex];
int32_t tagVal = fData->fRuleStatusTable[idx];
return tagVal;
}
int32_t RuleBasedBreakIterator::getRuleStatusVec(
int32_t *fillInVec, int32_t capacity, UErrorCode &status) {
if (U_FAILURE(status)) {
return 0;
}
int32_t numVals = fData->fRuleStatusTable[fRuleStatusIndex];
int32_t numValsToCopy = numVals;
if (numVals > capacity) {
status = U_BUFFER_OVERFLOW_ERROR;
numValsToCopy = capacity;
}
int i;
for (i=0; i<numValsToCopy; i++) {
fillInVec[i] = fData->fRuleStatusTable[fRuleStatusIndex + i + 1];
}
return numVals;
}
//-------------------------------------------------------------------------------
//
// getBinaryRules Access to the compiled form of the rules,
// for use by build system tools that save the data
// for standard iterator types.
//
//-------------------------------------------------------------------------------
const uint8_t *RuleBasedBreakIterator::getBinaryRules(uint32_t &length) {
const uint8_t *retPtr = NULL;
length = 0;
if (fData != NULL) {
retPtr = (const uint8_t *)fData->fHeader;
length = fData->fHeader->fLength;
}
return retPtr;
}
BreakIterator * RuleBasedBreakIterator::createBufferClone(void * /*stackBuffer*/,
int32_t &bufferSize,
UErrorCode &status)
{
if (U_FAILURE(status)){
return NULL;
}
if (bufferSize == 0) {
bufferSize = 1; // preflighting for deprecated functionality
return NULL;
}
BreakIterator *clonedBI = clone();
if (clonedBI == NULL) {
status = U_MEMORY_ALLOCATION_ERROR;
} else {
status = U_SAFECLONE_ALLOCATED_WARNING;
}
return (RuleBasedBreakIterator *)clonedBI;
}
U_NAMESPACE_END
static icu::UStack *gLanguageBreakFactories = nullptr;
static const icu::UnicodeString *gEmptyString = nullptr;
static icu::UInitOnce gLanguageBreakFactoriesInitOnce = U_INITONCE_INITIALIZER;
static icu::UInitOnce gRBBIInitOnce = U_INITONCE_INITIALIZER;
/**
* Release all static memory held by breakiterator.
*/
U_CDECL_BEGIN
static UBool U_CALLCONV rbbi_cleanup(void) {
delete gLanguageBreakFactories;
gLanguageBreakFactories = nullptr;
delete gEmptyString;
gEmptyString = nullptr;
gLanguageBreakFactoriesInitOnce.reset();
gRBBIInitOnce.reset();
return TRUE;
}
U_CDECL_END
U_CDECL_BEGIN
static void U_CALLCONV _deleteFactory(void *obj) {
delete (icu::LanguageBreakFactory *) obj;
}
U_CDECL_END
U_NAMESPACE_BEGIN
static void U_CALLCONV rbbiInit() {
gEmptyString = new UnicodeString();
ucln_common_registerCleanup(UCLN_COMMON_RBBI, rbbi_cleanup);
}
static void U_CALLCONV initLanguageFactories() {
UErrorCode status = U_ZERO_ERROR;
U_ASSERT(gLanguageBreakFactories == NULL);
gLanguageBreakFactories = new UStack(_deleteFactory, NULL, status);
if (gLanguageBreakFactories != NULL && U_SUCCESS(status)) {
ICULanguageBreakFactory *builtIn = new ICULanguageBreakFactory(status);
gLanguageBreakFactories->push(builtIn, status);
#ifdef U_LOCAL_SERVICE_HOOK
LanguageBreakFactory *extra = (LanguageBreakFactory *)uprv_svc_hook("languageBreakFactory", &status);
if (extra != NULL) {
gLanguageBreakFactories->push(extra, status);
}
#endif
}
ucln_common_registerCleanup(UCLN_COMMON_RBBI, rbbi_cleanup);
}
static const LanguageBreakEngine*
getLanguageBreakEngineFromFactory(UChar32 c)
{
umtx_initOnce(gLanguageBreakFactoriesInitOnce, &initLanguageFactories);
if (gLanguageBreakFactories == NULL) {
return NULL;
}
int32_t i = gLanguageBreakFactories->size();
const LanguageBreakEngine *lbe = NULL;
while (--i >= 0) {
LanguageBreakFactory *factory = (LanguageBreakFactory *)(gLanguageBreakFactories->elementAt(i));
lbe = factory->getEngineFor(c);
if (lbe != NULL) {
break;
}
}
return lbe;
}
//-------------------------------------------------------------------------------
//
// getLanguageBreakEngine Find an appropriate LanguageBreakEngine for the
// the character c.
//
//-------------------------------------------------------------------------------
const LanguageBreakEngine *
RuleBasedBreakIterator::getLanguageBreakEngine(UChar32 c) {
const LanguageBreakEngine *lbe = NULL;
UErrorCode status = U_ZERO_ERROR;
if (fLanguageBreakEngines == NULL) {
fLanguageBreakEngines = new UStack(status);
if (fLanguageBreakEngines == NULL || U_FAILURE(status)) {
delete fLanguageBreakEngines;
fLanguageBreakEngines = 0;
return NULL;
}
}
int32_t i = fLanguageBreakEngines->size();
while (--i >= 0) {
lbe = (const LanguageBreakEngine *)(fLanguageBreakEngines->elementAt(i));
if (lbe->handles(c)) {
return lbe;
}
}
// No existing dictionary took the character. See if a factory wants to
// give us a new LanguageBreakEngine for this character.
lbe = getLanguageBreakEngineFromFactory(c);
// If we got one, use it and push it on our stack.
if (lbe != NULL) {
fLanguageBreakEngines->push((void *)lbe, status);
// Even if we can't remember it, we can keep looking it up, so
// return it even if the push fails.
return lbe;
}
// No engine is forthcoming for this character. Add it to the
// reject set. Create the reject break engine if needed.
if (fUnhandledBreakEngine == NULL) {
fUnhandledBreakEngine = new UnhandledEngine(status);
if (U_SUCCESS(status) && fUnhandledBreakEngine == NULL) {
status = U_MEMORY_ALLOCATION_ERROR;
return nullptr;
}
// Put it last so that scripts for which we have an engine get tried
// first.
fLanguageBreakEngines->insertElementAt(fUnhandledBreakEngine, 0, status);
// If we can't insert it, or creation failed, get rid of it
if (U_FAILURE(status)) {
delete fUnhandledBreakEngine;
fUnhandledBreakEngine = 0;
return NULL;
}
}
// Tell the reject engine about the character; at its discretion, it may
// add more than just the one character.
fUnhandledBreakEngine->handleCharacter(c);
return fUnhandledBreakEngine;
}
void RuleBasedBreakIterator::dumpCache() {
fBreakCache->dumpCache();
}
void RuleBasedBreakIterator::dumpTables() {
fData->printData();
}
/**
* Returns the description used to create this iterator
*/
const UnicodeString&
RuleBasedBreakIterator::getRules() const {
if (fData != NULL) {
return fData->getRuleSourceString();
} else {
umtx_initOnce(gRBBIInitOnce, &rbbiInit);
return *gEmptyString;
}
}
U_NAMESPACE_END
#endif /* #if !UCONFIG_NO_BREAK_ITERATION */
| 16,197 |
778 | from KratosMultiphysics import ParallelEnvironment, IsDistributedRun
if IsDistributedRun():
from KratosMultiphysics.mpi import DataCommunicatorFactory
import KratosMultiphysics.KratosUnittest as UnitTest
import math
class TestDataCommunicatorFactory(UnitTest.TestCase):
def setUp(self):
self.registered_comms = []
self.default_data_communicator = ParallelEnvironment.GetDefaultDataCommunicator()
self.original_default = ParallelEnvironment.GetDefaultDataCommunicatorName()
def tearDown(self):
if len(self.registered_comms) > 0:
ParallelEnvironment.SetDefaultDataCommunicator(self.original_default)
for comm_name in self.registered_comms:
ParallelEnvironment.UnregisterDataCommunicator(comm_name)
def markForCleanUp(self,comm_name):
self.registered_comms.append(comm_name)
@UnitTest.skipUnless(IsDistributedRun(), "Test is distributed.")
def testDataCommunicatorDuplication(self):
duplicate_comm = DataCommunicatorFactory.DuplicateAndRegister(self.default_data_communicator, "Duplicate")
self.markForCleanUp("Duplicate") # to clean up during tearDown
self.assertEqual(duplicate_comm.Rank(), self.default_data_communicator.Rank())
self.assertEqual(duplicate_comm.Size(), self.default_data_communicator.Size())
@UnitTest.skipUnless(IsDistributedRun(), "Test is distributed.")
def testDataCommunicatorSplit(self):
rank = self.default_data_communicator.Rank()
size = self.default_data_communicator.Size()
split_comm = DataCommunicatorFactory.SplitAndRegister(self.default_data_communicator, rank % 2, 0, "EvenOdd")
self.markForCleanUp("EvenOdd") # to clean up during tearDown
expected_rank = rank // 2
if rank % 2 == 0:
expected_size = math.ceil(size/2)
else:
expected_size = math.floor(size/2)
self.assertEqual(split_comm.Rank(), expected_rank)
self.assertEqual(split_comm.Size(), expected_size)
@UnitTest.skipUnless(IsDistributedRun() and ParallelEnvironment.GetDefaultSize() > 1, "Test requires at least two ranks.")
def testDataCommunicatorCreateFromRange(self):
rank = self.default_data_communicator.Rank()
size = self.default_data_communicator.Size()
# Create a communicator using all ranks except the first
ranks = [i for i in range(1,size)]
range_comm = DataCommunicatorFactory.CreateFromRanksAndRegister(self.default_data_communicator, ranks, "AllExceptFirst")
self.markForCleanUp("AllExceptFirst") # to clean up during tearDown
if rank == 0:
self.assertTrue(range_comm.IsNullOnThisRank())
self.assertFalse(range_comm.IsDefinedOnThisRank())
else:
self.assertEqual(range_comm.Rank(), rank-1)
self.assertEqual(range_comm.Size(), size-1)
@UnitTest.skipUnless(IsDistributedRun() and ParallelEnvironment.GetDefaultSize() > 2, "Test requires at least three ranks.")
def testDataCommunicatorCreateUnion(self):
rank = self.default_data_communicator.Rank()
size = self.default_data_communicator.Size()
# Create a communicator using all ranks except the first
all_except_first = DataCommunicatorFactory.CreateFromRanksAndRegister(self.default_data_communicator, [i for i in range(1,size)], "AllExceptFirst")
self.markForCleanUp("AllExceptFirst") # to clean up during tearDown
all_except_last = DataCommunicatorFactory.CreateFromRanksAndRegister(self.default_data_communicator, [i for i in range(0,size-1)], "AllExceptLast")
self.markForCleanUp("AllExceptLast") # to clean up during tearDown
# Create union communicator (should contain all ranks)
union_comm = DataCommunicatorFactory.CreateUnionAndRegister(all_except_first, all_except_last, self.default_data_communicator, "Union")
self.markForCleanUp("Union") # to clean up during tearDown
self.assertFalse(union_comm.IsNullOnThisRank())
self.assertEqual(union_comm.Rank(), rank)
self.assertEqual(union_comm.Size(), size)
@UnitTest.skipUnless(IsDistributedRun() and ParallelEnvironment.GetDefaultSize() > 2, "Test requires at least three ranks.")
def testDataCommunicatorCreateIntersection(self):
rank = self.default_data_communicator.Rank()
size = self.default_data_communicator.Size()
# Create a communicator using all ranks except the first
all_except_first = DataCommunicatorFactory.CreateFromRanksAndRegister(self.default_data_communicator, [i for i in range(1,size)], "AllExceptFirst")
self.markForCleanUp("AllExceptFirst") # to clean up during tearDown
all_except_last = DataCommunicatorFactory.CreateFromRanksAndRegister(self.default_data_communicator, [i for i in range(0,size-1)], "AllExceptLast")
self.markForCleanUp("AllExceptLast") # to clean up during tearDown
intersection_comm = DataCommunicatorFactory.CreateIntersectionAndRegister(
all_except_first, all_except_last, self.default_data_communicator, "Intersection")
self.markForCleanUp("Intersection") # to clean up during tearDown
if rank == 0 or rank == size - 1:
# The first and last ranks do not participate in the intersection communicator
self.assertTrue(intersection_comm.IsNullOnThisRank())
else:
self.assertEqual(intersection_comm.Rank(), rank - 1 )
self.assertEqual(intersection_comm.Size(), size - 2 )
if __name__ == "__main__":
UnitTest.main()
| 2,020 |
1,382 | /* Simple Plugin API
*
* Copyright © 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 (including the next
* paragraph) shall be included in all copies or substantial portions of the
* Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
* THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
* DEALINGS IN THE SOFTWARE.
*/
#ifndef SPA_HOOK_H
#define SPA_HOOK_H
#ifdef __cplusplus
extern "C" {
#endif
#include <spa/utils/defs.h>
#include <spa/utils/list.h>
/** \defgroup spa_interfaces Interfaces
*
* \brief Generic implementation of implementation-independent interfaces
*
* A SPA Interface is a generic struct that, together with a few macros,
* provides a generic way of invoking methods on objects without knowing the
* details of the implementation.
*
* The primary interaction with interfaces is through macros that expand into
* the right method call. For the implementation of an interface, we need two
* structs and a macro to invoke the `bar` method:
*
* \code{.c}
* // this struct must be public and defines the interface to a
* // struct foo
* struct foo_methods {
* uint32_t version;
* void (*bar)(void *object, const char *msg);
* };
*
* // this struct does not need to be public
* struct foo {
* struct spa_interface iface; // must be first element, see foo_bar()
* int some_other_field;
* ...
* };
*
* // if struct foo is private, we need to cast to a
* // generic spa_interface object
* #define foo_bar(obj, ...) ({ \
* struct foo *f = obj;
* spa_interface_call((struct spa_interface *)f, // pointer to spa_interface in foo
* struct foo_methods, // type of callbacks
* bar, // name of methods
* 0, // hardcoded version to match foo_methods->version
* __VA_ARGS__ // pass rest of args through
* );/
* })
* \endcode
*
* The `struct foo_methods` and the invocation macro `foo_bar()` must be
* available to the caller. The implementation of `struct foo` can be private.
*
* \code{.c}
* void main(void) {
* struct foo *myfoo = get_foo_from_somewhere();
* foo_bar(myfoo, "Invoking bar() on myfoo");
* }
* \endcode
* The expansion of `foo_bar()` resolves roughly into this code:
* \code{.c}
* void main(void) {
* struct foo *myfoo = get_foo_from_somewhere();
* // foo_bar(myfoo, "Invoking bar() on myfoo");
* const struct foo_methods *methods = ((struct spa_interface*)myfoo)->cb;
* if (0 >= methods->version && // version check
* methods->bar) // compile error if this function does not exist,
* methods->bar(myfoo, "Invoking bar() on myfoo");
* }
* \endcode
*
* The typecast used in `foo_bar()` allows `struct foo` to be opaque to the
* caller. The implementation may assign the callback methods at object
* instantiation, and the caller will transparently invoke the method on the
* given object. For example, the following code assigns a different `bar()` method on
* Mondays - the caller does not need to know this.
* \code{.c}
*
* static void bar_stdout(struct foo *f, const char *msg) {
* printf(msg);
* }
* static void bar_stderr(struct foo *f, const char *msg) {
* fprintf(stderr, msg);
* }
*
* struct foo* get_foo_from_somewhere() {
* struct foo *f = calloc(sizeof struct foo);
* // illustrative only, use SPA_INTERFACE_INIT()
* f->iface->cb = (struct foo_methods*) { .bar = bar_stdout };
* if (today_is_monday)
* f->iface->cb = (struct foo_methods*) { .bar = bar_stderr };
* return f;
* }
* \endcode
*/
/**
* \addtogroup spa_interfaces
* \{
*/
/** \struct spa_callbacks
* Callbacks, contains the structure with functions and the data passed
* to the functions. The structure should also contain a version field that
* is checked. */
struct spa_callbacks {
const void *funcs;
void *data;
};
/** Check if a callback \a c is of at least version \a v */
#define SPA_CALLBACK_VERSION_MIN(c,v) ((c) && ((v) == 0 || (c)->version > (v)-1))
/** Check if a callback \a c has method \a m of version \a v */
#define SPA_CALLBACK_CHECK(c,m,v) (SPA_CALLBACK_VERSION_MIN(c,v) && (c)->m)
/**
* Initialize the set of functions \a funcs as a \ref spa_callbacks, together
* with \a _data.
*/
#define SPA_CALLBACKS_INIT(_funcs,_data) (struct spa_callbacks){ _funcs, _data, }
/** \struct spa_interface
*/
struct spa_interface {
const char *type;
uint32_t version;
struct spa_callbacks cb;
};
/**
* Initialize a \ref spa_interface.
*
* \code{.c}
* const static struct foo_methods foo_funcs = {
* .bar = some_bar_implementation,
* };
*
* struct foo *f = malloc(...);
* f->iface = SPA_INTERFACE_INIT("foo type", 0, foo_funcs, NULL);
* \endcode
*
*/
#define SPA_INTERFACE_INIT(_type,_version,_funcs,_data) \
(struct spa_interface){ _type, _version, SPA_CALLBACKS_INIT(_funcs,_data), }
/**
* Invoke method named \a method in the \a callbacks.
* The \a method_type defines the type of the method struct.
* Returns true if the method could be called, false otherwise.
*/
#define spa_callbacks_call(callbacks,type,method,vers,...) \
({ \
const type *_f = (const type *) (callbacks)->funcs; \
bool _res = SPA_CALLBACK_CHECK(_f,method,vers); \
if (SPA_LIKELY(_res)) \
_f->method((callbacks)->data, ## __VA_ARGS__); \
_res; \
})
/**
* True if the \a callbacks are of version \a vers, false otherwise
*/
#define spa_callback_version_min(callbacks,type,vers) \
({ \
const type *_f = (const type *) (callbacks)->funcs; \
SPA_CALLBACK_VERSION_MIN(_f,vers); \
})
/**
* True if the \a callbacks contains \a method of version
* \a vers, false otherwise
*/
#define spa_callback_check(callbacks,type,method,vers) \
({ \
const type *_f = (const type *) (callbacks)->funcs; \
SPA_CALLBACK_CHECK(_f,method,vers); \
})
/**
* Invoke method named \a method in the \a callbacks.
* The \a method_type defines the type of the method struct.
*
* The return value is stored in \a res.
*/
#define spa_callbacks_call_res(callbacks,type,res,method,vers,...) \
({ \
const type *_f = (const type *) (callbacks)->funcs; \
if (SPA_LIKELY(SPA_CALLBACK_CHECK(_f,method,vers))) \
res = _f->method((callbacks)->data, ## __VA_ARGS__); \
res; \
})
/**
* True if the \a iface's callbacks are of version \a vers, false otherwise
*/
#define spa_interface_callback_version_min(iface,method_type,vers) \
spa_callback_version_min(&(iface)->cb, method_type, vers)
/**
* True if the \a iface's callback \a method is of version \a vers
* and exists, false otherwise
*/
#define spa_interface_callback_check(iface,method_type,method,vers) \
spa_callback_check(&(iface)->cb, method_type, method, vers)
/**
* Invoke method named \a method in the callbacks on the given interface object.
* The \a method_type defines the type of the method struct, not the interface
* itself.
*/
#define spa_interface_call(iface,method_type,method,vers,...) \
spa_callbacks_call(&(iface)->cb,method_type,method,vers,##__VA_ARGS__)
/**
* Invoke method named \a method in the callbacks on the given interface object.
* The \a method_type defines the type of the method struct, not the interface
* itself.
*
* The return value is stored in \a res.
*/
#define spa_interface_call_res(iface,method_type,res,method,vers,...) \
spa_callbacks_call_res(&(iface)->cb,method_type,res,method,vers,##__VA_ARGS__)
/**
* \}
*/
/** \defgroup spa_hooks Hooks
*
* A SPA Hook is a data structure to keep track of callbacks. It is similar to
* the \ref spa_interfaces and typically used where an implementation allows
* for multiple external callback functions. For example, an implementation may
* use a hook list to implement signals with each caller using a hook to
* register callbacks to be invoked on those signals.
*
* The below (pseudo)code is a minimal example outlining the use of hooks:
* \code{.c}
* // the public interface
* struct bar_events {
* uint32_t version;
* void (*boom)(void *data, const char *msg);
* };
*
* // private implementation
* struct party {
* struct spa_hook_list bar_list;
* };
*
* void party_add_event_listener(struct party *p, struct spa_hook *listener,
* struct bar_events *events, void *data)
* {
* spa_hook_list_append(&p->bar_list, listener, events, data);
* }
*
* static void party_on(struct party *p)
* {
* spa_hook_list_call(&p->list, struct bar_events,
* boom, // function name
* 0 // hardcoded version,
* "party on, wayne");
* }
* \endcode
*
* In the caller, the hooks can be used like this:
* \code{.c}
* static void boom_cb(void *data, const char *msg) {
* // data is userdata from main()
* printf("%s", msg);
* }
*
* static const struct bar_events {
* .boom = boom_cb,
* };
*
* void main(void) {
* void *userdata = whatever;
* struct spa_hook hook;
* struct party *p = start_the_party();
*
* party_add_event_listener(p, &hook, boom_cb, userdata);
*
* mainloop();
* return 0;
* }
*
* \endcode
*/
/**
* \addtogroup spa_hooks
* \{
*/
/** \struct spa_hook_list
* A list of hooks. This struct is primarily used by
* implementation that use multiple caller-provided \ref spa_hook. */
struct spa_hook_list {
struct spa_list list;
};
/** \struct spa_hook
* A hook, contains the structure with functions and the data passed
* to the functions.
*
* A hook should be treated as opaque by the caller.
*/
struct spa_hook {
struct spa_list link;
struct spa_callbacks cb;
/** callback and data for the hook list, private to the
* hook_list implementor */
void (*removed) (struct spa_hook *hook);
void *priv;
};
/** Initialize a hook list to the empty list*/
static inline void spa_hook_list_init(struct spa_hook_list *list)
{
spa_list_init(&list->list);
}
static inline bool spa_hook_list_is_empty(struct spa_hook_list *list)
{
return spa_list_is_empty(&list->list);
}
/** Append a hook. */
static inline void spa_hook_list_append(struct spa_hook_list *list,
struct spa_hook *hook,
const void *funcs, void *data)
{
spa_zero(*hook);
hook->cb = SPA_CALLBACKS_INIT(funcs, data);
spa_list_append(&list->list, &hook->link);
}
/** Prepend a hook */
static inline void spa_hook_list_prepend(struct spa_hook_list *list,
struct spa_hook *hook,
const void *funcs, void *data)
{
spa_zero(*hook);
hook->cb = SPA_CALLBACKS_INIT(funcs, data);
spa_list_prepend(&list->list, &hook->link);
}
/** Remove a hook */
static inline void spa_hook_remove(struct spa_hook *hook)
{
spa_list_remove(&hook->link);
if (hook->removed)
hook->removed(hook);
}
/** Remove all hooks from the list */
static inline void spa_hook_list_clean(struct spa_hook_list *list)
{
struct spa_hook *h;
spa_list_consume(h, &list->list, link)
spa_hook_remove(h);
}
static inline void
spa_hook_list_isolate(struct spa_hook_list *list,
struct spa_hook_list *save,
struct spa_hook *hook,
const void *funcs, void *data)
{
/* init save list and move hooks to it */
spa_hook_list_init(save);
spa_list_insert_list(&save->list, &list->list);
/* init hooks and add single hook */
spa_hook_list_init(list);
spa_hook_list_append(list, hook, funcs, data);
}
static inline void
spa_hook_list_join(struct spa_hook_list *list,
struct spa_hook_list *save)
{
spa_list_insert_list(&list->list, &save->list);
}
#define spa_hook_list_call_simple(l,type,method,vers,...) \
({ \
struct spa_hook_list *_l = l; \
struct spa_hook *_h, *_t; \
spa_list_for_each_safe(_h, _t, &_l->list, link) \
spa_callbacks_call(&_h->cb,type,method,vers, ## __VA_ARGS__); \
})
/** Call all hooks in a list, starting from the given one and optionally stopping
* after calling the first non-NULL function, returns the number of methods
* called */
#define spa_hook_list_do_call(l,start,type,method,vers,once,...) \
({ \
struct spa_hook_list *_list = l; \
struct spa_list *_s = start ? (struct spa_list *)start : &_list->list; \
struct spa_hook _cursor = { 0 }, *_ci; \
int _count = 0; \
spa_list_cursor_start(_cursor, _s, link); \
spa_list_for_each_cursor(_ci, _cursor, &_list->list, link) { \
if (spa_callbacks_call(&_ci->cb,type,method,vers, ## __VA_ARGS__)) { \
_count++; \
if (once) \
break; \
} \
} \
spa_list_cursor_end(_cursor, link); \
_count; \
})
/**
* Call the method named \a m for each element in list \a l.
* \a t specifies the type of the callback struct.
*/
#define spa_hook_list_call(l,t,m,v,...) spa_hook_list_do_call(l,NULL,t,m,v,false,##__VA_ARGS__)
/**
* Call the method named \a m for each element in list \a l, stopping after
* the first invocation.
* \a t specifies the type of the callback struct.
*/
#define spa_hook_list_call_once(l,t,m,v,...) spa_hook_list_do_call(l,NULL,t,m,v,true,##__VA_ARGS__)
#define spa_hook_list_call_start(l,s,t,m,v,...) spa_hook_list_do_call(l,s,t,m,v,false,##__VA_ARGS__)
#define spa_hook_list_call_once_start(l,s,t,m,v,...) spa_hook_list_do_call(l,s,t,m,v,true,##__VA_ARGS__)
/**
* \}
*/
#ifdef __cplusplus
}
#endif
#endif /* SPA_HOOK_H */
| 5,364 |
5,169 | {
"name": "Swizzler",
"version": "0.1.0",
"summary": "Swizzling done right",
"description": " Swizzling done right:\n\n * Swizzling done right\n * Blocks API\n * Original implementation on your fingertips\n",
"homepage": "https://github.com/Wondermall/Swizzler",
"license": "MIT",
"authors": {
"<NAME>": "<EMAIL>"
},
"source": {
"git": "https://github.com/Wondermall/Swizzler.git",
"tag": "0.1.0"
},
"social_media_url": "https://twitter.com/zats",
"requires_arc": true,
"source_files": "Pod/**/*"
}
| 302 |
3,459 | <filename>Cores/Mednafen/mednafen-1.21/src/snes/src/ppu/mmio/mmio.hpp<gh_stars>1000+
struct {
//open bus support
uint8 ppu1_mdr, ppu2_mdr;
//bg line counters
uint16 bg_y[4];
//$2100
bool display_disabled;
uint8 display_brightness;
//$2101
uint8 oam_basesize;
uint8 oam_nameselect;
uint16 oam_tdaddr;
//$2102-$2103
uint16 oam_baseaddr;
uint16 oam_addr;
bool oam_priority;
uint8 oam_firstsprite;
//$2104
uint8 oam_latchdata;
//$2105
bool bg_tilesize[4];
bool bg3_priority;
uint8 bg_mode;
//$2106
uint8 mosaic_size;
bool mosaic_enabled[4];
uint16 mosaic_countdown;
//$2107-$210a
uint16 bg_scaddr[4];
uint8 bg_scsize[4];
//$210b-$210c
uint16 bg_tdaddr[4];
//$210d-$2114
uint8 bg_ofslatch;
uint16 m7_hofs, m7_vofs;
uint16 bg_hofs[4];
uint16 bg_vofs[4];
//$2115
bool vram_incmode;
uint8 vram_mapping;
uint8 vram_incsize;
//$2116-$2117
uint16 vram_addr;
//$211a
uint8 mode7_repeat;
bool mode7_vflip;
bool mode7_hflip;
//$211b-$2120
uint8 m7_latch;
uint16 m7a, m7b, m7c, m7d, m7x, m7y;
//$2121
uint16 cgram_addr;
//$2122
uint8 cgram_latchdata;
//$2123-$2125
bool window1_enabled[6];
bool window1_invert [6];
bool window2_enabled[6];
bool window2_invert [6];
//$2126-$2129
uint8 window1_left, window1_right;
uint8 window2_left, window2_right;
//$212a-$212b
uint8 window_mask[6];
//$212c-$212d
bool bg_enabled[5], bgsub_enabled[5];
//$212e-$212f
bool window_enabled[5], sub_window_enabled[5];
//$2130
uint8 color_mask, colorsub_mask;
bool addsub_mode;
bool direct_color;
//$2131
bool color_mode, color_halve;
bool color_enabled[6];
//$2132
uint8 color_r, color_g, color_b;
uint16 color_rgb;
//$2133
//overscan and interlace are checked once per frame to
//determine if entire frame should be interlaced/non-interlace
//and overscan adjusted. therefore, the variables act sort of
//like a buffer, but they do still affect internal rendering
bool mode7_extbg;
bool pseudo_hires;
bool overscan;
uint16 scanlines;
bool oam_interlace;
bool interlace;
//$2137
uint16 hcounter, vcounter;
bool latch_hcounter, latch_vcounter;
bool counters_latched;
//$2139-$213a
uint16 vram_readbuffer;
//$213e
bool time_over, range_over;
uint16 oam_itemcount, oam_tilecount;
} regs;
void mmio_w2100(uint8 value); //INIDISP
void mmio_w2101(uint8 value); //OBSEL
void mmio_w2102(uint8 value); //OAMADDL
void mmio_w2103(uint8 value); //OAMADDH
void mmio_w2104(uint8 value); //OAMDATA
void mmio_w2105(uint8 value); //BGMODE
void mmio_w2106(uint8 value); //MOSAIC
void mmio_w2107(uint8 value); //BG1SC
void mmio_w2108(uint8 value); //BG2SC
void mmio_w2109(uint8 value); //BG3SC
void mmio_w210a(uint8 value); //BG4SC
void mmio_w210b(uint8 value); //BG12NBA
void mmio_w210c(uint8 value); //BG34NBA
void mmio_w210d(uint8 value); //BG1HOFS
void mmio_w210e(uint8 value); //BG1VOFS
void mmio_w210f(uint8 value); //BG2HOFS
void mmio_w2110(uint8 value); //BG2VOFS
void mmio_w2111(uint8 value); //BG3HOFS
void mmio_w2112(uint8 value); //BG3VOFS
void mmio_w2113(uint8 value); //BG4HOFS
void mmio_w2114(uint8 value); //BG4VOFS
void mmio_w2115(uint8 value); //VMAIN
void mmio_w2116(uint8 value); //VMADDL
void mmio_w2117(uint8 value); //VMADDH
void mmio_w2118(uint8 value); //VMDATAL
void mmio_w2119(uint8 value); //VMDATAH
void mmio_w211a(uint8 value); //M7SEL
void mmio_w211b(uint8 value); //M7A
void mmio_w211c(uint8 value); //M7B
void mmio_w211d(uint8 value); //M7C
void mmio_w211e(uint8 value); //M7D
void mmio_w211f(uint8 value); //M7X
void mmio_w2120(uint8 value); //M7Y
void mmio_w2121(uint8 value); //CGADD
void mmio_w2122(uint8 value); //CGDATA
void mmio_w2123(uint8 value); //W12SEL
void mmio_w2124(uint8 value); //W34SEL
void mmio_w2125(uint8 value); //WOBJSEL
void mmio_w2126(uint8 value); //WH0
void mmio_w2127(uint8 value); //WH1
void mmio_w2128(uint8 value); //WH2
void mmio_w2129(uint8 value); //WH3
void mmio_w212a(uint8 value); //WBGLOG
void mmio_w212b(uint8 value); //WOBJLOG
void mmio_w212c(uint8 value); //TM
void mmio_w212d(uint8 value); //TS
void mmio_w212e(uint8 value); //TMW
void mmio_w212f(uint8 value); //TSW
void mmio_w2130(uint8 value); //CGWSEL
void mmio_w2131(uint8 value); //CGADDSUB
void mmio_w2132(uint8 value); //COLDATA
void mmio_w2133(uint8 value); //SETINI
uint8 mmio_r2134(); //MPYL
uint8 mmio_r2135(); //MPYM
uint8 mmio_r2136(); //MPYH
uint8 mmio_r2137(); //SLHV
uint8 mmio_r2138(); //OAMDATAREAD
uint8 mmio_r2139(); //VMDATALREAD
uint8 mmio_r213a(); //VMDATAHREAD
uint8 mmio_r213b(); //CGDATAREAD
uint8 mmio_r213c(); //OPHCT
uint8 mmio_r213d(); //OPVCT
uint8 mmio_r213e(); //STAT77
uint8 mmio_r213f(); //STAT78
uint8 mmio_read(unsigned addr);
void mmio_write(unsigned addr, uint8 data);
void latch_counters();
| 2,259 |
2,151 | // 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.
#ifndef UI_VIEWS_WIDGET_DESKTOP_AURA_WINDOW_EVENT_FILTER_H_
#define UI_VIEWS_WIDGET_DESKTOP_AURA_WINDOW_EVENT_FILTER_H_
#include "base/compiler_specific.h"
#include "base/macros.h"
#include "ui/events/event_handler.h"
#include "ui/views/views_export.h"
namespace views {
class DesktopWindowTreeHost;
// An EventFilter that sets properties on native windows.
// The downstream effort to add wayland and x11 support with ozone
// are using this class (to be upstreamed later).
class VIEWS_EXPORT WindowEventFilter : public ui::EventHandler {
public:
explicit WindowEventFilter(DesktopWindowTreeHost* window_tree_host);
~WindowEventFilter() override;
// Overridden from ui::EventHandler:
void OnMouseEvent(ui::MouseEvent* event) override;
private:
// Called when the user clicked the caption area.
void OnClickedCaption(ui::MouseEvent* event, int previous_click_component);
// Called when the user clicked the maximize button.
void OnClickedMaximizeButton(ui::MouseEvent* event);
void ToggleMaximizedState();
// Dispatches a message to the window manager to tell it to act as if a border
// or titlebar drag occurred with left mouse click. In case of X11, a
// _NET_WM_MOVERESIZE message is sent.
virtual void MaybeDispatchHostWindowDragMovement(int hittest,
ui::MouseEvent* event);
// A signal to lower an attached to this filter window to the bottom of the
// stack.
virtual void LowerWindow();
DesktopWindowTreeHost* window_tree_host_;
// The non-client component for the target of a MouseEvent. Mouse events can
// be destructive to the window tree, which can cause the component of a
// ui::EF_IS_DOUBLE_CLICK event to no longer be the same as that of the
// initial click. Acting on a double click should only occur for matching
// components.
int click_component_;
DISALLOW_COPY_AND_ASSIGN(WindowEventFilter);
};
} // namespace views
#endif // UI_VIEWS_WIDGET_DESKTOP_AURA_WINDOW_EVENT_FILTER_H_
| 693 |
1,473 | <gh_stars>1000+
#pragma once
#include "traceMemoryHistory.h"
namespace image
{
class Binary;
}
namespace trace
{
class Data;
/// build of the memory trace file
class RECOMPILER_API MemoryHistoryBuilder
{
public:
struct Page
{
uint32 m_id;
uint64 m_address;
uint32 m_entriesHead[MemoryHistory::ENTRIES_PER_PAGE];
uint32 m_entriesTail[MemoryHistory::ENTRIES_PER_PAGE];
Page(const uint64 adddres)
: m_id(0)
, m_address(adddres)
{
memset(&m_entriesHead[0],0,sizeof(m_entriesHead));
memset(&m_entriesTail[0],0,sizeof(m_entriesTail));
}
};
struct PageRange
{
uint64 m_address;
Page* m_pages[MemoryHistory::PAGES_PER_RANGE];
PageRange(const uint64 address)
: m_address(address)
{
memset(&m_pages[0], 0, sizeof(m_pages));
}
~PageRange()
{
for (uint32 i=0; i<MemoryHistory::PAGES_PER_RANGE; ++i)
{
delete m_pages[i];
}
}
};
uint32 m_nextEntryId;
uint64 m_entryDataStart;
FILE* m_outputFile;
PageRange* m_ranges[ MemoryHistory::MAX_RANGES ];
public:
MemoryHistoryBuilder();
~MemoryHistoryBuilder();
// build a memory trace file from normal data trace
bool BuildFile( class ILogOutput& log, decoding::Context& decodingContext, const Data& traceData, const wchar_t* outputFile);
private:
// add memory operation to range of addresses
const bool AddMemoryOperation(const uint32 traceEntryIndex, const uint64 memoryAddress, const uint8 type, const uint32 size, const void* data);
// add memory operation to given address
const bool AddMemoryOperationAt(const uint32 traceEntryIndex, const uint64 memoryAddress, const uint8 type, const uint8 data);
// get page range at given address base
PageRange* GetPageRange(const uint64 address);
// get page at given address base
Page* GetPage(const uint64 address);
// get file position
const uint64 GetFilePos() const;
// seek to file position
void SetFilePos(const uint64 pos);
// write to file
void WriteToFile(const void* data, const uint32 size);
// read from file
void ReadFromFile(void* data, const uint32 size);
};
} // trace | 815 |
769 | #ifndef __EXTI_H
#define __EXTI_H
#include "stm32l4xx.h"
// Definitions of EXTI lines
#define EXTI_LINE0 EXTI_IMR1_IM0
#define EXTI_LINE1 EXTI_IMR1_IM1
#define EXTI_LINE2 EXTI_IMR1_IM2
#define EXTI_LINE3 EXTI_IMR1_IM3
#define EXTI_LINE4 EXTI_IMR1_IM4
#define EXTI_LINE5 EXTI_IMR1_IM5
#define EXTI_LINE6 EXTI_IMR1_IM6
#define EXTI_LINE7 EXTI_IMR1_IM7
#define EXTI_LINE8 EXTI_IMR1_IM8
#define EXTI_LINE9 EXTI_IMR1_IM9
#define EXTI_LINE10 EXTI_IMR1_IM10
#define EXTI_LINE11 EXTI_IMR1_IM11
#define EXTI_LINE12 EXTI_IMR1_IM12
#define EXTI_LINE13 EXTI_IMR1_IM13
#define EXTI_LINE14 EXTI_IMR1_IM14
#define EXTI_LINE15 EXTI_IMR1_IM15
#if defined(EXTI_IMR1_IM16)
#define EXTI_LINE16 EXTI_IMR1_IM16
#endif
#define EXTI_LINE17 EXTI_IMR1_IM17
#define EXTI_LINE18 EXTI_IMR1_IM18
#define EXTI_LINE19 EXTI_IMR1_IM19
#if defined(EXTI_IMR1_IM20)
#define EXTI_LINE20 EXTI_IMR1_IM20
#endif
#if defined(EXTI_IMR1_IM21)
#define EXTI_LINE21 EXTI_IMR1_IM21
#endif
#if defined(EXTI_IMR1_IM22)
#define EXTI_LINE22 EXTI_IMR1_IM22
#endif
#define EXTI_LINE23 EXTI_IMR1_IM23
#if defined(EXTI_IMR1_IM24)
#define EXTI_LINE24 EXTI_IMR1_IM24
#endif
#if defined(EXTI_IMR1_IM25)
#define EXTI_LINE25 EXTI_IMR1_IM25
#endif
#if defined(EXTI_IMR1_IM26)
#define EXTI_LINE26 EXTI_IMR1_IM26
#endif
#if defined(EXTI_IMR1_IM27)
#define EXTI_LINE27 EXTI_IMR1_IM27
#endif
#if defined(EXTI_IMR1_IM28)
#define EXTI_LINE28 EXTI_IMR1_IM28
#endif
#if defined(EXTI_IMR1_IM29)
#define EXTI_LINE29 EXTI_IMR1_IM29
#endif
#if defined(EXTI_IMR1_IM30)
#define EXTI_LINE30 EXTI_IMR1_IM30
#endif
#if defined(EXTI_IMR1_IM31)
#define EXTI_LINE31 EXTI_IMR1_IM31
#endif
#define EXTI_LINE32 EXTI_IMR2_IM32
#define EXTI_LINE33 EXTI_IMR2_IM33
#define EXTI_LINE34 EXTI_IMR2_IM34
#define EXTI_LINE35 EXTI_IMR2_IM35
#define EXTI_LINE36 EXTI_IMR2_IM36
#define EXTI_LINE37 EXTI_IMR2_IM37
#define EXTI_LINE38 EXTI_IMR2_IM38
#define EXTI_LINE39 EXTI_IMR2_IM39
// Definitions of EXTI mode configuration
#define EXTI_MODE_NONE ((uint32_t)0x00000000U) // EXTI line disabled
#define EXTI_MODE_IRQ ((uint32_t)0x00000001U) // EXTI line generates IRQ
#define EXTI_MODE_EVT ((uint32_t)0x00000002U) // EXTI line generates event
#define EXTI_MODE_BOTH ((uint32_t)0x00000003U) // EXTI line generates both IRQ and event
// Definitions of EXTI trigger configuration
#define EXTI_TRG_NONE ((uint32_t)0x00000000U) // Trigger disabled
#define EXTI_TRG_RISING ((uint32_t)0x00000001U) // Trigger on rising edge
#define EXTI_TRG_FALLING ((uint32_t)0x00000002U) // Trigger on falling edge
#define EXTI_TRG_BOTH ((uint32_t)0x00000003U) // Trigger on both falling and rising edges
// Definitions of EXTI port sources
#define EXTI_SRC_PORTA ((uint32_t)0x00000000U) // Port A
#define EXTI_SRC_PORTB ((uint32_t)0x00000001U) // Port B
#define EXTI_SRC_PORTC ((uint32_t)0x00000002U) // Port C
#define EXTI_SRC_PORTD ((uint32_t)0x00000003U) // Port D
#define EXTI_SRC_PORTE ((uint32_t)0x00000004U) // Port E
#if defined(GPIOF)
#define EXTI_SRC_PORTF ((uint32_t)0x00000005U) // Port F
#endif
#if defined(GPIOG)
#define EXTI_SRC_PORTG ((uint32_t)0x00000006U) // Port G
#endif
#define EXTI_SRC_PORTH ((uint32_t)0x00000007U) // Port H
// Definitions of EXTI pin sources
#define EXTI_PIN_SRC0 ((uint32_t)0x00000000U)
#define EXTI_PIN_SRC1 ((uint32_t)0x00000001U)
#define EXTI_PIN_SRC2 ((uint32_t)0x00000002U)
#define EXTI_PIN_SRC3 ((uint32_t)0x00000003U)
#define EXTI_PIN_SRC4 ((uint32_t)0x00000004U)
#define EXTI_PIN_SRC5 ((uint32_t)0x00000005U)
#define EXTI_PIN_SRC6 ((uint32_t)0x00000006U)
#define EXTI_PIN_SRC7 ((uint32_t)0x00000007U)
#define EXTI_PIN_SRC8 ((uint32_t)0x00000008U)
#define EXTI_PIN_SRC9 ((uint32_t)0x00000009U)
#define EXTI_PIN_SRC10 ((uint32_t)0x0000000AU)
#define EXTI_PIN_SRC11 ((uint32_t)0x0000000BU)
#define EXTI_PIN_SRC12 ((uint32_t)0x0000000CU)
#define EXTI_PIN_SRC13 ((uint32_t)0x0000000DU)
#define EXTI_PIN_SRC14 ((uint32_t)0x0000000EU)
#define EXTI_PIN_SRC15 ((uint32_t)0x0000000FU)
// EXTI line handle structure
typedef struct {
uint32_t line; // EXTI line, one of EXTI_LineXX values
uint32_t port; // EXTI port, one of EXTI_SRC_PORTx values
uint32_t src; // EXTI source, one of EXTI_PIN_SRCxx values
IRQn_Type irq; // EXTI interrupt, one of EXTIxxx_IRQn values
} EXTI_HandleTypeDef;
// Public functions and macros
// Clear EXTI line flag(s) for lines in range from 0 to 31
// input:
// EXTI_Line - specifies the EXTI line(s), any combination of EXTI_Line[0..31] values
__STATIC_INLINE void EXTI_ClearFlag1(uint32_t EXTI_Line) {
EXTI->PR1 = EXTI_Line;
}
// Clear EXTI line flag(s) for lines in range from 32 to 39
// input:
// EXTI_Line - specifies the EXTI line(s), any combination of EXTI_Line[32..39] values
__STATIC_INLINE void EXTI_ClearFlag2(uint32_t EXTI_Line) {
EXTI->PR2 = EXTI_Line;
}
// Check if the EXTI line(s) flag is set for lines in range from 0 to 31
// input:
// EXTI_Line - specifies the EXTI line(s), any combination of EXTI_Line[0..31] values
// return: state of flag, 1 if all flags is set, 0 otherwise
__STATIC_INLINE uint32_t EXTI_IsActive1(uint32_t EXTI_Line) {
return ((EXTI->PR1 & EXTI_Line) == EXTI_Line);
}
// Check if the EXTI line(s) flag is set for lines in range from 32 to 39
// input:
// EXTI_Line - specifies the EXTI line(s), any combination of EXTI_Line[32..39] values
// return: state of flag, 1 if all flags is set, 0 otherwise
__STATIC_INLINE uint32_t EXTI_IsActive2(uint32_t EXTI_Line) {
return ((EXTI->PR2 & EXTI_Line) == EXTI_Line);
}
// Function prototypes
void EXTI_cfg1(uint32_t EXTI_Line, uint32_t EXTI_mode, uint32_t EXTI_trigger);
void EXTI_cfg2(uint32_t EXTI_Line, uint32_t EXTI_mode, uint32_t EXTI_trigger);
void EXTI_src(uint32_t port_src, uint32_t pin_src);
#endif // __EXTI_H
| 3,643 |
2,023 | <reponame>tdiprima/code
### Here is my implementation to partition based on funct's evaluation.
def partition(iterable, func):
result = {}
for i in iterable:
result.setdefault(func(i), []).append(i)
return result
### <NAME>'s Generalized group function
def group(seq):
'''seq is a sequence of tuple containing (item_to_be_categorized, category)'''
result = {}
for item, category in seq:
result.setdefault(category, []).append(item)
return result
########### Usage Example ###############
def is_odd(n):
return (n%2) == 1
l = range(10)
print partition(l, is_odd)
print group( (item, is_odd(item)) for item in l)
print group( (item, item%3) for item in l ) # no need for lamda/def
class Article (object):
def __init__(self, title, summary, author):
self.title = title
self.summary = summary
self.author = author
articles = [ Article('Politics & Me', 'about politics', 'Dave'),
Article('Fishes & Me', 'about fishes', 'ray'),
Article('Love & Me', 'about love', 'dave'),
Article('Spams & Me', 'about spams', 'Ray'), ]
# summaries of articles indexed by author
print group( (article.summary, article.author.lower()) for article in articles )
########### Output ###############
{False: [0, 2, 4, 6, 8], True: [1, 3, 5, 7, 9]}
{False: [0, 2, 4, 6, 8], True: [1, 3, 5, 7, 9]}
{0: [0, 3, 6, 9], 1: [1, 4, 7], 2: [2, 5, 8]}
{'dave': ['about politics', 'about love'], 'ray': ['about fishes', 'about spams']}
| 594 |
3,227 | <reponame>ffteja/cgal
/*!
\ingroup PkgTetrahedralRemeshingConcepts
\cgalConcept
\cgalRefines MeshCellBase_3
Cell base concept to be used in the triangulation type given to the function `CGAL::tetrahedral_isotropic_remeshing()`.
\cgalHasModel `CGAL::Tetrahedral_remeshing::Remeshing_cell_base_3`.
*/
class RemeshingCellBase_3
{};
| 129 |
310 | <gh_stars>100-1000
{
"name": "SR60i",
"description": "Headphones.",
"url": "https://www.amazon.com/Grado-Prestige-Headphones-Discontinued-Manufacturer/dp/B0006DPMU4"
} | 73 |
1,540 | package test.reports;
import static org.testng.Assert.assertEquals;
import static org.testng.Assert.assertTrue;
import java.util.ArrayList;
import java.util.List;
import org.testng.annotations.DataProvider;
import org.testng.annotations.Test;
public class GitHub447Sample {
@Test(dataProvider = "add")
public void add(List<Object> list, Object e, String expected) {
assertTrue(list.add(e));
assertEquals(list.toString(), expected);
}
@DataProvider(name = "add")
protected static final Object[][] addTestData() {
List<Object> list = new ArrayList<>(5);
Object[][] testData =
new Object[][] {
{list, null, "[null]"},
{list, "dup", "[null, dup]"},
{list, "dup", "[null, dup, dup]"},
{list, "str", "[null, dup, dup, str]"},
{list, null, "[null, dup, dup, str, null]"},
};
return testData;
}
}
| 357 |
344 | <gh_stars>100-1000
/*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
// Do not edit this file. It is machine generated.
{
"DebugConfig.failed": "Impossible de créer le fichier 'launch.json' dans le dossier '.vscode' ({0}).",
"app.launch.json.configurations": "Liste des configurations. Ajoutez de nouvelles configurations, ou modifiez celles qui existent déjà.",
"app.launch.json.title": "Lancer",
"app.launch.json.version": "Version de ce format de fichier.",
"debugNoType": "Le 'type' de l'adaptateur de débogage ne peut pas être omis. Il doit s'agir du type 'string'.",
"duplicateDebuggerType": "Le type de débogage '{0}' est déjà inscrit et a pour attribut '{1}'. Attribut '{1}' ignoré.",
"interactiveVariableNotFound": "L'adaptateur {0} ne contribue pas à la variable {1} spécifiée dans la configuration de lancement.",
"selectDebug": "Sélectionner l'environnement",
"vscode.extension.contributes.breakpoints": "Ajoute des points d'arrêt.",
"vscode.extension.contributes.breakpoints.language": "Autorisez les points d'arrêt pour ce langage.",
"vscode.extension.contributes.debuggers": "Ajoute des adaptateurs de débogage.",
"vscode.extension.contributes.debuggers.args": "Arguments facultatifs à passer à l'adaptateur.",
"vscode.extension.contributes.debuggers.configurationAttributes": "Configurations de schéma JSON pour la validation de 'launch.json'.",
"vscode.extension.contributes.debuggers.enableBreakpointsFor": "Autorisez les points d'arrêt pour ces langages.",
"vscode.extension.contributes.debuggers.enableBreakpointsFor.languageIds": "Liste des langages.",
"vscode.extension.contributes.debuggers.initialConfigurations": "Configurations pour la génération du fichier 'launch.json' initial.",
"vscode.extension.contributes.debuggers.label": "Nom complet de cet adaptateur de débogage.",
"vscode.extension.contributes.debuggers.linux": "Paramètres spécifiques à Linux.",
"vscode.extension.contributes.debuggers.linux.runtime": "Runtime utilisé pour Linux.",
"vscode.extension.contributes.debuggers.osx": "Paramètres spécifiques à OS X.",
"vscode.extension.contributes.debuggers.osx.runtime": "Runtime utilisé pour OS X.",
"vscode.extension.contributes.debuggers.program": "Chemin du programme de l'adaptateur de débogage. Le chemin est absolu ou relatif par rapport au dossier d'extensions.",
"vscode.extension.contributes.debuggers.runtime": "Runtime facultatif, si l'attribut de programme n'est pas un exécutable, mais qu'il nécessite un exécutable.",
"vscode.extension.contributes.debuggers.runtimeArgs": "Arguments du runtime facultatif.",
"vscode.extension.contributes.debuggers.type": "Identificateur unique de cet adaptateur de débogage.",
"vscode.extension.contributes.debuggers.variables": "Mappage à partir de variables interactives (par exemple, ${action.pickProcess}) dans 'launch.json' vers une commande.",
"vscode.extension.contributes.debuggers.windows": "Paramètres spécifiques à Windows.",
"vscode.extension.contributes.debuggers.windows.runtime": "Runtime utilisé pour Windows."
} | 1,058 |
937 | package cyclops.futurestream.react.simple;
import static org.hamcrest.Matchers.hasItem;
import static org.hamcrest.Matchers.is;
import static org.junit.Assert.assertThat;
import java.util.List;
import java.util.Queue;
import java.util.concurrent.ConcurrentLinkedQueue;
import java.util.concurrent.ExecutionException;
import org.junit.Test;
import cyclops.futurestream.SimpleReact;
public class PeekTest {
@Test
public void testPeek() throws InterruptedException,
ExecutionException {
Queue<String> peeked = new ConcurrentLinkedQueue<String>();
List<String> strings = new SimpleReact()
.<Integer> ofAsync(() -> 1, () -> 2, () -> 3)
.then(it -> it * 100)
.<String>then(it -> "*" + it)
.peek((String it) -> peeked.add(it))
.block();
assertThat(peeked.size(), is(strings.size()));
assertThat(strings,hasItem(peeked.peek()));
}
@Test
public void testPeekFirst() throws InterruptedException,
ExecutionException {
Queue<Integer> peeked = new ConcurrentLinkedQueue<Integer>();
List<String> strings = new SimpleReact()
.<Integer> ofAsync(() -> 1, () -> 2, () -> 3)
.peek(it -> peeked.add(it))
.then(it -> it * 100)
.then(it -> "*" + it)
.block();
assertThat(peeked.size(), is(strings.size()));
}
@Test
public void testPeekMultiple() throws InterruptedException,
ExecutionException {
Queue<Integer> peeked = new ConcurrentLinkedQueue<Integer>();
List<String> strings = new SimpleReact()
.<Integer> ofAsync(() -> 1, () -> 2, () -> 3)
.peek(it -> peeked.add(it))
.peek(it -> peeked.add(it))
.then(it -> it * 100)
.then(it -> "*" + it)
.block();
assertThat(peeked.size(), is(strings.size()*2));
}
}
| 665 |
13,111 | /*
* 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.skywalking.oap.server.library.util;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.nio.charset.Charset;
import java.util.List;
import org.junit.AfterClass;
import org.junit.Assert;
import org.junit.BeforeClass;
import org.junit.Test;
public class MultipleFilesChangeMonitorTest {
private static String FILE_NAME = "FileChangeMonitorTest.tmp";
@Test
public void test() throws InterruptedException, IOException {
StringBuilder content = new StringBuilder();
MultipleFilesChangeMonitor monitor = new MultipleFilesChangeMonitor(
1, new MultipleFilesChangeMonitor.FilesChangedNotifier() {
@Override
public void filesChanged(final List<byte[]> readableContents) {
Assert.assertEquals(2, readableContents.size());
Assert.assertNull(readableContents.get(1));
try {
content.delete(0, content.length());
content.append(new String(readableContents.get(0), 0, readableContents.get(0).length, "UTF-8"));
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
}
}, FILE_NAME, "XXXX_NOT_EXIST.SW");
monitor.start();
File file = new File(FILE_NAME);
BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(file));
bos.write("test context".getBytes(Charset.forName("UTF-8")));
bos.flush();
bos.close();
int countDown = 40;
boolean notified = false;
boolean notified2 = false;
while (countDown-- > 0) {
if ("test context".equals(content.toString())) {
file = new File(FILE_NAME);
bos = new BufferedOutputStream(new FileOutputStream(file));
bos.write("test context again".getBytes(Charset.forName("UTF-8")));
bos.flush();
bos.close();
notified = true;
} else if ("test context again".equals(content.toString())) {
notified2 = true;
break;
}
Thread.sleep(500);
}
Assert.assertTrue(notified);
Assert.assertTrue(notified2);
}
@BeforeClass
@AfterClass
public static void cleanup() {
File file = new File(FILE_NAME);
if (file.exists() && file.isFile()) {
file.delete();
}
}
}
| 1,341 |
356 | <filename>mind-map/scia-reto/src/main/java/com/igormaznitsa/sciareto/ui/platform/MacOSXAppHandlerOld.java
/*
* Copyright (C) 2018 <NAME>.
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
* MA 02110-1301 USA
*/
package com.igormaznitsa.sciareto.ui.platform;
import com.apple.eawt.Application;
import com.apple.eawt.ApplicationEvent;
import com.apple.eawt.ApplicationListener;
import com.igormaznitsa.meta.annotation.MayContainNull;
import com.igormaznitsa.meta.annotation.Warning;
import com.igormaznitsa.meta.common.utils.Assertions;
import com.igormaznitsa.mindmap.model.logger.Logger;
import com.igormaznitsa.mindmap.model.logger.LoggerFactory;
import com.igormaznitsa.sciareto.Main;
import javax.annotation.Nonnull;
import javax.annotation.Nullable;
import java.util.Collections;
import java.util.EnumMap;
import java.util.Map;
@Warning("It is accessible through Class.forName(), don't rename it!")
public final class MacOSXAppHandlerOld implements ApplicationListener, Platform {
private final Logger LOGGER = LoggerFactory.getLogger(MacOSXAppHandlerOld.class);
private final Map<PlatformMenuEvent, PlatformMenuAction> actions = Collections.synchronizedMap(new EnumMap<PlatformMenuEvent, PlatformMenuAction>(PlatformMenuEvent.class));
private final Application application;
public MacOSXAppHandlerOld(@Nonnull final Application application) {
this.application = application;
this.application.addApplicationListener(this);
this.application.setDockIconBadge(Main.APP_TITLE);
this.application.setDockIconImage(Main.APP_ICON);
}
private boolean processMenuEvent(@Nonnull final PlatformMenuEvent event, @Nullable @MayContainNull final Object... args) {
final PlatformMenuAction action = this.actions.get(event);
boolean handled = false;
if (action == null) {
LOGGER.info("No registered menu event handler : " + event);//NOI18N
} else {
handled = action.doPlatformMenuAction(event, args);
LOGGER.info("Processed menu event : " + event); //NOI18N
}
return handled;
}
@Override
public void init() {
}
@Override
public void dispose() {
}
@Nonnull
@Override
public String getDefaultLFClassName() {
return "";
}
@Override
public boolean registerPlatformMenuEvent(@Nonnull final PlatformMenuEvent event, @Nonnull final PlatformMenuAction action) {
this.actions.put(event, Assertions.assertNotNull(action));
switch (event) {
case ABOUT: {
this.application.setEnabledAboutMenu(true);
}
break;
case PREFERENCES: {
this.application.setEnabledPreferencesMenu(true);
}
break;
}
return true;
}
@Nonnull
@Override
public String getName() {
return "";
}
@Override
public void handleAbout(@Nonnull final ApplicationEvent ae) {
ae.setHandled(processMenuEvent(PlatformMenuEvent.ABOUT));
}
@Override
public void handleOpenApplication(@Nonnull final ApplicationEvent ae) {
}
@Override
public void handleOpenFile(@Nonnull final ApplicationEvent ae) {
ae.setHandled(processMenuEvent(PlatformMenuEvent.OPEN_FILE, ae.getFilename()));
}
@Override
public void handlePreferences(@Nonnull final ApplicationEvent ae) {
ae.setHandled(processMenuEvent(PlatformMenuEvent.PREFERENCES));
}
@Override
public void handlePrintFile(@Nonnull final ApplicationEvent ae) {
ae.setHandled(processMenuEvent(PlatformMenuEvent.PRINT_FILE, ae.getFilename()));
}
@Override
public void handleQuit(@Nonnull final ApplicationEvent ae) {
ae.setHandled(processMenuEvent(PlatformMenuEvent.QUIT));
}
@Override
public void handleReOpenApplication(@Nonnull final ApplicationEvent ae) {
ae.setHandled(processMenuEvent(PlatformMenuEvent.REOPEN_APPLICATION));
}
}
| 1,430 |
686 | <reponame>LiangTang1993/Icarus<filename>backend/model/_models.py
import traceback
import peewee
from model import db, BaseModel
from model.board_model import BoardModel
from model.follow import Follow
from model.comment_model import CommentModel
from model.manage_log import ManageLogModel
from model.mention import Mention
from model.notif import NotificationModel, UserNotifLastInfo
from model.post_stats import PostStatsModel, StatsLog
from model.test import Test
from model.topic_model import TopicModel
from model.upload_model import UploadModel
from model.user_model import UserModel
from model.user_oauth import UserOAuth
from model.user_token import UserToken
from model.wiki import WikiArticleModel
def sql_execute(sql):
try:
db.execute_sql(sql)
except Exception as e:
db.rollback()
def reset():
sql_execute("""
DROP TABLE IF EXISTS "board";
DROP TABLE IF EXISTS "comment";
DROP TABLE IF EXISTS "follow";
DROP TABLE IF EXISTS "notif";
DROP TABLE IF EXISTS "post_stats";
DROP TABLE IF EXISTS "stats_log";
DROP TABLE IF EXISTS "topic";
DROP TABLE IF EXISTS "user";
DROP TABLE IF EXISTS "user_notif_record";
DROP TABLE IF EXISTS "user_oauth";
DROP TABLE IF EXISTS "notif";
DROP TABLE IF EXISTS "user_notif_last_info";
DROP TABLE IF EXISTS "wiki_history";
DROP TABLE IF EXISTS "wiki_item";
DROP TABLE IF EXISTS "wiki_article";
DROP SEQUENCE IF EXISTS "id_gen_seq";
DROP SEQUENCE IF EXISTS "user_count_seq";
""")
def work():
try:
db.execute_sql(r"""
CREATE OR REPLACE FUNCTION int2bytea(v_number bigint) RETURNS bytea AS $$
DECLARE
v_str text;
BEGIN
v_str = to_hex(v_number)::text;
return decode(concat(repeat('0', length(v_str) %% 2), v_str), 'hex');
END;
$$ LANGUAGE plpgsql;
CREATE SEQUENCE IF NOT EXISTS id_gen_seq NO MINVALUE NO MAXVALUE START 4096 NO CYCLE; /* 0x1000 */
CREATE SEQUENCE IF NOT EXISTS user_count_seq NO MINVALUE NO MAXVALUE START 1 NO CYCLE;
""")
# 请注意,这俩需要数据库的 superuser 权限,因此普通用户是做不到的
# 会提示 permission denied to create extension "hstore" 这样的错误
# db.execute_sql("""
# CREATE EXTENSION IF NOT EXISTS hstore;
# CREATE EXTENSION IF NOT EXISTS citext;
# """)
except peewee.ProgrammingError as e:
db.rollback()
traceback.print_exc()
quit()
sql_execute('alter table "user" drop column key')
sql_execute('alter table "user" drop column key_time')
sql_execute('alter table "upload" add column filename text')
sql_execute('alter table "upload" add column source text')
db.connect()
work()
db.create_tables([Test, BoardModel, Follow, CommentModel, TopicModel, UserModel,
WikiArticleModel,
NotificationModel, UserNotifLastInfo,
UserOAuth,
UserToken,
UploadModel,
ManageLogModel,
Mention,
PostStatsModel,
StatsLog], safe=True)
work()
sql_execute("""
ALTER TABLE "board" ALTER COLUMN "id" SET DEFAULT int2bytea(nextval('id_gen_seq')::bigint);
ALTER TABLE "topic" ALTER COLUMN "id" SET DEFAULT int2bytea(nextval('id_gen_seq')::bigint);
ALTER TABLE "user" ALTER COLUMN "id" SET DEFAULT int2bytea(nextval('id_gen_seq')::bigint);
ALTER TABLE "user" ALTER COLUMN "number" SET DEFAULT nextval('user_count_seq')::bigint;
""")
WikiArticleModel.get_sidebar_article()
WikiArticleModel.get_main_page_article()
| 1,542 |
395 | <reponame>jonathan-stein/timely
package timely.test;
import java.util.HashMap;
import timely.configuration.Configuration;
public class TestConfiguration {
public static final String TIMELY_HTTP_ADDRESS_DEFAULT = "localhost";
public static final int WAIT_SECONDS = 2;
public static Configuration createMinimalConfigurationForTest() {
// @formatter:off
Configuration cfg = new Configuration();
cfg.getServer().setIp("127.0.0.1");
cfg.getServer().setTcpPort(54321);
cfg.getServer().setUdpPort(54325);
cfg.getServer().setShutdownQuietPeriod(0);
cfg.getHttp().setIp("127.0.0.1");
cfg.getHttp().setPort(54322);
cfg.getHttp().setHost("localhost");
cfg.getWebsocket().setIp("127.0.0.1");
cfg.getWebsocket().setPort(54323);
cfg.getWebsocket().setTimeout(20);
cfg.getAccumulo().setZookeepers("localhost:2181");
cfg.getAccumulo().setInstanceName("test");
cfg.getAccumulo().setUsername("root");
cfg.getAccumulo().setPassword("<PASSWORD>");
cfg.getAccumulo().getWrite().setLatency("100ms");
cfg.getSecurity().getServerSsl().setUseGeneratedKeypair(true);
HashMap<String,Integer> ageoff = new HashMap<>();
ageoff.put("default", 10);
cfg.setMetricAgeOffDays(ageoff);
// @formatter:on
return cfg;
}
}
| 611 |
324 | <filename>providers/profitbricks/src/test/java/org/jclouds/profitbricks/features/StorageApiMockTest.java<gh_stars>100-1000
/*
* 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.jclouds.profitbricks.features;
import static org.testng.Assert.assertEquals;
import static org.testng.Assert.assertFalse;
import static org.testng.Assert.assertNotNull;
import static org.testng.Assert.assertNull;
import static org.testng.Assert.assertTrue;
import java.util.List;
import org.jclouds.profitbricks.ProfitBricksApi;
import org.jclouds.profitbricks.domain.Storage;
import org.jclouds.profitbricks.internal.BaseProfitBricksMockTest;
import org.testng.annotations.Test;
import com.squareup.okhttp.mockwebserver.MockResponse;
import com.squareup.okhttp.mockwebserver.MockWebServer;
@Test(groups = "unit", testName = "StorageApiMockTest")
public class StorageApiMockTest extends BaseProfitBricksMockTest {
@Test
public void testGetAllStorages() throws Exception {
MockWebServer server = mockWebServer();
server.enqueue(new MockResponse().setBody(payloadFromResource("/storage/storages.xml")));
ProfitBricksApi pbApi = api(server.getUrl(rootUrl));
StorageApi api = pbApi.storageApi();
try {
List<Storage> storages = api.getAllStorages();
assertRequestHasCommonProperties(server.takeRequest(), "<ws:getAllStorages/>");
assertNotNull(storages);
assertTrue(storages.size() == 2);
} finally {
pbApi.close();
server.shutdown();
}
}
@Test
public void testGetAllStoragesReturning404() throws Exception {
MockWebServer server = mockWebServer();
server.enqueue(new MockResponse().setResponseCode(404));
ProfitBricksApi pbApi = api(server.getUrl(rootUrl));
StorageApi api = pbApi.storageApi();
try {
List<Storage> storages = api.getAllStorages();
assertRequestHasCommonProperties(server.takeRequest());
assertTrue(storages.isEmpty());
} finally {
pbApi.close();
server.shutdown();
}
}
@Test
public void testGetStorage() throws Exception {
MockWebServer server = mockWebServer();
server.enqueue(new MockResponse().setBody(payloadFromResource("/storage/storage.xml")));
ProfitBricksApi pbApi = api(server.getUrl(rootUrl));
StorageApi api = pbApi.storageApi();
String id = "qswdefrg-qaws-qaws-defe-rgrgdsvcxbrh";
String content = "<ws:getStorage><storageId>" + id + "</storageId></ws:getStorage>";
try {
Storage storage = api.getStorage(id);
assertRequestHasCommonProperties(server.takeRequest(), content);
assertNotNull(storage);
assertEquals(storage.id(), id);
} finally {
pbApi.close();
server.shutdown();
}
}
@Test
public void testGetNonExistingStorage() throws Exception {
MockWebServer server = mockWebServer();
server.enqueue(new MockResponse().setResponseCode(404));
ProfitBricksApi pbApi = api(server.getUrl(rootUrl));
StorageApi api = pbApi.storageApi();
String id = "random-non-existing-id";
try {
Storage storage = api.getStorage(id);
assertRequestHasCommonProperties(server.takeRequest());
assertNull(storage);
} finally {
pbApi.close();
server.shutdown();
}
}
@Test
public void testConnectStorageToServer() throws Exception {
MockWebServer server = mockWebServer();
server.enqueue(new MockResponse().setBody(payloadFromResource("/storage/storage-connect.xml")));
ProfitBricksApi pbApi = api(server.getUrl(rootUrl));
StorageApi api = pbApi.storageApi();
String storageId = "qswdefrg-qaws-qaws-defe-rgrgdsvcxbrh";
String serverId = "qwertyui-qwer-qwer-<KEY>";
String content = "<ws:connectStorageToServer><request>"
+ "<storageId>" + storageId + "</storageId>"
+ "<serverId>" + serverId + "</serverId>"
+ "<busType>VIRTIO</busType>"
+ "<deviceNumber>2</deviceNumber>"
+ "</request></ws:connectStorageToServer>";
try {
String requestId = api.connectStorageToServer(
Storage.Request.connectingBuilder()
.serverId(serverId)
.storageId(storageId)
.busType(Storage.BusType.VIRTIO)
.deviceNumber(2)
.build()
);
assertRequestHasCommonProperties(server.takeRequest(), content);
assertEquals(requestId, "16463317");
} finally {
pbApi.close();
server.shutdown();
}
}
@Test
public void testDisconnectStorageFromServer() throws Exception {
MockWebServer server = mockWebServer();
server.enqueue(new MockResponse().setBody(payloadFromResource("/storage/storage-disconnect.xml")));
ProfitBricksApi pbApi = api(server.getUrl(rootUrl));
StorageApi api = pbApi.storageApi();
String storageId = "qswdefrg-qaws-qaws-defe-rgrgdsvcxbrh";
String serverId = "qwertyui-qwer-qwer-qwer-qwertyyuiiop";
String content = "<ws:disconnectStorageFromServer>"
+ "<storageId>" + storageId + "</storageId>"
+ "<serverId>" + serverId + "</serverId>"
+ "</ws:disconnectStorageFromServer>";
try {
String requestId = api.disconnectStorageFromServer(storageId, serverId);
assertRequestHasCommonProperties(server.takeRequest(), content);
assertEquals(requestId, "16463318");
} finally {
pbApi.close();
server.shutdown();
}
}
@Test
public void testCreateStorage() throws Exception {
MockWebServer server = mockWebServer();
server.enqueue(new MockResponse().setBody(payloadFromResource("/storage/storage-create.xml")));
ProfitBricksApi pbApi = api(server.getUrl(rootUrl));
StorageApi api = pbApi.storageApi();
String dataCenterId = "aaaaaaaa-bbbb-cccc-dddd-eeeeeeeeeeee";
String imageId = "f0a59a5c-7940-11e4-8053-52540066fee9";
String content = "<ws:createStorage><request>"
+ "<dataCenterId>" + dataCenterId + "</dataCenterId>"
+ "<storageName>hdd-1</storageName>" + "<size>80</size>"
+ "<mountImageId>" + imageId + "</mountImageId>"
+ "<profitBricksImagePassword><PASSWORD></profitBricksImagePassword>"
+ "</request></ws:createStorage>";
try {
String storageId = api.createStorage(
Storage.Request.creatingBuilder()
.dataCenterId(dataCenterId)
.name("hdd-1")
.size(80f)
.mountImageId(imageId)
.imagePassword("<PASSWORD>")
.build());
assertRequestHasCommonProperties(server.takeRequest(), content);
assertNotNull(storageId);
assertEquals(storageId, "qswdefrg-qaws-qaws-defe-rgrgdsvcxbrh");
} finally {
pbApi.close();
server.shutdown();
}
}
@Test
public void testUpdateStorage() throws Exception {
MockWebServer server = mockWebServer();
server.enqueue(new MockResponse().setBody(payloadFromResource("/storage/storage-update.xml")));
ProfitBricksApi pbApi = api(server.getUrl(rootUrl));
StorageApi api = pbApi.storageApi();
String storageId = "qswdefrg-qaws-qaws-defe-rgrgdsvcxbrh";
String imageId = "f4742db0-9160-11e4-9d74-52540066fee9";
String content = "<ws:updateStorage><request>"
+ "<storageId>" + storageId + "</storageId>"
+ "<size>20</size><storageName>hdd-2</storageName>"
+ "<mountImageId>" + imageId + "</mountImageId>"
+ "</request></ws:updateStorage>";
try {
String requestId = api.updateStorage(
Storage.Request.updatingBuilder()
.id(storageId)
.size(20f)
.name("hdd-2")
.mountImageId(imageId)
.build());
assertRequestHasCommonProperties(server.takeRequest(), content);
assertNotNull(requestId);
assertEquals(requestId, "1234568");
} finally {
pbApi.close();
server.shutdown();
}
}
@Test
public void testDeleteStorage() throws Exception {
MockWebServer server = mockWebServer();
server.enqueue(new MockResponse().setBody(payloadFromResource("/storage/storage-delete.xml")));
ProfitBricksApi pbApi = api(server.getUrl(rootUrl));
StorageApi api = pbApi.storageApi();
String storageId = "qswdefrg-qaws-qaws-defe-rgrgdsvcxbrh";
String content = "<ws:deleteStorage><storageId>" + storageId + "</storageId></ws:deleteStorage>";
try {
boolean result = api.deleteStorage(storageId);
assertRequestHasCommonProperties(server.takeRequest(), content);
assertTrue(result);
} finally {
pbApi.close();
server.shutdown();
}
}
@Test
public void testDeleteNonExistingStorage() throws Exception {
MockWebServer server = mockWebServer();
server.enqueue(new MockResponse().setResponseCode(404));
ProfitBricksApi pbApi = api(server.getUrl(rootUrl));
StorageApi api = pbApi.storageApi();
String id = "random-non-existing-id";
try {
boolean result = api.deleteStorage(id);
assertRequestHasCommonProperties(server.takeRequest());
assertFalse(result);
} finally {
pbApi.close();
server.shutdown();
}
}
}
| 4,321 |
1,083 | /*
* 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.carbondata.core.stream;
import java.io.ByteArrayOutputStream;
import org.apache.carbondata.core.constants.CarbonCommonConstants;
import org.apache.carbondata.core.memory.CarbonUnsafe;
public class ExtendedByteArrayOutputStream extends ByteArrayOutputStream {
public ExtendedByteArrayOutputStream() {
}
public ExtendedByteArrayOutputStream(int initialSize) {
super(initialSize);
}
public byte[] getBuffer() {
return buf;
}
public long copyToAddress() {
final long address =
CarbonUnsafe.getUnsafe().allocateMemory(CarbonCommonConstants.INT_SIZE_IN_BYTE + count);
CarbonUnsafe.getUnsafe().putInt(address, count);
CarbonUnsafe.getUnsafe().copyMemory(buf, CarbonUnsafe.BYTE_ARRAY_OFFSET, null,
address + CarbonCommonConstants.INT_SIZE_IN_BYTE, count);
return address;
}
}
| 475 |
684 | /*
* Anyplace: A free and open Indoor Navigation Service with superb accuracy!
*
* Anyplace is a first-of-a-kind indoor information service offering GPS-less
* localization, navigation and search inside buildings using ordinary smartphones.
*
* Author(s): <NAME>, <NAME>
*
* Supervisor: <NAME>
*
* URL: http://anyplace.cs.ucy.ac.cy
* Contact: <EMAIL>
*
* Copyright (c) 2015, Data Management Systems Lab (DMSL), University of Cyprus.
* All rights reserved.
*
* Permission is hereby granted, free of charge, to any person obtaining a copy of
* this software and associated documentation files (the "Software"), to deal in the
* Software without restriction, including without limitation the rights to use, copy,
* modify, merge, publish, distribute, sublicense, and/or sell copies of the Software,
* and to permit persons to whom the Software is furnished to do so, subject to the
* following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
* OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
* DEALINGS IN THE SOFTWARE.
*
*/
package cy.ac.ucy.cs.anyplace.navigator;
import java.io.File;
import java.net.URLDecoder;
import java.util.ArrayList;
import java.util.List;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.Window;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Spinner;
import android.widget.Toast;
import androidx.fragment.app.FragmentActivity;
import cy.ac.ucy.cs.anyplace.lib.android.AnyplaceDebug;
import cy.ac.ucy.cs.anyplace.lib.android.cache.ObjectCache;
import cy.ac.ucy.cs.anyplace.lib.android.nav.BuildingModel;
import cy.ac.ucy.cs.anyplace.lib.android.nav.FloorModel;
import cy.ac.ucy.cs.anyplace.lib.android.floor.Algo1Server;
import cy.ac.ucy.cs.anyplace.lib.android.floor.FloorSelector;
import cy.ac.ucy.cs.anyplace.lib.android.floor.FloorSelector.ErrorAnyplaceFloorListener;
import cy.ac.ucy.cs.anyplace.lib.android.floor.FloorSelector.FloorAnyplaceFloorListener;
import cy.ac.ucy.cs.anyplace.lib.android.tasks.FetchBuildingsTask.FetchBuildingsTaskListener;
import cy.ac.ucy.cs.anyplace.lib.android.tasks.FetchBuildingsByBuidTask;
import cy.ac.ucy.cs.anyplace.lib.android.tasks.FetchFloorPlanTask;
import cy.ac.ucy.cs.anyplace.lib.android.tasks.FetchFloorsByBuidTask;
import cy.ac.ucy.cs.anyplace.lib.android.tasks.FetchNearBuildingsTask;
/**
* TODO:PM competely redo this.
* A recycler view, that can pull all buildings, owner buldings, etc, based on design.
* AND reuse this on Navigator and Logger. the same activity.
*/
public class SelectBuildingActivity extends FragmentActivity implements FloorAnyplaceFloorListener,
ErrorAnyplaceFloorListener {
public enum Mode {
NONE, NEAREST, // Automatically show nearby Building
INVISIBLE // Automatically submit
}
private Spinner spinnerBuildings;
private Spinner spinnerFloors;
private Button btnRefreshWorldBuildings;
private Button btnRefreshNearmeBuildings;
private Button btnRefreshFloors;
private String lat;
private String lon;
private Mode mode;
private Integer selectedFloorIndex = 0;
// <Floor Selector>
private boolean isBuildingsLoadingFinished;
private boolean isfloorSelectorJobFinished;
private FloorSelector floorSelector;
private String floorResult;
private ProgressDialog floorSelectorDialog;
// </Floor Selector>
private boolean isBuildingsJobRunning = false;
private boolean isFloorsJobRunning = false;
private ObjectCache mAnyplaceCache = null;
private NavigatorApp app;
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
app = (NavigatorApp) getApplication();
requestWindowFeature((int) Window.FEATURE_NO_TITLE);
setContentView(R.layout.activity_select_building);
// get the AnyplaceCache instance
mAnyplaceCache = ObjectCache.getInstance(app);
btnRefreshWorldBuildings = (Button) findViewById(R.id.btnWorldBuildingsRefresh);
btnRefreshWorldBuildings.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
if (isBuildingsJobRunning) {
Toast.makeText(getBaseContext(), "Another building request is in process...", Toast.LENGTH_SHORT).show();
return;
}
startBuildingsFetch(false, true);
}
});
btnRefreshNearmeBuildings = (Button) findViewById(R.id.btnNearmeBuildingsRefresh);
btnRefreshNearmeBuildings.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
if (isBuildingsJobRunning) {
Toast.makeText(getBaseContext(), "Another building request is in process...", Toast.LENGTH_SHORT).show();
return;
}
startBuildingsFetch(true, false);
}
});
spinnerFloors = (Spinner) findViewById(R.id.floors);
spinnerFloors.setOnItemSelectedListener(new OnItemSelectedListener() {
@Override
public void onItemSelected(AdapterView<?> parent, View view, int pos, long id) {
selectedFloorIndex = pos;
}
@Override
public void onNothingSelected(AdapterView<?> parent) {
}
});
spinnerBuildings = (Spinner) findViewById(R.id.buildings);
spinnerBuildings.setOnItemSelectedListener(new OnItemSelectedListener() {
@Override
public void onItemSelected(AdapterView<?> parent, View view, int pos, long id) {
if (isFloorsJobRunning) {
Toast.makeText(getBaseContext(), "Another request is in process...", Toast.LENGTH_SHORT).show();
return;
}
mAnyplaceCache.setSelectedBuildingIndex(pos);
BuildingModel build = mAnyplaceCache.getSelectedBuilding();
if (build != null && build.isFloorsLoaded()) {
setFloorSpinner(build.getLoadedFloors());
try {
spinnerFloors.setSelection(build.getSelectedFloorIndex());
} catch (IndexOutOfBoundsException ex) {
}
onFloorsLoaded(build.getLoadedFloors());
} else {
startFloorFetch();
}
}
@Override
public void onNothingSelected(AdapterView<?> parent) {
}
});
btnRefreshFloors = (Button) findViewById(R.id.btnFloorsRefresh);
btnRefreshFloors.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
if (isFloorsJobRunning) {
Toast.makeText(getBaseContext(), "Another floor request is in process...", Toast.LENGTH_SHORT).show();
return;
}
try {
startFloorFetch();
} catch (IndexOutOfBoundsException ex) {
Toast.makeText(getBaseContext(), "Check again the building selected...", Toast.LENGTH_SHORT).show();
}
}
});
Button done = (Button) findViewById(R.id.btnDone);
done.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
startFloorPlanTask();
}
});
Bundle b = this.getIntent().getExtras();
if (b == null) {
mode = Mode.NONE;
lat = "0.0";
lon = "0.0";
} else {
mode = (Mode) b.getSerializable("mode");
if (mode == null)
mode = Mode.NONE;
lat = b.getString("coordinates_lat");
if (lat == null) {
lat = "0.0";
mode = Mode.NONE;
btnRefreshNearmeBuildings.setEnabled(false);
}
lon = b.getString("coordinates_lon");
if (lon == null) {
lon = "0.0";
mode = Mode.NONE;
btnRefreshNearmeBuildings.setEnabled(false);
}
}
// start automatically the buildings task if invisible mode
if (mode != Mode.NONE) {
floorSelectorDialog = new ProgressDialog(SelectBuildingActivity.this);
floorSelectorDialog.setIndeterminate(true);
floorSelectorDialog.setTitle("Detecting floor");
floorSelectorDialog.setMessage("Please be patient...");
floorSelectorDialog.setCancelable(true);
floorSelectorDialog.setCanceledOnTouchOutside(false);
floorSelector = new Algo1Server(app);
floorSelector.addListener((FloorSelector.FloorAnyplaceFloorListener) this);
floorSelector.addListener((FloorSelector.ErrorAnyplaceFloorListener) this);
isBuildingsLoadingFinished = false;
isfloorSelectorJobFinished = false;
floorSelector.Start(lat, lon);
startBuildingsFetch(true, false);
} else {
List<BuildingModel> buildings = mAnyplaceCache.getSpinnerBuildings();
if (buildings.size() == 0) {
startBuildingsFetch(false, false);
} else {
setBuildingSpinner(buildings);
spinnerBuildings.setSelection(mAnyplaceCache.getSelectedBuildingIndex());
}
}
}
@Override
protected void onStart() {
super.onStart();
}
@Override
protected void onResume() {
super.onResume();
}
// /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
@Override
protected void onPause() {
super.onPause();
}
// ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
@Override
protected void onStop() {
super.onStop();
}
// //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
@Override
protected void onRestart() {
super.onRestart();
}
// /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
@Override
protected void onDestroy() {
super.onDestroy();
if (floorSelector != null) {
floorSelector.removeListener((FloorSelector.FloorAnyplaceFloorListener) this);
floorSelector.removeListener((FloorSelector.ErrorAnyplaceFloorListener) this);
floorSelector.Destoy();
}
System.gc();
}
/**
* @see android.app.Activity#onCreateOptionsMenu(Menu)
*/
@Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.main_menu_select_building, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.main_menu_add_building: {
AlertDialog.Builder alert = new AlertDialog.Builder(this);
alert.setTitle("Add Building");
alert.setMessage("Private Building's ID");
// Set an EditText view to get user input
final EditText editText = new EditText(this);
alert.setView(editText);
alert.setPositiveButton("Ok", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
try {
// http://anyplace.cs.ucy.ac.cy/viewer/?buid=building_2f25420e-3cb1-4bc1-9996-3939e5530d30_1414014035379
// OR
// building_2f25420e-3cb1-4bc1-9996-3939e5530d30_1414014035379
String input = editText.getText().toString().trim();
String buid = input;
if (input.startsWith("http")) {
Uri uri = Uri.parse(URLDecoder.decode(input, "UTF-8"));
buid = uri.getQueryParameter("buid");
if (buid == null) {
throw new Exception("Missing buid parameter");
}
}
new FetchBuildingsByBuidTask(new FetchBuildingsByBuidTask.FetchBuildingsByBuidTaskListener() {
@Override
public void onSuccess(String result, BuildingModel b) {
ArrayList<BuildingModel> list = new ArrayList<BuildingModel>(1);
list.add(b);
setBuildingSpinner(list);
}
@Override
public void onErrorOrCancel(String result) {
Toast.makeText(getBaseContext(), result, Toast.LENGTH_SHORT).show();
}
}, SelectBuildingActivity.this, buid).execute();
} catch (Exception e) {
Toast.makeText(getBaseContext(), e.getMessage(), Toast.LENGTH_SHORT).show();
}
}
});
alert.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
// Canceled.
}
});
alert.show();
return true;
}
}
return false;
}
private void startBuildingsFetch(final Boolean nearestOnly, Boolean forceReload) {
final boolean btnRefreshWorldBuildingsState = btnRefreshWorldBuildings.isEnabled();
final boolean btnRefreshNearmeBuildingsState = btnRefreshNearmeBuildings.isEnabled();
btnRefreshWorldBuildings.setEnabled(false);
btnRefreshNearmeBuildings.setEnabled(false);
isBuildingsJobRunning = true;
mAnyplaceCache.loadWorldBuildings(this, new FetchBuildingsTaskListener() {
@Override
public void onSuccess(String result, List<BuildingModel> buildings) {
finishJob();
if (nearestOnly) {
FetchNearBuildingsTask nearBuildings = new FetchNearBuildingsTask();
nearBuildings.run(buildings.iterator(), lat, lon, 10000);
// if the user should not interact with the gui and
// automatically load the building
if (mode == Mode.INVISIBLE && (nearBuildings.buildings.isEmpty() || nearBuildings.distances.get(0) > 200)) {
// exit the activity since no building exists in your area
Intent returnIntent = new Intent();
returnIntent.putExtra("message", "No buildings around you!");
setResult(RESULT_CANCELED, returnIntent);
finish();
} else if (nearBuildings.buildings.isEmpty()) {
Toast.makeText(getBaseContext(), "No buildings around you!", Toast.LENGTH_SHORT).show();
} else {
setBuildingSpinner(nearBuildings.buildings, nearBuildings.distances);
}
} else {
setBuildingSpinner(buildings);
}
}
@Override
public void onErrorOrCancel(String result) {
finishJob();
Toast.makeText(getBaseContext(), result, Toast.LENGTH_SHORT).show();
}
private void finishJob() {
// Enable only if invisibleSelection==false
btnRefreshWorldBuildings.setEnabled(btnRefreshWorldBuildingsState);
btnRefreshNearmeBuildings.setEnabled(btnRefreshNearmeBuildingsState);
isBuildingsJobRunning = false;
}
}, forceReload);
}
private void startFloorFetch() throws IndexOutOfBoundsException {
BuildingModel building = mAnyplaceCache.getSelectedBuilding();
if (building != null) {
spinnerBuildings.setEnabled(false);
building.loadFloors(this, new FetchFloorsByBuidTask.FetchFloorsByBuidTaskListener() {
@Override
public void onSuccess(String result, List<? extends FloorModel> floors) {
finishJob((List<FloorModel>) floors);
onFloorsLoaded((List<FloorModel>) floors);
}
@Override
public void onErrorOrCancel(String result) {
finishJob(new ArrayList<FloorModel>());
Toast.makeText(getBaseContext(), result, Toast.LENGTH_SHORT).show();
}
private void finishJob(List<FloorModel> floors) {
// UPDATE SPINNER FOR FLOORS
setFloorSpinner(floors);
spinnerBuildings.setEnabled(true);
isFloorsJobRunning = false;
}
}, true, true);
}
}
// Create a list for the name of each building
private void setBuildingSpinner(List<BuildingModel> buildings) {
setBuildingSpinner(buildings, null);
}
private void setBuildingSpinner(List<BuildingModel> buildings, List<Double> distance) {
if (!buildings.isEmpty()) {
mAnyplaceCache.setSpinnerBuildings(app,buildings);
List<String> list = new ArrayList<String>();
if (distance == null) {
for (BuildingModel building : buildings) {
list.add(building.getName());
}
} else {
for (int i = 0; i < buildings.size(); i++) {
double value = distance.get(i);
if (value < 1000) {
list.add(String.format("[%.0f m] %s", value, buildings.get(i).getName()));
} else {
list.add(String.format("[%.1f km] %s", value / 1000, buildings.get(i).getName()));
}
}
}
ArrayAdapter<String> spinnerBuildingsAdapter;
spinnerBuildingsAdapter = new ArrayAdapter<String>(getBaseContext(), android.R.layout.simple_spinner_item, list);
spinnerBuildingsAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinnerBuildings.setAdapter(spinnerBuildingsAdapter);
}
}
// Create a list for the number of each floor
private void setFloorSpinner(List<FloorModel> floors) {
List<String> list = new ArrayList<String>();
for (FloorModel floor : floors) {
list.add(floor.toString());
}
ArrayAdapter<String> spinnerFloorsAdapter;
spinnerFloorsAdapter = new ArrayAdapter<String>(getBaseContext(), android.R.layout.simple_spinner_item, list);
spinnerFloorsAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinnerFloors.setAdapter(spinnerFloorsAdapter);
}
@Override
public void onFloorError(Exception ex) {
onNewFloor("0");
}
private void loadFloor(String floorNumber) {
BuildingModel build = mAnyplaceCache.getSelectedBuilding();
if (build != null) {
selectedFloorIndex = build.checkFloorIndex(floorNumber);
if (selectedFloorIndex == null) {
selectedFloorIndex = 0;
}
try {
spinnerFloors.setSelection(selectedFloorIndex);
if (mode == Mode.INVISIBLE)
startFloorPlanTask();
} catch (IndexOutOfBoundsException ex) {
}
}
}
@Override
public void onNewFloor(String floor) {
floorSelector.Stop();
isfloorSelectorJobFinished = true;
if (isBuildingsLoadingFinished && floorSelectorDialog.isShowing()) {
floorSelectorDialog.dismiss();
loadFloor(floor);
} else {
floorResult = floor;
}
}
private void onFloorsLoaded(List<FloorModel> floors) {
// if the user should not interact with the gui and
// automatically
// load the building
if (mode != Mode.NONE) {
// TODO - automatically choose the floor to be shown if
// it's
// only one
if (floors.isEmpty()) {
Toast.makeText(getBaseContext(), "No floors exist for the selected building!", Toast.LENGTH_SHORT).show();
SelectBuildingActivity.this.finish();
} else if (floors.size() == 1) {
if (mode == Mode.INVISIBLE)
startFloorPlanTask();
} else {
isBuildingsLoadingFinished = true;
if (isfloorSelectorJobFinished) {
loadFloor(floorResult);
} else {
if (!AnyplaceDebug.FLOOR_SELECTOR) {
loadFloor("0");
} else {
// Wait Floor Selector Answer
floorSelectorDialog.show();
}
}
}
} else {
if (floors.isEmpty()) {
Toast.makeText(getBaseContext(), "No floors exist for the selected building!", Toast.LENGTH_SHORT).show();
}
}
}
/* * TASKS */
private void startFloorPlanTask() {
try {
final BuildingModel b = mAnyplaceCache.getSelectedBuilding();
if (b == null) {
Toast.makeText(getBaseContext(), "You haven't selected both building and floor...!", Toast.LENGTH_SHORT).show();
setResult(RESULT_CANCELED);
finish();
return;
}
final FloorModel f = b.getLoadedFloors().get(selectedFloorIndex);
final FetchFloorPlanTask fetchFloorPlanTask = new FetchFloorPlanTask(this, b.buid, f.floor_number);
fetchFloorPlanTask.setCallbackInterface(new FetchFloorPlanTask.Callback() {
private ProgressDialog dialog;
@Override
public void onSuccess(String result, File floor_plan_file) {
if (dialog != null)
dialog.dismiss();
Intent returnIntent = new Intent();
returnIntent.putExtra("bmodel", mAnyplaceCache.getSelectedBuildingIndex());
returnIntent.putExtra("fmodel", selectedFloorIndex);
returnIntent.putExtra("floor_plan_path", floor_plan_file.getAbsolutePath());
returnIntent.putExtra("message", result);
setResult(RESULT_OK, returnIntent);
finish();
}
@Override
public void onErrorOrCancel(String result) {
if (dialog != null)
dialog.dismiss();
Toast.makeText(getBaseContext(), result, Toast.LENGTH_SHORT).show();
Intent returnIntent = new Intent();
returnIntent.putExtra("message", result);
setResult(RESULT_CANCELED);
finish();
}
@Override
public void onPrepareLongExecute() {
dialog = new ProgressDialog(SelectBuildingActivity.this);
dialog.setIndeterminate(true);
dialog.setTitle("Downloading floor plan");
dialog.setMessage("Please be patient...");
dialog.setCancelable(true);
dialog.setCanceledOnTouchOutside(false);
dialog.setOnCancelListener(new DialogInterface.OnCancelListener() {
@Override
public void onCancel(DialogInterface dialog) {
fetchFloorPlanTask.cancel(true);
}
});
dialog.show();
}
});
fetchFloorPlanTask.execute();
} catch (IndexOutOfBoundsException e) {
Toast.makeText(getBaseContext(), "You haven't selected both building and floor...!", Toast.LENGTH_SHORT).show();
setResult(RESULT_CANCELED);
finish();
return;
}
}
}
| 7,604 |
580 | package net.floodlightcontroller.cpanalyzer;
import net.floodlightcontroller.core.module.IFloodlightService;
public interface ICPAnalyzerService extends IFloodlightService {
}
| 53 |
898 | package com.spotify.heroic.grammar;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.runners.MockitoJUnitRunner;
import java.util.function.BiFunction;
import java.util.function.Consumer;
import java.util.stream.Stream;
import static org.junit.Assert.assertEquals;
import static org.mockito.Mockito.verify;
@RunWith(MockitoJUnitRunner.class)
public class MinusExpressionTest extends AbstractExpressionTest<MinusExpression> {
@Override
protected MinusExpression build(final Context ctx) {
return new MinusExpression(ctx, a, b);
}
@Override
protected BiFunction<Expression.Visitor<Void>, MinusExpression, Void> visitorMethod() {
return Expression.Visitor::visitMinus;
}
@Override
protected Stream<Consumer<MinusExpression>> accessors() {
return Stream.of(accessorTest(a, MinusExpression::getLeft),
accessorTest(b, MinusExpression::getRight));
}
@Override
public void evalTest() {
super.evalTest();
verify(a).eval(scope);
verify(b).eval(scope);
}
}
| 408 |
566 | <reponame>uf-reef-avl/dvo_slam
/**
* This file is part of dvo.
*
* Copyright 2012 <NAME> <<EMAIL>> (Technical University of Munich)
* For more information see <http://vision.in.tum.de/data/software/dvo>.
*
* dvo is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* dvo 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 dvo. If not, see <http://www.gnu.org/licenses/>.
*/
#ifndef DENSE_TRACKER_H_
#define DENSE_TRACKER_H_
#include <opencv2/opencv.hpp>
#include <Eigen/Core>
#include <Eigen/Geometry>
#include <dvo/core/datatypes.h>
#include <dvo/core/intrinsic_matrix.h>
#include <dvo/core/rgbd_image.h>
#include <dvo/core/point_selection.h>
#include <dvo/core/point_selection_predicates.h>
#include <dvo/core/least_squares.h>
#include <dvo/core/weight_calculation.h>
namespace dvo
{
class DenseTracker
{
public:
struct Config
{
int FirstLevel, LastLevel;
int MaxIterationsPerLevel;
double Precision;
double Mu; // precision (1/sigma^2) of prior
bool UseInitialEstimate;
bool UseWeighting;
bool UseParallel;
dvo::core::InfluenceFunctions::enum_t InfluenceFuntionType;
float InfluenceFunctionParam;
dvo::core::ScaleEstimators::enum_t ScaleEstimatorType;
float ScaleEstimatorParam;
float IntensityDerivativeThreshold;
float DepthDerivativeThreshold;
Config();
size_t getNumLevels() const;
bool UseEstimateSmoothing() const;
bool IsSane() const;
};
struct TerminationCriteria
{
enum Enum
{
IterationsExceeded,
IncrementTooSmall,
LogLikelihoodDecreased,
TooFewConstraints,
NumCriteria
};
};
struct IterationStats
{
EIGEN_MAKE_ALIGNED_OPERATOR_NEW;
size_t Id, ValidConstraints;
double TDistributionLogLikelihood;
Eigen::Vector2d TDistributionMean;
Eigen::Matrix2d TDistributionPrecision;
double PriorLogLikelihood;
dvo::core::Vector6d EstimateIncrement;
dvo::core::Matrix6d EstimateInformation;
void InformationEigenValues(dvo::core::Vector6d& eigenvalues) const;
double InformationConditionNumber() const;
};
typedef std::vector<IterationStats, Eigen::aligned_allocator<IterationStats> > IterationStatsVector;
struct LevelStats
{
size_t Id, MaxValidPixels, ValidPixels;
TerminationCriteria::Enum TerminationCriterion;
IterationStatsVector Iterations;
bool HasIterationWithIncrement() const;
IterationStats& LastIterationWithIncrement();
IterationStats& LastIteration();
const IterationStats& LastIterationWithIncrement() const;
const IterationStats& LastIteration() const;
};
typedef std::vector<LevelStats> LevelStatsVector;
struct Stats
{
LevelStatsVector Levels;
};
struct Result
{
EIGEN_MAKE_ALIGNED_OPERATOR_NEW;
dvo::core::AffineTransformd Transformation;
dvo::core::Matrix6d Information;
double LogLikelihood;
Stats Statistics;
Result();
bool isNaN() const;
void setIdentity();
void clearStatistics();
};
static const Config& getDefaultConfig();
EIGEN_MAKE_ALIGNED_OPERATOR_NEW
DenseTracker(const Config& cfg = getDefaultConfig());
DenseTracker(const dvo::DenseTracker& other);
const Config& configuration() const
{
return cfg;
}
void configure(const Config& cfg);
bool match(dvo::core::RgbdImagePyramid& reference, dvo::core::RgbdImagePyramid& current, dvo::core::AffineTransformd& transformation);
bool match(dvo::core::PointSelection& reference, dvo::core::RgbdImagePyramid& current, dvo::core::AffineTransformd& transformation);
bool match(dvo::core::RgbdImagePyramid& reference, dvo::core::RgbdImagePyramid& current, dvo::DenseTracker::Result& result);
bool match(dvo::core::PointSelection& reference, dvo::core::RgbdImagePyramid& current, dvo::DenseTracker::Result& result);
cv::Mat computeIntensityErrorImage(dvo::core::RgbdImagePyramid& reference, dvo::core::RgbdImagePyramid& current, const dvo::core::AffineTransformd& transformation, size_t level = 0);
static inline void computeJacobianOfProjectionAndTransformation(const dvo::core::Vector4& p, dvo::core::Matrix2x6& jacobian);
static inline void compute3rdRowOfJacobianOfTransformation(const dvo::core::Vector4& p, dvo::core::Vector6& j);
typedef std::vector<Eigen::Vector2f, Eigen::aligned_allocator<Eigen::Vector2f> > ResidualVectorType;
typedef std::vector<float> WeightVectorType;
private:
struct IterationContext
{
const Config& cfg;
int Level;
int Iteration;
double Error, LastError;
IterationContext(const Config& cfg);
// returns true if this is the first iteration
bool IsFirstIteration() const;
// returns true if this is the first iteration on the current level
bool IsFirstIterationOnLevel() const;
// returns true if this is the first level
bool IsFirstLevel() const;
// returns true if this is the last level
bool IsLastLevel() const;
bool IterationsExceeded() const;
// returns LastError - Error
double ErrorDiff() const;
};
Config cfg;
IterationContext itctx_;
dvo::core::WeightCalculation weight_calculation_;
dvo::core::PointSelection reference_selection_;
dvo::core::ValidPointAndGradientThresholdPredicate selection_predicate_;
dvo::core::PointWithIntensityAndDepth::VectorType points, points_error;
ResidualVectorType residuals;
WeightVectorType weights;
};
} /* namespace dvo */
template<typename CharT, typename Traits>
std::ostream& operator<< (std::basic_ostream<CharT, Traits> &out, const dvo::DenseTracker::Config &config)
{
out
<< "First Level = " << config.FirstLevel
<< ", Last Level = " << config.LastLevel
<< ", Max Iterations per Level = " << config.MaxIterationsPerLevel
<< ", Precision = " << config.Precision
<< ", Mu = " << config.Mu
<< ", Use Initial Estimate = " << (config.UseInitialEstimate ? "true" : "false")
<< ", Use Weighting = " << (config.UseWeighting ? "true" : "false")
<< ", Scale Estimator = " << dvo::core::ScaleEstimators::str(config.ScaleEstimatorType)
<< ", Scale Estimator Param = " << config.ScaleEstimatorParam
<< ", Influence Function = " << dvo::core::InfluenceFunctions::str(config.InfluenceFuntionType)
<< ", Influence Function Param = " << config.InfluenceFunctionParam
<< ", Intensity Derivative Threshold = " << config.IntensityDerivativeThreshold
<< ", Depth Derivative Threshold = " << config.DepthDerivativeThreshold
;
return out;
}
template<typename CharT, typename Traits>
std::ostream& operator<< (std::basic_ostream<CharT, Traits> &o, const dvo::DenseTracker::IterationStats &s)
{
o << "Iteration: " << s.Id << " ValidConstraints: " << s.ValidConstraints << " DataLogLikelihood: " << s.TDistributionLogLikelihood << " PriorLogLikelihood: " << s.PriorLogLikelihood << std::endl;
return o;
}
template<typename CharT, typename Traits>
std::ostream& operator<< (std::basic_ostream<CharT, Traits> &o, const dvo::DenseTracker::LevelStats &s)
{
std::string termination;
switch(s.TerminationCriterion)
{
case dvo::DenseTracker::TerminationCriteria::IterationsExceeded:
termination = "IterationsExceeded";
break;
case dvo::DenseTracker::TerminationCriteria::IncrementTooSmall:
termination = "IncrementTooSmall";
break;
case dvo::DenseTracker::TerminationCriteria::LogLikelihoodDecreased:
termination = "LogLikelihoodDecreased";
break;
case dvo::DenseTracker::TerminationCriteria::TooFewConstraints:
termination = "TooFewConstraints";
break;
default:
break;
}
o << "Level: " << s.Id << " Pixel: " << s.ValidPixels << "/" << s.MaxValidPixels << " Termination: " << termination << " Iterations: " << s.Iterations.size() << std::endl;
for(dvo::DenseTracker::IterationStatsVector::const_iterator it = s.Iterations.begin(); it != s.Iterations.end(); ++it)
{
o << *it;
}
return o;
}
template<typename CharT, typename Traits>
std::ostream& operator<< (std::basic_ostream<CharT, Traits> &o, const dvo::DenseTracker::Stats &s)
{
o << s.Levels.size() << " levels" << std::endl;
for(dvo::DenseTracker::LevelStatsVector::const_iterator it = s.Levels.begin(); it != s.Levels.end(); ++it)
{
o << *it;
}
return o;
}
#endif /* DENSE_TRACKER_H_ */
| 2,977 |
307 | # $Id$
import pytest
import sys
import os
def run_all(extra_args=None):
"""
Run all the tests of riptable.
Parameters
----------
extra_args : list
List of extra arguments (e.g. ['--verbosity=3'])
"""
if extra_args is None:
extra_args = []
pytest.main(extra_args + ['-k', 'test_', os.path.dirname(__file__)])
# Usage: "python -m riptable.tests.run"
# You can add more arguments to the pytest, like "python -m riptable.tests.run --verbosity=2"
if __name__ == "__main__":
run_all(sys.argv[1:])
| 256 |
3,402 | <reponame>ApacheSourceCode/kylin<filename>core-metadata/src/main/java/org/apache/kylin/metadata/cachesync/SingleValueCache.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.kylin.metadata.cachesync;
import java.util.Collection;
import java.util.Collections;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;
import org.apache.kylin.common.KylinConfig;
/**
* @author xjiang
*/
public abstract class SingleValueCache<K, V> extends AbstractCache<K, V> {
private final ConcurrentMap<K, V> innerCache;
public SingleValueCache(KylinConfig config, String syncEntity) {
this(config, syncEntity, new ConcurrentHashMap<K, V>());
}
public SingleValueCache(KylinConfig config, String syncEntity, ConcurrentMap<K, V> innerCache) {
super(config, syncEntity);
this.innerCache = innerCache;
}
public void put(K key, V value) {
boolean exists = innerCache.containsKey(key);
innerCache.put(key, value);
if (!exists) {
getBroadcaster().announce(syncEntity, Broadcaster.Event.CREATE.getType(), key.toString());
} else {
getBroadcaster().announce(syncEntity, Broadcaster.Event.UPDATE.getType(), key.toString());
}
}
public void putLocal(K key, V value) {
innerCache.put(key, value);
}
public void remove(K key) {
boolean exists = innerCache.containsKey(key);
innerCache.remove(key);
if (exists) {
getBroadcaster().announce(syncEntity, Broadcaster.Event.DROP.getType(), key.toString());
}
}
public void removeLocal(K key) {
innerCache.remove(key);
}
public void clear() {
innerCache.clear();
}
public int size() {
return innerCache.size();
}
public V get(K key) {
return innerCache.get(key);
}
public Collection<V> values() {
return innerCache.values();
}
public boolean containsKey(String key) {
return innerCache.containsKey(key);
}
public Map<K, V> getMap() {
return Collections.unmodifiableMap(innerCache);
}
public Set<K> keySet() {
return innerCache.keySet();
}
}
| 1,081 |
1,481 | <reponame>1-c/Corange
/**
*** :: Audio ::
***
*** Basic Audio layer.
***
*** Currently only plays flat sounds.
*** No support for source manipulation.
*** Could do with some more love.
***
**/
#ifndef caudio_h
#define caudio_h
#include "cengine.h"
#include "assets/sound.h"
#include "assets/music.h"
void audio_init();
void audio_finish();
int audio_sound_play(sound* s, int loops);
void audio_sound_pause(int channel);
void audio_sound_resume(int channel);
void audio_sound_stop(int channel);
void audio_music_play(music* m);
void audio_music_pause();
void audio_music_resume();
void audio_music_stop();
void audio_music_set_volume(float volume);
float audio_music_get_volume();
#endif
| 246 |
984 | <reponame>petchw/subvim1
#include <iostream>
#define TEST_CPP_FOR_OPERATOR_CLANG_FORMAT_LONG_MACRO " CPP for vim-operator-clang-complete"
void f(){ std::cout << "hello\n"; }
int main()
{
int * hoge = {1,3,5,7};
for(int i=0;i<4;++i){
if(i%2==0) std::cout << hoge[i] << std::endl;
}
std::cout << "this is very very long one-line string. so this line go over 80 column .\n";
std::cout << "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:";
return 0;
}
| 293 |
522 | #include "third_party/vulkan-deps/spirv-cross/src/spirv_cfg.cpp"
#include "third_party/vulkan-deps/spirv-cross/src/spirv_cross.cpp"
#include "third_party/vulkan-deps/spirv-cross/src/spirv_cross_parsed_ir.cpp"
#include "third_party/vulkan-deps/spirv-cross/src/spirv_cross_util.cpp"
#include "third_party/vulkan-deps/spirv-cross/src/spirv_glsl.cpp"
#include "third_party/vulkan-deps/spirv-cross/src/spirv_hlsl.cpp"
#include "third_party/vulkan-deps/spirv-cross/src/spirv_msl.cpp"
#include "third_party/vulkan-deps/spirv-cross/src/spirv_parser.cpp"
#include "third_party/vulkan-deps/spirv-cross/src/spirv_reflect.cpp"
| 263 |
573 | <reponame>Esigodini/dynarmic<filename>externals/mp/include/mp/metavalue/bit_and.h
/* This file is part of the mp project.
* Copyright (c) 2020 MerryMage
* SPDX-License-Identifier: 0BSD
*/
#pragma once
#include <mp/metavalue/lift_value.h>
namespace mp {
/// Bitwise and of metavalues Vs
template<class... Vs>
using bit_and = lift_value<(Vs::value & ...)>;
/// Bitwise and of metavalues Vs
template<class... Vs>
constexpr auto bit_and_v = (Vs::value & ...);
} // namespace mp
| 180 |
2,361 | def pytest_addoption(parser):
parser.addoption("--runslow", action="store_true",
help="Run slow tests")
| 56 |
826 | <reponame>CYXiang/TenMinDemo<gh_stars>100-1000
//
// TableViewController.h
// KIFTest1
//
// Created by 陈燕翔 on 2017/7/9.
// Copyright © 2017年 陈燕翔. All rights reserved.
//
#import <UIKit/UIKit.h>
@interface TableViewController : UITableViewController
@end
| 117 |
1,025 | #import <Cocoa/Cocoa.h>
@interface CDEProjectBrowserWindowController : NSWindowController
#pragma mark - Working with the project browser
- (void)showWithProjectDirectoryURL:(NSURL *)projectDirectoryURL;
- (void)updateProjectDirectoryURL:(NSURL *)projectDirectoryURL;
@end
| 80 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.